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# information about snapshot formats that gitweb is capable of serving 170our%known_snapshot_formats= ( 171# name => { 172# 'display' => display name, 173# 'type' => mime type, 174# 'suffix' => filename suffix, 175# 'format' => --format for git-archive, 176# 'compressor' => [compressor command and arguments] 177# (array reference, optional) 178# 'disabled' => boolean (optional)} 179# 180'tgz'=> { 181'display'=>'tar.gz', 182'type'=>'application/x-gzip', 183'suffix'=>'.tar.gz', 184'format'=>'tar', 185'compressor'=> ['gzip']}, 186 187'tbz2'=> { 188'display'=>'tar.bz2', 189'type'=>'application/x-bzip2', 190'suffix'=>'.tar.bz2', 191'format'=>'tar', 192'compressor'=> ['bzip2']}, 193 194'txz'=> { 195'display'=>'tar.xz', 196'type'=>'application/x-xz', 197'suffix'=>'.tar.xz', 198'format'=>'tar', 199'compressor'=> ['xz'], 200'disabled'=>1}, 201 202'zip'=> { 203'display'=>'zip', 204'type'=>'application/x-zip', 205'suffix'=>'.zip', 206'format'=>'zip'}, 207); 208 209# Aliases so we understand old gitweb.snapshot values in repository 210# configuration. 211our%known_snapshot_format_aliases= ( 212'gzip'=>'tgz', 213'bzip2'=>'tbz2', 214'xz'=>'txz', 215 216# backward compatibility: legacy gitweb config support 217'x-gzip'=>undef,'gz'=>undef, 218'x-bzip2'=>undef,'bz2'=>undef, 219'x-zip'=>undef,''=>undef, 220); 221 222# Pixel sizes for icons and avatars. If the default font sizes or lineheights 223# are changed, it may be appropriate to change these values too via 224# $GITWEB_CONFIG. 225our%avatar_size= ( 226'default'=>16, 227'double'=>32 228); 229 230# Used to set the maximum load that we will still respond to gitweb queries. 231# If server load exceed this value then return "503 server busy" error. 232# If gitweb cannot determined server load, it is taken to be 0. 233# Leave it undefined (or set to 'undef') to turn off load checking. 234our$maxload=300; 235 236# configuration for 'highlight' (http://www.andre-simon.de/) 237# match by basename 238our%highlight_basename= ( 239#'Program' => 'py', 240#'Library' => 'py', 241'SConstruct'=>'py',# SCons equivalent of Makefile 242'Makefile'=>'make', 243); 244# match by extension 245our%highlight_ext= ( 246# main extensions, defining name of syntax; 247# see files in /usr/share/highlight/langDefs/ directory 248map{$_=>$_} 249qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl), 250# alternate extensions, see /etc/highlight/filetypes.conf 251'h'=>'c', 252map{$_=>'cpp'}qw(cxx c++ cc), 253map{$_=>'php'}qw(php3 php4), 254map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 255'mak'=>'make', 256map{$_=>'xml'}qw(xhtml html htm), 257); 258 259# You define site-wide feature defaults here; override them with 260# $GITWEB_CONFIG as necessary. 261our%feature= ( 262# feature => { 263# 'sub' => feature-sub (subroutine), 264# 'override' => allow-override (boolean), 265# 'default' => [ default options...] (array reference)} 266# 267# if feature is overridable (it means that allow-override has true value), 268# then feature-sub will be called with default options as parameters; 269# return value of feature-sub indicates if to enable specified feature 270# 271# if there is no 'sub' key (no feature-sub), then feature cannot be 272# overridden 273# 274# use gitweb_get_feature(<feature>) to retrieve the <feature> value 275# (an array) or gitweb_check_feature(<feature>) to check if <feature> 276# is enabled 277 278# Enable the 'blame' blob view, showing the last commit that modified 279# each line in the file. This can be very CPU-intensive. 280 281# To enable system wide have in $GITWEB_CONFIG 282# $feature{'blame'}{'default'} = [1]; 283# To have project specific config enable override in $GITWEB_CONFIG 284# $feature{'blame'}{'override'} = 1; 285# and in project config gitweb.blame = 0|1; 286'blame'=> { 287'sub'=>sub{ feature_bool('blame',@_) }, 288'override'=>0, 289'default'=> [0]}, 290 291# Enable the 'snapshot' link, providing a compressed archive of any 292# tree. This can potentially generate high traffic if you have large 293# project. 294 295# Value is a list of formats defined in %known_snapshot_formats that 296# you wish to offer. 297# To disable system wide have in $GITWEB_CONFIG 298# $feature{'snapshot'}{'default'} = []; 299# To have project specific config enable override in $GITWEB_CONFIG 300# $feature{'snapshot'}{'override'} = 1; 301# and in project config, a comma-separated list of formats or "none" 302# to disable. Example: gitweb.snapshot = tbz2,zip; 303'snapshot'=> { 304'sub'=> \&feature_snapshot, 305'override'=>0, 306'default'=> ['tgz']}, 307 308# Enable text search, which will list the commits which match author, 309# committer or commit text to a given string. Enabled by default. 310# Project specific override is not supported. 311'search'=> { 312'override'=>0, 313'default'=> [1]}, 314 315# Enable grep search, which will list the files in currently selected 316# tree containing the given string. Enabled by default. This can be 317# potentially CPU-intensive, of course. 318 319# To enable system wide have in $GITWEB_CONFIG 320# $feature{'grep'}{'default'} = [1]; 321# To have project specific config enable override in $GITWEB_CONFIG 322# $feature{'grep'}{'override'} = 1; 323# and in project config gitweb.grep = 0|1; 324'grep'=> { 325'sub'=>sub{ feature_bool('grep',@_) }, 326'override'=>0, 327'default'=> [1]}, 328 329# Enable the pickaxe search, which will list the commits that modified 330# a given string in a file. This can be practical and quite faster 331# alternative to 'blame', but still potentially CPU-intensive. 332 333# To enable system wide have in $GITWEB_CONFIG 334# $feature{'pickaxe'}{'default'} = [1]; 335# To have project specific config enable override in $GITWEB_CONFIG 336# $feature{'pickaxe'}{'override'} = 1; 337# and in project config gitweb.pickaxe = 0|1; 338'pickaxe'=> { 339'sub'=>sub{ feature_bool('pickaxe',@_) }, 340'override'=>0, 341'default'=> [1]}, 342 343# Enable showing size of blobs in a 'tree' view, in a separate 344# column, similar to what 'ls -l' does. This cost a bit of IO. 345 346# To disable system wide have in $GITWEB_CONFIG 347# $feature{'show-sizes'}{'default'} = [0]; 348# To have project specific config enable override in $GITWEB_CONFIG 349# $feature{'show-sizes'}{'override'} = 1; 350# and in project config gitweb.showsizes = 0|1; 351'show-sizes'=> { 352'sub'=>sub{ feature_bool('showsizes',@_) }, 353'override'=>0, 354'default'=> [1]}, 355 356# Make gitweb use an alternative format of the URLs which can be 357# more readable and natural-looking: project name is embedded 358# directly in the path and the query string contains other 359# auxiliary information. All gitweb installations recognize 360# URL in either format; this configures in which formats gitweb 361# generates links. 362 363# To enable system wide have in $GITWEB_CONFIG 364# $feature{'pathinfo'}{'default'} = [1]; 365# Project specific override is not supported. 366 367# Note that you will need to change the default location of CSS, 368# favicon, logo and possibly other files to an absolute URL. Also, 369# if gitweb.cgi serves as your indexfile, you will need to force 370# $my_uri to contain the script name in your $GITWEB_CONFIG. 371'pathinfo'=> { 372'override'=>0, 373'default'=> [0]}, 374 375# Make gitweb consider projects in project root subdirectories 376# to be forks of existing projects. Given project $projname.git, 377# projects matching $projname/*.git will not be shown in the main 378# projects list, instead a '+' mark will be added to $projname 379# there and a 'forks' view will be enabled for the project, listing 380# all the forks. If project list is taken from a file, forks have 381# to be listed after the main project. 382 383# To enable system wide have in $GITWEB_CONFIG 384# $feature{'forks'}{'default'} = [1]; 385# Project specific override is not supported. 386'forks'=> { 387'override'=>0, 388'default'=> [0]}, 389 390# Insert custom links to the action bar of all project pages. 391# This enables you mainly to link to third-party scripts integrating 392# into gitweb; e.g. git-browser for graphical history representation 393# or custom web-based repository administration interface. 394 395# The 'default' value consists of a list of triplets in the form 396# (label, link, position) where position is the label after which 397# to insert the link and link is a format string where %n expands 398# to the project name, %f to the project path within the filesystem, 399# %h to the current hash (h gitweb parameter) and %b to the current 400# hash base (hb gitweb parameter); %% expands to %. 401 402# To enable system wide have in $GITWEB_CONFIG e.g. 403# $feature{'actions'}{'default'} = [('graphiclog', 404# '/git-browser/by-commit.html?r=%n', 'summary')]; 405# Project specific override is not supported. 406'actions'=> { 407'override'=>0, 408'default'=> []}, 409 410# Allow gitweb scan project content tags described in ctags/ 411# of project repository, and display the popular Web 2.0-ish 412# "tag cloud" near the project list. Note that this is something 413# COMPLETELY different from the normal Git tags. 414 415# gitweb by itself can show existing tags, but it does not handle 416# tagging itself; you need an external application for that. 417# For an example script, check Girocco's cgi/tagproj.cgi. 418# You may want to install the HTML::TagCloud Perl module to get 419# a pretty tag cloud instead of just a list of tags. 420 421# To enable system wide have in $GITWEB_CONFIG 422# $feature{'ctags'}{'default'} = ['path_to_tag_script']; 423# Project specific override is not supported. 424'ctags'=> { 425'override'=>0, 426'default'=> [0]}, 427 428# The maximum number of patches in a patchset generated in patch 429# view. Set this to 0 or undef to disable patch view, or to a 430# negative number to remove any limit. 431 432# To disable system wide have in $GITWEB_CONFIG 433# $feature{'patches'}{'default'} = [0]; 434# To have project specific config enable override in $GITWEB_CONFIG 435# $feature{'patches'}{'override'} = 1; 436# and in project config gitweb.patches = 0|n; 437# where n is the maximum number of patches allowed in a patchset. 438'patches'=> { 439'sub'=> \&feature_patches, 440'override'=>0, 441'default'=> [16]}, 442 443# Avatar support. When this feature is enabled, views such as 444# shortlog or commit will display an avatar associated with 445# the email of the committer(s) and/or author(s). 446 447# Currently available providers are gravatar and picon. 448# If an unknown provider is specified, the feature is disabled. 449 450# Gravatar depends on Digest::MD5. 451# Picon currently relies on the indiana.edu database. 452 453# To enable system wide have in $GITWEB_CONFIG 454# $feature{'avatar'}{'default'} = ['<provider>']; 455# where <provider> is either gravatar or picon. 456# To have project specific config enable override in $GITWEB_CONFIG 457# $feature{'avatar'}{'override'} = 1; 458# and in project config gitweb.avatar = <provider>; 459'avatar'=> { 460'sub'=> \&feature_avatar, 461'override'=>0, 462'default'=> ['']}, 463 464# Enable displaying how much time and how many git commands 465# it took to generate and display page. Disabled by default. 466# Project specific override is not supported. 467'timed'=> { 468'override'=>0, 469'default'=> [0]}, 470 471# Enable turning some links into links to actions which require 472# JavaScript to run (like 'blame_incremental'). Not enabled by 473# default. Project specific override is currently not supported. 474'javascript-actions'=> { 475'override'=>0, 476'default'=> [0]}, 477 478# Syntax highlighting support. This is based on Daniel Svensson's 479# and Sham Chukoury's work in gitweb-xmms2.git. 480# It requires the 'highlight' program present in $PATH, 481# and therefore is disabled by default. 482 483# To enable system wide have in $GITWEB_CONFIG 484# $feature{'highlight'}{'default'} = [1]; 485 486'highlight'=> { 487'sub'=>sub{ feature_bool('highlight',@_) }, 488'override'=>0, 489'default'=> [0]}, 490); 491 492sub gitweb_get_feature { 493my($name) =@_; 494return unlessexists$feature{$name}; 495my($sub,$override,@defaults) = ( 496$feature{$name}{'sub'}, 497$feature{$name}{'override'}, 498@{$feature{$name}{'default'}}); 499# project specific override is possible only if we have project 500our$git_dir;# global variable, declared later 501if(!$override|| !defined$git_dir) { 502return@defaults; 503} 504if(!defined$sub) { 505warn"feature$nameis not overridable"; 506return@defaults; 507} 508return$sub->(@defaults); 509} 510 511# A wrapper to check if a given feature is enabled. 512# With this, you can say 513# 514# my $bool_feat = gitweb_check_feature('bool_feat'); 515# gitweb_check_feature('bool_feat') or somecode; 516# 517# instead of 518# 519# my ($bool_feat) = gitweb_get_feature('bool_feat'); 520# (gitweb_get_feature('bool_feat'))[0] or somecode; 521# 522sub gitweb_check_feature { 523return(gitweb_get_feature(@_))[0]; 524} 525 526 527sub feature_bool { 528my$key=shift; 529my($val) = git_get_project_config($key,'--bool'); 530 531if(!defined$val) { 532return($_[0]); 533}elsif($valeq'true') { 534return(1); 535}elsif($valeq'false') { 536return(0); 537} 538} 539 540sub feature_snapshot { 541my(@fmts) =@_; 542 543my($val) = git_get_project_config('snapshot'); 544 545if($val) { 546@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 547} 548 549return@fmts; 550} 551 552sub feature_patches { 553my@val= (git_get_project_config('patches','--int')); 554 555if(@val) { 556return@val; 557} 558 559return($_[0]); 560} 561 562sub feature_avatar { 563my@val= (git_get_project_config('avatar')); 564 565return@val?@val:@_; 566} 567 568# checking HEAD file with -e is fragile if the repository was 569# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 570# and then pruned. 571sub check_head_link { 572my($dir) =@_; 573my$headfile="$dir/HEAD"; 574return((-e $headfile) || 575(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 576} 577 578sub check_export_ok { 579my($dir) =@_; 580return(check_head_link($dir) && 581(!$export_ok|| -e "$dir/$export_ok") && 582(!$export_auth_hook||$export_auth_hook->($dir))); 583} 584 585# process alternate names for backward compatibility 586# filter out unsupported (unknown) snapshot formats 587sub filter_snapshot_fmts { 588my@fmts=@_; 589 590@fmts=map{ 591exists$known_snapshot_format_aliases{$_} ? 592$known_snapshot_format_aliases{$_} :$_}@fmts; 593@fmts=grep{ 594exists$known_snapshot_formats{$_} && 595!$known_snapshot_formats{$_}{'disabled'}}@fmts; 596} 597 598our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM); 599sub evaluate_gitweb_config { 600our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 601our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 602# die if there are errors parsing config file 603if(-e $GITWEB_CONFIG) { 604do$GITWEB_CONFIG; 605die$@if$@; 606}elsif(-e $GITWEB_CONFIG_SYSTEM) { 607do$GITWEB_CONFIG_SYSTEM; 608die$@if$@; 609} 610} 611 612# Get loadavg of system, to compare against $maxload. 613# Currently it requires '/proc/loadavg' present to get loadavg; 614# if it is not present it returns 0, which means no load checking. 615sub get_loadavg { 616if( -e '/proc/loadavg'){ 617open my$fd,'<','/proc/loadavg' 618orreturn0; 619my@load=split(/\s+/,scalar<$fd>); 620close$fd; 621 622# The first three columns measure CPU and IO utilization of the last one, 623# five, and 10 minute periods. The fourth column shows the number of 624# currently running processes and the total number of processes in the m/n 625# format. The last column displays the last process ID used. 626return$load[0] ||0; 627} 628# additional checks for load average should go here for things that don't export 629# /proc/loadavg 630 631return0; 632} 633 634# version of the core git binary 635our$git_version; 636sub evaluate_git_version { 637our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 638$number_of_git_cmds++; 639} 640 641sub check_loadavg { 642if(defined$maxload&& get_loadavg() >$maxload) { 643 die_error(503,"The load average on the server is too high"); 644} 645} 646 647# ====================================================================== 648# input validation and dispatch 649 650# input parameters can be collected from a variety of sources (presently, CGI 651# and PATH_INFO), so we define an %input_params hash that collects them all 652# together during validation: this allows subsequent uses (e.g. href()) to be 653# agnostic of the parameter origin 654 655our%input_params= (); 656 657# input parameters are stored with the long parameter name as key. This will 658# also be used in the href subroutine to convert parameters to their CGI 659# equivalent, and since the href() usage is the most frequent one, we store 660# the name -> CGI key mapping here, instead of the reverse. 661# 662# XXX: Warning: If you touch this, check the search form for updating, 663# too. 664 665our@cgi_param_mapping= ( 666 project =>"p", 667 action =>"a", 668 file_name =>"f", 669 file_parent =>"fp", 670 hash =>"h", 671 hash_parent =>"hp", 672 hash_base =>"hb", 673 hash_parent_base =>"hpb", 674 page =>"pg", 675 order =>"o", 676 searchtext =>"s", 677 searchtype =>"st", 678 snapshot_format =>"sf", 679 extra_options =>"opt", 680 search_use_regexp =>"sr", 681# this must be last entry (for manipulation from JavaScript) 682 javascript =>"js" 683); 684our%cgi_param_mapping=@cgi_param_mapping; 685 686# we will also need to know the possible actions, for validation 687our%actions= ( 688"blame"=> \&git_blame, 689"blame_incremental"=> \&git_blame_incremental, 690"blame_data"=> \&git_blame_data, 691"blobdiff"=> \&git_blobdiff, 692"blobdiff_plain"=> \&git_blobdiff_plain, 693"blob"=> \&git_blob, 694"blob_plain"=> \&git_blob_plain, 695"commitdiff"=> \&git_commitdiff, 696"commitdiff_plain"=> \&git_commitdiff_plain, 697"commit"=> \&git_commit, 698"forks"=> \&git_forks, 699"heads"=> \&git_heads, 700"history"=> \&git_history, 701"log"=> \&git_log, 702"patch"=> \&git_patch, 703"patches"=> \&git_patches, 704"rss"=> \&git_rss, 705"atom"=> \&git_atom, 706"search"=> \&git_search, 707"search_help"=> \&git_search_help, 708"shortlog"=> \&git_shortlog, 709"summary"=> \&git_summary, 710"tag"=> \&git_tag, 711"tags"=> \&git_tags, 712"tree"=> \&git_tree, 713"snapshot"=> \&git_snapshot, 714"object"=> \&git_object, 715# those below don't need $project 716"opml"=> \&git_opml, 717"project_list"=> \&git_project_list, 718"project_index"=> \&git_project_index, 719); 720 721# finally, we have the hash of allowed extra_options for the commands that 722# allow them 723our%allowed_options= ( 724"--no-merges"=> [qw(rss atom log shortlog history)], 725); 726 727# fill %input_params with the CGI parameters. All values except for 'opt' 728# should be single values, but opt can be an array. We should probably 729# build an array of parameters that can be multi-valued, but since for the time 730# being it's only this one, we just single it out 731sub evaluate_query_params { 732our$cgi; 733 734while(my($name,$symbol) =each%cgi_param_mapping) { 735if($symboleq'opt') { 736$input_params{$name} = [$cgi->param($symbol) ]; 737}else{ 738$input_params{$name} =$cgi->param($symbol); 739} 740} 741} 742 743# now read PATH_INFO and update the parameter list for missing parameters 744sub evaluate_path_info { 745return ifdefined$input_params{'project'}; 746return if!$path_info; 747$path_info=~ s,^/+,,; 748return if!$path_info; 749 750# find which part of PATH_INFO is project 751my$project=$path_info; 752$project=~ s,/+$,,; 753while($project&& !check_head_link("$projectroot/$project")) { 754$project=~ s,/*[^/]*$,,; 755} 756return unless$project; 757$input_params{'project'} =$project; 758 759# do not change any parameters if an action is given using the query string 760return if$input_params{'action'}; 761$path_info=~ s,^\Q$project\E/*,,; 762 763# next, check if we have an action 764my$action=$path_info; 765$action=~ s,/.*$,,; 766if(exists$actions{$action}) { 767$path_info=~ s,^$action/*,,; 768$input_params{'action'} =$action; 769} 770 771# list of actions that want hash_base instead of hash, but can have no 772# pathname (f) parameter 773my@wants_base= ( 774'tree', 775'history', 776); 777 778# we want to catch 779# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 780my($parentrefname,$parentpathname,$refname,$pathname) = 781($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/); 782 783# first, analyze the 'current' part 784if(defined$pathname) { 785# we got "branch:filename" or "branch:dir/" 786# we could use git_get_type(branch:pathname), but: 787# - it needs $git_dir 788# - it does a git() call 789# - the convention of terminating directories with a slash 790# makes it superfluous 791# - embedding the action in the PATH_INFO would make it even 792# more superfluous 793$pathname=~ s,^/+,,; 794if(!$pathname||substr($pathname, -1)eq"/") { 795$input_params{'action'} ||="tree"; 796$pathname=~ s,/$,,; 797}else{ 798# the default action depends on whether we had parent info 799# or not 800if($parentrefname) { 801$input_params{'action'} ||="blobdiff_plain"; 802}else{ 803$input_params{'action'} ||="blob_plain"; 804} 805} 806$input_params{'hash_base'} ||=$refname; 807$input_params{'file_name'} ||=$pathname; 808}elsif(defined$refname) { 809# we got "branch". In this case we have to choose if we have to 810# set hash or hash_base. 811# 812# Most of the actions without a pathname only want hash to be 813# set, except for the ones specified in @wants_base that want 814# hash_base instead. It should also be noted that hand-crafted 815# links having 'history' as an action and no pathname or hash 816# set will fail, but that happens regardless of PATH_INFO. 817$input_params{'action'} ||="shortlog"; 818if(grep{$_eq$input_params{'action'} }@wants_base) { 819$input_params{'hash_base'} ||=$refname; 820}else{ 821$input_params{'hash'} ||=$refname; 822} 823} 824 825# next, handle the 'parent' part, if present 826if(defined$parentrefname) { 827# a missing pathspec defaults to the 'current' filename, allowing e.g. 828# someproject/blobdiff/oldrev..newrev:/filename 829if($parentpathname) { 830$parentpathname=~ s,^/+,,; 831$parentpathname=~ s,/$,,; 832$input_params{'file_parent'} ||=$parentpathname; 833}else{ 834$input_params{'file_parent'} ||=$input_params{'file_name'}; 835} 836# we assume that hash_parent_base is wanted if a path was specified, 837# or if the action wants hash_base instead of hash 838if(defined$input_params{'file_parent'} || 839grep{$_eq$input_params{'action'} }@wants_base) { 840$input_params{'hash_parent_base'} ||=$parentrefname; 841}else{ 842$input_params{'hash_parent'} ||=$parentrefname; 843} 844} 845 846# for the snapshot action, we allow URLs in the form 847# $project/snapshot/$hash.ext 848# where .ext determines the snapshot and gets removed from the 849# passed $refname to provide the $hash. 850# 851# To be able to tell that $refname includes the format extension, we 852# require the following two conditions to be satisfied: 853# - the hash input parameter MUST have been set from the $refname part 854# of the URL (i.e. they must be equal) 855# - the snapshot format MUST NOT have been defined already (e.g. from 856# CGI parameter sf) 857# It's also useless to try any matching unless $refname has a dot, 858# so we check for that too 859if(defined$input_params{'action'} && 860$input_params{'action'}eq'snapshot'&& 861defined$refname&&index($refname,'.') != -1&& 862$refnameeq$input_params{'hash'} && 863!defined$input_params{'snapshot_format'}) { 864# We loop over the known snapshot formats, checking for 865# extensions. Allowed extensions are both the defined suffix 866# (which includes the initial dot already) and the snapshot 867# format key itself, with a prepended dot 868while(my($fmt,$opt) =each%known_snapshot_formats) { 869my$hash=$refname; 870unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 871next; 872} 873my$sfx=$1; 874# a valid suffix was found, so set the snapshot format 875# and reset the hash parameter 876$input_params{'snapshot_format'} =$fmt; 877$input_params{'hash'} =$hash; 878# we also set the format suffix to the one requested 879# in the URL: this way a request for e.g. .tgz returns 880# a .tgz instead of a .tar.gz 881$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 882last; 883} 884} 885} 886 887our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 888$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 889$searchtext,$search_regexp); 890sub evaluate_and_validate_params { 891our$action=$input_params{'action'}; 892if(defined$action) { 893if(!validate_action($action)) { 894 die_error(400,"Invalid action parameter"); 895} 896} 897 898# parameters which are pathnames 899our$project=$input_params{'project'}; 900if(defined$project) { 901if(!validate_project($project)) { 902undef$project; 903 die_error(404,"No such project"); 904} 905} 906 907our$file_name=$input_params{'file_name'}; 908if(defined$file_name) { 909if(!validate_pathname($file_name)) { 910 die_error(400,"Invalid file parameter"); 911} 912} 913 914our$file_parent=$input_params{'file_parent'}; 915if(defined$file_parent) { 916if(!validate_pathname($file_parent)) { 917 die_error(400,"Invalid file parent parameter"); 918} 919} 920 921# parameters which are refnames 922our$hash=$input_params{'hash'}; 923if(defined$hash) { 924if(!validate_refname($hash)) { 925 die_error(400,"Invalid hash parameter"); 926} 927} 928 929our$hash_parent=$input_params{'hash_parent'}; 930if(defined$hash_parent) { 931if(!validate_refname($hash_parent)) { 932 die_error(400,"Invalid hash parent parameter"); 933} 934} 935 936our$hash_base=$input_params{'hash_base'}; 937if(defined$hash_base) { 938if(!validate_refname($hash_base)) { 939 die_error(400,"Invalid hash base parameter"); 940} 941} 942 943our@extra_options= @{$input_params{'extra_options'}}; 944# @extra_options is always defined, since it can only be (currently) set from 945# CGI, and $cgi->param() returns the empty array in array context if the param 946# is not set 947foreachmy$opt(@extra_options) { 948if(not exists$allowed_options{$opt}) { 949 die_error(400,"Invalid option parameter"); 950} 951if(not grep(/^$action$/, @{$allowed_options{$opt}})) { 952 die_error(400,"Invalid option parameter for this action"); 953} 954} 955 956our$hash_parent_base=$input_params{'hash_parent_base'}; 957if(defined$hash_parent_base) { 958if(!validate_refname($hash_parent_base)) { 959 die_error(400,"Invalid hash parent base parameter"); 960} 961} 962 963# other parameters 964our$page=$input_params{'page'}; 965if(defined$page) { 966if($page=~m/[^0-9]/) { 967 die_error(400,"Invalid page parameter"); 968} 969} 970 971our$searchtype=$input_params{'searchtype'}; 972if(defined$searchtype) { 973if($searchtype=~m/[^a-z]/) { 974 die_error(400,"Invalid searchtype parameter"); 975} 976} 977 978our$search_use_regexp=$input_params{'search_use_regexp'}; 979 980our$searchtext=$input_params{'searchtext'}; 981our$search_regexp; 982if(defined$searchtext) { 983if(length($searchtext) <2) { 984 die_error(403,"At least two characters are required for search parameter"); 985} 986$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext; 987} 988} 989 990# path to the current git repository 991our$git_dir; 992sub evaluate_git_dir { 993our$git_dir="$projectroot/$project"if$project; 994} 995 996our(@snapshot_fmts,$git_avatar); 997sub configure_gitweb_features { 998# list of supported snapshot formats 999our@snapshot_fmts= gitweb_get_feature('snapshot');1000@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);10011002# check that the avatar feature is set to a known provider name,1003# and for each provider check if the dependencies are satisfied.1004# if the provider name is invalid or the dependencies are not met,1005# reset $git_avatar to the empty string.1006our($git_avatar) = gitweb_get_feature('avatar');1007if($git_avatareq'gravatar') {1008$git_avatar=''unless(eval{require Digest::MD5;1; });1009}elsif($git_avatareq'picon') {1010# no dependencies1011}else{1012$git_avatar='';1013}1014}10151016# custom error handler: 'die <message>' is Internal Server Error1017sub handle_errors_html {1018my$msg=shift;# it is already HTML escaped10191020# to avoid infinite loop where error occurs in die_error,1021# change handler to default handler, disabling handle_errors_html1022 set_message("Error occured when inside die_error:\n$msg");10231024# you cannot jump out of die_error when called as error handler;1025# the subroutine set via CGI::Carp::set_message is called _after_1026# HTTP headers are already written, so it cannot write them itself1027 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1028}1029set_message(\&handle_errors_html);10301031# dispatch1032sub dispatch {1033if(!defined$action) {1034if(defined$hash) {1035$action= git_get_type($hash);1036}elsif(defined$hash_base&&defined$file_name) {1037$action= git_get_type("$hash_base:$file_name");1038}elsif(defined$project) {1039$action='summary';1040}else{1041$action='project_list';1042}1043}1044if(!defined($actions{$action})) {1045 die_error(400,"Unknown action");1046}1047if($action!~m/^(?:opml|project_list|project_index)$/&&1048!$project) {1049 die_error(400,"Project needed");1050}1051$actions{$action}->();1052}10531054sub reset_timer {1055our$t0= [Time::HiRes::gettimeofday()]1056ifdefined$t0;1057our$number_of_git_cmds=0;1058}10591060sub run_request {1061 reset_timer();10621063 evaluate_uri();1064 evaluate_gitweb_config();1065 check_loadavg();10661067# $projectroot and $projects_list might be set in gitweb config file1068$projects_list||=$projectroot;10691070 evaluate_query_params();1071 evaluate_path_info();1072 evaluate_and_validate_params();1073 evaluate_git_dir();10741075 configure_gitweb_features();10761077 dispatch();1078}10791080our$is_last_request=sub{1};1081our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1082our$CGI='CGI';1083our$cgi;1084sub configure_as_fcgi {1085require CGI::Fast;1086our$CGI='CGI::Fast';10871088my$request_number=0;1089# let each child service 100 requests1090our$is_last_request=sub{ ++$request_number>100};1091}1092sub evaluate_argv {1093my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1094 configure_as_fcgi()1095if$script_name=~/\.fcgi$/;10961097return unless(@ARGV);10981099require Getopt::Long;1100 Getopt::Long::GetOptions(1101'fastcgi|fcgi|f'=> \&configure_as_fcgi,1102'nproc|n=i'=>sub{1103my($arg,$val) =@_;1104return unlesseval{require FCGI::ProcManager;1; };1105my$proc_manager= FCGI::ProcManager->new({1106 n_processes =>$val,1107});1108our$pre_listen_hook=sub{$proc_manager->pm_manage() };1109our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1110our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1111},1112);1113}11141115sub run {1116 evaluate_argv();1117 evaluate_git_version();11181119$pre_listen_hook->()1120if$pre_listen_hook;11211122 REQUEST:1123while($cgi=$CGI->new()) {1124$pre_dispatch_hook->()1125if$pre_dispatch_hook;11261127 run_request();11281129$post_dispatch_hook->()1130if$post_dispatch_hook;11311132last REQUEST if($is_last_request->());1133}11341135 DONE_GITWEB:11361;1137}11381139run();11401141if(defined caller) {1142# wrapped in a subroutine processing requests,1143# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1144return;1145}else{1146# pure CGI script, serving single request1147exit;1148}11491150## ======================================================================1151## action links11521153# possible values of extra options1154# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1155# -replay => 1 - start from a current view (replay with modifications)1156# -path_info => 0|1 - don't use/use path_info URL (if possible)1157sub href {1158my%params=@_;1159# default is to use -absolute url() i.e. $my_uri1160my$href=$params{-full} ?$my_url:$my_uri;11611162$params{'project'} =$projectunlessexists$params{'project'};11631164if($params{-replay}) {1165while(my($name,$symbol) =each%cgi_param_mapping) {1166if(!exists$params{$name}) {1167$params{$name} =$input_params{$name};1168}1169}1170}11711172my$use_pathinfo= gitweb_check_feature('pathinfo');1173if(defined$params{'project'} &&1174(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1175# try to put as many parameters as possible in PATH_INFO:1176# - project name1177# - action1178# - hash_parent or hash_parent_base:/file_parent1179# - hash or hash_base:/filename1180# - the snapshot_format as an appropriate suffix11811182# When the script is the root DirectoryIndex for the domain,1183# $href here would be something like http://gitweb.example.com/1184# Thus, we strip any trailing / from $href, to spare us double1185# slashes in the final URL1186$href=~ s,/$,,;11871188# Then add the project name, if present1189$href.="/".esc_url($params{'project'});1190delete$params{'project'};11911192# since we destructively absorb parameters, we keep this1193# boolean that remembers if we're handling a snapshot1194my$is_snapshot=$params{'action'}eq'snapshot';11951196# Summary just uses the project path URL, any other action is1197# added to the URL1198if(defined$params{'action'}) {1199$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary';1200delete$params{'action'};1201}12021203# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1204# stripping nonexistent or useless pieces1205$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1206||$params{'hash_parent'} ||$params{'hash'});1207if(defined$params{'hash_base'}) {1208if(defined$params{'hash_parent_base'}) {1209$href.= esc_url($params{'hash_parent_base'});1210# skip the file_parent if it's the same as the file_name1211if(defined$params{'file_parent'}) {1212if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1213delete$params{'file_parent'};1214}elsif($params{'file_parent'} !~/\.\./) {1215$href.=":/".esc_url($params{'file_parent'});1216delete$params{'file_parent'};1217}1218}1219$href.="..";1220delete$params{'hash_parent'};1221delete$params{'hash_parent_base'};1222}elsif(defined$params{'hash_parent'}) {1223$href.= esc_url($params{'hash_parent'})."..";1224delete$params{'hash_parent'};1225}12261227$href.= esc_url($params{'hash_base'});1228if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1229$href.=":/".esc_url($params{'file_name'});1230delete$params{'file_name'};1231}1232delete$params{'hash'};1233delete$params{'hash_base'};1234}elsif(defined$params{'hash'}) {1235$href.= esc_url($params{'hash'});1236delete$params{'hash'};1237}12381239# If the action was a snapshot, we can absorb the1240# snapshot_format parameter too1241if($is_snapshot) {1242my$fmt=$params{'snapshot_format'};1243# snapshot_format should always be defined when href()1244# is called, but just in case some code forgets, we1245# fall back to the default1246$fmt||=$snapshot_fmts[0];1247$href.=$known_snapshot_formats{$fmt}{'suffix'};1248delete$params{'snapshot_format'};1249}1250}12511252# now encode the parameters explicitly1253my@result= ();1254for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1255my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1256if(defined$params{$name}) {1257if(ref($params{$name})eq"ARRAY") {1258foreachmy$par(@{$params{$name}}) {1259push@result,$symbol."=". esc_param($par);1260}1261}else{1262push@result,$symbol."=". esc_param($params{$name});1263}1264}1265}1266$href.="?".join(';',@result)ifscalar@result;12671268return$href;1269}127012711272## ======================================================================1273## validation, quoting/unquoting and escaping12741275sub validate_action {1276my$input=shift||returnundef;1277returnundefunlessexists$actions{$input};1278return$input;1279}12801281sub validate_project {1282my$input=shift||returnundef;1283if(!validate_pathname($input) ||1284!(-d "$projectroot/$input") ||1285!check_export_ok("$projectroot/$input") ||1286($strict_export&& !project_in_list($input))) {1287returnundef;1288}else{1289return$input;1290}1291}12921293sub validate_pathname {1294my$input=shift||returnundef;12951296# no '.' or '..' as elements of path, i.e. no '.' nor '..'1297# at the beginning, at the end, and between slashes.1298# also this catches doubled slashes1299if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1300returnundef;1301}1302# no null characters1303if($input=~m!\0!) {1304returnundef;1305}1306return$input;1307}13081309sub validate_refname {1310my$input=shift||returnundef;13111312# textual hashes are O.K.1313if($input=~m/^[0-9a-fA-F]{40}$/) {1314return$input;1315}1316# it must be correct pathname1317$input= validate_pathname($input)1318orreturnundef;1319# restrictions on ref name according to git-check-ref-format1320if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1321returnundef;1322}1323return$input;1324}13251326# decode sequences of octets in utf8 into Perl's internal form,1327# which is utf-8 with utf8 flag set if needed. gitweb writes out1328# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1329sub to_utf8 {1330my$str=shift;1331returnundefunlessdefined$str;1332if(utf8::valid($str)) {1333 utf8::decode($str);1334return$str;1335}else{1336return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1337}1338}13391340# quote unsafe chars, but keep the slash, even when it's not1341# correct, but quoted slashes look too horrible in bookmarks1342sub esc_param {1343my$str=shift;1344returnundefunlessdefined$str;1345$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1346$str=~s/ /\+/g;1347return$str;1348}13491350# quote unsafe chars in whole URL, so some characters cannot be quoted1351sub esc_url {1352my$str=shift;1353returnundefunlessdefined$str;1354$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1355$str=~s/ /\+/g;1356return$str;1357}13581359# quote unsafe characters in HTML attributes1360sub esc_attr {13611362# for XHTML conformance escaping '"' to '"' is not enough1363return esc_html(@_);1364}13651366# replace invalid utf8 character with SUBSTITUTION sequence1367sub esc_html {1368my$str=shift;1369my%opts=@_;13701371returnundefunlessdefined$str;13721373$str= to_utf8($str);1374$str=$cgi->escapeHTML($str);1375if($opts{'-nbsp'}) {1376$str=~s/ / /g;1377}1378$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1379return$str;1380}13811382# quote control characters and escape filename to HTML1383sub esc_path {1384my$str=shift;1385my%opts=@_;13861387returnundefunlessdefined$str;13881389$str= to_utf8($str);1390$str=$cgi->escapeHTML($str);1391if($opts{'-nbsp'}) {1392$str=~s/ / /g;1393}1394$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1395return$str;1396}13971398# Make control characters "printable", using character escape codes (CEC)1399sub quot_cec {1400my$cntrl=shift;1401my%opts=@_;1402my%es= (# character escape codes, aka escape sequences1403"\t"=>'\t',# tab (HT)1404"\n"=>'\n',# line feed (LF)1405"\r"=>'\r',# carrige return (CR)1406"\f"=>'\f',# form feed (FF)1407"\b"=>'\b',# backspace (BS)1408"\a"=>'\a',# alarm (bell) (BEL)1409"\e"=>'\e',# escape (ESC)1410"\013"=>'\v',# vertical tab (VT)1411"\000"=>'\0',# nul character (NUL)1412);1413my$chr= ( (exists$es{$cntrl})1414?$es{$cntrl}1415:sprintf('\%2x',ord($cntrl)) );1416if($opts{-nohtml}) {1417return$chr;1418}else{1419return"<span class=\"cntrl\">$chr</span>";1420}1421}14221423# Alternatively use unicode control pictures codepoints,1424# Unicode "printable representation" (PR)1425sub quot_upr {1426my$cntrl=shift;1427my%opts=@_;14281429my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1430if($opts{-nohtml}) {1431return$chr;1432}else{1433return"<span class=\"cntrl\">$chr</span>";1434}1435}14361437# git may return quoted and escaped filenames1438sub unquote {1439my$str=shift;14401441sub unq {1442my$seq=shift;1443my%es= (# character escape codes, aka escape sequences1444't'=>"\t",# tab (HT, TAB)1445'n'=>"\n",# newline (NL)1446'r'=>"\r",# return (CR)1447'f'=>"\f",# form feed (FF)1448'b'=>"\b",# backspace (BS)1449'a'=>"\a",# alarm (bell) (BEL)1450'e'=>"\e",# escape (ESC)1451'v'=>"\013",# vertical tab (VT)1452);14531454if($seq=~m/^[0-7]{1,3}$/) {1455# octal char sequence1456returnchr(oct($seq));1457}elsif(exists$es{$seq}) {1458# C escape sequence, aka character escape code1459return$es{$seq};1460}1461# quoted ordinary character1462return$seq;1463}14641465if($str=~m/^"(.*)"$/) {1466# needs unquoting1467$str=$1;1468$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1469}1470return$str;1471}14721473# escape tabs (convert tabs to spaces)1474sub untabify {1475my$line=shift;14761477while((my$pos=index($line,"\t")) != -1) {1478if(my$count= (8- ($pos%8))) {1479my$spaces=' ' x $count;1480$line=~s/\t/$spaces/;1481}1482}14831484return$line;1485}14861487sub project_in_list {1488my$project=shift;1489my@list= git_get_projects_list();1490return@list&&scalar(grep{$_->{'path'}eq$project}@list);1491}14921493## ----------------------------------------------------------------------1494## HTML aware string manipulation14951496# Try to chop given string on a word boundary between position1497# $len and $len+$add_len. If there is no word boundary there,1498# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1499# (marking chopped part) would be longer than given string.1500sub chop_str {1501my$str=shift;1502my$len=shift;1503my$add_len=shift||10;1504my$where=shift||'right';# 'left' | 'center' | 'right'15051506# Make sure perl knows it is utf8 encoded so we don't1507# cut in the middle of a utf8 multibyte char.1508$str= to_utf8($str);15091510# allow only $len chars, but don't cut a word if it would fit in $add_len1511# if it doesn't fit, cut it if it's still longer than the dots we would add1512# remove chopped character entities entirely15131514# when chopping in the middle, distribute $len into left and right part1515# return early if chopping wouldn't make string shorter1516if($whereeq'center') {1517return$strif($len+5>=length($str));# filler is length 51518$len=int($len/2);1519}else{1520return$strif($len+4>=length($str));# filler is length 41521}15221523# regexps: ending and beginning with word part up to $add_len1524my$endre=qr/.{$len}\w{0,$add_len}/;1525my$begre=qr/\w{0,$add_len}.{$len}/;15261527if($whereeq'left') {1528$str=~m/^(.*?)($begre)$/;1529my($lead,$body) = ($1,$2);1530if(length($lead) >4) {1531$lead=" ...";1532}1533return"$lead$body";15341535}elsif($whereeq'center') {1536$str=~m/^($endre)(.*)$/;1537my($left,$str) = ($1,$2);1538$str=~m/^(.*?)($begre)$/;1539my($mid,$right) = ($1,$2);1540if(length($mid) >5) {1541$mid=" ... ";1542}1543return"$left$mid$right";15441545}else{1546$str=~m/^($endre)(.*)$/;1547my$body=$1;1548my$tail=$2;1549if(length($tail) >4) {1550$tail="... ";1551}1552return"$body$tail";1553}1554}15551556# takes the same arguments as chop_str, but also wraps a <span> around the1557# result with a title attribute if it does get chopped. Additionally, the1558# string is HTML-escaped.1559sub chop_and_escape_str {1560my($str) =@_;15611562my$chopped= chop_str(@_);1563if($choppedeq$str) {1564return esc_html($chopped);1565}else{1566$str=~s/[[:cntrl:]]/?/g;1567return$cgi->span({-title=>$str}, esc_html($chopped));1568}1569}15701571## ----------------------------------------------------------------------1572## functions returning short strings15731574# CSS class for given age value (in seconds)1575sub age_class {1576my$age=shift;15771578if(!defined$age) {1579return"noage";1580}elsif($age<60*60*2) {1581return"age0";1582}elsif($age<60*60*24*2) {1583return"age1";1584}else{1585return"age2";1586}1587}15881589# convert age in seconds to "nn units ago" string1590sub age_string {1591my$age=shift;1592my$age_str;15931594if($age>60*60*24*365*2) {1595$age_str= (int$age/60/60/24/365);1596$age_str.=" years ago";1597}elsif($age>60*60*24*(365/12)*2) {1598$age_str=int$age/60/60/24/(365/12);1599$age_str.=" months ago";1600}elsif($age>60*60*24*7*2) {1601$age_str=int$age/60/60/24/7;1602$age_str.=" weeks ago";1603}elsif($age>60*60*24*2) {1604$age_str=int$age/60/60/24;1605$age_str.=" days ago";1606}elsif($age>60*60*2) {1607$age_str=int$age/60/60;1608$age_str.=" hours ago";1609}elsif($age>60*2) {1610$age_str=int$age/60;1611$age_str.=" min ago";1612}elsif($age>2) {1613$age_str=int$age;1614$age_str.=" sec ago";1615}else{1616$age_str.=" right now";1617}1618return$age_str;1619}16201621useconstant{1622 S_IFINVALID =>0030000,1623 S_IFGITLINK =>0160000,1624};16251626# submodule/subproject, a commit object reference1627sub S_ISGITLINK {1628my$mode=shift;16291630return(($mode& S_IFMT) == S_IFGITLINK)1631}16321633# convert file mode in octal to symbolic file mode string1634sub mode_str {1635my$mode=oct shift;16361637if(S_ISGITLINK($mode)) {1638return'm---------';1639}elsif(S_ISDIR($mode& S_IFMT)) {1640return'drwxr-xr-x';1641}elsif(S_ISLNK($mode)) {1642return'lrwxrwxrwx';1643}elsif(S_ISREG($mode)) {1644# git cares only about the executable bit1645if($mode& S_IXUSR) {1646return'-rwxr-xr-x';1647}else{1648return'-rw-r--r--';1649};1650}else{1651return'----------';1652}1653}16541655# convert file mode in octal to file type string1656sub file_type {1657my$mode=shift;16581659if($mode!~m/^[0-7]+$/) {1660return$mode;1661}else{1662$mode=oct$mode;1663}16641665if(S_ISGITLINK($mode)) {1666return"submodule";1667}elsif(S_ISDIR($mode& S_IFMT)) {1668return"directory";1669}elsif(S_ISLNK($mode)) {1670return"symlink";1671}elsif(S_ISREG($mode)) {1672return"file";1673}else{1674return"unknown";1675}1676}16771678# convert file mode in octal to file type description string1679sub file_type_long {1680my$mode=shift;16811682if($mode!~m/^[0-7]+$/) {1683return$mode;1684}else{1685$mode=oct$mode;1686}16871688if(S_ISGITLINK($mode)) {1689return"submodule";1690}elsif(S_ISDIR($mode& S_IFMT)) {1691return"directory";1692}elsif(S_ISLNK($mode)) {1693return"symlink";1694}elsif(S_ISREG($mode)) {1695if($mode& S_IXUSR) {1696return"executable";1697}else{1698return"file";1699};1700}else{1701return"unknown";1702}1703}170417051706## ----------------------------------------------------------------------1707## functions returning short HTML fragments, or transforming HTML fragments1708## which don't belong to other sections17091710# format line of commit message.1711sub format_log_line_html {1712my$line=shift;17131714$line= esc_html($line, -nbsp=>1);1715$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1716$cgi->a({-href => href(action=>"object", hash=>$1),1717-class=>"text"},$1);1718}eg;17191720return$line;1721}17221723# format marker of refs pointing to given object17241725# the destination action is chosen based on object type and current context:1726# - for annotated tags, we choose the tag view unless it's the current view1727# already, in which case we go to shortlog view1728# - for other refs, we keep the current view if we're in history, shortlog or1729# log view, and select shortlog otherwise1730sub format_ref_marker {1731my($refs,$id) =@_;1732my$markers='';17331734if(defined$refs->{$id}) {1735foreachmy$ref(@{$refs->{$id}}) {1736# this code exploits the fact that non-lightweight tags are the1737# only indirect objects, and that they are the only objects for which1738# we want to use tag instead of shortlog as action1739my($type,$name) =qw();1740my$indirect= ($ref=~s/\^\{\}$//);1741# e.g. tags/v2.6.11 or heads/next1742if($ref=~m!^(.*?)s?/(.*)$!) {1743$type=$1;1744$name=$2;1745}else{1746$type="ref";1747$name=$ref;1748}17491750my$class=$type;1751$class.=" indirect"if$indirect;17521753my$dest_action="shortlog";17541755if($indirect) {1756$dest_action="tag"unless$actioneq"tag";1757}elsif($action=~/^(history|(short)?log)$/) {1758$dest_action=$action;1759}17601761my$dest="";1762$dest.="refs/"unless$ref=~ m!^refs/!;1763$dest.=$ref;17641765my$link=$cgi->a({1766-href => href(1767 action=>$dest_action,1768 hash=>$dest1769)},$name);17701771$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".1772$link."</span>";1773}1774}17751776if($markers) {1777return' <span class="refs">'.$markers.'</span>';1778}else{1779return"";1780}1781}17821783# format, perhaps shortened and with markers, title line1784sub format_subject_html {1785my($long,$short,$href,$extra) =@_;1786$extra=''unlessdefined($extra);17871788if(length($short) <length($long)) {1789$long=~s/[[:cntrl:]]/?/g;1790return$cgi->a({-href =>$href, -class=>"list subject",1791-title => to_utf8($long)},1792 esc_html($short)) .$extra;1793}else{1794return$cgi->a({-href =>$href, -class=>"list subject"},1795 esc_html($long)) .$extra;1796}1797}17981799# Rather than recomputing the url for an email multiple times, we cache it1800# after the first hit. This gives a visible benefit in views where the avatar1801# for the same email is used repeatedly (e.g. shortlog).1802# The cache is shared by all avatar engines (currently gravatar only), which1803# are free to use it as preferred. Since only one avatar engine is used for any1804# given page, there's no risk for cache conflicts.1805our%avatar_cache= ();18061807# Compute the picon url for a given email, by using the picon search service over at1808# http://www.cs.indiana.edu/picons/search.html1809sub picon_url {1810my$email=lc shift;1811if(!$avatar_cache{$email}) {1812my($user,$domain) =split('@',$email);1813$avatar_cache{$email} =1814"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1815"$domain/$user/".1816"users+domains+unknown/up/single";1817}1818return$avatar_cache{$email};1819}18201821# Compute the gravatar url for a given email, if it's not in the cache already.1822# Gravatar stores only the part of the URL before the size, since that's the1823# one computationally more expensive. This also allows reuse of the cache for1824# different sizes (for this particular engine).1825sub gravatar_url {1826my$email=lc shift;1827my$size=shift;1828$avatar_cache{$email} ||=1829"http://www.gravatar.com/avatar/".1830 Digest::MD5::md5_hex($email) ."?s=";1831return$avatar_cache{$email} .$size;1832}18331834# Insert an avatar for the given $email at the given $size if the feature1835# is enabled.1836sub git_get_avatar {1837my($email,%opts) =@_;1838my$pre_white= ($opts{-pad_before} ?" ":"");1839my$post_white= ($opts{-pad_after} ?" ":"");1840$opts{-size} ||='default';1841my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1842my$url="";1843if($git_avatareq'gravatar') {1844$url= gravatar_url($email,$size);1845}elsif($git_avatareq'picon') {1846$url= picon_url($email);1847}1848# Other providers can be added by extending the if chain, defining $url1849# as needed. If no variant puts something in $url, we assume avatars1850# are completely disabled/unavailable.1851if($url) {1852return$pre_white.1853"<img width=\"$size\"".1854"class=\"avatar\"".1855"src=\"".esc_url($url)."\"".1856"alt=\"\"".1857"/>".$post_white;1858}else{1859return"";1860}1861}18621863sub format_search_author {1864my($author,$searchtype,$displaytext) =@_;1865my$have_search= gitweb_check_feature('search');18661867if($have_search) {1868my$performed="";1869if($searchtypeeq'author') {1870$performed="authored";1871}elsif($searchtypeeq'committer') {1872$performed="committed";1873}18741875return$cgi->a({-href => href(action=>"search", hash=>$hash,1876 searchtext=>$author,1877 searchtype=>$searchtype),class=>"list",1878 title=>"Search for commits$performedby$author"},1879$displaytext);18801881}else{1882return$displaytext;1883}1884}18851886# format the author name of the given commit with the given tag1887# the author name is chopped and escaped according to the other1888# optional parameters (see chop_str).1889sub format_author_html {1890my$tag=shift;1891my$co=shift;1892my$author= chop_and_escape_str($co->{'author_name'},@_);1893return"<$tagclass=\"author\">".1894 format_search_author($co->{'author_name'},"author",1895 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1896$author) .1897"</$tag>";1898}18991900# format git diff header line, i.e. "diff --(git|combined|cc) ..."1901sub format_git_diff_header_line {1902my$line=shift;1903my$diffinfo=shift;1904my($from,$to) =@_;19051906if($diffinfo->{'nparents'}) {1907# combined diff1908$line=~s!^(diff (.*?) )"?.*$!$1!;1909if($to->{'href'}) {1910$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1911 esc_path($to->{'file'}));1912}else{# file was deleted (no href)1913$line.= esc_path($to->{'file'});1914}1915}else{1916# "ordinary" diff1917$line=~s!^(diff (.*?) )"?a/.*$!$1!;1918if($from->{'href'}) {1919$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1920'a/'. esc_path($from->{'file'}));1921}else{# file was added (no href)1922$line.='a/'. esc_path($from->{'file'});1923}1924$line.=' ';1925if($to->{'href'}) {1926$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1927'b/'. esc_path($to->{'file'}));1928}else{# file was deleted1929$line.='b/'. esc_path($to->{'file'});1930}1931}19321933return"<div class=\"diff header\">$line</div>\n";1934}19351936# format extended diff header line, before patch itself1937sub format_extended_diff_header_line {1938my$line=shift;1939my$diffinfo=shift;1940my($from,$to) =@_;19411942# match <path>1943if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1944$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1945 esc_path($from->{'file'}));1946}1947if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1948$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1949 esc_path($to->{'file'}));1950}1951# match single <mode>1952if($line=~m/\s(\d{6})$/) {1953$line.='<span class="info"> ('.1954 file_type_long($1) .1955')</span>';1956}1957# match <hash>1958if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1959# can match only for combined diff1960$line='index ';1961for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1962if($from->{'href'}[$i]) {1963$line.=$cgi->a({-href=>$from->{'href'}[$i],1964-class=>"hash"},1965substr($diffinfo->{'from_id'}[$i],0,7));1966}else{1967$line.='0' x 7;1968}1969# separator1970$line.=','if($i<$diffinfo->{'nparents'} -1);1971}1972$line.='..';1973if($to->{'href'}) {1974$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1975substr($diffinfo->{'to_id'},0,7));1976}else{1977$line.='0' x 7;1978}19791980}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {1981# can match only for ordinary diff1982my($from_link,$to_link);1983if($from->{'href'}) {1984$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},1985substr($diffinfo->{'from_id'},0,7));1986}else{1987$from_link='0' x 7;1988}1989if($to->{'href'}) {1990$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1991substr($diffinfo->{'to_id'},0,7));1992}else{1993$to_link='0' x 7;1994}1995my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});1996$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;1997}19981999return$line."<br/>\n";2000}20012002# format from-file/to-file diff header2003sub format_diff_from_to_header {2004my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2005my$line;2006my$result='';20072008$line=$from_line;2009#assert($line =~ m/^---/) if DEBUG;2010# no extra formatting for "^--- /dev/null"2011if(!$diffinfo->{'nparents'}) {2012# ordinary (single parent) diff2013if($line=~m!^--- "?a/!) {2014if($from->{'href'}) {2015$line='--- a/'.2016$cgi->a({-href=>$from->{'href'}, -class=>"path"},2017 esc_path($from->{'file'}));2018}else{2019$line='--- a/'.2020 esc_path($from->{'file'});2021}2022}2023$result.= qq!<div class="diff from_file">$line</div>\n!;20242025}else{2026# combined diff (merge commit)2027for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2028if($from->{'href'}[$i]) {2029$line='--- '.2030$cgi->a({-href=>href(action=>"blobdiff",2031 hash_parent=>$diffinfo->{'from_id'}[$i],2032 hash_parent_base=>$parents[$i],2033 file_parent=>$from->{'file'}[$i],2034 hash=>$diffinfo->{'to_id'},2035 hash_base=>$hash,2036 file_name=>$to->{'file'}),2037-class=>"path",2038-title=>"diff". ($i+1)},2039$i+1) .2040'/'.2041$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2042 esc_path($from->{'file'}[$i]));2043}else{2044$line='--- /dev/null';2045}2046$result.= qq!<div class="diff from_file">$line</div>\n!;2047}2048}20492050$line=$to_line;2051#assert($line =~ m/^\+\+\+/) if DEBUG;2052# no extra formatting for "^+++ /dev/null"2053if($line=~m!^\+\+\+ "?b/!) {2054if($to->{'href'}) {2055$line='+++ b/'.2056$cgi->a({-href=>$to->{'href'}, -class=>"path"},2057 esc_path($to->{'file'}));2058}else{2059$line='+++ b/'.2060 esc_path($to->{'file'});2061}2062}2063$result.= qq!<div class="diff to_file">$line</div>\n!;20642065return$result;2066}20672068# create note for patch simplified by combined diff2069sub format_diff_cc_simplified {2070my($diffinfo,@parents) =@_;2071my$result='';20722073$result.="<div class=\"diff header\">".2074"diff --cc ";2075if(!is_deleted($diffinfo)) {2076$result.=$cgi->a({-href => href(action=>"blob",2077 hash_base=>$hash,2078 hash=>$diffinfo->{'to_id'},2079 file_name=>$diffinfo->{'to_file'}),2080-class=>"path"},2081 esc_path($diffinfo->{'to_file'}));2082}else{2083$result.= esc_path($diffinfo->{'to_file'});2084}2085$result.="</div>\n".# class="diff header"2086"<div class=\"diff nodifferences\">".2087"Simple merge".2088"</div>\n";# class="diff nodifferences"20892090return$result;2091}20922093# format patch (diff) line (not to be used for diff headers)2094sub format_diff_line {2095my$line=shift;2096my($from,$to) =@_;2097my$diff_class="";20982099chomp$line;21002101if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2102# combined diff2103my$prefix=substr($line,0,scalar@{$from->{'href'}});2104if($line=~m/^\@{3}/) {2105$diff_class=" chunk_header";2106}elsif($line=~m/^\\/) {2107$diff_class=" incomplete";2108}elsif($prefix=~tr/+/+/) {2109$diff_class=" add";2110}elsif($prefix=~tr/-/-/) {2111$diff_class=" rem";2112}2113}else{2114# assume ordinary diff2115my$char=substr($line,0,1);2116if($chareq'+') {2117$diff_class=" add";2118}elsif($chareq'-') {2119$diff_class=" rem";2120}elsif($chareq'@') {2121$diff_class=" chunk_header";2122}elsif($chareq"\\") {2123$diff_class=" incomplete";2124}2125}2126$line= untabify($line);2127if($from&&$to&&$line=~m/^\@{2} /) {2128my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2129$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;21302131$from_lines=0unlessdefined$from_lines;2132$to_lines=0unlessdefined$to_lines;21332134if($from->{'href'}) {2135$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2136-class=>"list"},$from_text);2137}2138if($to->{'href'}) {2139$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2140-class=>"list"},$to_text);2141}2142$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2143"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2144return"<div class=\"diff$diff_class\">$line</div>\n";2145}elsif($from&&$to&&$line=~m/^\@{3}/) {2146my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2147my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);21482149@from_text=split(' ',$ranges);2150for(my$i=0;$i<@from_text; ++$i) {2151($from_start[$i],$from_nlines[$i]) =2152(split(',',substr($from_text[$i],1)),0);2153}21542155$to_text=pop@from_text;2156$to_start=pop@from_start;2157$to_nlines=pop@from_nlines;21582159$line="<span class=\"chunk_info\">$prefix";2160for(my$i=0;$i<@from_text; ++$i) {2161if($from->{'href'}[$i]) {2162$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2163-class=>"list"},$from_text[$i]);2164}else{2165$line.=$from_text[$i];2166}2167$line.=" ";2168}2169if($to->{'href'}) {2170$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2171-class=>"list"},$to_text);2172}else{2173$line.=$to_text;2174}2175$line.="$prefix</span>".2176"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2177return"<div class=\"diff$diff_class\">$line</div>\n";2178}2179return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";2180}21812182# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2183# linked. Pass the hash of the tree/commit to snapshot.2184sub format_snapshot_links {2185my($hash) =@_;2186my$num_fmts=@snapshot_fmts;2187if($num_fmts>1) {2188# A parenthesized list of links bearing format names.2189# e.g. "snapshot (_tar.gz_ _zip_)"2190return"snapshot (".join(' ',map2191$cgi->a({2192-href => href(2193 action=>"snapshot",2194 hash=>$hash,2195 snapshot_format=>$_2196)2197},$known_snapshot_formats{$_}{'display'})2198,@snapshot_fmts) .")";2199}elsif($num_fmts==1) {2200# A single "snapshot" link whose tooltip bears the format name.2201# i.e. "_snapshot_"2202my($fmt) =@snapshot_fmts;2203return2204$cgi->a({2205-href => href(2206 action=>"snapshot",2207 hash=>$hash,2208 snapshot_format=>$fmt2209),2210-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2211},"snapshot");2212}else{# $num_fmts == 02213returnundef;2214}2215}22162217## ......................................................................2218## functions returning values to be passed, perhaps after some2219## transformation, to other functions; e.g. returning arguments to href()22202221# returns hash to be passed to href to generate gitweb URL2222# in -title key it returns description of link2223sub get_feed_info {2224my$format=shift||'Atom';2225my%res= (action =>lc($format));22262227# feed links are possible only for project views2228return unless(defined$project);2229# some views should link to OPML, or to generic project feed,2230# or don't have specific feed yet (so they should use generic)2231return if($action=~/^(?:tags|heads|forks|tag|search)$/x);22322233my$branch;2234# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2235# from tag links; this also makes possible to detect branch links2236if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2237(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2238$branch=$1;2239}2240# find log type for feed description (title)2241my$type='log';2242if(defined$file_name) {2243$type="history of$file_name";2244$type.="/"if($actioneq'tree');2245$type.=" on '$branch'"if(defined$branch);2246}else{2247$type="log of$branch"if(defined$branch);2248}22492250$res{-title} =$type;2251$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2252$res{'file_name'} =$file_name;22532254return%res;2255}22562257## ----------------------------------------------------------------------2258## git utility subroutines, invoking git commands22592260# returns path to the core git executable and the --git-dir parameter as list2261sub git_cmd {2262$number_of_git_cmds++;2263return$GIT,'--git-dir='.$git_dir;2264}22652266# quote the given arguments for passing them to the shell2267# quote_command("command", "arg 1", "arg with ' and ! characters")2268# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2269# Try to avoid using this function wherever possible.2270sub quote_command {2271returnjoin(' ',2272map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2273}22742275# get HEAD ref of given project as hash2276sub git_get_head_hash {2277return git_get_full_hash(shift,'HEAD');2278}22792280sub git_get_full_hash {2281return git_get_hash(@_);2282}22832284sub git_get_short_hash {2285return git_get_hash(@_,'--short=7');2286}22872288sub git_get_hash {2289my($project,$hash,@options) =@_;2290my$o_git_dir=$git_dir;2291my$retval=undef;2292$git_dir="$projectroot/$project";2293if(open my$fd,'-|', git_cmd(),'rev-parse',2294'--verify','-q',@options,$hash) {2295$retval= <$fd>;2296chomp$retvalifdefined$retval;2297close$fd;2298}2299if(defined$o_git_dir) {2300$git_dir=$o_git_dir;2301}2302return$retval;2303}23042305# get type of given object2306sub git_get_type {2307my$hash=shift;23082309open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2310my$type= <$fd>;2311close$fdorreturn;2312chomp$type;2313return$type;2314}23152316# repository configuration2317our$config_file='';2318our%config;23192320# store multiple values for single key as anonymous array reference2321# single values stored directly in the hash, not as [ <value> ]2322sub hash_set_multi {2323my($hash,$key,$value) =@_;23242325if(!exists$hash->{$key}) {2326$hash->{$key} =$value;2327}elsif(!ref$hash->{$key}) {2328$hash->{$key} = [$hash->{$key},$value];2329}else{2330push@{$hash->{$key}},$value;2331}2332}23332334# return hash of git project configuration2335# optionally limited to some section, e.g. 'gitweb'2336sub git_parse_project_config {2337my$section_regexp=shift;2338my%config;23392340local$/="\0";23412342open my$fh,"-|", git_cmd(),"config",'-z','-l',2343orreturn;23442345while(my$keyval= <$fh>) {2346chomp$keyval;2347my($key,$value) =split(/\n/,$keyval,2);23482349 hash_set_multi(\%config,$key,$value)2350if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2351}2352close$fh;23532354return%config;2355}23562357# convert config value to boolean: 'true' or 'false'2358# no value, number > 0, 'true' and 'yes' values are true2359# rest of values are treated as false (never as error)2360sub config_to_bool {2361my$val=shift;23622363return1if!defined$val;# section.key23642365# strip leading and trailing whitespace2366$val=~s/^\s+//;2367$val=~s/\s+$//;23682369return(($val=~/^\d+$/&&$val) ||# section.key = 12370($val=~/^(?:true|yes)$/i));# section.key = true2371}23722373# convert config value to simple decimal number2374# an optional value suffix of 'k', 'm', or 'g' will cause the value2375# to be multiplied by 1024, 1048576, or 10737418242376sub config_to_int {2377my$val=shift;23782379# strip leading and trailing whitespace2380$val=~s/^\s+//;2381$val=~s/\s+$//;23822383if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2384$unit=lc($unit);2385# unknown unit is treated as 12386return$num* ($uniteq'g'?1073741824:2387$uniteq'm'?1048576:2388$uniteq'k'?1024:1);2389}2390return$val;2391}23922393# convert config value to array reference, if needed2394sub config_to_multi {2395my$val=shift;23962397returnref($val) ?$val: (defined($val) ? [$val] : []);2398}23992400sub git_get_project_config {2401my($key,$type) =@_;24022403return unlessdefined$git_dir;24042405# key sanity check2406return unless($key);2407$key=~s/^gitweb\.//;2408return if($key=~m/\W/);24092410# type sanity check2411if(defined$type) {2412$type=~s/^--//;2413$type=undef2414unless($typeeq'bool'||$typeeq'int');2415}24162417# get config2418if(!defined$config_file||2419$config_filene"$git_dir/config") {2420%config= git_parse_project_config('gitweb');2421$config_file="$git_dir/config";2422}24232424# check if config variable (key) exists2425return unlessexists$config{"gitweb.$key"};24262427# ensure given type2428if(!defined$type) {2429return$config{"gitweb.$key"};2430}elsif($typeeq'bool') {2431# backward compatibility: 'git config --bool' returns true/false2432return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2433}elsif($typeeq'int') {2434return config_to_int($config{"gitweb.$key"});2435}2436return$config{"gitweb.$key"};2437}24382439# get hash of given path at given ref2440sub git_get_hash_by_path {2441my$base=shift;2442my$path=shift||returnundef;2443my$type=shift;24442445$path=~ s,/+$,,;24462447open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2448or die_error(500,"Open git-ls-tree failed");2449my$line= <$fd>;2450close$fdorreturnundef;24512452if(!defined$line) {2453# there is no tree or hash given by $path at $base2454returnundef;2455}24562457#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2458$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2459if(defined$type&&$typene$2) {2460# type doesn't match2461returnundef;2462}2463return$3;2464}24652466# get path of entry with given hash at given tree-ish (ref)2467# used to get 'from' filename for combined diff (merge commit) for renames2468sub git_get_path_by_hash {2469my$base=shift||return;2470my$hash=shift||return;24712472local$/="\0";24732474open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2475orreturnundef;2476while(my$line= <$fd>) {2477chomp$line;24782479#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2480#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2481if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2482close$fd;2483return$1;2484}2485}2486close$fd;2487returnundef;2488}24892490## ......................................................................2491## git utility functions, directly accessing git repository24922493sub git_get_project_description {2494my$path=shift;24952496$git_dir="$projectroot/$path";2497open my$fd,'<',"$git_dir/description"2498orreturn git_get_project_config('description');2499my$descr= <$fd>;2500close$fd;2501if(defined$descr) {2502chomp$descr;2503}2504return$descr;2505}25062507sub git_get_project_ctags {2508my$path=shift;2509my$ctags= {};25102511$git_dir="$projectroot/$path";2512opendir my$dh,"$git_dir/ctags"2513orreturn$ctags;2514foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2515open my$ct,'<',$_ornext;2516my$val= <$ct>;2517chomp$val;2518close$ct;2519my$ctag=$_;$ctag=~ s#.*/##;2520$ctags->{$ctag} =$val;2521}2522closedir$dh;2523$ctags;2524}25252526sub git_populate_project_tagcloud {2527my$ctags=shift;25282529# First, merge different-cased tags; tags vote on casing2530my%ctags_lc;2531foreach(keys%$ctags) {2532$ctags_lc{lc$_}->{count} +=$ctags->{$_};2533if(not$ctags_lc{lc$_}->{topcount}2534or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2535$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2536$ctags_lc{lc$_}->{topname} =$_;2537}2538}25392540my$cloud;2541if(eval{require HTML::TagCloud;1; }) {2542$cloud= HTML::TagCloud->new;2543foreach(sort keys%ctags_lc) {2544# Pad the title with spaces so that the cloud looks2545# less crammed.2546my$title=$ctags_lc{$_}->{topname};2547$title=~s/ / /g;2548$title=~s/^/ /g;2549$title=~s/$/ /g;2550$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2551}2552}else{2553$cloud= \%ctags_lc;2554}2555$cloud;2556}25572558sub git_show_project_tagcloud {2559my($cloud,$count) =@_;2560print STDERR ref($cloud)."..\n";2561if(ref$cloudeq'HTML::TagCloud') {2562return$cloud->html_and_css($count);2563}else{2564my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2565return'<p align="center">'.join(', ',map{2566$cgi->a({-href=>"$home_link?by_tag=$_"},$cloud->{$_}->{topname})2567}splice(@tags,0,$count)) .'</p>';2568}2569}25702571sub git_get_project_url_list {2572my$path=shift;25732574$git_dir="$projectroot/$path";2575open my$fd,'<',"$git_dir/cloneurl"2576orreturnwantarray?2577@{ config_to_multi(git_get_project_config('url')) } :2578 config_to_multi(git_get_project_config('url'));2579my@git_project_url_list=map{chomp;$_} <$fd>;2580close$fd;25812582returnwantarray?@git_project_url_list: \@git_project_url_list;2583}25842585sub git_get_projects_list {2586my($filter) =@_;2587my@list;25882589$filter||='';2590$filter=~s/\.git$//;25912592my$check_forks= gitweb_check_feature('forks');25932594if(-d $projects_list) {2595# search in directory2596my$dir=$projects_list. ($filter?"/$filter":'');2597# remove the trailing "/"2598$dir=~s!/+$!!;2599my$pfxlen=length("$dir");2600my$pfxdepth= ($dir=~tr!/!!);26012602 File::Find::find({2603 follow_fast =>1,# follow symbolic links2604 follow_skip =>2,# ignore duplicates2605 dangling_symlinks =>0,# ignore dangling symlinks, silently2606 wanted =>sub{2607# global variables2608our$project_maxdepth;2609our$projectroot;2610# skip project-list toplevel, if we get it.2611return if(m!^[/.]$!);2612# only directories can be git repositories2613return unless(-d $_);2614# don't traverse too deep (Find is super slow on os x)2615if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2616$File::Find::prune =1;2617return;2618}26192620my$subdir=substr($File::Find::name,$pfxlen+1);2621# we check related file in $projectroot2622my$path= ($filter?"$filter/":'') .$subdir;2623if(check_export_ok("$projectroot/$path")) {2624push@list, { path =>$path};2625$File::Find::prune =1;2626}2627},2628},"$dir");26292630}elsif(-f $projects_list) {2631# read from file(url-encoded):2632# 'git%2Fgit.git Linus+Torvalds'2633# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2634# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2635my%paths;2636open my$fd,'<',$projects_listorreturn;2637 PROJECT:2638while(my$line= <$fd>) {2639chomp$line;2640my($path,$owner) =split' ',$line;2641$path= unescape($path);2642$owner= unescape($owner);2643if(!defined$path) {2644next;2645}2646if($filterne'') {2647# looking for forks;2648my$pfx=substr($path,0,length($filter));2649if($pfxne$filter) {2650next PROJECT;2651}2652my$sfx=substr($path,length($filter));2653if($sfx!~/^\/.*\.git$/) {2654next PROJECT;2655}2656}elsif($check_forks) {2657 PATH:2658foreachmy$filter(keys%paths) {2659# looking for forks;2660my$pfx=substr($path,0,length($filter));2661if($pfxne$filter) {2662next PATH;2663}2664my$sfx=substr($path,length($filter));2665if($sfx!~/^\/.*\.git$/) {2666next PATH;2667}2668# is a fork, don't include it in2669# the list2670next PROJECT;2671}2672}2673if(check_export_ok("$projectroot/$path")) {2674my$pr= {2675 path =>$path,2676 owner => to_utf8($owner),2677};2678push@list,$pr;2679(my$forks_path=$path) =~s/\.git$//;2680$paths{$forks_path}++;2681}2682}2683close$fd;2684}2685return@list;2686}26872688our$gitweb_project_owner=undef;2689sub git_get_project_list_from_file {26902691return if(defined$gitweb_project_owner);26922693$gitweb_project_owner= {};2694# read from file (url-encoded):2695# 'git%2Fgit.git Linus+Torvalds'2696# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2697# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2698if(-f $projects_list) {2699open(my$fd,'<',$projects_list);2700while(my$line= <$fd>) {2701chomp$line;2702my($pr,$ow) =split' ',$line;2703$pr= unescape($pr);2704$ow= unescape($ow);2705$gitweb_project_owner->{$pr} = to_utf8($ow);2706}2707close$fd;2708}2709}27102711sub git_get_project_owner {2712my$project=shift;2713my$owner;27142715returnundefunless$project;2716$git_dir="$projectroot/$project";27172718if(!defined$gitweb_project_owner) {2719 git_get_project_list_from_file();2720}27212722if(exists$gitweb_project_owner->{$project}) {2723$owner=$gitweb_project_owner->{$project};2724}2725if(!defined$owner){2726$owner= git_get_project_config('owner');2727}2728if(!defined$owner) {2729$owner= get_file_owner("$git_dir");2730}27312732return$owner;2733}27342735sub git_get_last_activity {2736my($path) =@_;2737my$fd;27382739$git_dir="$projectroot/$path";2740open($fd,"-|", git_cmd(),'for-each-ref',2741'--format=%(committer)',2742'--sort=-committerdate',2743'--count=1',2744'refs/heads')orreturn;2745my$most_recent= <$fd>;2746close$fdorreturn;2747if(defined$most_recent&&2748$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2749my$timestamp=$1;2750my$age=time-$timestamp;2751return($age, age_string($age));2752}2753return(undef,undef);2754}27552756sub git_get_references {2757my$type=shift||"";2758my%refs;2759# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112760# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2761open my$fd,"-|", git_cmd(),"show-ref","--dereference",2762($type? ("--","refs/$type") : ())# use -- <pattern> if $type2763orreturn;27642765while(my$line= <$fd>) {2766chomp$line;2767if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2768if(defined$refs{$1}) {2769push@{$refs{$1}},$2;2770}else{2771$refs{$1} = [$2];2772}2773}2774}2775close$fdorreturn;2776return \%refs;2777}27782779sub git_get_rev_name_tags {2780my$hash=shift||returnundef;27812782open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2783orreturn;2784my$name_rev= <$fd>;2785close$fd;27862787if($name_rev=~ m|^$hash tags/(.*)$|) {2788return$1;2789}else{2790# catches also '$hash undefined' output2791returnundef;2792}2793}27942795## ----------------------------------------------------------------------2796## parse to hash functions27972798sub parse_date {2799my$epoch=shift;2800my$tz=shift||"-0000";28012802my%date;2803my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2804my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2805my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2806$date{'hour'} =$hour;2807$date{'minute'} =$min;2808$date{'mday'} =$mday;2809$date{'day'} =$days[$wday];2810$date{'month'} =$months[$mon];2811$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2812$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2813$date{'mday-time'} =sprintf"%d%s%02d:%02d",2814$mday,$months[$mon],$hour,$min;2815$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",28161900+$year,1+$mon,$mday,$hour,$min,$sec;28172818$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2819my$local=$epoch+ ((int$1+ ($2/60)) *3600);2820($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2821$date{'hour_local'} =$hour;2822$date{'minute_local'} =$min;2823$date{'tz_local'} =$tz;2824$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",28251900+$year,$mon+1,$mday,2826$hour,$min,$sec,$tz);2827return%date;2828}28292830sub parse_tag {2831my$tag_id=shift;2832my%tag;2833my@comment;28342835open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2836$tag{'id'} =$tag_id;2837while(my$line= <$fd>) {2838chomp$line;2839if($line=~m/^object ([0-9a-fA-F]{40})$/) {2840$tag{'object'} =$1;2841}elsif($line=~m/^type (.+)$/) {2842$tag{'type'} =$1;2843}elsif($line=~m/^tag (.+)$/) {2844$tag{'name'} =$1;2845}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2846$tag{'author'} =$1;2847$tag{'author_epoch'} =$2;2848$tag{'author_tz'} =$3;2849if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2850$tag{'author_name'} =$1;2851$tag{'author_email'} =$2;2852}else{2853$tag{'author_name'} =$tag{'author'};2854}2855}elsif($line=~m/--BEGIN/) {2856push@comment,$line;2857last;2858}elsif($lineeq"") {2859last;2860}2861}2862push@comment, <$fd>;2863$tag{'comment'} = \@comment;2864close$fdorreturn;2865if(!defined$tag{'name'}) {2866return2867};2868return%tag2869}28702871sub parse_commit_text {2872my($commit_text,$withparents) =@_;2873my@commit_lines=split'\n',$commit_text;2874my%co;28752876pop@commit_lines;# Remove '\0'28772878if(!@commit_lines) {2879return;2880}28812882my$header=shift@commit_lines;2883if($header!~m/^[0-9a-fA-F]{40}/) {2884return;2885}2886($co{'id'},my@parents) =split' ',$header;2887while(my$line=shift@commit_lines) {2888last if$lineeq"\n";2889if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2890$co{'tree'} =$1;2891}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2892push@parents,$1;2893}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2894$co{'author'} = to_utf8($1);2895$co{'author_epoch'} =$2;2896$co{'author_tz'} =$3;2897if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2898$co{'author_name'} =$1;2899$co{'author_email'} =$2;2900}else{2901$co{'author_name'} =$co{'author'};2902}2903}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2904$co{'committer'} = to_utf8($1);2905$co{'committer_epoch'} =$2;2906$co{'committer_tz'} =$3;2907if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2908$co{'committer_name'} =$1;2909$co{'committer_email'} =$2;2910}else{2911$co{'committer_name'} =$co{'committer'};2912}2913}2914}2915if(!defined$co{'tree'}) {2916return;2917};2918$co{'parents'} = \@parents;2919$co{'parent'} =$parents[0];29202921foreachmy$title(@commit_lines) {2922$title=~s/^ //;2923if($titlene"") {2924$co{'title'} = chop_str($title,80,5);2925# remove leading stuff of merges to make the interesting part visible2926if(length($title) >50) {2927$title=~s/^Automatic //;2928$title=~s/^merge (of|with) /Merge ... /i;2929if(length($title) >50) {2930$title=~s/(http|rsync):\/\///;2931}2932if(length($title) >50) {2933$title=~s/(master|www|rsync)\.//;2934}2935if(length($title) >50) {2936$title=~s/kernel.org:?//;2937}2938if(length($title) >50) {2939$title=~s/\/pub\/scm//;2940}2941}2942$co{'title_short'} = chop_str($title,50,5);2943last;2944}2945}2946if(!defined$co{'title'} ||$co{'title'}eq"") {2947$co{'title'} =$co{'title_short'} ='(no commit message)';2948}2949# remove added spaces2950foreachmy$line(@commit_lines) {2951$line=~s/^ //;2952}2953$co{'comment'} = \@commit_lines;29542955my$age=time-$co{'committer_epoch'};2956$co{'age'} =$age;2957$co{'age_string'} = age_string($age);2958my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2959if($age>60*60*24*7*2) {2960$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2961$co{'age_string_age'} =$co{'age_string'};2962}else{2963$co{'age_string_date'} =$co{'age_string'};2964$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2965}2966return%co;2967}29682969sub parse_commit {2970my($commit_id) =@_;2971my%co;29722973local$/="\0";29742975open my$fd,"-|", git_cmd(),"rev-list",2976"--parents",2977"--header",2978"--max-count=1",2979$commit_id,2980"--",2981or die_error(500,"Open git-rev-list failed");2982%co= parse_commit_text(<$fd>,1);2983close$fd;29842985return%co;2986}29872988sub parse_commits {2989my($commit_id,$maxcount,$skip,$filename,@args) =@_;2990my@cos;29912992$maxcount||=1;2993$skip||=0;29942995local$/="\0";29962997open my$fd,"-|", git_cmd(),"rev-list",2998"--header",2999@args,3000("--max-count=".$maxcount),3001("--skip=".$skip),3002@extra_options,3003$commit_id,3004"--",3005($filename? ($filename) : ())3006or die_error(500,"Open git-rev-list failed");3007while(my$line= <$fd>) {3008my%co= parse_commit_text($line);3009push@cos, \%co;3010}3011close$fd;30123013returnwantarray?@cos: \@cos;3014}30153016# parse line of git-diff-tree "raw" output3017sub parse_difftree_raw_line {3018my$line=shift;3019my%res;30203021# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3022# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3023if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3024$res{'from_mode'} =$1;3025$res{'to_mode'} =$2;3026$res{'from_id'} =$3;3027$res{'to_id'} =$4;3028$res{'status'} =$5;3029$res{'similarity'} =$6;3030if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3031($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3032}else{3033$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3034}3035}3036# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3037# combined diff (for merge commit)3038elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3039$res{'nparents'} =length($1);3040$res{'from_mode'} = [split(' ',$2) ];3041$res{'to_mode'} =pop@{$res{'from_mode'}};3042$res{'from_id'} = [split(' ',$3) ];3043$res{'to_id'} =pop@{$res{'from_id'}};3044$res{'status'} = [split('',$4) ];3045$res{'to_file'} = unquote($5);3046}3047# 'c512b523472485aef4fff9e57b229d9d243c967f'3048elsif($line=~m/^([0-9a-fA-F]{40})$/) {3049$res{'commit'} =$1;3050}30513052returnwantarray?%res: \%res;3053}30543055# wrapper: return parsed line of git-diff-tree "raw" output3056# (the argument might be raw line, or parsed info)3057sub parsed_difftree_line {3058my$line_or_ref=shift;30593060if(ref($line_or_ref)eq"HASH") {3061# pre-parsed (or generated by hand)3062return$line_or_ref;3063}else{3064return parse_difftree_raw_line($line_or_ref);3065}3066}30673068# parse line of git-ls-tree output3069sub parse_ls_tree_line {3070my$line=shift;3071my%opts=@_;3072my%res;30733074if($opts{'-l'}) {3075#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3076$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;30773078$res{'mode'} =$1;3079$res{'type'} =$2;3080$res{'hash'} =$3;3081$res{'size'} =$4;3082if($opts{'-z'}) {3083$res{'name'} =$5;3084}else{3085$res{'name'} = unquote($5);3086}3087}else{3088#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3089$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;30903091$res{'mode'} =$1;3092$res{'type'} =$2;3093$res{'hash'} =$3;3094if($opts{'-z'}) {3095$res{'name'} =$4;3096}else{3097$res{'name'} = unquote($4);3098}3099}31003101returnwantarray?%res: \%res;3102}31033104# generates _two_ hashes, references to which are passed as 2 and 3 argument3105sub parse_from_to_diffinfo {3106my($diffinfo,$from,$to,@parents) =@_;31073108if($diffinfo->{'nparents'}) {3109# combined diff3110$from->{'file'} = [];3111$from->{'href'} = [];3112 fill_from_file_info($diffinfo,@parents)3113unlessexists$diffinfo->{'from_file'};3114for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3115$from->{'file'}[$i] =3116defined$diffinfo->{'from_file'}[$i] ?3117$diffinfo->{'from_file'}[$i] :3118$diffinfo->{'to_file'};3119if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3120$from->{'href'}[$i] = href(action=>"blob",3121 hash_base=>$parents[$i],3122 hash=>$diffinfo->{'from_id'}[$i],3123 file_name=>$from->{'file'}[$i]);3124}else{3125$from->{'href'}[$i] =undef;3126}3127}3128}else{3129# ordinary (not combined) diff3130$from->{'file'} =$diffinfo->{'from_file'};3131if($diffinfo->{'status'}ne"A") {# not new (added) file3132$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3133 hash=>$diffinfo->{'from_id'},3134 file_name=>$from->{'file'});3135}else{3136delete$from->{'href'};3137}3138}31393140$to->{'file'} =$diffinfo->{'to_file'};3141if(!is_deleted($diffinfo)) {# file exists in result3142$to->{'href'} = href(action=>"blob", hash_base=>$hash,3143 hash=>$diffinfo->{'to_id'},3144 file_name=>$to->{'file'});3145}else{3146delete$to->{'href'};3147}3148}31493150## ......................................................................3151## parse to array of hashes functions31523153sub git_get_heads_list {3154my$limit=shift;3155my@headslist;31563157open my$fd,'-|', git_cmd(),'for-each-ref',3158($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3159'--format=%(objectname) %(refname) %(subject)%00%(committer)',3160'refs/heads'3161orreturn;3162while(my$line= <$fd>) {3163my%ref_item;31643165chomp$line;3166my($refinfo,$committerinfo) =split(/\0/,$line);3167my($hash,$name,$title) =split(' ',$refinfo,3);3168my($committer,$epoch,$tz) =3169($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3170$ref_item{'fullname'} =$name;3171$name=~s!^refs/heads/!!;31723173$ref_item{'name'} =$name;3174$ref_item{'id'} =$hash;3175$ref_item{'title'} =$title||'(no commit message)';3176$ref_item{'epoch'} =$epoch;3177if($epoch) {3178$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3179}else{3180$ref_item{'age'} ="unknown";3181}31823183push@headslist, \%ref_item;3184}3185close$fd;31863187returnwantarray?@headslist: \@headslist;3188}31893190sub git_get_tags_list {3191my$limit=shift;3192my@tagslist;31933194open my$fd,'-|', git_cmd(),'for-each-ref',3195($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3196'--format=%(objectname) %(objecttype) %(refname) '.3197'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3198'refs/tags'3199orreturn;3200while(my$line= <$fd>) {3201my%ref_item;32023203chomp$line;3204my($refinfo,$creatorinfo) =split(/\0/,$line);3205my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3206my($creator,$epoch,$tz) =3207($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3208$ref_item{'fullname'} =$name;3209$name=~s!^refs/tags/!!;32103211$ref_item{'type'} =$type;3212$ref_item{'id'} =$id;3213$ref_item{'name'} =$name;3214if($typeeq"tag") {3215$ref_item{'subject'} =$title;3216$ref_item{'reftype'} =$reftype;3217$ref_item{'refid'} =$refid;3218}else{3219$ref_item{'reftype'} =$type;3220$ref_item{'refid'} =$id;3221}32223223if($typeeq"tag"||$typeeq"commit") {3224$ref_item{'epoch'} =$epoch;3225if($epoch) {3226$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3227}else{3228$ref_item{'age'} ="unknown";3229}3230}32313232push@tagslist, \%ref_item;3233}3234close$fd;32353236returnwantarray?@tagslist: \@tagslist;3237}32383239## ----------------------------------------------------------------------3240## filesystem-related functions32413242sub get_file_owner {3243my$path=shift;32443245my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3246my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3247if(!defined$gcos) {3248returnundef;3249}3250my$owner=$gcos;3251$owner=~s/[,;].*$//;3252return to_utf8($owner);3253}32543255# assume that file exists3256sub insert_file {3257my$filename=shift;32583259open my$fd,'<',$filename;3260print map{ to_utf8($_) } <$fd>;3261close$fd;3262}32633264## ......................................................................3265## mimetype related functions32663267sub mimetype_guess_file {3268my$filename=shift;3269my$mimemap=shift;3270-r $mimemaporreturnundef;32713272my%mimemap;3273open(my$mh,'<',$mimemap)orreturnundef;3274while(<$mh>) {3275next ifm/^#/;# skip comments3276my($mimetype,$exts) =split(/\t+/);3277if(defined$exts) {3278my@exts=split(/\s+/,$exts);3279foreachmy$ext(@exts) {3280$mimemap{$ext} =$mimetype;3281}3282}3283}3284close($mh);32853286$filename=~/\.([^.]*)$/;3287return$mimemap{$1};3288}32893290sub mimetype_guess {3291my$filename=shift;3292my$mime;3293$filename=~/\./orreturnundef;32943295if($mimetypes_file) {3296my$file=$mimetypes_file;3297if($file!~m!^/!) {# if it is relative path3298# it is relative to project3299$file="$projectroot/$project/$file";3300}3301$mime= mimetype_guess_file($filename,$file);3302}3303$mime||= mimetype_guess_file($filename,'/etc/mime.types');3304return$mime;3305}33063307sub blob_mimetype {3308my$fd=shift;3309my$filename=shift;33103311if($filename) {3312my$mime= mimetype_guess($filename);3313$mimeandreturn$mime;3314}33153316# just in case3317return$default_blob_plain_mimetypeunless$fd;33183319if(-T $fd) {3320return'text/plain';3321}elsif(!$filename) {3322return'application/octet-stream';3323}elsif($filename=~m/\.png$/i) {3324return'image/png';3325}elsif($filename=~m/\.gif$/i) {3326return'image/gif';3327}elsif($filename=~m/\.jpe?g$/i) {3328return'image/jpeg';3329}else{3330return'application/octet-stream';3331}3332}33333334sub blob_contenttype {3335my($fd,$file_name,$type) =@_;33363337$type||= blob_mimetype($fd,$file_name);3338if($typeeq'text/plain'&&defined$default_text_plain_charset) {3339$type.="; charset=$default_text_plain_charset";3340}33413342return$type;3343}33443345# guess file syntax for syntax highlighting; return undef if no highlighting3346# the name of syntax can (in the future) depend on syntax highlighter used3347sub guess_file_syntax {3348my($highlight,$mimetype,$file_name) =@_;3349returnundefunless($highlight&&defined$file_name);3350my$basename= basename($file_name,'.in');3351return$highlight_basename{$basename}3352ifexists$highlight_basename{$basename};33533354$basename=~/\.([^.]*)$/;3355my$ext=$1orreturnundef;3356return$highlight_ext{$ext}3357ifexists$highlight_ext{$ext};33583359returnundef;3360}33613362# run highlighter and return FD of its output,3363# or return original FD if no highlighting3364sub run_highlighter {3365my($fd,$highlight,$syntax) =@_;3366return$fdunless($highlight&&defined$syntax);33673368close$fd3369or die_error(404,"Reading blob failed");3370open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3371"highlight --xhtml --fragment --syntax$syntax|"3372or die_error(500,"Couldn't open file or run syntax highlighter");3373return$fd;3374}33753376## ======================================================================3377## functions printing HTML: header, footer, error page33783379sub get_page_title {3380my$title= to_utf8($site_name);33813382return$titleunless(defined$project);3383$title.=" - ". to_utf8($project);33843385return$titleunless(defined$action);3386$title.="/$action";# $action is US-ASCII (7bit ASCII)33873388return$titleunless(defined$file_name);3389$title.=" - ". esc_path($file_name);3390if($actioneq"tree"&&$file_name!~ m|/$|) {3391$title.="/";3392}33933394return$title;3395}33963397sub git_header_html {3398my$status=shift||"200 OK";3399my$expires=shift;3400my%opts=@_;34013402my$title= get_page_title();3403my$content_type;3404# require explicit support from the UA if we are to send the page as3405# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3406# we have to do this because MSIE sometimes globs '*/*', pretending to3407# support xhtml+xml but choking when it gets what it asked for.3408if(defined$cgi->http('HTTP_ACCEPT') &&3409$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3410$cgi->Accept('application/xhtml+xml') !=0) {3411$content_type='application/xhtml+xml';3412}else{3413$content_type='text/html';3414}3415print$cgi->header(-type=>$content_type, -charset =>'utf-8',3416-status=>$status, -expires =>$expires)3417unless($opts{'-no_http_header'});3418my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3419print<<EOF;3420<?xml version="1.0" encoding="utf-8"?>3421<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3422<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3423<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3424<!-- git core binaries version$git_version-->3425<head>3426<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3427<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3428<meta name="robots" content="index, nofollow"/>3429<title>$title</title>3430EOF3431# the stylesheet, favicon etc urls won't work correctly with path_info3432# unless we set the appropriate base URL3433if($ENV{'PATH_INFO'}) {3434print"<base href=\"".esc_url($base_url)."\"/>\n";3435}3436# print out each stylesheet that exist, providing backwards capability3437# for those people who defined $stylesheet in a config file3438if(defined$stylesheet) {3439print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3440}else{3441foreachmy$stylesheet(@stylesheets) {3442next unless$stylesheet;3443print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3444}3445}3446if(defined$project) {3447my%href_params= get_feed_info();3448if(!exists$href_params{'-title'}) {3449$href_params{'-title'} ='log';3450}34513452foreachmy$formatqw(RSS Atom){3453my$type=lc($format);3454my%link_attr= (3455'-rel'=>'alternate',3456'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3457'-type'=>"application/$type+xml"3458);34593460$href_params{'action'} =$type;3461$link_attr{'-href'} = href(%href_params);3462print"<link ".3463"rel=\"$link_attr{'-rel'}\"".3464"title=\"$link_attr{'-title'}\"".3465"href=\"$link_attr{'-href'}\"".3466"type=\"$link_attr{'-type'}\"".3467"/>\n";34683469$href_params{'extra_options'} ='--no-merges';3470$link_attr{'-href'} = href(%href_params);3471$link_attr{'-title'} .=' (no merges)';3472print"<link ".3473"rel=\"$link_attr{'-rel'}\"".3474"title=\"$link_attr{'-title'}\"".3475"href=\"$link_attr{'-href'}\"".3476"type=\"$link_attr{'-type'}\"".3477"/>\n";3478}34793480}else{3481printf('<link rel="alternate" title="%sprojects list" '.3482'href="%s" type="text/plain; charset=utf-8" />'."\n",3483 esc_attr($site_name), href(project=>undef, action=>"project_index"));3484printf('<link rel="alternate" title="%sprojects feeds" '.3485'href="%s" type="text/x-opml" />'."\n",3486 esc_attr($site_name), href(project=>undef, action=>"opml"));3487}3488if(defined$favicon) {3489printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3490}34913492print"</head>\n".3493"<body>\n";34943495if(defined$site_header&& -f $site_header) {3496 insert_file($site_header);3497}34983499print"<div class=\"page_header\">\n".3500$cgi->a({-href => esc_url($logo_url),3501-title =>$logo_label},3502qq(<img src=").esc_url($logo).qq(" width="72" height="27" alt="git" class="logo"/>));3503print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3504if(defined$project) {3505print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3506if(defined$action) {3507print" /$action";3508}3509print"\n";3510}3511print"</div>\n";35123513my$have_search= gitweb_check_feature('search');3514if(defined$project&&$have_search) {3515if(!defined$searchtext) {3516$searchtext="";3517}3518my$search_hash;3519if(defined$hash_base) {3520$search_hash=$hash_base;3521}elsif(defined$hash) {3522$search_hash=$hash;3523}else{3524$search_hash="HEAD";3525}3526my$action=$my_uri;3527my$use_pathinfo= gitweb_check_feature('pathinfo');3528if($use_pathinfo) {3529$action.="/".esc_url($project);3530}3531print$cgi->startform(-method=>"get", -action =>$action) .3532"<div class=\"search\">\n".3533(!$use_pathinfo&&3534$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3535$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3536$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3537$cgi->popup_menu(-name =>'st', -default=>'commit',3538-values=> ['commit','grep','author','committer','pickaxe']) .3539$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3540" search:\n",3541$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3542"<span title=\"Extended regular expression\">".3543$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3544-checked =>$search_use_regexp) .3545"</span>".3546"</div>".3547$cgi->end_form() ."\n";3548}3549}35503551sub git_footer_html {3552my$feed_class='rss_logo';35533554print"<div class=\"page_footer\">\n";3555if(defined$project) {3556my$descr= git_get_project_description($project);3557if(defined$descr) {3558print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3559}35603561my%href_params= get_feed_info();3562if(!%href_params) {3563$feed_class.=' generic';3564}3565$href_params{'-title'} ||='log';35663567foreachmy$formatqw(RSS Atom){3568$href_params{'action'} =lc($format);3569print$cgi->a({-href => href(%href_params),3570-title =>"$href_params{'-title'}$formatfeed",3571-class=>$feed_class},$format)."\n";3572}35733574}else{3575print$cgi->a({-href => href(project=>undef, action=>"opml"),3576-class=>$feed_class},"OPML") ." ";3577print$cgi->a({-href => href(project=>undef, action=>"project_index"),3578-class=>$feed_class},"TXT") ."\n";3579}3580print"</div>\n";# class="page_footer"35813582if(defined$t0&& gitweb_check_feature('timed')) {3583print"<div id=\"generating_info\">\n";3584print'This page took '.3585'<span id="generating_time" class="time_span">'.3586 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).3587' seconds </span>'.3588' and '.3589'<span id="generating_cmd">'.3590$number_of_git_cmds.3591'</span> git commands '.3592" to generate.\n";3593print"</div>\n";# class="page_footer"3594}35953596if(defined$site_footer&& -f $site_footer) {3597 insert_file($site_footer);3598}35993600print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;3601if(defined$action&&3602$actioneq'blame_incremental') {3603print qq!<script type="text/javascript">\n!.3604 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.3605 qq!"!. href() .qq!");\n!.3606 qq!</script>\n!;3607}elsif(gitweb_check_feature('javascript-actions')) {3608print qq!<script type="text/javascript">\n!.3609 qq!window.onload = fixLinks;\n!.3610 qq!</script>\n!;3611}36123613print"</body>\n".3614"</html>";3615}36163617# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])3618# Example: die_error(404, 'Hash not found')3619# By convention, use the following status codes (as defined in RFC 2616):3620# 400: Invalid or missing CGI parameters, or3621# requested object exists but has wrong type.3622# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3623# this server or project.3624# 404: Requested object/revision/project doesn't exist.3625# 500: The server isn't configured properly, or3626# an internal error occurred (e.g. failed assertions caused by bugs), or3627# an unknown error occurred (e.g. the git binary died unexpectedly).3628# 503: The server is currently unavailable (because it is overloaded,3629# or down for maintenance). Generally, this is a temporary state.3630sub die_error {3631my$status=shift||500;3632my$error= esc_html(shift) ||"Internal Server Error";3633my$extra=shift;3634my%opts=@_;36353636my%http_responses= (3637400=>'400 Bad Request',3638403=>'403 Forbidden',3639404=>'404 Not Found',3640500=>'500 Internal Server Error',3641503=>'503 Service Unavailable',3642);3643 git_header_html($http_responses{$status},undef,%opts);3644print<<EOF;3645<div class="page_body">3646<br /><br />3647$status-$error3648<br />3649EOF3650if(defined$extra) {3651print"<hr />\n".3652"$extra\n";3653}3654print"</div>\n";36553656 git_footer_html();3657goto DONE_GITWEB3658unless($opts{'-error_handler'});3659}36603661## ----------------------------------------------------------------------3662## functions printing or outputting HTML: navigation36633664sub git_print_page_nav {3665my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3666$extra=''if!defined$extra;# pager or formats36673668my@navs=qw(summary shortlog log commit commitdiff tree);3669if($suppress) {3670@navs=grep{$_ne$suppress}@navs;3671}36723673my%arg=map{$_=> {action=>$_} }@navs;3674if(defined$head) {3675for(qw(commit commitdiff)) {3676$arg{$_}{'hash'} =$head;3677}3678if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3679for(qw(shortlog log)) {3680$arg{$_}{'hash'} =$head;3681}3682}3683}36843685$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3686$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;36873688my@actions= gitweb_get_feature('actions');3689my%repl= (3690'%'=>'%',3691'n'=>$project,# project name3692'f'=>$git_dir,# project path within filesystem3693'h'=>$treehead||'',# current hash ('h' parameter)3694'b'=>$treebase||'',# hash base ('hb' parameter)3695);3696while(@actions) {3697my($label,$link,$pos) =splice(@actions,0,3);3698# insert3699@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3700# munch munch3701$link=~s/%([%nfhb])/$repl{$1}/g;3702$arg{$label}{'_href'} =$link;3703}37043705print"<div class=\"page_nav\">\n".3706(join" | ",3707map{$_eq$current?3708$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3709}@navs);3710print"<br/>\n$extra<br/>\n".3711"</div>\n";3712}37133714sub format_paging_nav {3715my($action,$page,$has_next_link) =@_;3716my$paging_nav;371737183719if($page>0) {3720$paging_nav.=3721$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .3722" ⋅ ".3723$cgi->a({-href => href(-replay=>1, page=>$page-1),3724-accesskey =>"p", -title =>"Alt-p"},"prev");3725}else{3726$paging_nav.="first ⋅ prev";3727}37283729if($has_next_link) {3730$paging_nav.=" ⋅ ".3731$cgi->a({-href => href(-replay=>1, page=>$page+1),3732-accesskey =>"n", -title =>"Alt-n"},"next");3733}else{3734$paging_nav.=" ⋅ next";3735}37363737return$paging_nav;3738}37393740## ......................................................................3741## functions printing or outputting HTML: div37423743sub git_print_header_div {3744my($action,$title,$hash,$hash_base) =@_;3745my%args= ();37463747$args{'action'} =$action;3748$args{'hash'} =$hashif$hash;3749$args{'hash_base'} =$hash_baseif$hash_base;37503751print"<div class=\"header\">\n".3752$cgi->a({-href => href(%args), -class=>"title"},3753$title?$title:$action) .3754"\n</div>\n";3755}37563757sub print_local_time {3758print format_local_time(@_);3759}37603761sub format_local_time {3762my$localtime='';3763my%date=@_;3764if($date{'hour_local'} <6) {3765$localtime.=sprintf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3766$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3767}else{3768$localtime.=sprintf(" (%02d:%02d%s)",3769$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3770}37713772return$localtime;3773}37743775# Outputs the author name and date in long form3776sub git_print_authorship {3777my$co=shift;3778my%opts=@_;3779my$tag=$opts{-tag} ||'div';3780my$author=$co->{'author_name'};37813782my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3783print"<$tagclass=\"author_date\">".3784 format_search_author($author,"author", esc_html($author)) .3785" [$ad{'rfc2822'}";3786 print_local_time(%ad)if($opts{-localtime});3787print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3788."</$tag>\n";3789}37903791# Outputs table rows containing the full author or committer information,3792# in the format expected for 'commit' view (& similar).3793# Parameters are a commit hash reference, followed by the list of people3794# to output information for. If the list is empty it defaults to both3795# author and committer.3796sub git_print_authorship_rows {3797my$co=shift;3798# too bad we can't use @people = @_ || ('author', 'committer')3799my@people=@_;3800@people= ('author','committer')unless@people;3801foreachmy$who(@people) {3802my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3803print"<tr><td>$who</td><td>".3804 format_search_author($co->{"${who}_name"},$who,3805 esc_html($co->{"${who}_name"})) ." ".3806 format_search_author($co->{"${who}_email"},$who,3807 esc_html("<".$co->{"${who}_email"} .">")) .3808"</td><td rowspan=\"2\">".3809 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3810"</td></tr>\n".3811"<tr>".3812"<td></td><td>$wd{'rfc2822'}";3813 print_local_time(%wd);3814print"</td>".3815"</tr>\n";3816}3817}38183819sub git_print_page_path {3820my$name=shift;3821my$type=shift;3822my$hb=shift;382338243825print"<div class=\"page_path\">";3826print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3827-title =>'tree root'}, to_utf8("[$project]"));3828print" / ";3829if(defined$name) {3830my@dirname=split'/',$name;3831my$basename=pop@dirname;3832my$fullname='';38333834foreachmy$dir(@dirname) {3835$fullname.= ($fullname?'/':'') .$dir;3836print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3837 hash_base=>$hb),3838-title =>$fullname}, esc_path($dir));3839print" / ";3840}3841if(defined$type&&$typeeq'blob') {3842print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3843 hash_base=>$hb),3844-title =>$name}, esc_path($basename));3845}elsif(defined$type&&$typeeq'tree') {3846print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3847 hash_base=>$hb),3848-title =>$name}, esc_path($basename));3849print" / ";3850}else{3851print esc_path($basename);3852}3853}3854print"<br/></div>\n";3855}38563857sub git_print_log {3858my$log=shift;3859my%opts=@_;38603861if($opts{'-remove_title'}) {3862# remove title, i.e. first line of log3863shift@$log;3864}3865# remove leading empty lines3866while(defined$log->[0] &&$log->[0]eq"") {3867shift@$log;3868}38693870# print log3871my$signoff=0;3872my$empty=0;3873foreachmy$line(@$log) {3874if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3875$signoff=1;3876$empty=0;3877if(!$opts{'-remove_signoff'}) {3878print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3879next;3880}else{3881# remove signoff lines3882next;3883}3884}else{3885$signoff=0;3886}38873888# print only one empty line3889# do not print empty line after signoff3890if($lineeq"") {3891next if($empty||$signoff);3892$empty=1;3893}else{3894$empty=0;3895}38963897print format_log_line_html($line) ."<br/>\n";3898}38993900if($opts{'-final_empty_line'}) {3901# end with single empty line3902print"<br/>\n"unless$empty;3903}3904}39053906# return link target (what link points to)3907sub git_get_link_target {3908my$hash=shift;3909my$link_target;39103911# read link3912open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3913orreturn;3914{3915local$/=undef;3916$link_target= <$fd>;3917}3918close$fd3919orreturn;39203921return$link_target;3922}39233924# given link target, and the directory (basedir) the link is in,3925# return target of link relative to top directory (top tree);3926# return undef if it is not possible (including absolute links).3927sub normalize_link_target {3928my($link_target,$basedir) =@_;39293930# absolute symlinks (beginning with '/') cannot be normalized3931return if(substr($link_target,0,1)eq'/');39323933# normalize link target to path from top (root) tree (dir)3934my$path;3935if($basedir) {3936$path=$basedir.'/'.$link_target;3937}else{3938# we are in top (root) tree (dir)3939$path=$link_target;3940}39413942# remove //, /./, and /../3943my@path_parts;3944foreachmy$part(split('/',$path)) {3945# discard '.' and ''3946next if(!$part||$parteq'.');3947# handle '..'3948if($parteq'..') {3949if(@path_parts) {3950pop@path_parts;3951}else{3952# link leads outside repository (outside top dir)3953return;3954}3955}else{3956push@path_parts,$part;3957}3958}3959$path=join('/',@path_parts);39603961return$path;3962}39633964# print tree entry (row of git_tree), but without encompassing <tr> element3965sub git_print_tree_entry {3966my($t,$basedir,$hash_base,$have_blame) =@_;39673968my%base_key= ();3969$base_key{'hash_base'} =$hash_baseifdefined$hash_base;39703971# The format of a table row is: mode list link. Where mode is3972# the mode of the entry, list is the name of the entry, an href,3973# and link is the action links of the entry.39743975print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3976if(exists$t->{'size'}) {3977print"<td class=\"size\">$t->{'size'}</td>\n";3978}3979if($t->{'type'}eq"blob") {3980print"<td class=\"list\">".3981$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3982 file_name=>"$basedir$t->{'name'}",%base_key),3983-class=>"list"}, esc_path($t->{'name'}));3984if(S_ISLNK(oct$t->{'mode'})) {3985my$link_target= git_get_link_target($t->{'hash'});3986if($link_target) {3987my$norm_target= normalize_link_target($link_target,$basedir);3988if(defined$norm_target) {3989print" -> ".3990$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,3991 file_name=>$norm_target),3992-title =>$norm_target}, esc_path($link_target));3993}else{3994print" -> ". esc_path($link_target);3995}3996}3997}3998print"</td>\n";3999print"<td class=\"link\">";4000print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4001 file_name=>"$basedir$t->{'name'}",%base_key)},4002"blob");4003if($have_blame) {4004print" | ".4005$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4006 file_name=>"$basedir$t->{'name'}",%base_key)},4007"blame");4008}4009if(defined$hash_base) {4010print" | ".4011$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4012 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4013"history");4014}4015print" | ".4016$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4017 file_name=>"$basedir$t->{'name'}")},4018"raw");4019print"</td>\n";40204021}elsif($t->{'type'}eq"tree") {4022print"<td class=\"list\">";4023print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4024 file_name=>"$basedir$t->{'name'}",4025%base_key)},4026 esc_path($t->{'name'}));4027print"</td>\n";4028print"<td class=\"link\">";4029print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4030 file_name=>"$basedir$t->{'name'}",4031%base_key)},4032"tree");4033if(defined$hash_base) {4034print" | ".4035$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4036 file_name=>"$basedir$t->{'name'}")},4037"history");4038}4039print"</td>\n";4040}else{4041# unknown object: we can only present history for it4042# (this includes 'commit' object, i.e. submodule support)4043print"<td class=\"list\">".4044 esc_path($t->{'name'}) .4045"</td>\n";4046print"<td class=\"link\">";4047if(defined$hash_base) {4048print$cgi->a({-href => href(action=>"history",4049 hash_base=>$hash_base,4050 file_name=>"$basedir$t->{'name'}")},4051"history");4052}4053print"</td>\n";4054}4055}40564057## ......................................................................4058## functions printing large fragments of HTML40594060# get pre-image filenames for merge (combined) diff4061sub fill_from_file_info {4062my($diff,@parents) =@_;40634064$diff->{'from_file'} = [ ];4065$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4066for(my$i=0;$i<$diff->{'nparents'};$i++) {4067if($diff->{'status'}[$i]eq'R'||4068$diff->{'status'}[$i]eq'C') {4069$diff->{'from_file'}[$i] =4070 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4071}4072}40734074return$diff;4075}40764077# is current raw difftree line of file deletion4078sub is_deleted {4079my$diffinfo=shift;40804081return$diffinfo->{'to_id'}eq('0' x 40);4082}40834084# does patch correspond to [previous] difftree raw line4085# $diffinfo - hashref of parsed raw diff format4086# $patchinfo - hashref of parsed patch diff format4087# (the same keys as in $diffinfo)4088sub is_patch_split {4089my($diffinfo,$patchinfo) =@_;40904091returndefined$diffinfo&&defined$patchinfo4092&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4093}409440954096sub git_difftree_body {4097my($difftree,$hash,@parents) =@_;4098my($parent) =$parents[0];4099my$have_blame= gitweb_check_feature('blame');4100print"<div class=\"list_head\">\n";4101if($#{$difftree} >10) {4102print(($#{$difftree} +1) ." files changed:\n");4103}4104print"</div>\n";41054106print"<table class=\"".4107(@parents>1?"combined ":"") .4108"diff_tree\">\n";41094110# header only for combined diff in 'commitdiff' view4111my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4112if($has_header) {4113# table header4114print"<thead><tr>\n".4115"<th></th><th></th>\n";# filename, patchN link4116for(my$i=0;$i<@parents;$i++) {4117my$par=$parents[$i];4118print"<th>".4119$cgi->a({-href => href(action=>"commitdiff",4120 hash=>$hash, hash_parent=>$par),4121-title =>'commitdiff to parent number '.4122($i+1) .': '.substr($par,0,7)},4123$i+1) .4124" </th>\n";4125}4126print"</tr></thead>\n<tbody>\n";4127}41284129my$alternate=1;4130my$patchno=0;4131foreachmy$line(@{$difftree}) {4132my$diff= parsed_difftree_line($line);41334134if($alternate) {4135print"<tr class=\"dark\">\n";4136}else{4137print"<tr class=\"light\">\n";4138}4139$alternate^=1;41404141if(exists$diff->{'nparents'}) {# combined diff41424143 fill_from_file_info($diff,@parents)4144unlessexists$diff->{'from_file'};41454146if(!is_deleted($diff)) {4147# file exists in the result (child) commit4148print"<td>".4149$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4150 file_name=>$diff->{'to_file'},4151 hash_base=>$hash),4152-class=>"list"}, esc_path($diff->{'to_file'})) .4153"</td>\n";4154}else{4155print"<td>".4156 esc_path($diff->{'to_file'}) .4157"</td>\n";4158}41594160if($actioneq'commitdiff') {4161# link to patch4162$patchno++;4163print"<td class=\"link\">".4164$cgi->a({-href =>"#patch$patchno"},"patch") .4165" | ".4166"</td>\n";4167}41684169my$has_history=0;4170my$not_deleted=0;4171for(my$i=0;$i<$diff->{'nparents'};$i++) {4172my$hash_parent=$parents[$i];4173my$from_hash=$diff->{'from_id'}[$i];4174my$from_path=$diff->{'from_file'}[$i];4175my$status=$diff->{'status'}[$i];41764177$has_history||= ($statusne'A');4178$not_deleted||= ($statusne'D');41794180if($statuseq'A') {4181print"<td class=\"link\"align=\"right\"> | </td>\n";4182}elsif($statuseq'D') {4183print"<td class=\"link\">".4184$cgi->a({-href => href(action=>"blob",4185 hash_base=>$hash,4186 hash=>$from_hash,4187 file_name=>$from_path)},4188"blob". ($i+1)) .4189" | </td>\n";4190}else{4191if($diff->{'to_id'}eq$from_hash) {4192print"<td class=\"link nochange\">";4193}else{4194print"<td class=\"link\">";4195}4196print$cgi->a({-href => href(action=>"blobdiff",4197 hash=>$diff->{'to_id'},4198 hash_parent=>$from_hash,4199 hash_base=>$hash,4200 hash_parent_base=>$hash_parent,4201 file_name=>$diff->{'to_file'},4202 file_parent=>$from_path)},4203"diff". ($i+1)) .4204" | </td>\n";4205}4206}42074208print"<td class=\"link\">";4209if($not_deleted) {4210print$cgi->a({-href => href(action=>"blob",4211 hash=>$diff->{'to_id'},4212 file_name=>$diff->{'to_file'},4213 hash_base=>$hash)},4214"blob");4215print" | "if($has_history);4216}4217if($has_history) {4218print$cgi->a({-href => href(action=>"history",4219 file_name=>$diff->{'to_file'},4220 hash_base=>$hash)},4221"history");4222}4223print"</td>\n";42244225print"</tr>\n";4226next;# instead of 'else' clause, to avoid extra indent4227}4228# else ordinary diff42294230my($to_mode_oct,$to_mode_str,$to_file_type);4231my($from_mode_oct,$from_mode_str,$from_file_type);4232if($diff->{'to_mode'}ne('0' x 6)) {4233$to_mode_oct=oct$diff->{'to_mode'};4234if(S_ISREG($to_mode_oct)) {# only for regular file4235$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4236}4237$to_file_type= file_type($diff->{'to_mode'});4238}4239if($diff->{'from_mode'}ne('0' x 6)) {4240$from_mode_oct=oct$diff->{'from_mode'};4241if(S_ISREG($to_mode_oct)) {# only for regular file4242$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4243}4244$from_file_type= file_type($diff->{'from_mode'});4245}42464247if($diff->{'status'}eq"A") {# created4248my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4249$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4250$mode_chng.="]</span>";4251print"<td>";4252print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4253 hash_base=>$hash, file_name=>$diff->{'file'}),4254-class=>"list"}, esc_path($diff->{'file'}));4255print"</td>\n";4256print"<td>$mode_chng</td>\n";4257print"<td class=\"link\">";4258if($actioneq'commitdiff') {4259# link to patch4260$patchno++;4261print$cgi->a({-href =>"#patch$patchno"},"patch");4262print" | ";4263}4264print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4265 hash_base=>$hash, file_name=>$diff->{'file'})},4266"blob");4267print"</td>\n";42684269}elsif($diff->{'status'}eq"D") {# deleted4270my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4271print"<td>";4272print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4273 hash_base=>$parent, file_name=>$diff->{'file'}),4274-class=>"list"}, esc_path($diff->{'file'}));4275print"</td>\n";4276print"<td>$mode_chng</td>\n";4277print"<td class=\"link\">";4278if($actioneq'commitdiff') {4279# link to patch4280$patchno++;4281print$cgi->a({-href =>"#patch$patchno"},"patch");4282print" | ";4283}4284print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4285 hash_base=>$parent, file_name=>$diff->{'file'})},4286"blob") ." | ";4287if($have_blame) {4288print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4289 file_name=>$diff->{'file'})},4290"blame") ." | ";4291}4292print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4293 file_name=>$diff->{'file'})},4294"history");4295print"</td>\n";42964297}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4298my$mode_chnge="";4299if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4300$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4301if($from_file_typene$to_file_type) {4302$mode_chnge.=" from$from_file_typeto$to_file_type";4303}4304if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4305if($from_mode_str&&$to_mode_str) {4306$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4307}elsif($to_mode_str) {4308$mode_chnge.=" mode:$to_mode_str";4309}4310}4311$mode_chnge.="]</span>\n";4312}4313print"<td>";4314print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4315 hash_base=>$hash, file_name=>$diff->{'file'}),4316-class=>"list"}, esc_path($diff->{'file'}));4317print"</td>\n";4318print"<td>$mode_chnge</td>\n";4319print"<td class=\"link\">";4320if($actioneq'commitdiff') {4321# link to patch4322$patchno++;4323print$cgi->a({-href =>"#patch$patchno"},"patch") .4324" | ";4325}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4326# "commit" view and modified file (not onlu mode changed)4327print$cgi->a({-href => href(action=>"blobdiff",4328 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4329 hash_base=>$hash, hash_parent_base=>$parent,4330 file_name=>$diff->{'file'})},4331"diff") .4332" | ";4333}4334print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4335 hash_base=>$hash, file_name=>$diff->{'file'})},4336"blob") ." | ";4337if($have_blame) {4338print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4339 file_name=>$diff->{'file'})},4340"blame") ." | ";4341}4342print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4343 file_name=>$diff->{'file'})},4344"history");4345print"</td>\n";43464347}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4348my%status_name= ('R'=>'moved','C'=>'copied');4349my$nstatus=$status_name{$diff->{'status'}};4350my$mode_chng="";4351if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4352# mode also for directories, so we cannot use $to_mode_str4353$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4354}4355print"<td>".4356$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4357 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4358-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4359"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4360$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4361 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4362-class=>"list"}, esc_path($diff->{'from_file'})) .4363" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4364"<td class=\"link\">";4365if($actioneq'commitdiff') {4366# link to patch4367$patchno++;4368print$cgi->a({-href =>"#patch$patchno"},"patch") .4369" | ";4370}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4371# "commit" view and modified file (not only pure rename or copy)4372print$cgi->a({-href => href(action=>"blobdiff",4373 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4374 hash_base=>$hash, hash_parent_base=>$parent,4375 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},4376"diff") .4377" | ";4378}4379print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4380 hash_base=>$parent, file_name=>$diff->{'to_file'})},4381"blob") ." | ";4382if($have_blame) {4383print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4384 file_name=>$diff->{'to_file'})},4385"blame") ." | ";4386}4387print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4388 file_name=>$diff->{'to_file'})},4389"history");4390print"</td>\n";43914392}# we should not encounter Unmerged (U) or Unknown (X) status4393print"</tr>\n";4394}4395print"</tbody>"if$has_header;4396print"</table>\n";4397}43984399sub git_patchset_body {4400my($fd,$difftree,$hash,@hash_parents) =@_;4401my($hash_parent) =$hash_parents[0];44024403my$is_combined= (@hash_parents>1);4404my$patch_idx=0;4405my$patch_number=0;4406my$patch_line;4407my$diffinfo;4408my$to_name;4409my(%from,%to);44104411print"<div class=\"patchset\">\n";44124413# skip to first patch4414while($patch_line= <$fd>) {4415chomp$patch_line;44164417last if($patch_line=~m/^diff /);4418}44194420 PATCH:4421while($patch_line) {44224423# parse "git diff" header line4424if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4425# $1 is from_name, which we do not use4426$to_name= unquote($2);4427$to_name=~s!^b/!!;4428}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4429# $1 is 'cc' or 'combined', which we do not use4430$to_name= unquote($2);4431}else{4432$to_name=undef;4433}44344435# check if current patch belong to current raw line4436# and parse raw git-diff line if needed4437if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4438# this is continuation of a split patch4439print"<div class=\"patch cont\">\n";4440}else{4441# advance raw git-diff output if needed4442$patch_idx++ifdefined$diffinfo;44434444# read and prepare patch information4445$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);44464447# compact combined diff output can have some patches skipped4448# find which patch (using pathname of result) we are at now;4449if($is_combined) {4450while($to_namene$diffinfo->{'to_file'}) {4451print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4452 format_diff_cc_simplified($diffinfo,@hash_parents) .4453"</div>\n";# class="patch"44544455$patch_idx++;4456$patch_number++;44574458last if$patch_idx>$#$difftree;4459$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4460}4461}44624463# modifies %from, %to hashes4464 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);44654466# this is first patch for raw difftree line with $patch_idx index4467# we index @$difftree array from 0, but number patches from 14468print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4469}44704471# git diff header4472#assert($patch_line =~ m/^diff /) if DEBUG;4473#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4474$patch_number++;4475# print "git diff" header4476print format_git_diff_header_line($patch_line,$diffinfo,4477 \%from, \%to);44784479# print extended diff header4480print"<div class=\"diff extended_header\">\n";4481 EXTENDED_HEADER:4482while($patch_line= <$fd>) {4483chomp$patch_line;44844485last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);44864487print format_extended_diff_header_line($patch_line,$diffinfo,4488 \%from, \%to);4489}4490print"</div>\n";# class="diff extended_header"44914492# from-file/to-file diff header4493if(!$patch_line) {4494print"</div>\n";# class="patch"4495last PATCH;4496}4497next PATCH if($patch_line=~m/^diff /);4498#assert($patch_line =~ m/^---/) if DEBUG;44994500my$last_patch_line=$patch_line;4501$patch_line= <$fd>;4502chomp$patch_line;4503#assert($patch_line =~ m/^\+\+\+/) if DEBUG;45044505print format_diff_from_to_header($last_patch_line,$patch_line,4506$diffinfo, \%from, \%to,4507@hash_parents);45084509# the patch itself4510 LINE:4511while($patch_line= <$fd>) {4512chomp$patch_line;45134514next PATCH if($patch_line=~m/^diff /);45154516print format_diff_line($patch_line, \%from, \%to);4517}45184519}continue{4520print"</div>\n";# class="patch"4521}45224523# for compact combined (--cc) format, with chunk and patch simplification4524# the patchset might be empty, but there might be unprocessed raw lines4525for(++$patch_idxif$patch_number>0;4526$patch_idx<@$difftree;4527++$patch_idx) {4528# read and prepare patch information4529$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);45304531# generate anchor for "patch" links in difftree / whatchanged part4532print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4533 format_diff_cc_simplified($diffinfo,@hash_parents) .4534"</div>\n";# class="patch"45354536$patch_number++;4537}45384539if($patch_number==0) {4540if(@hash_parents>1) {4541print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4542}else{4543print"<div class=\"diff nodifferences\">No differences found</div>\n";4544}4545}45464547print"</div>\n";# class="patchset"4548}45494550# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45514552# fills project list info (age, description, owner, forks) for each4553# project in the list, removing invalid projects from returned list4554# NOTE: modifies $projlist, but does not remove entries from it4555sub fill_project_list_info {4556my($projlist,$check_forks) =@_;4557my@projects;45584559my$show_ctags= gitweb_check_feature('ctags');4560 PROJECT:4561foreachmy$pr(@$projlist) {4562my(@activity) = git_get_last_activity($pr->{'path'});4563unless(@activity) {4564next PROJECT;4565}4566($pr->{'age'},$pr->{'age_string'}) =@activity;4567if(!defined$pr->{'descr'}) {4568my$descr= git_get_project_description($pr->{'path'}) ||"";4569$descr= to_utf8($descr);4570$pr->{'descr_long'} =$descr;4571$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4572}4573if(!defined$pr->{'owner'}) {4574$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4575}4576if($check_forks) {4577my$pname=$pr->{'path'};4578if(($pname=~s/\.git$//) &&4579($pname!~/\/$/) &&4580(-d "$projectroot/$pname")) {4581$pr->{'forks'} ="-d$projectroot/$pname";4582}else{4583$pr->{'forks'} =0;4584}4585}4586$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4587push@projects,$pr;4588}45894590return@projects;4591}45924593# print 'sort by' <th> element, generating 'sort by $name' replay link4594# if that order is not selected4595sub print_sort_th {4596print format_sort_th(@_);4597}45984599sub format_sort_th {4600my($name,$order,$header) =@_;4601my$sort_th="";4602$header||=ucfirst($name);46034604if($ordereq$name) {4605$sort_th.="<th>$header</th>\n";4606}else{4607$sort_th.="<th>".4608$cgi->a({-href => href(-replay=>1, order=>$name),4609-class=>"header"},$header) .4610"</th>\n";4611}46124613return$sort_th;4614}46154616sub git_project_list_body {4617# actually uses global variable $project4618my($projlist,$order,$from,$to,$extra,$no_header) =@_;46194620my$check_forks= gitweb_check_feature('forks');4621my@projects= fill_project_list_info($projlist,$check_forks);46224623$order||=$default_projects_order;4624$from=0unlessdefined$from;4625$to=$#projectsif(!defined$to||$#projects<$to);46264627my%order_info= (4628 project => { key =>'path', type =>'str'},4629 descr => { key =>'descr_long', type =>'str'},4630 owner => { key =>'owner', type =>'str'},4631 age => { key =>'age', type =>'num'}4632);4633my$oi=$order_info{$order};4634if($oi->{'type'}eq'str') {4635@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4636}else{4637@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4638}46394640my$show_ctags= gitweb_check_feature('ctags');4641if($show_ctags) {4642my%ctags;4643foreachmy$p(@projects) {4644foreachmy$ct(keys%{$p->{'ctags'}}) {4645$ctags{$ct} +=$p->{'ctags'}->{$ct};4646}4647}4648my$cloud= git_populate_project_tagcloud(\%ctags);4649print git_show_project_tagcloud($cloud,64);4650}46514652print"<table class=\"project_list\">\n";4653unless($no_header) {4654print"<tr>\n";4655if($check_forks) {4656print"<th></th>\n";4657}4658 print_sort_th('project',$order,'Project');4659 print_sort_th('descr',$order,'Description');4660 print_sort_th('owner',$order,'Owner');4661 print_sort_th('age',$order,'Last Change');4662print"<th></th>\n".# for links4663"</tr>\n";4664}4665my$alternate=1;4666my$tagfilter=$cgi->param('by_tag');4667for(my$i=$from;$i<=$to;$i++) {4668my$pr=$projects[$i];46694670next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4671next if$searchtextand not$pr->{'path'} =~/$searchtext/4672and not$pr->{'descr_long'} =~/$searchtext/;4673# Weed out forks or non-matching entries of search4674if($check_forks) {4675my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4676$forkbase="^$forkbase"if$forkbase;4677next ifnot$searchtextand not$tagfilterand$show_ctags4678and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4679}46804681if($alternate) {4682print"<tr class=\"dark\">\n";4683}else{4684print"<tr class=\"light\">\n";4685}4686$alternate^=1;4687if($check_forks) {4688print"<td>";4689if($pr->{'forks'}) {4690print"<!--$pr->{'forks'} -->\n";4691print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4692}4693print"</td>\n";4694}4695print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4696-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4697"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4698-class=>"list", -title =>$pr->{'descr_long'}},4699 esc_html($pr->{'descr'})) ."</td>\n".4700"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4701print"<td class=\"". age_class($pr->{'age'}) ."\">".4702(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4703"<td class=\"link\">".4704$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4705$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4706$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4707$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4708($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4709"</td>\n".4710"</tr>\n";4711}4712if(defined$extra) {4713print"<tr>\n";4714if($check_forks) {4715print"<td></td>\n";4716}4717print"<td colspan=\"5\">$extra</td>\n".4718"</tr>\n";4719}4720print"</table>\n";4721}47224723sub git_log_body {4724# uses global variable $project4725my($commitlist,$from,$to,$refs,$extra) =@_;47264727$from=0unlessdefined$from;4728$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47294730for(my$i=0;$i<=$to;$i++) {4731my%co= %{$commitlist->[$i]};4732next if!%co;4733my$commit=$co{'id'};4734my$ref= format_ref_marker($refs,$commit);4735my%ad= parse_date($co{'author_epoch'});4736 git_print_header_div('commit',4737"<span class=\"age\">$co{'age_string'}</span>".4738 esc_html($co{'title'}) .$ref,4739$commit);4740print"<div class=\"title_text\">\n".4741"<div class=\"log_link\">\n".4742$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .4743" | ".4744$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .4745" | ".4746$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .4747"<br/>\n".4748"</div>\n";4749 git_print_authorship(\%co, -tag =>'span');4750print"<br/>\n</div>\n";47514752print"<div class=\"log_body\">\n";4753 git_print_log($co{'comment'}, -final_empty_line=>1);4754print"</div>\n";4755}4756if($extra) {4757print"<div class=\"page_nav\">\n";4758print"$extra\n";4759print"</div>\n";4760}4761}47624763sub git_shortlog_body {4764# uses global variable $project4765my($commitlist,$from,$to,$refs,$extra) =@_;47664767$from=0unlessdefined$from;4768$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);47694770print"<table class=\"shortlog\">\n";4771my$alternate=1;4772for(my$i=$from;$i<=$to;$i++) {4773my%co= %{$commitlist->[$i]};4774my$commit=$co{'id'};4775my$ref= format_ref_marker($refs,$commit);4776if($alternate) {4777print"<tr class=\"dark\">\n";4778}else{4779print"<tr class=\"light\">\n";4780}4781$alternate^=1;4782# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4783print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4784 format_author_html('td', \%co,10) ."<td>";4785print format_subject_html($co{'title'},$co{'title_short'},4786 href(action=>"commit", hash=>$commit),$ref);4787print"</td>\n".4788"<td class=\"link\">".4789$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4790$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4791$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4792my$snapshot_links= format_snapshot_links($commit);4793if(defined$snapshot_links) {4794print" | ".$snapshot_links;4795}4796print"</td>\n".4797"</tr>\n";4798}4799if(defined$extra) {4800print"<tr>\n".4801"<td colspan=\"4\">$extra</td>\n".4802"</tr>\n";4803}4804print"</table>\n";4805}48064807sub git_history_body {4808# Warning: assumes constant type (blob or tree) during history4809my($commitlist,$from,$to,$refs,$extra,4810$file_name,$file_hash,$ftype) =@_;48114812$from=0unlessdefined$from;4813$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});48144815print"<table class=\"history\">\n";4816my$alternate=1;4817for(my$i=$from;$i<=$to;$i++) {4818my%co= %{$commitlist->[$i]};4819if(!%co) {4820next;4821}4822my$commit=$co{'id'};48234824my$ref= format_ref_marker($refs,$commit);48254826if($alternate) {4827print"<tr class=\"dark\">\n";4828}else{4829print"<tr class=\"light\">\n";4830}4831$alternate^=1;4832print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4833# shortlog: format_author_html('td', \%co, 10)4834 format_author_html('td', \%co,15,3) ."<td>";4835# originally git_history used chop_str($co{'title'}, 50)4836print format_subject_html($co{'title'},$co{'title_short'},4837 href(action=>"commit", hash=>$commit),$ref);4838print"</td>\n".4839"<td class=\"link\">".4840$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4841$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");48424843if($ftypeeq'blob') {4844my$blob_current=$file_hash;4845my$blob_parent= git_get_hash_by_path($commit,$file_name);4846if(defined$blob_current&&defined$blob_parent&&4847$blob_currentne$blob_parent) {4848print" | ".4849$cgi->a({-href => href(action=>"blobdiff",4850 hash=>$blob_current, hash_parent=>$blob_parent,4851 hash_base=>$hash_base, hash_parent_base=>$commit,4852 file_name=>$file_name)},4853"diff to current");4854}4855}4856print"</td>\n".4857"</tr>\n";4858}4859if(defined$extra) {4860print"<tr>\n".4861"<td colspan=\"4\">$extra</td>\n".4862"</tr>\n";4863}4864print"</table>\n";4865}48664867sub git_tags_body {4868# uses global variable $project4869my($taglist,$from,$to,$extra) =@_;4870$from=0unlessdefined$from;4871$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);48724873print"<table class=\"tags\">\n";4874my$alternate=1;4875for(my$i=$from;$i<=$to;$i++) {4876my$entry=$taglist->[$i];4877my%tag=%$entry;4878my$comment=$tag{'subject'};4879my$comment_short;4880if(defined$comment) {4881$comment_short= chop_str($comment,30,5);4882}4883if($alternate) {4884print"<tr class=\"dark\">\n";4885}else{4886print"<tr class=\"light\">\n";4887}4888$alternate^=1;4889if(defined$tag{'age'}) {4890print"<td><i>$tag{'age'}</i></td>\n";4891}else{4892print"<td></td>\n";4893}4894print"<td>".4895$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4896-class=>"list name"}, esc_html($tag{'name'})) .4897"</td>\n".4898"<td>";4899if(defined$comment) {4900print format_subject_html($comment,$comment_short,4901 href(action=>"tag", hash=>$tag{'id'}));4902}4903print"</td>\n".4904"<td class=\"selflink\">";4905if($tag{'type'}eq"tag") {4906print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4907}else{4908print" ";4909}4910print"</td>\n".4911"<td class=\"link\">"." | ".4912$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4913if($tag{'reftype'}eq"commit") {4914print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4915" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4916}elsif($tag{'reftype'}eq"blob") {4917print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4918}4919print"</td>\n".4920"</tr>";4921}4922if(defined$extra) {4923print"<tr>\n".4924"<td colspan=\"5\">$extra</td>\n".4925"</tr>\n";4926}4927print"</table>\n";4928}49294930sub git_heads_body {4931# uses global variable $project4932my($headlist,$head,$from,$to,$extra) =@_;4933$from=0unlessdefined$from;4934$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);49354936print"<table class=\"heads\">\n";4937my$alternate=1;4938for(my$i=$from;$i<=$to;$i++) {4939my$entry=$headlist->[$i];4940my%ref=%$entry;4941my$curr=$ref{'id'}eq$head;4942if($alternate) {4943print"<tr class=\"dark\">\n";4944}else{4945print"<tr class=\"light\">\n";4946}4947$alternate^=1;4948print"<td><i>$ref{'age'}</i></td>\n".4949($curr?"<td class=\"current_head\">":"<td>") .4950$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4951-class=>"list name"},esc_html($ref{'name'})) .4952"</td>\n".4953"<td class=\"link\">".4954$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4955$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4956$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})},"tree") .4957"</td>\n".4958"</tr>";4959}4960if(defined$extra) {4961print"<tr>\n".4962"<td colspan=\"3\">$extra</td>\n".4963"</tr>\n";4964}4965print"</table>\n";4966}49674968sub git_search_grep_body {4969my($commitlist,$from,$to,$extra) =@_;4970$from=0unlessdefined$from;4971$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);49724973print"<table class=\"commit_search\">\n";4974my$alternate=1;4975for(my$i=$from;$i<=$to;$i++) {4976my%co= %{$commitlist->[$i]};4977if(!%co) {4978next;4979}4980my$commit=$co{'id'};4981if($alternate) {4982print"<tr class=\"dark\">\n";4983}else{4984print"<tr class=\"light\">\n";4985}4986$alternate^=1;4987print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4988 format_author_html('td', \%co,15,5) .4989"<td>".4990$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),4991-class=>"list subject"},4992 chop_and_escape_str($co{'title'},50) ."<br/>");4993my$comment=$co{'comment'};4994foreachmy$line(@$comment) {4995if($line=~m/^(.*?)($search_regexp)(.*)$/i) {4996my($lead,$match,$trail) = ($1,$2,$3);4997$match= chop_str($match,70,5,'center');4998my$contextlen=int((80-length($match))/2);4999$contextlen=30if($contextlen>30);5000$lead= chop_str($lead,$contextlen,10,'left');5001$trail= chop_str($trail,$contextlen,10,'right');50025003$lead= esc_html($lead);5004$match= esc_html($match);5005$trail= esc_html($trail);50065007print"$lead<span class=\"match\">$match</span>$trail<br />";5008}5009}5010print"</td>\n".5011"<td class=\"link\">".5012$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5013" | ".5014$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .5015" | ".5016$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5017print"</td>\n".5018"</tr>\n";5019}5020if(defined$extra) {5021print"<tr>\n".5022"<td colspan=\"3\">$extra</td>\n".5023"</tr>\n";5024}5025print"</table>\n";5026}50275028## ======================================================================5029## ======================================================================5030## actions50315032sub git_project_list {5033my$order=$input_params{'order'};5034if(defined$order&&$order!~m/none|project|descr|owner|age/) {5035 die_error(400,"Unknown order parameter");5036}50375038my@list= git_get_projects_list();5039if(!@list) {5040 die_error(404,"No projects found");5041}50425043 git_header_html();5044if(defined$home_text&& -f $home_text) {5045print"<div class=\"index_include\">\n";5046 insert_file($home_text);5047print"</div>\n";5048}5049print$cgi->startform(-method=>"get") .5050"<p class=\"projsearch\">Search:\n".5051$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".5052"</p>".5053$cgi->end_form() ."\n";5054 git_project_list_body(\@list,$order);5055 git_footer_html();5056}50575058sub git_forks {5059my$order=$input_params{'order'};5060if(defined$order&&$order!~m/none|project|descr|owner|age/) {5061 die_error(400,"Unknown order parameter");5062}50635064my@list= git_get_projects_list($project);5065if(!@list) {5066 die_error(404,"No forks found");5067}50685069 git_header_html();5070 git_print_page_nav('','');5071 git_print_header_div('summary',"$projectforks");5072 git_project_list_body(\@list,$order);5073 git_footer_html();5074}50755076sub git_project_index {5077my@projects= git_get_projects_list($project);50785079print$cgi->header(5080-type =>'text/plain',5081-charset =>'utf-8',5082-content_disposition =>'inline; filename="index.aux"');50835084foreachmy$pr(@projects) {5085if(!exists$pr->{'owner'}) {5086$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");5087}50885089my($path,$owner) = ($pr->{'path'},$pr->{'owner'});5090# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '5091$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5092$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;5093$path=~s/ /\+/g;5094$owner=~s/ /\+/g;50955096print"$path$owner\n";5097}5098}50995100sub git_summary {5101my$descr= git_get_project_description($project) ||"none";5102my%co= parse_commit("HEAD");5103my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();5104my$head=$co{'id'};51055106my$owner= git_get_project_owner($project);51075108my$refs= git_get_references();5109# These get_*_list functions return one more to allow us to see if5110# there are more ...5111my@taglist= git_get_tags_list(16);5112my@headlist= git_get_heads_list(16);5113my@forklist;5114my$check_forks= gitweb_check_feature('forks');51155116if($check_forks) {5117@forklist= git_get_projects_list($project);5118}51195120 git_header_html();5121 git_print_page_nav('summary','',$head);51225123print"<div class=\"title\"> </div>\n";5124print"<table class=\"projects_list\">\n".5125"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".5126"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";5127if(defined$cd{'rfc2822'}) {5128print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";5129}51305131# use per project git URL list in $projectroot/$project/cloneurl5132# or make project git URL from git base URL and project name5133my$url_tag="URL";5134my@url_list= git_get_project_url_list($project);5135@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;5136foreachmy$git_url(@url_list) {5137next unless$git_url;5138print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";5139$url_tag="";5140}51415142# Tag cloud5143my$show_ctags= gitweb_check_feature('ctags');5144if($show_ctags) {5145my$ctags= git_get_project_ctags($project);5146my$cloud= git_populate_project_tagcloud($ctags);5147print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";5148print"</td>\n<td>"unless%$ctags;5149print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";5150print"</td>\n<td>"if%$ctags;5151print git_show_project_tagcloud($cloud,48);5152print"</td></tr>";5153}51545155print"</table>\n";51565157# If XSS prevention is on, we don't include README.html.5158# TODO: Allow a readme in some safe format.5159if(!$prevent_xss&& -s "$projectroot/$project/README.html") {5160print"<div class=\"title\">readme</div>\n".5161"<div class=\"readme\">\n";5162 insert_file("$projectroot/$project/README.html");5163print"\n</div>\n";# class="readme"5164}51655166# we need to request one more than 16 (0..15) to check if5167# those 16 are all5168my@commitlist=$head? parse_commits($head,17) : ();5169if(@commitlist) {5170 git_print_header_div('shortlog');5171 git_shortlog_body(\@commitlist,0,15,$refs,5172$#commitlist<=15?undef:5173$cgi->a({-href => href(action=>"shortlog")},"..."));5174}51755176if(@taglist) {5177 git_print_header_div('tags');5178 git_tags_body(\@taglist,0,15,5179$#taglist<=15?undef:5180$cgi->a({-href => href(action=>"tags")},"..."));5181}51825183if(@headlist) {5184 git_print_header_div('heads');5185 git_heads_body(\@headlist,$head,0,15,5186$#headlist<=15?undef:5187$cgi->a({-href => href(action=>"heads")},"..."));5188}51895190if(@forklist) {5191 git_print_header_div('forks');5192 git_project_list_body(\@forklist,'age',0,15,5193$#forklist<=15?undef:5194$cgi->a({-href => href(action=>"forks")},"..."),5195'no_header');5196}51975198 git_footer_html();5199}52005201sub git_tag {5202my%tag= parse_tag($hash);52035204if(!%tag) {5205 die_error(404,"Unknown tag object");5206}52075208my$head= git_get_head_hash($project);5209 git_header_html();5210 git_print_page_nav('','',$head,undef,$head);5211 git_print_header_div('commit', esc_html($tag{'name'}),$hash);5212print"<div class=\"title_text\">\n".5213"<table class=\"object_header\">\n".5214"<tr>\n".5215"<td>object</td>\n".5216"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5217$tag{'object'}) ."</td>\n".5218"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},5219$tag{'type'}) ."</td>\n".5220"</tr>\n";5221if(defined($tag{'author'})) {5222 git_print_authorship_rows(\%tag,'author');5223}5224print"</table>\n\n".5225"</div>\n";5226print"<div class=\"page_body\">";5227my$comment=$tag{'comment'};5228foreachmy$line(@$comment) {5229chomp$line;5230print esc_html($line, -nbsp=>1) ."<br/>\n";5231}5232print"</div>\n";5233 git_footer_html();5234}52355236sub git_blame_common {5237my$format=shift||'porcelain';5238if($formateq'porcelain'&&$cgi->param('js')) {5239$format='incremental';5240$action='blame_incremental';# for page title etc5241}52425243# permissions5244 gitweb_check_feature('blame')5245or die_error(403,"Blame view not allowed");52465247# error checking5248 die_error(400,"No file name given")unless$file_name;5249$hash_base||= git_get_head_hash($project);5250 die_error(404,"Couldn't find base commit")unless$hash_base;5251my%co= parse_commit($hash_base)5252or die_error(404,"Commit not found");5253my$ftype="blob";5254if(!defined$hash) {5255$hash= git_get_hash_by_path($hash_base,$file_name,"blob")5256or die_error(404,"Error looking up file");5257}else{5258$ftype= git_get_type($hash);5259if($ftype!~"blob") {5260 die_error(400,"Object is not a blob");5261}5262}52635264my$fd;5265if($formateq'incremental') {5266# get file contents (as base)5267open$fd,"-|", git_cmd(),'cat-file','blob',$hash5268or die_error(500,"Open git-cat-file failed");5269}elsif($formateq'data') {5270# run git-blame --incremental5271open$fd,"-|", git_cmd(),"blame","--incremental",5272$hash_base,"--",$file_name5273or die_error(500,"Open git-blame --incremental failed");5274}else{5275# run git-blame --porcelain5276open$fd,"-|", git_cmd(),"blame",'-p',5277$hash_base,'--',$file_name5278or die_error(500,"Open git-blame --porcelain failed");5279}52805281# incremental blame data returns early5282if($formateq'data') {5283print$cgi->header(5284-type=>"text/plain", -charset =>"utf-8",5285-status=>"200 OK");5286local$| =1;# output autoflush5287printwhile<$fd>;5288close$fd5289or print"ERROR$!\n";52905291print'END';5292if(defined$t0&& gitweb_check_feature('timed')) {5293print' '.5294 Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]).5295' '.$number_of_git_cmds;5296}5297print"\n";52985299return;5300}53015302# page header5303 git_header_html();5304my$formats_nav=5305$cgi->a({-href => href(action=>"blob", -replay=>1)},5306"blob") .5307" | ";5308if($formateq'incremental') {5309$formats_nav.=5310$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},5311"blame") ." (non-incremental)";5312}else{5313$formats_nav.=5314$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},5315"blame") ." (incremental)";5316}5317$formats_nav.=5318" | ".5319$cgi->a({-href => href(action=>"history", -replay=>1)},5320"history") .5321" | ".5322$cgi->a({-href => href(action=>$action, file_name=>$file_name)},5323"HEAD");5324 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5325 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5326 git_print_page_path($file_name,$ftype,$hash_base);53275328# page body5329if($formateq'incremental') {5330print"<noscript>\n<div class=\"error\"><center><b>\n".5331"This page requires JavaScript to run.\nUse ".5332$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},5333'this page').5334" instead.\n".5335"</b></center></div>\n</noscript>\n";53365337print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;5338}53395340print qq!<div class="page_body">\n!;5341print qq!<div id="progress_info">.../ ...</div>\n!5342if($formateq'incremental');5343print qq!<table id="blame_table"class="blame" width="100%">\n!.5344#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.5345 qq!<thead>\n!.5346 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.5347 qq!</thead>\n!.5348 qq!<tbody>\n!;53495350my@rev_color=qw(light dark);5351my$num_colors=scalar(@rev_color);5352my$current_color=0;53535354if($formateq'incremental') {5355my$color_class=$rev_color[$current_color];53565357#contents of a file5358my$linenr=0;5359 LINE:5360while(my$line= <$fd>) {5361chomp$line;5362$linenr++;53635364print qq!<tr id="l$linenr"class="$color_class">!.5365 qq!<td class="sha1"><a href=""> </a></td>!.5366 qq!<td class="linenr">!.5367 qq!<a class="linenr" href="">$linenr</a></td>!;5368print qq!<td class="pre">! . esc_html($line) ."</td>\n";5369print qq!</tr>\n!;5370}53715372}else{# porcelain, i.e. ordinary blame5373my%metainfo= ();# saves information about commits53745375# blame data5376 LINE:5377while(my$line= <$fd>) {5378chomp$line;5379# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]5380# no <lines in group> for subsequent lines in group of lines5381my($full_rev,$orig_lineno,$lineno,$group_size) =5382($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);5383if(!exists$metainfo{$full_rev}) {5384$metainfo{$full_rev} = {'nprevious'=>0};5385}5386my$meta=$metainfo{$full_rev};5387my$data;5388while($data= <$fd>) {5389chomp$data;5390last if($data=~s/^\t//);# contents of line5391if($data=~/^(\S+)(?: (.*))?$/) {5392$meta->{$1} =$2unlessexists$meta->{$1};5393}5394if($data=~/^previous /) {5395$meta->{'nprevious'}++;5396}5397}5398my$short_rev=substr($full_rev,0,8);5399my$author=$meta->{'author'};5400my%date=5401 parse_date($meta->{'author-time'},$meta->{'author-tz'});5402my$date=$date{'iso-tz'};5403if($group_size) {5404$current_color= ($current_color+1) %$num_colors;5405}5406my$tr_class=$rev_color[$current_color];5407$tr_class.=' boundary'if(exists$meta->{'boundary'});5408$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);5409$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);5410print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";5411if($group_size) {5412print"<td class=\"sha1\"";5413print" title=\"". esc_html($author) .",$date\"";5414print" rowspan=\"$group_size\""if($group_size>1);5415print">";5416print$cgi->a({-href => href(action=>"commit",5417 hash=>$full_rev,5418 file_name=>$file_name)},5419 esc_html($short_rev));5420if($group_size>=2) {5421my@author_initials= ($author=~/\b([[:upper:]])\B/g);5422if(@author_initials) {5423print"<br />".5424 esc_html(join('',@author_initials));5425# or join('.', ...)5426}5427}5428print"</td>\n";5429}5430# 'previous' <sha1 of parent commit> <filename at commit>5431if(exists$meta->{'previous'} &&5432$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {5433$meta->{'parent'} =$1;5434$meta->{'file_parent'} = unquote($2);5435}5436my$linenr_commit=5437exists($meta->{'parent'}) ?5438$meta->{'parent'} :$full_rev;5439my$linenr_filename=5440exists($meta->{'file_parent'}) ?5441$meta->{'file_parent'} : unquote($meta->{'filename'});5442my$blamed= href(action =>'blame',5443 file_name =>$linenr_filename,5444 hash_base =>$linenr_commit);5445print"<td class=\"linenr\">";5446print$cgi->a({ -href =>"$blamed#l$orig_lineno",5447-class=>"linenr"},5448 esc_html($lineno));5449print"</td>";5450print"<td class=\"pre\">". esc_html($data) ."</td>\n";5451print"</tr>\n";5452}# end while54535454}54555456# footer5457print"</tbody>\n".5458"</table>\n";# class="blame"5459print"</div>\n";# class="blame_body"5460close$fd5461or print"Reading blob failed\n";54625463 git_footer_html();5464}54655466sub git_blame {5467 git_blame_common();5468}54695470sub git_blame_incremental {5471 git_blame_common('incremental');5472}54735474sub git_blame_data {5475 git_blame_common('data');5476}54775478sub git_tags {5479my$head= git_get_head_hash($project);5480 git_header_html();5481 git_print_page_nav('','',$head,undef,$head);5482 git_print_header_div('summary',$project);54835484my@tagslist= git_get_tags_list();5485if(@tagslist) {5486 git_tags_body(\@tagslist);5487}5488 git_footer_html();5489}54905491sub git_heads {5492my$head= git_get_head_hash($project);5493 git_header_html();5494 git_print_page_nav('','',$head,undef,$head);5495 git_print_header_div('summary',$project);54965497my@headslist= git_get_heads_list();5498if(@headslist) {5499 git_heads_body(\@headslist,$head);5500}5501 git_footer_html();5502}55035504sub git_blob_plain {5505my$type=shift;5506my$expires;55075508if(!defined$hash) {5509if(defined$file_name) {5510my$base=$hash_base|| git_get_head_hash($project);5511$hash= git_get_hash_by_path($base,$file_name,"blob")5512or die_error(404,"Cannot find file");5513}else{5514 die_error(400,"No file name defined");5515}5516}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5517# blobs defined by non-textual hash id's can be cached5518$expires="+1d";5519}55205521open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5522or die_error(500,"Open git-cat-file blob '$hash' failed");55235524# content-type (can include charset)5525$type= blob_contenttype($fd,$file_name,$type);55265527# "save as" filename, even when no $file_name is given5528my$save_as="$hash";5529if(defined$file_name) {5530$save_as=$file_name;5531}elsif($type=~m/^text\//) {5532$save_as.='.txt';5533}55345535# With XSS prevention on, blobs of all types except a few known safe5536# ones are served with "Content-Disposition: attachment" to make sure5537# they don't run in our security domain. For certain image types,5538# blob view writes an <img> tag referring to blob_plain view, and we5539# want to be sure not to break that by serving the image as an5540# attachment (though Firefox 3 doesn't seem to care).5541my$sandbox=$prevent_xss&&5542$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;55435544print$cgi->header(5545-type =>$type,5546-expires =>$expires,5547-content_disposition =>5548($sandbox?'attachment':'inline')5549.'; filename="'.$save_as.'"');5550local$/=undef;5551binmode STDOUT,':raw';5552print<$fd>;5553binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5554close$fd;5555}55565557sub git_blob {5558my$expires;55595560if(!defined$hash) {5561if(defined$file_name) {5562my$base=$hash_base|| git_get_head_hash($project);5563$hash= git_get_hash_by_path($base,$file_name,"blob")5564or die_error(404,"Cannot find file");5565}else{5566 die_error(400,"No file name defined");5567}5568}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5569# blobs defined by non-textual hash id's can be cached5570$expires="+1d";5571}55725573my$have_blame= gitweb_check_feature('blame');5574open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5575or die_error(500,"Couldn't cat$file_name,$hash");5576my$mimetype= blob_mimetype($fd,$file_name);5577# use 'blob_plain' (aka 'raw') view for files that cannot be displayed5578if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {5579close$fd;5580return git_blob_plain($mimetype);5581}5582# we can have blame only for text/* mimetype5583$have_blame&&= ($mimetype=~m!^text/!);55845585my$highlight= gitweb_check_feature('highlight');5586my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);5587$fd= run_highlighter($fd,$highlight,$syntax)5588if$syntax;55895590 git_header_html(undef,$expires);5591my$formats_nav='';5592if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5593if(defined$file_name) {5594if($have_blame) {5595$formats_nav.=5596$cgi->a({-href => href(action=>"blame", -replay=>1)},5597"blame") .5598" | ";5599}5600$formats_nav.=5601$cgi->a({-href => href(action=>"history", -replay=>1)},5602"history") .5603" | ".5604$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5605"raw") .5606" | ".5607$cgi->a({-href => href(action=>"blob",5608 hash_base=>"HEAD", file_name=>$file_name)},5609"HEAD");5610}else{5611$formats_nav.=5612$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5613"raw");5614}5615 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5616 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5617}else{5618print"<div class=\"page_nav\">\n".5619"<br/><br/></div>\n".5620"<div class=\"title\">".esc_html($hash)."</div>\n";5621}5622 git_print_page_path($file_name,"blob",$hash_base);5623print"<div class=\"page_body\">\n";5624if($mimetype=~m!^image/!) {5625print qq!<img type="!.esc_attr($mimetype).qq!"!;5626if($file_name) {5627print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;5628}5629print qq! src="! .5630 href(action=>"blob_plain", hash=>$hash,5631 hash_base=>$hash_base, file_name=>$file_name) .5632 qq!"/>\n!;5633}else{5634my$nr;5635while(my$line= <$fd>) {5636chomp$line;5637$nr++;5638$line= untabify($line);5639printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,5640$nr, esc_attr(href(-replay =>1)),$nr,$nr,$syntax?$line: esc_html($line, -nbsp=>1);5641}5642}5643close$fd5644or print"Reading blob failed.\n";5645print"</div>";5646 git_footer_html();5647}56485649sub git_tree {5650if(!defined$hash_base) {5651$hash_base="HEAD";5652}5653if(!defined$hash) {5654if(defined$file_name) {5655$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5656}else{5657$hash=$hash_base;5658}5659}5660 die_error(404,"No such tree")unlessdefined($hash);56615662my$show_sizes= gitweb_check_feature('show-sizes');5663my$have_blame= gitweb_check_feature('blame');56645665my@entries= ();5666{5667local$/="\0";5668open my$fd,"-|", git_cmd(),"ls-tree",'-z',5669($show_sizes?'-l': ()),@extra_options,$hash5670or die_error(500,"Open git-ls-tree failed");5671@entries=map{chomp;$_} <$fd>;5672close$fd5673or die_error(404,"Reading tree failed");5674}56755676my$refs= git_get_references();5677my$ref= format_ref_marker($refs,$hash_base);5678 git_header_html();5679my$basedir='';5680if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5681my@views_nav= ();5682if(defined$file_name) {5683push@views_nav,5684$cgi->a({-href => href(action=>"history", -replay=>1)},5685"history"),5686$cgi->a({-href => href(action=>"tree",5687 hash_base=>"HEAD", file_name=>$file_name)},5688"HEAD"),5689}5690my$snapshot_links= format_snapshot_links($hash);5691if(defined$snapshot_links) {5692# FIXME: Should be available when we have no hash base as well.5693push@views_nav,$snapshot_links;5694}5695 git_print_page_nav('tree','',$hash_base,undef,undef,5696join(' | ',@views_nav));5697 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5698}else{5699undef$hash_base;5700print"<div class=\"page_nav\">\n";5701print"<br/><br/></div>\n";5702print"<div class=\"title\">".esc_html($hash)."</div>\n";5703}5704if(defined$file_name) {5705$basedir=$file_name;5706if($basedirne''&&substr($basedir, -1)ne'/') {5707$basedir.='/';5708}5709 git_print_page_path($file_name,'tree',$hash_base);5710}5711print"<div class=\"page_body\">\n";5712print"<table class=\"tree\">\n";5713my$alternate=1;5714# '..' (top directory) link if possible5715if(defined$hash_base&&5716defined$file_name&&$file_name=~m![^/]+$!) {5717if($alternate) {5718print"<tr class=\"dark\">\n";5719}else{5720print"<tr class=\"light\">\n";5721}5722$alternate^=1;57235724my$up=$file_name;5725$up=~s!/?[^/]+$!!;5726undef$upunless$up;5727# based on git_print_tree_entry5728print'<td class="mode">'. mode_str('040000') ."</td>\n";5729print'<td class="size"> </td>'."\n"if$show_sizes;5730print'<td class="list">';5731print$cgi->a({-href => href(action=>"tree",5732 hash_base=>$hash_base,5733 file_name=>$up)},5734"..");5735print"</td>\n";5736print"<td class=\"link\"></td>\n";57375738print"</tr>\n";5739}5740foreachmy$line(@entries) {5741my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);57425743if($alternate) {5744print"<tr class=\"dark\">\n";5745}else{5746print"<tr class=\"light\">\n";5747}5748$alternate^=1;57495750 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);57515752print"</tr>\n";5753}5754print"</table>\n".5755"</div>";5756 git_footer_html();5757}57585759sub snapshot_name {5760my($project,$hash) =@_;57615762# path/to/project.git -> project5763# path/to/project/.git -> project5764my$name= to_utf8($project);5765$name=~ s,([^/])/*\.git$,$1,;5766$name= basename($name);5767# sanitize name5768$name=~s/[[:cntrl:]]/?/g;57695770my$ver=$hash;5771if($hash=~/^[0-9a-fA-F]+$/) {5772# shorten SHA-1 hash5773my$full_hash= git_get_full_hash($project,$hash);5774if($full_hash=~/^$hash/&&length($hash) >7) {5775$ver= git_get_short_hash($project,$hash);5776}5777}elsif($hash=~m!^refs/tags/(.*)$!) {5778# tags don't need shortened SHA-1 hash5779$ver=$1;5780}else{5781# branches and other need shortened SHA-1 hash5782if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {5783$ver=$1;5784}5785$ver.='-'. git_get_short_hash($project,$hash);5786}5787# in case of hierarchical branch names5788$ver=~s!/!.!g;57895790# name = project-version_string5791$name="$name-$ver";57925793returnwantarray? ($name,$name) :$name;5794}57955796sub git_snapshot {5797my$format=$input_params{'snapshot_format'};5798if(!@snapshot_fmts) {5799 die_error(403,"Snapshots not allowed");5800}5801# default to first supported snapshot format5802$format||=$snapshot_fmts[0];5803if($format!~m/^[a-z0-9]+$/) {5804 die_error(400,"Invalid snapshot format parameter");5805}elsif(!exists($known_snapshot_formats{$format})) {5806 die_error(400,"Unknown snapshot format");5807}elsif($known_snapshot_formats{$format}{'disabled'}) {5808 die_error(403,"Snapshot format not allowed");5809}elsif(!grep($_eq$format,@snapshot_fmts)) {5810 die_error(403,"Unsupported snapshot format");5811}58125813my$type= git_get_type("$hash^{}");5814if(!$type) {5815 die_error(404,'Object does not exist');5816}elsif($typeeq'blob') {5817 die_error(400,'Object is not a tree-ish');5818}58195820my($name,$prefix) = snapshot_name($project,$hash);5821my$filename="$name$known_snapshot_formats{$format}{'suffix'}";5822my$cmd= quote_command(5823 git_cmd(),'archive',5824"--format=$known_snapshot_formats{$format}{'format'}",5825"--prefix=$prefix/",$hash);5826if(exists$known_snapshot_formats{$format}{'compressor'}) {5827$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5828}58295830$filename=~s/(["\\])/\\$1/g;5831print$cgi->header(5832-type =>$known_snapshot_formats{$format}{'type'},5833-content_disposition =>'inline; filename="'.$filename.'"',5834-status =>'200 OK');58355836open my$fd,"-|",$cmd5837or die_error(500,"Execute git-archive failed");5838binmode STDOUT,':raw';5839print<$fd>;5840binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5841close$fd;5842}58435844sub git_log_generic {5845my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;58465847my$head= git_get_head_hash($project);5848if(!defined$base) {5849$base=$head;5850}5851if(!defined$page) {5852$page=0;5853}5854my$refs= git_get_references();58555856my$commit_hash=$base;5857if(defined$parent) {5858$commit_hash="$parent..$base";5859}5860my@commitlist=5861 parse_commits($commit_hash,101, (100*$page),5862defined$file_name? ($file_name,"--full-history") : ());58635864my$ftype;5865if(!defined$file_hash&&defined$file_name) {5866# some commits could have deleted file in question,5867# and not have it in tree, but one of them has to have it5868for(my$i=0;$i<@commitlist;$i++) {5869$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5870last ifdefined$file_hash;5871}5872}5873if(defined$file_hash) {5874$ftype= git_get_type($file_hash);5875}5876if(defined$file_name&& !defined$ftype) {5877 die_error(500,"Unknown type of object");5878}5879my%co;5880if(defined$file_name) {5881%co= parse_commit($base)5882or die_error(404,"Unknown commit object");5883}588458855886my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);5887my$next_link='';5888if($#commitlist>=100) {5889$next_link=5890$cgi->a({-href => href(-replay=>1, page=>$page+1),5891-accesskey =>"n", -title =>"Alt-n"},"next");5892}5893my$patch_max= gitweb_get_feature('patches');5894if($patch_max&& !defined$file_name) {5895if($patch_max<0||@commitlist<=$patch_max) {5896$paging_nav.=" ⋅ ".5897$cgi->a({-href => href(action=>"patches", -replay=>1)},5898"patches");5899}5900}59015902 git_header_html();5903 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);5904if(defined$file_name) {5905 git_print_header_div('commit', esc_html($co{'title'}),$base);5906}else{5907 git_print_header_div('summary',$project)5908}5909 git_print_page_path($file_name,$ftype,$hash_base)5910if(defined$file_name);59115912$body_subr->(\@commitlist,0,99,$refs,$next_link,5913$file_name,$file_hash,$ftype);59145915 git_footer_html();5916}59175918sub git_log {5919 git_log_generic('log', \&git_log_body,5920$hash,$hash_parent);5921}59225923sub git_commit {5924$hash||=$hash_base||"HEAD";5925my%co= parse_commit($hash)5926or die_error(404,"Unknown commit object");59275928my$parent=$co{'parent'};5929my$parents=$co{'parents'};# listref59305931# we need to prepare $formats_nav before any parameter munging5932my$formats_nav;5933if(!defined$parent) {5934# --root commitdiff5935$formats_nav.='(initial)';5936}elsif(@$parents==1) {5937# single parent commit5938$formats_nav.=5939'(parent: '.5940$cgi->a({-href => href(action=>"commit",5941 hash=>$parent)},5942 esc_html(substr($parent,0,7))) .5943')';5944}else{5945# merge commit5946$formats_nav.=5947'(merge: '.5948join(' ',map{5949$cgi->a({-href => href(action=>"commit",5950 hash=>$_)},5951 esc_html(substr($_,0,7)));5952}@$parents) .5953')';5954}5955if(gitweb_check_feature('patches') &&@$parents<=1) {5956$formats_nav.=" | ".5957$cgi->a({-href => href(action=>"patch", -replay=>1)},5958"patch");5959}59605961if(!defined$parent) {5962$parent="--root";5963}5964my@difftree;5965open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",5966@diff_opts,5967(@$parents<=1?$parent:'-c'),5968$hash,"--"5969or die_error(500,"Open git-diff-tree failed");5970@difftree=map{chomp;$_} <$fd>;5971close$fdor die_error(404,"Reading git-diff-tree failed");59725973# non-textual hash id's can be cached5974my$expires;5975if($hash=~m/^[0-9a-fA-F]{40}$/) {5976$expires="+1d";5977}5978my$refs= git_get_references();5979my$ref= format_ref_marker($refs,$co{'id'});59805981 git_header_html(undef,$expires);5982 git_print_page_nav('commit','',5983$hash,$co{'tree'},$hash,5984$formats_nav);59855986if(defined$co{'parent'}) {5987 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);5988}else{5989 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);5990}5991print"<div class=\"title_text\">\n".5992"<table class=\"object_header\">\n";5993 git_print_authorship_rows(\%co);5994print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";5995print"<tr>".5996"<td>tree</td>".5997"<td class=\"sha1\">".5998$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),5999class=>"list"},$co{'tree'}) .6000"</td>".6001"<td class=\"link\">".6002$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},6003"tree");6004my$snapshot_links= format_snapshot_links($hash);6005if(defined$snapshot_links) {6006print" | ".$snapshot_links;6007}6008print"</td>".6009"</tr>\n";60106011foreachmy$par(@$parents) {6012print"<tr>".6013"<td>parent</td>".6014"<td class=\"sha1\">".6015$cgi->a({-href => href(action=>"commit", hash=>$par),6016class=>"list"},$par) .6017"</td>".6018"<td class=\"link\">".6019$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .6020" | ".6021$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .6022"</td>".6023"</tr>\n";6024}6025print"</table>".6026"</div>\n";60276028print"<div class=\"page_body\">\n";6029 git_print_log($co{'comment'});6030print"</div>\n";60316032 git_difftree_body(\@difftree,$hash,@$parents);60336034 git_footer_html();6035}60366037sub git_object {6038# object is defined by:6039# - hash or hash_base alone6040# - hash_base and file_name6041my$type;60426043# - hash or hash_base alone6044if($hash|| ($hash_base&& !defined$file_name)) {6045my$object_id=$hash||$hash_base;60466047open my$fd,"-|", quote_command(6048 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'6049or die_error(404,"Object does not exist");6050$type= <$fd>;6051chomp$type;6052close$fd6053or die_error(404,"Object does not exist");60546055# - hash_base and file_name6056}elsif($hash_base&&defined$file_name) {6057$file_name=~ s,/+$,,;60586059system(git_cmd(),"cat-file",'-e',$hash_base) ==06060or die_error(404,"Base object does not exist");60616062# here errors should not hapen6063open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name6064or die_error(500,"Open git-ls-tree failed");6065my$line= <$fd>;6066close$fd;60676068#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'6069unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {6070 die_error(404,"File or directory for given base does not exist");6071}6072$type=$2;6073$hash=$3;6074}else{6075 die_error(400,"Not enough information to find object");6076}60776078print$cgi->redirect(-uri => href(action=>$type, -full=>1,6079 hash=>$hash, hash_base=>$hash_base,6080 file_name=>$file_name),6081-status =>'302 Found');6082}60836084sub git_blobdiff {6085my$format=shift||'html';60866087my$fd;6088my@difftree;6089my%diffinfo;6090my$expires;60916092# preparing $fd and %diffinfo for git_patchset_body6093# new style URI6094if(defined$hash_base&&defined$hash_parent_base) {6095if(defined$file_name) {6096# read raw output6097open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6098$hash_parent_base,$hash_base,6099"--", (defined$file_parent?$file_parent: ()),$file_name6100or die_error(500,"Open git-diff-tree failed");6101@difftree=map{chomp;$_} <$fd>;6102close$fd6103or die_error(404,"Reading git-diff-tree failed");6104@difftree6105or die_error(404,"Blob diff not found");61066107}elsif(defined$hash&&6108$hash=~/[0-9a-fA-F]{40}/) {6109# try to find filename from $hash61106111# read filtered raw output6112open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6113$hash_parent_base,$hash_base,"--"6114or die_error(500,"Open git-diff-tree failed");6115@difftree=6116# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'6117# $hash == to_id6118grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}6119map{chomp;$_} <$fd>;6120close$fd6121or die_error(404,"Reading git-diff-tree failed");6122@difftree6123or die_error(404,"Blob diff not found");61246125}else{6126 die_error(400,"Missing one of the blob diff parameters");6127}61286129if(@difftree>1) {6130 die_error(400,"Ambiguous blob diff specification");6131}61326133%diffinfo= parse_difftree_raw_line($difftree[0]);6134$file_parent||=$diffinfo{'from_file'} ||$file_name;6135$file_name||=$diffinfo{'to_file'};61366137$hash_parent||=$diffinfo{'from_id'};6138$hash||=$diffinfo{'to_id'};61396140# non-textual hash id's can be cached6141if($hash_base=~m/^[0-9a-fA-F]{40}$/&&6142$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {6143$expires='+1d';6144}61456146# open patch output6147open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6148'-p', ($formateq'html'?"--full-index": ()),6149$hash_parent_base,$hash_base,6150"--", (defined$file_parent?$file_parent: ()),$file_name6151or die_error(500,"Open git-diff-tree failed");6152}61536154# old/legacy style URI -- not generated anymore since 1.4.3.6155if(!%diffinfo) {6156 die_error('404 Not Found',"Missing one of the blob diff parameters")6157}61586159# header6160if($formateq'html') {6161my$formats_nav=6162$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},6163"raw");6164 git_header_html(undef,$expires);6165if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6166 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6167 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6168}else{6169print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";6170print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";6171}6172if(defined$file_name) {6173 git_print_page_path($file_name,"blob",$hash_base);6174}else{6175print"<div class=\"page_path\"></div>\n";6176}61776178}elsif($formateq'plain') {6179print$cgi->header(6180-type =>'text/plain',6181-charset =>'utf-8',6182-expires =>$expires,6183-content_disposition =>'inline; filename="'."$file_name".'.patch"');61846185print"X-Git-Url: ".$cgi->self_url() ."\n\n";61866187}else{6188 die_error(400,"Unknown blobdiff format");6189}61906191# patch6192if($formateq'html') {6193print"<div class=\"page_body\">\n";61946195 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);6196close$fd;61976198print"</div>\n";# class="page_body"6199 git_footer_html();62006201}else{6202while(my$line= <$fd>) {6203$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;6204$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;62056206print$line;62076208last if$line=~m!^\+\+\+!;6209}6210local$/=undef;6211print<$fd>;6212close$fd;6213}6214}62156216sub git_blobdiff_plain {6217 git_blobdiff('plain');6218}62196220sub git_commitdiff {6221my%params=@_;6222my$format=$params{-format} ||'html';62236224my($patch_max) = gitweb_get_feature('patches');6225if($formateq'patch') {6226 die_error(403,"Patch view not allowed")unless$patch_max;6227}62286229$hash||=$hash_base||"HEAD";6230my%co= parse_commit($hash)6231or die_error(404,"Unknown commit object");62326233# choose format for commitdiff for merge6234if(!defined$hash_parent&& @{$co{'parents'}} >1) {6235$hash_parent='--cc';6236}6237# we need to prepare $formats_nav before almost any parameter munging6238my$formats_nav;6239if($formateq'html') {6240$formats_nav=6241$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},6242"raw");6243if($patch_max&& @{$co{'parents'}} <=1) {6244$formats_nav.=" | ".6245$cgi->a({-href => href(action=>"patch", -replay=>1)},6246"patch");6247}62486249if(defined$hash_parent&&6250$hash_parentne'-c'&&$hash_parentne'--cc') {6251# commitdiff with two commits given6252my$hash_parent_short=$hash_parent;6253if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {6254$hash_parent_short=substr($hash_parent,0,7);6255}6256$formats_nav.=6257' (from';6258for(my$i=0;$i< @{$co{'parents'}};$i++) {6259if($co{'parents'}[$i]eq$hash_parent) {6260$formats_nav.=' parent '. ($i+1);6261last;6262}6263}6264$formats_nav.=': '.6265$cgi->a({-href => href(action=>"commitdiff",6266 hash=>$hash_parent)},6267 esc_html($hash_parent_short)) .6268')';6269}elsif(!$co{'parent'}) {6270# --root commitdiff6271$formats_nav.=' (initial)';6272}elsif(scalar@{$co{'parents'}} ==1) {6273# single parent commit6274$formats_nav.=6275' (parent: '.6276$cgi->a({-href => href(action=>"commitdiff",6277 hash=>$co{'parent'})},6278 esc_html(substr($co{'parent'},0,7))) .6279')';6280}else{6281# merge commit6282if($hash_parenteq'--cc') {6283$formats_nav.=' | '.6284$cgi->a({-href => href(action=>"commitdiff",6285 hash=>$hash, hash_parent=>'-c')},6286'combined');6287}else{# $hash_parent eq '-c'6288$formats_nav.=' | '.6289$cgi->a({-href => href(action=>"commitdiff",6290 hash=>$hash, hash_parent=>'--cc')},6291'compact');6292}6293$formats_nav.=6294' (merge: '.6295join(' ',map{6296$cgi->a({-href => href(action=>"commitdiff",6297 hash=>$_)},6298 esc_html(substr($_,0,7)));6299} @{$co{'parents'}} ) .6300')';6301}6302}63036304my$hash_parent_param=$hash_parent;6305if(!defined$hash_parent_param) {6306# --cc for multiple parents, --root for parentless6307$hash_parent_param=6308@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';6309}63106311# read commitdiff6312my$fd;6313my@difftree;6314if($formateq'html') {6315open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6316"--no-commit-id","--patch-with-raw","--full-index",6317$hash_parent_param,$hash,"--"6318or die_error(500,"Open git-diff-tree failed");63196320while(my$line= <$fd>) {6321chomp$line;6322# empty line ends raw part of diff-tree output6323last unless$line;6324push@difftree,scalar parse_difftree_raw_line($line);6325}63266327}elsif($formateq'plain') {6328open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6329'-p',$hash_parent_param,$hash,"--"6330or die_error(500,"Open git-diff-tree failed");6331}elsif($formateq'patch') {6332# For commit ranges, we limit the output to the number of6333# patches specified in the 'patches' feature.6334# For single commits, we limit the output to a single patch,6335# diverging from the git-format-patch default.6336my@commit_spec= ();6337if($hash_parent) {6338if($patch_max>0) {6339push@commit_spec,"-$patch_max";6340}6341push@commit_spec,'-n',"$hash_parent..$hash";6342}else{6343if($params{-single}) {6344push@commit_spec,'-1';6345}else{6346if($patch_max>0) {6347push@commit_spec,"-$patch_max";6348}6349push@commit_spec,"-n";6350}6351push@commit_spec,'--root',$hash;6352}6353open$fd,"-|", git_cmd(),"format-patch",@diff_opts,6354'--encoding=utf8','--stdout',@commit_spec6355or die_error(500,"Open git-format-patch failed");6356}else{6357 die_error(400,"Unknown commitdiff format");6358}63596360# non-textual hash id's can be cached6361my$expires;6362if($hash=~m/^[0-9a-fA-F]{40}$/) {6363$expires="+1d";6364}63656366# write commit message6367if($formateq'html') {6368my$refs= git_get_references();6369my$ref= format_ref_marker($refs,$co{'id'});63706371 git_header_html(undef,$expires);6372 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);6373 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);6374print"<div class=\"title_text\">\n".6375"<table class=\"object_header\">\n";6376 git_print_authorship_rows(\%co);6377print"</table>".6378"</div>\n";6379print"<div class=\"page_body\">\n";6380if(@{$co{'comment'}} >1) {6381print"<div class=\"log\">\n";6382 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);6383print"</div>\n";# class="log"6384}63856386}elsif($formateq'plain') {6387my$refs= git_get_references("tags");6388my$tagname= git_get_rev_name_tags($hash);6389my$filename= basename($project) ."-$hash.patch";63906391print$cgi->header(6392-type =>'text/plain',6393-charset =>'utf-8',6394-expires =>$expires,6395-content_disposition =>'inline; filename="'."$filename".'"');6396my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});6397print"From: ". to_utf8($co{'author'}) ."\n";6398print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";6399print"Subject: ". to_utf8($co{'title'}) ."\n";64006401print"X-Git-Tag:$tagname\n"if$tagname;6402print"X-Git-Url: ".$cgi->self_url() ."\n\n";64036404foreachmy$line(@{$co{'comment'}}) {6405print to_utf8($line) ."\n";6406}6407print"---\n\n";6408}elsif($formateq'patch') {6409my$filename= basename($project) ."-$hash.patch";64106411print$cgi->header(6412-type =>'text/plain',6413-charset =>'utf-8',6414-expires =>$expires,6415-content_disposition =>'inline; filename="'."$filename".'"');6416}64176418# write patch6419if($formateq'html') {6420my$use_parents= !defined$hash_parent||6421$hash_parenteq'-c'||$hash_parenteq'--cc';6422 git_difftree_body(\@difftree,$hash,6423$use_parents? @{$co{'parents'}} :$hash_parent);6424print"<br/>\n";64256426 git_patchset_body($fd, \@difftree,$hash,6427$use_parents? @{$co{'parents'}} :$hash_parent);6428close$fd;6429print"</div>\n";# class="page_body"6430 git_footer_html();64316432}elsif($formateq'plain') {6433local$/=undef;6434print<$fd>;6435close$fd6436or print"Reading git-diff-tree failed\n";6437}elsif($formateq'patch') {6438local$/=undef;6439print<$fd>;6440close$fd6441or print"Reading git-format-patch failed\n";6442}6443}64446445sub git_commitdiff_plain {6446 git_commitdiff(-format =>'plain');6447}64486449# format-patch-style patches6450sub git_patch {6451 git_commitdiff(-format =>'patch', -single =>1);6452}64536454sub git_patches {6455 git_commitdiff(-format =>'patch');6456}64576458sub git_history {6459 git_log_generic('history', \&git_history_body,6460$hash_base,$hash_parent_base,6461$file_name,$hash);6462}64636464sub git_search {6465 gitweb_check_feature('search')or die_error(403,"Search is disabled");6466if(!defined$searchtext) {6467 die_error(400,"Text field is empty");6468}6469if(!defined$hash) {6470$hash= git_get_head_hash($project);6471}6472my%co= parse_commit($hash);6473if(!%co) {6474 die_error(404,"Unknown commit object");6475}6476if(!defined$page) {6477$page=0;6478}64796480$searchtype||='commit';6481if($searchtypeeq'pickaxe') {6482# pickaxe may take all resources of your box and run for several minutes6483# with every query - so decide by yourself how public you make this feature6484 gitweb_check_feature('pickaxe')6485or die_error(403,"Pickaxe is disabled");6486}6487if($searchtypeeq'grep') {6488 gitweb_check_feature('grep')6489or die_error(403,"Grep is disabled");6490}64916492 git_header_html();64936494if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {6495my$greptype;6496if($searchtypeeq'commit') {6497$greptype="--grep=";6498}elsif($searchtypeeq'author') {6499$greptype="--author=";6500}elsif($searchtypeeq'committer') {6501$greptype="--committer=";6502}6503$greptype.=$searchtext;6504my@commitlist= parse_commits($hash,101, (100*$page),undef,6505$greptype,'--regexp-ignore-case',6506$search_use_regexp?'--extended-regexp':'--fixed-strings');65076508my$paging_nav='';6509if($page>0) {6510$paging_nav.=6511$cgi->a({-href => href(action=>"search", hash=>$hash,6512 searchtext=>$searchtext,6513 searchtype=>$searchtype)},6514"first");6515$paging_nav.=" ⋅ ".6516$cgi->a({-href => href(-replay=>1, page=>$page-1),6517-accesskey =>"p", -title =>"Alt-p"},"prev");6518}else{6519$paging_nav.="first";6520$paging_nav.=" ⋅ prev";6521}6522my$next_link='';6523if($#commitlist>=100) {6524$next_link=6525$cgi->a({-href => href(-replay=>1, page=>$page+1),6526-accesskey =>"n", -title =>"Alt-n"},"next");6527$paging_nav.=" ⋅$next_link";6528}else{6529$paging_nav.=" ⋅ next";6530}65316532 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6533 git_print_header_div('commit', esc_html($co{'title'}),$hash);6534if($page==0&& !@commitlist) {6535print"<p>No match.</p>\n";6536}else{6537 git_search_grep_body(\@commitlist,0,99,$next_link);6538}6539}65406541if($searchtypeeq'pickaxe') {6542 git_print_page_nav('','',$hash,$co{'tree'},$hash);6543 git_print_header_div('commit', esc_html($co{'title'}),$hash);65446545print"<table class=\"pickaxe search\">\n";6546my$alternate=1;6547local$/="\n";6548open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6549'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6550($search_use_regexp?'--pickaxe-regex': ());6551undef%co;6552my@files;6553while(my$line= <$fd>) {6554chomp$line;6555next unless$line;65566557my%set= parse_difftree_raw_line($line);6558if(defined$set{'commit'}) {6559# finish previous commit6560if(%co) {6561print"</td>\n".6562"<td class=\"link\">".6563$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6564" | ".6565$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6566print"</td>\n".6567"</tr>\n";6568}65696570if($alternate) {6571print"<tr class=\"dark\">\n";6572}else{6573print"<tr class=\"light\">\n";6574}6575$alternate^=1;6576%co= parse_commit($set{'commit'});6577my$author= chop_and_escape_str($co{'author_name'},15,5);6578print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6579"<td><i>$author</i></td>\n".6580"<td>".6581$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6582-class=>"list subject"},6583 chop_and_escape_str($co{'title'},50) ."<br/>");6584}elsif(defined$set{'to_id'}) {6585next if($set{'to_id'} =~m/^0{40}$/);65866587print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6588 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6589-class=>"list"},6590"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6591"<br/>\n";6592}6593}6594close$fd;65956596# finish last commit (warning: repetition!)6597if(%co) {6598print"</td>\n".6599"<td class=\"link\">".6600$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6601" | ".6602$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6603print"</td>\n".6604"</tr>\n";6605}66066607print"</table>\n";6608}66096610if($searchtypeeq'grep') {6611 git_print_page_nav('','',$hash,$co{'tree'},$hash);6612 git_print_header_div('commit', esc_html($co{'title'}),$hash);66136614print"<table class=\"grep_search\">\n";6615my$alternate=1;6616my$matches=0;6617local$/="\n";6618open my$fd,"-|", git_cmd(),'grep','-n',6619$search_use_regexp? ('-E','-i') :'-F',6620$searchtext,$co{'tree'};6621my$lastfile='';6622while(my$line= <$fd>) {6623chomp$line;6624my($file,$lno,$ltext,$binary);6625last if($matches++>1000);6626if($line=~/^Binary file (.+) matches$/) {6627$file=$1;6628$binary=1;6629}else{6630(undef,$file,$lno,$ltext) =split(/:/,$line,4);6631}6632if($filene$lastfile) {6633$lastfileand print"</td></tr>\n";6634if($alternate++) {6635print"<tr class=\"dark\">\n";6636}else{6637print"<tr class=\"light\">\n";6638}6639print"<td class=\"list\">".6640$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6641 file_name=>"$file"),6642-class=>"list"}, esc_path($file));6643print"</td><td>\n";6644$lastfile=$file;6645}6646if($binary) {6647print"<div class=\"binary\">Binary file</div>\n";6648}else{6649$ltext= untabify($ltext);6650if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6651$ltext= esc_html($1, -nbsp=>1);6652$ltext.='<span class="match">';6653$ltext.= esc_html($2, -nbsp=>1);6654$ltext.='</span>';6655$ltext.= esc_html($3, -nbsp=>1);6656}else{6657$ltext= esc_html($ltext, -nbsp=>1);6658}6659print"<div class=\"pre\">".6660$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6661 file_name=>"$file").'#l'.$lno,6662-class=>"linenr"},sprintf('%4i',$lno))6663.' '.$ltext."</div>\n";6664}6665}6666if($lastfile) {6667print"</td></tr>\n";6668if($matches>1000) {6669print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6670}6671}else{6672print"<div class=\"diff nodifferences\">No matches found</div>\n";6673}6674close$fd;66756676print"</table>\n";6677}6678 git_footer_html();6679}66806681sub git_search_help {6682 git_header_html();6683 git_print_page_nav('','',$hash,$hash,$hash);6684print<<EOT;6685<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6686regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6687the pattern entered is recognized as the POSIX extended6688<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6689insensitive).</p>6690<dl>6691<dt><b>commit</b></dt>6692<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6693EOT6694my$have_grep= gitweb_check_feature('grep');6695if($have_grep) {6696print<<EOT;6697<dt><b>grep</b></dt>6698<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6699 a different one) are searched for the given pattern. On large trees, this search can take6700a while and put some strain on the server, so please use it with some consideration. Note that6701due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6702case-sensitive.</dd>6703EOT6704}6705print<<EOT;6706<dt><b>author</b></dt>6707<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6708<dt><b>committer</b></dt>6709<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6710EOT6711my$have_pickaxe= gitweb_check_feature('pickaxe');6712if($have_pickaxe) {6713print<<EOT;6714<dt><b>pickaxe</b></dt>6715<dd>All commits that caused the string to appear or disappear from any file (changes that6716added, removed or "modified" the string) will be listed. This search can take a while and6717takes a lot of strain on the server, so please use it wisely. Note that since you may be6718interested even in changes just changing the case as well, this search is case sensitive.</dd>6719EOT6720}6721print"</dl>\n";6722 git_footer_html();6723}67246725sub git_shortlog {6726 git_log_generic('shortlog', \&git_shortlog_body,6727$hash,$hash_parent);6728}67296730## ......................................................................6731## feeds (RSS, Atom; OPML)67326733sub git_feed {6734my$format=shift||'atom';6735my$have_blame= gitweb_check_feature('blame');67366737# Atom: http://www.atomenabled.org/developers/syndication/6738# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6739if($formatne'rss'&&$formatne'atom') {6740 die_error(400,"Unknown web feed format");6741}67426743# log/feed of current (HEAD) branch, log of given branch, history of file/directory6744my$head=$hash||'HEAD';6745my@commitlist= parse_commits($head,150,0,$file_name);67466747my%latest_commit;6748my%latest_date;6749my$content_type="application/$format+xml";6750if(defined$cgi->http('HTTP_ACCEPT') &&6751$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6752# browser (feed reader) prefers text/xml6753$content_type='text/xml';6754}6755if(defined($commitlist[0])) {6756%latest_commit= %{$commitlist[0]};6757my$latest_epoch=$latest_commit{'committer_epoch'};6758%latest_date= parse_date($latest_epoch);6759my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6760if(defined$if_modified) {6761my$since;6762if(eval{require HTTP::Date;1; }) {6763$since= HTTP::Date::str2time($if_modified);6764}elsif(eval{require Time::ParseDate;1; }) {6765$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6766}6767if(defined$since&&$latest_epoch<=$since) {6768print$cgi->header(6769-type =>$content_type,6770-charset =>'utf-8',6771-last_modified =>$latest_date{'rfc2822'},6772-status =>'304 Not Modified');6773return;6774}6775}6776print$cgi->header(6777-type =>$content_type,6778-charset =>'utf-8',6779-last_modified =>$latest_date{'rfc2822'});6780}else{6781print$cgi->header(6782-type =>$content_type,6783-charset =>'utf-8');6784}67856786# Optimization: skip generating the body if client asks only6787# for Last-Modified date.6788return if($cgi->request_method()eq'HEAD');67896790# header variables6791my$title="$site_name-$project/$action";6792my$feed_type='log';6793if(defined$hash) {6794$title.=" - '$hash'";6795$feed_type='branch log';6796if(defined$file_name) {6797$title.=" ::$file_name";6798$feed_type='history';6799}6800}elsif(defined$file_name) {6801$title.=" -$file_name";6802$feed_type='history';6803}6804$title.="$feed_type";6805my$descr= git_get_project_description($project);6806if(defined$descr) {6807$descr= esc_html($descr);6808}else{6809$descr="$project".6810($formateq'rss'?'RSS':'Atom') .6811" feed";6812}6813my$owner= git_get_project_owner($project);6814$owner= esc_html($owner);68156816#header6817my$alt_url;6818if(defined$file_name) {6819$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6820}elsif(defined$hash) {6821$alt_url= href(-full=>1, action=>"log", hash=>$hash);6822}else{6823$alt_url= href(-full=>1, action=>"summary");6824}6825print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6826if($formateq'rss') {6827print<<XML;6828<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6829<channel>6830XML6831print"<title>$title</title>\n".6832"<link>$alt_url</link>\n".6833"<description>$descr</description>\n".6834"<language>en</language>\n".6835# project owner is responsible for 'editorial' content6836"<managingEditor>$owner</managingEditor>\n";6837if(defined$logo||defined$favicon) {6838# prefer the logo to the favicon, since RSS6839# doesn't allow both6840my$img= esc_url($logo||$favicon);6841print"<image>\n".6842"<url>$img</url>\n".6843"<title>$title</title>\n".6844"<link>$alt_url</link>\n".6845"</image>\n";6846}6847if(%latest_date) {6848print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6849print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6850}6851print"<generator>gitweb v.$version/$git_version</generator>\n";6852}elsif($formateq'atom') {6853print<<XML;6854<feed xmlns="http://www.w3.org/2005/Atom">6855XML6856print"<title>$title</title>\n".6857"<subtitle>$descr</subtitle>\n".6858'<link rel="alternate" type="text/html" href="'.6859$alt_url.'" />'."\n".6860'<link rel="self" type="'.$content_type.'" href="'.6861$cgi->self_url() .'" />'."\n".6862"<id>". href(-full=>1) ."</id>\n".6863# use project owner for feed author6864"<author><name>$owner</name></author>\n";6865if(defined$favicon) {6866print"<icon>". esc_url($favicon) ."</icon>\n";6867}6868if(defined$logo_url) {6869# not twice as wide as tall: 72 x 27 pixels6870print"<logo>". esc_url($logo) ."</logo>\n";6871}6872if(!%latest_date) {6873# dummy date to keep the feed valid until commits trickle in:6874print"<updated>1970-01-01T00:00:00Z</updated>\n";6875}else{6876print"<updated>$latest_date{'iso-8601'}</updated>\n";6877}6878print"<generator version='$version/$git_version'>gitweb</generator>\n";6879}68806881# contents6882for(my$i=0;$i<=$#commitlist;$i++) {6883my%co= %{$commitlist[$i]};6884my$commit=$co{'id'};6885# we read 150, we always show 30 and the ones more recent than 48 hours6886if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6887last;6888}6889my%cd= parse_date($co{'author_epoch'});68906891# get list of changed files6892open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6893$co{'parent'} ||"--root",6894$co{'id'},"--", (defined$file_name?$file_name: ())6895ornext;6896my@difftree=map{chomp;$_} <$fd>;6897close$fd6898ornext;68996900# print element (entry, item)6901my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6902if($formateq'rss') {6903print"<item>\n".6904"<title>". esc_html($co{'title'}) ."</title>\n".6905"<author>". esc_html($co{'author'}) ."</author>\n".6906"<pubDate>$cd{'rfc2822'}</pubDate>\n".6907"<guid isPermaLink=\"true\">$co_url</guid>\n".6908"<link>$co_url</link>\n".6909"<description>". esc_html($co{'title'}) ."</description>\n".6910"<content:encoded>".6911"<![CDATA[\n";6912}elsif($formateq'atom') {6913print"<entry>\n".6914"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6915"<updated>$cd{'iso-8601'}</updated>\n".6916"<author>\n".6917" <name>". esc_html($co{'author_name'}) ."</name>\n";6918if($co{'author_email'}) {6919print" <email>". esc_html($co{'author_email'}) ."</email>\n";6920}6921print"</author>\n".6922# use committer for contributor6923"<contributor>\n".6924" <name>". esc_html($co{'committer_name'}) ."</name>\n";6925if($co{'committer_email'}) {6926print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6927}6928print"</contributor>\n".6929"<published>$cd{'iso-8601'}</published>\n".6930"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6931"<id>$co_url</id>\n".6932"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6933"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6934}6935my$comment=$co{'comment'};6936print"<pre>\n";6937foreachmy$line(@$comment) {6938$line= esc_html($line);6939print"$line\n";6940}6941print"</pre><ul>\n";6942foreachmy$difftree_line(@difftree) {6943my%difftree= parse_difftree_raw_line($difftree_line);6944next if!$difftree{'from_id'};69456946my$file=$difftree{'file'} ||$difftree{'to_file'};69476948print"<li>".6949"[".6950$cgi->a({-href => href(-full=>1, action=>"blobdiff",6951 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6952 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},6953 file_name=>$file, file_parent=>$difftree{'from_file'}),6954-title =>"diff"},'D');6955if($have_blame) {6956print$cgi->a({-href => href(-full=>1, action=>"blame",6957 file_name=>$file, hash_base=>$commit),6958-title =>"blame"},'B');6959}6960# if this is not a feed of a file history6961if(!defined$file_name||$file_namene$file) {6962print$cgi->a({-href => href(-full=>1, action=>"history",6963 file_name=>$file, hash=>$commit),6964-title =>"history"},'H');6965}6966$file= esc_path($file);6967print"] ".6968"$file</li>\n";6969}6970if($formateq'rss') {6971print"</ul>]]>\n".6972"</content:encoded>\n".6973"</item>\n";6974}elsif($formateq'atom') {6975print"</ul>\n</div>\n".6976"</content>\n".6977"</entry>\n";6978}6979}69806981# end of feed6982if($formateq'rss') {6983print"</channel>\n</rss>\n";6984}elsif($formateq'atom') {6985print"</feed>\n";6986}6987}69886989sub git_rss {6990 git_feed('rss');6991}69926993sub git_atom {6994 git_feed('atom');6995}69966997sub git_opml {6998my@list= git_get_projects_list();69997000print$cgi->header(7001-type =>'text/xml',7002-charset =>'utf-8',7003-content_disposition =>'inline; filename="opml.xml"');70047005print<<XML;7006<?xml version="1.0" encoding="utf-8"?>7007<opml version="1.0">7008<head>7009 <title>$site_nameOPML Export</title>7010</head>7011<body>7012<outline text="git RSS feeds">7013XML70147015foreachmy$pr(@list) {7016my%proj=%$pr;7017my$head= git_get_head_hash($proj{'path'});7018if(!defined$head) {7019next;7020}7021$git_dir="$projectroot/$proj{'path'}";7022my%co= parse_commit($head);7023if(!%co) {7024next;7025}70267027my$path= esc_html(chop_str($proj{'path'},25,5));7028my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);7029my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);7030print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";7031}7032print<<XML;7033</outline>7034</body>7035</opml>7036XML7037}