1#!/usr/bin/perl 2 3# gitweb - simple web interface to track changes in git repositories 4# 5# (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org> 6# (C) 2005, Christian Gierke 7# 8# This program is licensed under the GPLv2 9 10use5.008; 11use strict; 12use warnings; 13use CGI qw(:standard :escapeHTML -nosticky); 14use CGI::Util qw(unescape); 15use CGI::Carp qw(fatalsToBrowser set_message); 16use Encode; 17use Fcntl ':mode'; 18use File::Find qw(); 19use File::Basename qw(basename); 20use Time::HiRes qw(gettimeofday tv_interval); 21binmode STDOUT,':utf8'; 22 23our$t0= [ gettimeofday() ]; 24our$number_of_git_cmds=0; 25 26BEGIN{ 27 CGI->compile()if$ENV{'MOD_PERL'}; 28} 29 30our$version="++GIT_VERSION++"; 31 32our($my_url,$my_uri,$base_url,$path_info,$home_link); 33sub evaluate_uri { 34our$cgi; 35 36our$my_url=$cgi->url(); 37our$my_uri=$cgi->url(-absolute =>1); 38 39# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 40# needed and used only for URLs with nonempty PATH_INFO 41our$base_url=$my_url; 42 43# When the script is used as DirectoryIndex, the URL does not contain the name 44# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 45# have to do it ourselves. We make $path_info global because it's also used 46# later on. 47# 48# Another issue with the script being the DirectoryIndex is that the resulting 49# $my_url data is not the full script URL: this is good, because we want 50# generated links to keep implying the script name if it wasn't explicitly 51# indicated in the URL we're handling, but it means that $my_url cannot be used 52# as base URL. 53# Therefore, if we needed to strip PATH_INFO, then we know that we have 54# to build the base URL ourselves: 55our$path_info= decode_utf8($ENV{"PATH_INFO"}); 56if($path_info) { 57# $path_info has already been URL-decoded by the web server, but 58# $my_url and $my_uri have not. URL-decode them so we can properly 59# strip $path_info. 60$my_url= unescape($my_url); 61$my_uri= unescape($my_uri); 62if($my_url=~ s,\Q$path_info\E$,, && 63$my_uri=~ s,\Q$path_info\E$,, && 64defined$ENV{'SCRIPT_NAME'}) { 65$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 66} 67} 68 69# target of the home link on top of all pages 70our$home_link=$my_uri||"/"; 71} 72 73# core git executable to use 74# this can just be "git" if your webserver has a sensible PATH 75our$GIT="++GIT_BINDIR++/git"; 76 77# absolute fs-path which will be prepended to the project path 78#our $projectroot = "/pub/scm"; 79our$projectroot="++GITWEB_PROJECTROOT++"; 80 81# fs traversing limit for getting project list 82# the number is relative to the projectroot 83our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 84 85# string of the home link on top of all pages 86our$home_link_str="++GITWEB_HOME_LINK_STR++"; 87 88# name of your site or organization to appear in page titles 89# replace this with something more descriptive for clearer bookmarks 90our$site_name="++GITWEB_SITENAME++" 91|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 92 93# html snippet to include in the <head> section of each page 94our$site_html_head_string="++GITWEB_SITE_HTML_HEAD_STRING++"; 95# filename of html text to include at top of each page 96our$site_header="++GITWEB_SITE_HEADER++"; 97# html text to include at home page 98our$home_text="++GITWEB_HOMETEXT++"; 99# filename of html text to include at bottom of each page 100our$site_footer="++GITWEB_SITE_FOOTER++"; 101 102# URI of stylesheets 103our@stylesheets= ("++GITWEB_CSS++"); 104# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 105our$stylesheet=undef; 106# URI of GIT logo (72x27 size) 107our$logo="++GITWEB_LOGO++"; 108# URI of GIT favicon, assumed to be image/png type 109our$favicon="++GITWEB_FAVICON++"; 110# URI of gitweb.js (JavaScript code for gitweb) 111our$javascript="++GITWEB_JS++"; 112 113# URI and label (title) of GIT logo link 114#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 115#our $logo_label = "git documentation"; 116our$logo_url="http://git-scm.com/"; 117our$logo_label="git homepage"; 118 119# source of projects list 120our$projects_list="++GITWEB_LIST++"; 121 122# the width (in characters) of the projects list "Description" column 123our$projects_list_description_width=25; 124 125# group projects by category on the projects list 126# (enabled if this variable evaluates to true) 127our$projects_list_group_categories=0; 128 129# default category if none specified 130# (leave the empty string for no category) 131our$project_list_default_category=""; 132 133# default order of projects list 134# valid values are none, project, descr, owner, and age 135our$default_projects_order="project"; 136 137# show repository only if this file exists 138# (only effective if this variable evaluates to true) 139our$export_ok="++GITWEB_EXPORT_OK++"; 140 141# don't generate age column on the projects list page 142our$omit_age_column=0; 143 144# don't generate information about owners of repositories 145our$omit_owner=0; 146 147# show repository only if this subroutine returns true 148# when given the path to the project, for example: 149# sub { return -e "$_[0]/git-daemon-export-ok"; } 150our$export_auth_hook=undef; 151 152# only allow viewing of repositories also shown on the overview page 153our$strict_export="++GITWEB_STRICT_EXPORT++"; 154 155# list of git base URLs used for URL to where fetch project from, 156# i.e. full URL is "$git_base_url/$project" 157our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 158 159# default blob_plain mimetype and default charset for text/plain blob 160our$default_blob_plain_mimetype='text/plain'; 161our$default_text_plain_charset=undef; 162 163# file to use for guessing MIME types before trying /etc/mime.types 164# (relative to the current git repository) 165our$mimetypes_file=undef; 166 167# assume this charset if line contains non-UTF-8 characters; 168# it should be valid encoding (see Encoding::Supported(3pm) for list), 169# for which encoding all byte sequences are valid, for example 170# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 171# could be even 'utf-8' for the old behavior) 172our$fallback_encoding='latin1'; 173 174# rename detection options for git-diff and git-diff-tree 175# - default is '-M', with the cost proportional to 176# (number of removed files) * (number of new files). 177# - more costly is '-C' (which implies '-M'), with the cost proportional to 178# (number of changed files + number of removed files) * (number of new files) 179# - even more costly is '-C', '--find-copies-harder' with cost 180# (number of files in the original tree) * (number of new files) 181# - one might want to include '-B' option, e.g. '-B', '-M' 182our@diff_opts= ('-M');# taken from git_commit 183 184# Disables features that would allow repository owners to inject script into 185# the gitweb domain. 186our$prevent_xss=0; 187 188# Path to the highlight executable to use (must be the one from 189# http://www.andre-simon.de due to assumptions about parameters and output). 190# Useful if highlight is not installed on your webserver's PATH. 191# [Default: highlight] 192our$highlight_bin="++HIGHLIGHT_BIN++"; 193 194# information about snapshot formats that gitweb is capable of serving 195our%known_snapshot_formats= ( 196# name => { 197# 'display' => display name, 198# 'type' => mime type, 199# 'suffix' => filename suffix, 200# 'format' => --format for git-archive, 201# 'compressor' => [compressor command and arguments] 202# (array reference, optional) 203# 'disabled' => boolean (optional)} 204# 205'tgz'=> { 206'display'=>'tar.gz', 207'type'=>'application/x-gzip', 208'suffix'=>'.tar.gz', 209'format'=>'tar', 210'compressor'=> ['gzip','-n']}, 211 212'tbz2'=> { 213'display'=>'tar.bz2', 214'type'=>'application/x-bzip2', 215'suffix'=>'.tar.bz2', 216'format'=>'tar', 217'compressor'=> ['bzip2']}, 218 219'txz'=> { 220'display'=>'tar.xz', 221'type'=>'application/x-xz', 222'suffix'=>'.tar.xz', 223'format'=>'tar', 224'compressor'=> ['xz'], 225'disabled'=>1}, 226 227'zip'=> { 228'display'=>'zip', 229'type'=>'application/x-zip', 230'suffix'=>'.zip', 231'format'=>'zip'}, 232); 233 234# Aliases so we understand old gitweb.snapshot values in repository 235# configuration. 236our%known_snapshot_format_aliases= ( 237'gzip'=>'tgz', 238'bzip2'=>'tbz2', 239'xz'=>'txz', 240 241# backward compatibility: legacy gitweb config support 242'x-gzip'=>undef,'gz'=>undef, 243'x-bzip2'=>undef,'bz2'=>undef, 244'x-zip'=>undef,''=>undef, 245); 246 247# Pixel sizes for icons and avatars. If the default font sizes or lineheights 248# are changed, it may be appropriate to change these values too via 249# $GITWEB_CONFIG. 250our%avatar_size= ( 251'default'=>16, 252'double'=>32 253); 254 255# Used to set the maximum load that we will still respond to gitweb queries. 256# If server load exceed this value then return "503 server busy" error. 257# If gitweb cannot determined server load, it is taken to be 0. 258# Leave it undefined (or set to 'undef') to turn off load checking. 259our$maxload=300; 260 261# configuration for 'highlight' (http://www.andre-simon.de/) 262# match by basename 263our%highlight_basename= ( 264#'Program' => 'py', 265#'Library' => 'py', 266'SConstruct'=>'py',# SCons equivalent of Makefile 267'Makefile'=>'make', 268); 269# match by extension 270our%highlight_ext= ( 271# main extensions, defining name of syntax; 272# see files in /usr/share/highlight/langDefs/ directory 273(map{$_=>$_}qw(py rb java css js tex bib xml awk bat ini spec tcl sql)), 274# alternate extensions, see /etc/highlight/filetypes.conf 275(map{$_=>'c'}qw(c h)), 276(map{$_=>'sh'}qw(sh bash zsh ksh)), 277(map{$_=>'cpp'}qw(cpp cxx c++ cc)), 278(map{$_=>'php'}qw(php php3 php4 php5 phps)), 279(map{$_=>'pl'}qw(pl perl pm)),# perhaps also 'cgi' 280(map{$_=>'make'}qw(make mak mk)), 281(map{$_=>'xml'}qw(xml xhtml html htm)), 282); 283 284# You define site-wide feature defaults here; override them with 285# $GITWEB_CONFIG as necessary. 286our%feature= ( 287# feature => { 288# 'sub' => feature-sub (subroutine), 289# 'override' => allow-override (boolean), 290# 'default' => [ default options...] (array reference)} 291# 292# if feature is overridable (it means that allow-override has true value), 293# then feature-sub will be called with default options as parameters; 294# return value of feature-sub indicates if to enable specified feature 295# 296# if there is no 'sub' key (no feature-sub), then feature cannot be 297# overridden 298# 299# use gitweb_get_feature(<feature>) to retrieve the <feature> value 300# (an array) or gitweb_check_feature(<feature>) to check if <feature> 301# is enabled 302 303# Enable the 'blame' blob view, showing the last commit that modified 304# each line in the file. This can be very CPU-intensive. 305 306# To enable system wide have in $GITWEB_CONFIG 307# $feature{'blame'}{'default'} = [1]; 308# To have project specific config enable override in $GITWEB_CONFIG 309# $feature{'blame'}{'override'} = 1; 310# and in project config gitweb.blame = 0|1; 311'blame'=> { 312'sub'=>sub{ feature_bool('blame',@_) }, 313'override'=>0, 314'default'=> [0]}, 315 316# Enable the 'snapshot' link, providing a compressed archive of any 317# tree. This can potentially generate high traffic if you have large 318# project. 319 320# Value is a list of formats defined in %known_snapshot_formats that 321# you wish to offer. 322# To disable system wide have in $GITWEB_CONFIG 323# $feature{'snapshot'}{'default'} = []; 324# To have project specific config enable override in $GITWEB_CONFIG 325# $feature{'snapshot'}{'override'} = 1; 326# and in project config, a comma-separated list of formats or "none" 327# to disable. Example: gitweb.snapshot = tbz2,zip; 328'snapshot'=> { 329'sub'=> \&feature_snapshot, 330'override'=>0, 331'default'=> ['tgz']}, 332 333# Enable text search, which will list the commits which match author, 334# committer or commit text to a given string. Enabled by default. 335# Project specific override is not supported. 336# 337# Note that this controls all search features, which means that if 338# it is disabled, then 'grep' and 'pickaxe' search would also be 339# disabled. 340'search'=> { 341'override'=>0, 342'default'=> [1]}, 343 344# Enable grep search, which will list the files in currently selected 345# tree containing the given string. Enabled by default. This can be 346# potentially CPU-intensive, of course. 347# Note that you need to have 'search' feature enabled too. 348 349# To enable system wide have in $GITWEB_CONFIG 350# $feature{'grep'}{'default'} = [1]; 351# To have project specific config enable override in $GITWEB_CONFIG 352# $feature{'grep'}{'override'} = 1; 353# and in project config gitweb.grep = 0|1; 354'grep'=> { 355'sub'=>sub{ feature_bool('grep',@_) }, 356'override'=>0, 357'default'=> [1]}, 358 359# Enable the pickaxe search, which will list the commits that modified 360# a given string in a file. This can be practical and quite faster 361# alternative to 'blame', but still potentially CPU-intensive. 362# Note that you need to have 'search' feature enabled too. 363 364# To enable system wide have in $GITWEB_CONFIG 365# $feature{'pickaxe'}{'default'} = [1]; 366# To have project specific config enable override in $GITWEB_CONFIG 367# $feature{'pickaxe'}{'override'} = 1; 368# and in project config gitweb.pickaxe = 0|1; 369'pickaxe'=> { 370'sub'=>sub{ feature_bool('pickaxe',@_) }, 371'override'=>0, 372'default'=> [1]}, 373 374# Enable showing size of blobs in a 'tree' view, in a separate 375# column, similar to what 'ls -l' does. This cost a bit of IO. 376 377# To disable system wide have in $GITWEB_CONFIG 378# $feature{'show-sizes'}{'default'} = [0]; 379# To have project specific config enable override in $GITWEB_CONFIG 380# $feature{'show-sizes'}{'override'} = 1; 381# and in project config gitweb.showsizes = 0|1; 382'show-sizes'=> { 383'sub'=>sub{ feature_bool('showsizes',@_) }, 384'override'=>0, 385'default'=> [1]}, 386 387# Make gitweb use an alternative format of the URLs which can be 388# more readable and natural-looking: project name is embedded 389# directly in the path and the query string contains other 390# auxiliary information. All gitweb installations recognize 391# URL in either format; this configures in which formats gitweb 392# generates links. 393 394# To enable system wide have in $GITWEB_CONFIG 395# $feature{'pathinfo'}{'default'} = [1]; 396# Project specific override is not supported. 397 398# Note that you will need to change the default location of CSS, 399# favicon, logo and possibly other files to an absolute URL. Also, 400# if gitweb.cgi serves as your indexfile, you will need to force 401# $my_uri to contain the script name in your $GITWEB_CONFIG. 402'pathinfo'=> { 403'override'=>0, 404'default'=> [0]}, 405 406# Make gitweb consider projects in project root subdirectories 407# to be forks of existing projects. Given project $projname.git, 408# projects matching $projname/*.git will not be shown in the main 409# projects list, instead a '+' mark will be added to $projname 410# there and a 'forks' view will be enabled for the project, listing 411# all the forks. If project list is taken from a file, forks have 412# to be listed after the main project. 413 414# To enable system wide have in $GITWEB_CONFIG 415# $feature{'forks'}{'default'} = [1]; 416# Project specific override is not supported. 417'forks'=> { 418'override'=>0, 419'default'=> [0]}, 420 421# Insert custom links to the action bar of all project pages. 422# This enables you mainly to link to third-party scripts integrating 423# into gitweb; e.g. git-browser for graphical history representation 424# or custom web-based repository administration interface. 425 426# The 'default' value consists of a list of triplets in the form 427# (label, link, position) where position is the label after which 428# to insert the link and link is a format string where %n expands 429# to the project name, %f to the project path within the filesystem, 430# %h to the current hash (h gitweb parameter) and %b to the current 431# hash base (hb gitweb parameter); %% expands to %. 432 433# To enable system wide have in $GITWEB_CONFIG e.g. 434# $feature{'actions'}{'default'} = [('graphiclog', 435# '/git-browser/by-commit.html?r=%n', 'summary')]; 436# Project specific override is not supported. 437'actions'=> { 438'override'=>0, 439'default'=> []}, 440 441# Allow gitweb scan project content tags of project repository, 442# and display the popular Web 2.0-ish "tag cloud" near the projects 443# list. Note that this is something COMPLETELY different from the 444# normal Git tags. 445 446# gitweb by itself can show existing tags, but it does not handle 447# tagging itself; you need to do it externally, outside gitweb. 448# The format is described in git_get_project_ctags() subroutine. 449# You may want to install the HTML::TagCloud Perl module to get 450# a pretty tag cloud instead of just a list of tags. 451 452# To enable system wide have in $GITWEB_CONFIG 453# $feature{'ctags'}{'default'} = [1]; 454# Project specific override is not supported. 455 456# In the future whether ctags editing is enabled might depend 457# on the value, but using 1 should always mean no editing of ctags. 458'ctags'=> { 459'override'=>0, 460'default'=> [0]}, 461 462# The maximum number of patches in a patchset generated in patch 463# view. Set this to 0 or undef to disable patch view, or to a 464# negative number to remove any limit. 465 466# To disable system wide have in $GITWEB_CONFIG 467# $feature{'patches'}{'default'} = [0]; 468# To have project specific config enable override in $GITWEB_CONFIG 469# $feature{'patches'}{'override'} = 1; 470# and in project config gitweb.patches = 0|n; 471# where n is the maximum number of patches allowed in a patchset. 472'patches'=> { 473'sub'=> \&feature_patches, 474'override'=>0, 475'default'=> [16]}, 476 477# Avatar support. When this feature is enabled, views such as 478# shortlog or commit will display an avatar associated with 479# the email of the committer(s) and/or author(s). 480 481# Currently available providers are gravatar and picon. 482# If an unknown provider is specified, the feature is disabled. 483 484# Gravatar depends on Digest::MD5. 485# Picon currently relies on the indiana.edu database. 486 487# To enable system wide have in $GITWEB_CONFIG 488# $feature{'avatar'}{'default'} = ['<provider>']; 489# where <provider> is either gravatar or picon. 490# To have project specific config enable override in $GITWEB_CONFIG 491# $feature{'avatar'}{'override'} = 1; 492# and in project config gitweb.avatar = <provider>; 493'avatar'=> { 494'sub'=> \&feature_avatar, 495'override'=>0, 496'default'=> ['']}, 497 498# Enable displaying how much time and how many git commands 499# it took to generate and display page. Disabled by default. 500# Project specific override is not supported. 501'timed'=> { 502'override'=>0, 503'default'=> [0]}, 504 505# Enable turning some links into links to actions which require 506# JavaScript to run (like 'blame_incremental'). Not enabled by 507# default. Project specific override is currently not supported. 508'javascript-actions'=> { 509'override'=>0, 510'default'=> [0]}, 511 512# Enable and configure ability to change common timezone for dates 513# in gitweb output via JavaScript. Enabled by default. 514# Project specific override is not supported. 515'javascript-timezone'=> { 516'override'=>0, 517'default'=> [ 518'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 519# or undef to turn off this feature 520'gitweb_tz',# name of cookie where to store selected timezone 521'datetime',# CSS class used to mark up dates for manipulation 522]}, 523 524# Syntax highlighting support. This is based on Daniel Svensson's 525# and Sham Chukoury's work in gitweb-xmms2.git. 526# It requires the 'highlight' program present in $PATH, 527# and therefore is disabled by default. 528 529# To enable system wide have in $GITWEB_CONFIG 530# $feature{'highlight'}{'default'} = [1]; 531 532'highlight'=> { 533'sub'=>sub{ feature_bool('highlight',@_) }, 534'override'=>0, 535'default'=> [0]}, 536 537# Enable displaying of remote heads in the heads list 538 539# To enable system wide have in $GITWEB_CONFIG 540# $feature{'remote_heads'}{'default'} = [1]; 541# To have project specific config enable override in $GITWEB_CONFIG 542# $feature{'remote_heads'}{'override'} = 1; 543# and in project config gitweb.remote_heads = 0|1; 544'remote_heads'=> { 545'sub'=>sub{ feature_bool('remote_heads',@_) }, 546'override'=>0, 547'default'=> [0]}, 548); 549 550sub gitweb_get_feature { 551my($name) =@_; 552return unlessexists$feature{$name}; 553my($sub,$override,@defaults) = ( 554$feature{$name}{'sub'}, 555$feature{$name}{'override'}, 556@{$feature{$name}{'default'}}); 557# project specific override is possible only if we have project 558our$git_dir;# global variable, declared later 559if(!$override|| !defined$git_dir) { 560return@defaults; 561} 562if(!defined$sub) { 563warn"feature$nameis not overridable"; 564return@defaults; 565} 566return$sub->(@defaults); 567} 568 569# A wrapper to check if a given feature is enabled. 570# With this, you can say 571# 572# my $bool_feat = gitweb_check_feature('bool_feat'); 573# gitweb_check_feature('bool_feat') or somecode; 574# 575# instead of 576# 577# my ($bool_feat) = gitweb_get_feature('bool_feat'); 578# (gitweb_get_feature('bool_feat'))[0] or somecode; 579# 580sub gitweb_check_feature { 581return(gitweb_get_feature(@_))[0]; 582} 583 584 585sub feature_bool { 586my$key=shift; 587my($val) = git_get_project_config($key,'--bool'); 588 589if(!defined$val) { 590return($_[0]); 591}elsif($valeq'true') { 592return(1); 593}elsif($valeq'false') { 594return(0); 595} 596} 597 598sub feature_snapshot { 599my(@fmts) =@_; 600 601my($val) = git_get_project_config('snapshot'); 602 603if($val) { 604@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 605} 606 607return@fmts; 608} 609 610sub feature_patches { 611my@val= (git_get_project_config('patches','--int')); 612 613if(@val) { 614return@val; 615} 616 617return($_[0]); 618} 619 620sub feature_avatar { 621my@val= (git_get_project_config('avatar')); 622 623return@val?@val:@_; 624} 625 626# checking HEAD file with -e is fragile if the repository was 627# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 628# and then pruned. 629sub check_head_link { 630my($dir) =@_; 631my$headfile="$dir/HEAD"; 632return((-e $headfile) || 633(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 634} 635 636sub check_export_ok { 637my($dir) =@_; 638return(check_head_link($dir) && 639(!$export_ok|| -e "$dir/$export_ok") && 640(!$export_auth_hook||$export_auth_hook->($dir))); 641} 642 643# process alternate names for backward compatibility 644# filter out unsupported (unknown) snapshot formats 645sub filter_snapshot_fmts { 646my@fmts=@_; 647 648@fmts=map{ 649exists$known_snapshot_format_aliases{$_} ? 650$known_snapshot_format_aliases{$_} :$_}@fmts; 651@fmts=grep{ 652exists$known_snapshot_formats{$_} && 653!$known_snapshot_formats{$_}{'disabled'}}@fmts; 654} 655 656# If it is set to code reference, it is code that it is to be run once per 657# request, allowing updating configurations that change with each request, 658# while running other code in config file only once. 659# 660# Otherwise, if it is false then gitweb would process config file only once; 661# if it is true then gitweb config would be run for each request. 662our$per_request_config=1; 663 664# read and parse gitweb config file given by its parameter. 665# returns true on success, false on recoverable error, allowing 666# to chain this subroutine, using first file that exists. 667# dies on errors during parsing config file, as it is unrecoverable. 668sub read_config_file { 669my$filename=shift; 670return unlessdefined$filename; 671# die if there are errors parsing config file 672if(-e $filename) { 673do$filename; 674die$@if$@; 675return1; 676} 677return; 678} 679 680our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 681sub evaluate_gitweb_config { 682our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 683our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 684our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 685 686# Protect agains duplications of file names, to not read config twice. 687# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 688# there possibility of duplication of filename there doesn't matter. 689$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 690$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 691 692# Common system-wide settings for convenience. 693# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 694 read_config_file($GITWEB_CONFIG_COMMON); 695 696# Use first config file that exists. This means use the per-instance 697# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 698 read_config_file($GITWEB_CONFIG)andreturn; 699 read_config_file($GITWEB_CONFIG_SYSTEM); 700} 701 702# Get loadavg of system, to compare against $maxload. 703# Currently it requires '/proc/loadavg' present to get loadavg; 704# if it is not present it returns 0, which means no load checking. 705sub get_loadavg { 706if( -e '/proc/loadavg'){ 707open my$fd,'<','/proc/loadavg' 708orreturn0; 709my@load=split(/\s+/,scalar<$fd>); 710close$fd; 711 712# The first three columns measure CPU and IO utilization of the last one, 713# five, and 10 minute periods. The fourth column shows the number of 714# currently running processes and the total number of processes in the m/n 715# format. The last column displays the last process ID used. 716return$load[0] ||0; 717} 718# additional checks for load average should go here for things that don't export 719# /proc/loadavg 720 721return0; 722} 723 724# version of the core git binary 725our$git_version; 726sub evaluate_git_version { 727our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 728$number_of_git_cmds++; 729} 730 731sub check_loadavg { 732if(defined$maxload&& get_loadavg() >$maxload) { 733 die_error(503,"The load average on the server is too high"); 734} 735} 736 737# ====================================================================== 738# input validation and dispatch 739 740# input parameters can be collected from a variety of sources (presently, CGI 741# and PATH_INFO), so we define an %input_params hash that collects them all 742# together during validation: this allows subsequent uses (e.g. href()) to be 743# agnostic of the parameter origin 744 745our%input_params= (); 746 747# input parameters are stored with the long parameter name as key. This will 748# also be used in the href subroutine to convert parameters to their CGI 749# equivalent, and since the href() usage is the most frequent one, we store 750# the name -> CGI key mapping here, instead of the reverse. 751# 752# XXX: Warning: If you touch this, check the search form for updating, 753# too. 754 755our@cgi_param_mapping= ( 756 project =>"p", 757 action =>"a", 758 file_name =>"f", 759 file_parent =>"fp", 760 hash =>"h", 761 hash_parent =>"hp", 762 hash_base =>"hb", 763 hash_parent_base =>"hpb", 764 page =>"pg", 765 order =>"o", 766 searchtext =>"s", 767 searchtype =>"st", 768 snapshot_format =>"sf", 769 extra_options =>"opt", 770 search_use_regexp =>"sr", 771 ctag =>"by_tag", 772 diff_style =>"ds", 773 project_filter =>"pf", 774# this must be last entry (for manipulation from JavaScript) 775 javascript =>"js" 776); 777our%cgi_param_mapping=@cgi_param_mapping; 778 779# we will also need to know the possible actions, for validation 780our%actions= ( 781"blame"=> \&git_blame, 782"blame_incremental"=> \&git_blame_incremental, 783"blame_data"=> \&git_blame_data, 784"blobdiff"=> \&git_blobdiff, 785"blobdiff_plain"=> \&git_blobdiff_plain, 786"blob"=> \&git_blob, 787"blob_plain"=> \&git_blob_plain, 788"commitdiff"=> \&git_commitdiff, 789"commitdiff_plain"=> \&git_commitdiff_plain, 790"commit"=> \&git_commit, 791"forks"=> \&git_forks, 792"heads"=> \&git_heads, 793"history"=> \&git_history, 794"log"=> \&git_log, 795"patch"=> \&git_patch, 796"patches"=> \&git_patches, 797"remotes"=> \&git_remotes, 798"rss"=> \&git_rss, 799"atom"=> \&git_atom, 800"search"=> \&git_search, 801"search_help"=> \&git_search_help, 802"shortlog"=> \&git_shortlog, 803"summary"=> \&git_summary, 804"tag"=> \&git_tag, 805"tags"=> \&git_tags, 806"tree"=> \&git_tree, 807"snapshot"=> \&git_snapshot, 808"object"=> \&git_object, 809# those below don't need $project 810"opml"=> \&git_opml, 811"project_list"=> \&git_project_list, 812"project_index"=> \&git_project_index, 813); 814 815# finally, we have the hash of allowed extra_options for the commands that 816# allow them 817our%allowed_options= ( 818"--no-merges"=> [qw(rss atom log shortlog history)], 819); 820 821# fill %input_params with the CGI parameters. All values except for 'opt' 822# should be single values, but opt can be an array. We should probably 823# build an array of parameters that can be multi-valued, but since for the time 824# being it's only this one, we just single it out 825sub evaluate_query_params { 826our$cgi; 827 828while(my($name,$symbol) =each%cgi_param_mapping) { 829if($symboleq'opt') { 830$input_params{$name} = [map{ decode_utf8($_) }$cgi->param($symbol) ]; 831}else{ 832$input_params{$name} = decode_utf8($cgi->param($symbol)); 833} 834} 835} 836 837# now read PATH_INFO and update the parameter list for missing parameters 838sub evaluate_path_info { 839return ifdefined$input_params{'project'}; 840return if!$path_info; 841$path_info=~ s,^/+,,; 842return if!$path_info; 843 844# find which part of PATH_INFO is project 845my$project=$path_info; 846$project=~ s,/+$,,; 847while($project&& !check_head_link("$projectroot/$project")) { 848$project=~ s,/*[^/]*$,,; 849} 850return unless$project; 851$input_params{'project'} =$project; 852 853# do not change any parameters if an action is given using the query string 854return if$input_params{'action'}; 855$path_info=~ s,^\Q$project\E/*,,; 856 857# next, check if we have an action 858my$action=$path_info; 859$action=~ s,/.*$,,; 860if(exists$actions{$action}) { 861$path_info=~ s,^$action/*,,; 862$input_params{'action'} =$action; 863} 864 865# list of actions that want hash_base instead of hash, but can have no 866# pathname (f) parameter 867my@wants_base= ( 868'tree', 869'history', 870); 871 872# we want to catch, among others 873# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 874my($parentrefname,$parentpathname,$refname,$pathname) = 875($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 876 877# first, analyze the 'current' part 878if(defined$pathname) { 879# we got "branch:filename" or "branch:dir/" 880# we could use git_get_type(branch:pathname), but: 881# - it needs $git_dir 882# - it does a git() call 883# - the convention of terminating directories with a slash 884# makes it superfluous 885# - embedding the action in the PATH_INFO would make it even 886# more superfluous 887$pathname=~ s,^/+,,; 888if(!$pathname||substr($pathname, -1)eq"/") { 889$input_params{'action'} ||="tree"; 890$pathname=~ s,/$,,; 891}else{ 892# the default action depends on whether we had parent info 893# or not 894if($parentrefname) { 895$input_params{'action'} ||="blobdiff_plain"; 896}else{ 897$input_params{'action'} ||="blob_plain"; 898} 899} 900$input_params{'hash_base'} ||=$refname; 901$input_params{'file_name'} ||=$pathname; 902}elsif(defined$refname) { 903# we got "branch". In this case we have to choose if we have to 904# set hash or hash_base. 905# 906# Most of the actions without a pathname only want hash to be 907# set, except for the ones specified in @wants_base that want 908# hash_base instead. It should also be noted that hand-crafted 909# links having 'history' as an action and no pathname or hash 910# set will fail, but that happens regardless of PATH_INFO. 911if(defined$parentrefname) { 912# if there is parent let the default be 'shortlog' action 913# (for http://git.example.com/repo.git/A..B links); if there 914# is no parent, dispatch will detect type of object and set 915# action appropriately if required (if action is not set) 916$input_params{'action'} ||="shortlog"; 917} 918if($input_params{'action'} && 919grep{$_eq$input_params{'action'} }@wants_base) { 920$input_params{'hash_base'} ||=$refname; 921}else{ 922$input_params{'hash'} ||=$refname; 923} 924} 925 926# next, handle the 'parent' part, if present 927if(defined$parentrefname) { 928# a missing pathspec defaults to the 'current' filename, allowing e.g. 929# someproject/blobdiff/oldrev..newrev:/filename 930if($parentpathname) { 931$parentpathname=~ s,^/+,,; 932$parentpathname=~ s,/$,,; 933$input_params{'file_parent'} ||=$parentpathname; 934}else{ 935$input_params{'file_parent'} ||=$input_params{'file_name'}; 936} 937# we assume that hash_parent_base is wanted if a path was specified, 938# or if the action wants hash_base instead of hash 939if(defined$input_params{'file_parent'} || 940grep{$_eq$input_params{'action'} }@wants_base) { 941$input_params{'hash_parent_base'} ||=$parentrefname; 942}else{ 943$input_params{'hash_parent'} ||=$parentrefname; 944} 945} 946 947# for the snapshot action, we allow URLs in the form 948# $project/snapshot/$hash.ext 949# where .ext determines the snapshot and gets removed from the 950# passed $refname to provide the $hash. 951# 952# To be able to tell that $refname includes the format extension, we 953# require the following two conditions to be satisfied: 954# - the hash input parameter MUST have been set from the $refname part 955# of the URL (i.e. they must be equal) 956# - the snapshot format MUST NOT have been defined already (e.g. from 957# CGI parameter sf) 958# It's also useless to try any matching unless $refname has a dot, 959# so we check for that too 960if(defined$input_params{'action'} && 961$input_params{'action'}eq'snapshot'&& 962defined$refname&&index($refname,'.') != -1&& 963$refnameeq$input_params{'hash'} && 964!defined$input_params{'snapshot_format'}) { 965# We loop over the known snapshot formats, checking for 966# extensions. Allowed extensions are both the defined suffix 967# (which includes the initial dot already) and the snapshot 968# format key itself, with a prepended dot 969while(my($fmt,$opt) =each%known_snapshot_formats) { 970my$hash=$refname; 971unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 972next; 973} 974my$sfx=$1; 975# a valid suffix was found, so set the snapshot format 976# and reset the hash parameter 977$input_params{'snapshot_format'} =$fmt; 978$input_params{'hash'} =$hash; 979# we also set the format suffix to the one requested 980# in the URL: this way a request for e.g. .tgz returns 981# a .tgz instead of a .tar.gz 982$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 983last; 984} 985} 986} 987 988our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 989$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 990$searchtext,$search_regexp,$project_filter); 991sub evaluate_and_validate_params { 992our$action=$input_params{'action'}; 993if(defined$action) { 994if(!validate_action($action)) { 995 die_error(400,"Invalid action parameter"); 996} 997} 998 999# parameters which are pathnames1000our$project=$input_params{'project'};1001if(defined$project) {1002if(!validate_project($project)) {1003undef$project;1004 die_error(404,"No such project");1005}1006}10071008our$project_filter=$input_params{'project_filter'};1009if(defined$project_filter) {1010if(!validate_pathname($project_filter)) {1011 die_error(404,"Invalid project_filter parameter");1012}1013}10141015our$file_name=$input_params{'file_name'};1016if(defined$file_name) {1017if(!validate_pathname($file_name)) {1018 die_error(400,"Invalid file parameter");1019}1020}10211022our$file_parent=$input_params{'file_parent'};1023if(defined$file_parent) {1024if(!validate_pathname($file_parent)) {1025 die_error(400,"Invalid file parent parameter");1026}1027}10281029# parameters which are refnames1030our$hash=$input_params{'hash'};1031if(defined$hash) {1032if(!validate_refname($hash)) {1033 die_error(400,"Invalid hash parameter");1034}1035}10361037our$hash_parent=$input_params{'hash_parent'};1038if(defined$hash_parent) {1039if(!validate_refname($hash_parent)) {1040 die_error(400,"Invalid hash parent parameter");1041}1042}10431044our$hash_base=$input_params{'hash_base'};1045if(defined$hash_base) {1046if(!validate_refname($hash_base)) {1047 die_error(400,"Invalid hash base parameter");1048}1049}10501051our@extra_options= @{$input_params{'extra_options'}};1052# @extra_options is always defined, since it can only be (currently) set from1053# CGI, and $cgi->param() returns the empty array in array context if the param1054# is not set1055foreachmy$opt(@extra_options) {1056if(not exists$allowed_options{$opt}) {1057 die_error(400,"Invalid option parameter");1058}1059if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1060 die_error(400,"Invalid option parameter for this action");1061}1062}10631064our$hash_parent_base=$input_params{'hash_parent_base'};1065if(defined$hash_parent_base) {1066if(!validate_refname($hash_parent_base)) {1067 die_error(400,"Invalid hash parent base parameter");1068}1069}10701071# other parameters1072our$page=$input_params{'page'};1073if(defined$page) {1074if($page=~m/[^0-9]/) {1075 die_error(400,"Invalid page parameter");1076}1077}10781079our$searchtype=$input_params{'searchtype'};1080if(defined$searchtype) {1081if($searchtype=~m/[^a-z]/) {1082 die_error(400,"Invalid searchtype parameter");1083}1084}10851086our$search_use_regexp=$input_params{'search_use_regexp'};10871088our$searchtext=$input_params{'searchtext'};1089our$search_regexp;1090if(defined$searchtext) {1091if(length($searchtext) <2) {1092 die_error(403,"At least two characters are required for search parameter");1093}1094if($search_use_regexp) {1095$search_regexp=$searchtext;1096if(!eval{qr/$search_regexp/;1; }) {1097(my$error=$@) =~s/ at \S+ line \d+.*\n?//;1098 die_error(400,"Invalid search regexp '$search_regexp'",1099 esc_html($error));1100}1101}else{1102$search_regexp=quotemeta$searchtext;1103}1104}1105}11061107# path to the current git repository1108our$git_dir;1109sub evaluate_git_dir {1110our$git_dir="$projectroot/$project"if$project;1111}11121113our(@snapshot_fmts,$git_avatar);1114sub configure_gitweb_features {1115# list of supported snapshot formats1116our@snapshot_fmts= gitweb_get_feature('snapshot');1117@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);11181119# check that the avatar feature is set to a known provider name,1120# and for each provider check if the dependencies are satisfied.1121# if the provider name is invalid or the dependencies are not met,1122# reset $git_avatar to the empty string.1123our($git_avatar) = gitweb_get_feature('avatar');1124if($git_avatareq'gravatar') {1125$git_avatar=''unless(eval{require Digest::MD5;1; });1126}elsif($git_avatareq'picon') {1127# no dependencies1128}else{1129$git_avatar='';1130}1131}11321133# custom error handler: 'die <message>' is Internal Server Error1134sub handle_errors_html {1135my$msg=shift;# it is already HTML escaped11361137# to avoid infinite loop where error occurs in die_error,1138# change handler to default handler, disabling handle_errors_html1139 set_message("Error occured when inside die_error:\n$msg");11401141# you cannot jump out of die_error when called as error handler;1142# the subroutine set via CGI::Carp::set_message is called _after_1143# HTTP headers are already written, so it cannot write them itself1144 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1145}1146set_message(\&handle_errors_html);11471148# dispatch1149sub dispatch {1150if(!defined$action) {1151if(defined$hash) {1152$action= git_get_type($hash);1153$actionor die_error(404,"Object does not exist");1154}elsif(defined$hash_base&&defined$file_name) {1155$action= git_get_type("$hash_base:$file_name");1156$actionor die_error(404,"File or directory does not exist");1157}elsif(defined$project) {1158$action='summary';1159}else{1160$action='project_list';1161}1162}1163if(!defined($actions{$action})) {1164 die_error(400,"Unknown action");1165}1166if($action!~m/^(?:opml|project_list|project_index)$/&&1167!$project) {1168 die_error(400,"Project needed");1169}1170$actions{$action}->();1171}11721173sub reset_timer {1174our$t0= [ gettimeofday() ]1175ifdefined$t0;1176our$number_of_git_cmds=0;1177}11781179our$first_request=1;1180sub run_request {1181 reset_timer();11821183 evaluate_uri();1184if($first_request) {1185 evaluate_gitweb_config();1186 evaluate_git_version();1187}1188if($per_request_config) {1189if(ref($per_request_config)eq'CODE') {1190$per_request_config->();1191}elsif(!$first_request) {1192 evaluate_gitweb_config();1193}1194}1195 check_loadavg();11961197# $projectroot and $projects_list might be set in gitweb config file1198$projects_list||=$projectroot;11991200 evaluate_query_params();1201 evaluate_path_info();1202 evaluate_and_validate_params();1203 evaluate_git_dir();12041205 configure_gitweb_features();12061207 dispatch();1208}12091210our$is_last_request=sub{1};1211our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1212our$CGI='CGI';1213our$cgi;1214sub configure_as_fcgi {1215require CGI::Fast;1216our$CGI='CGI::Fast';12171218my$request_number=0;1219# let each child service 100 requests1220our$is_last_request=sub{ ++$request_number>100};1221}1222sub evaluate_argv {1223my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1224 configure_as_fcgi()1225if$script_name=~/\.fcgi$/;12261227return unless(@ARGV);12281229require Getopt::Long;1230 Getopt::Long::GetOptions(1231'fastcgi|fcgi|f'=> \&configure_as_fcgi,1232'nproc|n=i'=>sub{1233my($arg,$val) =@_;1234return unlesseval{require FCGI::ProcManager;1; };1235my$proc_manager= FCGI::ProcManager->new({1236 n_processes =>$val,1237});1238our$pre_listen_hook=sub{$proc_manager->pm_manage() };1239our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1240our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1241},1242);1243}12441245sub run {1246 evaluate_argv();12471248$first_request=1;1249$pre_listen_hook->()1250if$pre_listen_hook;12511252 REQUEST:1253while($cgi=$CGI->new()) {1254$pre_dispatch_hook->()1255if$pre_dispatch_hook;12561257 run_request();12581259$post_dispatch_hook->()1260if$post_dispatch_hook;1261$first_request=0;12621263last REQUEST if($is_last_request->());1264}12651266 DONE_GITWEB:12671;1268}12691270run();12711272if(defined caller) {1273# wrapped in a subroutine processing requests,1274# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1275return;1276}else{1277# pure CGI script, serving single request1278exit;1279}12801281## ======================================================================1282## action links12831284# possible values of extra options1285# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1286# -replay => 1 - start from a current view (replay with modifications)1287# -path_info => 0|1 - don't use/use path_info URL (if possible)1288# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1289sub href {1290my%params=@_;1291# default is to use -absolute url() i.e. $my_uri1292my$href=$params{-full} ?$my_url:$my_uri;12931294# implicit -replay, must be first of implicit params1295$params{-replay} =1if(keys%params==1&&$params{-anchor});12961297$params{'project'} =$projectunlessexists$params{'project'};12981299if($params{-replay}) {1300while(my($name,$symbol) =each%cgi_param_mapping) {1301if(!exists$params{$name}) {1302$params{$name} =$input_params{$name};1303}1304}1305}13061307my$use_pathinfo= gitweb_check_feature('pathinfo');1308if(defined$params{'project'} &&1309(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1310# try to put as many parameters as possible in PATH_INFO:1311# - project name1312# - action1313# - hash_parent or hash_parent_base:/file_parent1314# - hash or hash_base:/filename1315# - the snapshot_format as an appropriate suffix13161317# When the script is the root DirectoryIndex for the domain,1318# $href here would be something like http://gitweb.example.com/1319# Thus, we strip any trailing / from $href, to spare us double1320# slashes in the final URL1321$href=~ s,/$,,;13221323# Then add the project name, if present1324$href.="/".esc_path_info($params{'project'});1325delete$params{'project'};13261327# since we destructively absorb parameters, we keep this1328# boolean that remembers if we're handling a snapshot1329my$is_snapshot=$params{'action'}eq'snapshot';13301331# Summary just uses the project path URL, any other action is1332# added to the URL1333if(defined$params{'action'}) {1334$href.="/".esc_path_info($params{'action'})1335unless$params{'action'}eq'summary';1336delete$params{'action'};1337}13381339# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1340# stripping nonexistent or useless pieces1341$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1342||$params{'hash_parent'} ||$params{'hash'});1343if(defined$params{'hash_base'}) {1344if(defined$params{'hash_parent_base'}) {1345$href.= esc_path_info($params{'hash_parent_base'});1346# skip the file_parent if it's the same as the file_name1347if(defined$params{'file_parent'}) {1348if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1349delete$params{'file_parent'};1350}elsif($params{'file_parent'} !~/\.\./) {1351$href.=":/".esc_path_info($params{'file_parent'});1352delete$params{'file_parent'};1353}1354}1355$href.="..";1356delete$params{'hash_parent'};1357delete$params{'hash_parent_base'};1358}elsif(defined$params{'hash_parent'}) {1359$href.= esc_path_info($params{'hash_parent'})."..";1360delete$params{'hash_parent'};1361}13621363$href.= esc_path_info($params{'hash_base'});1364if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1365$href.=":/".esc_path_info($params{'file_name'});1366delete$params{'file_name'};1367}1368delete$params{'hash'};1369delete$params{'hash_base'};1370}elsif(defined$params{'hash'}) {1371$href.= esc_path_info($params{'hash'});1372delete$params{'hash'};1373}13741375# If the action was a snapshot, we can absorb the1376# snapshot_format parameter too1377if($is_snapshot) {1378my$fmt=$params{'snapshot_format'};1379# snapshot_format should always be defined when href()1380# is called, but just in case some code forgets, we1381# fall back to the default1382$fmt||=$snapshot_fmts[0];1383$href.=$known_snapshot_formats{$fmt}{'suffix'};1384delete$params{'snapshot_format'};1385}1386}13871388# now encode the parameters explicitly1389my@result= ();1390for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1391my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1392if(defined$params{$name}) {1393if(ref($params{$name})eq"ARRAY") {1394foreachmy$par(@{$params{$name}}) {1395push@result,$symbol."=". esc_param($par);1396}1397}else{1398push@result,$symbol."=". esc_param($params{$name});1399}1400}1401}1402$href.="?".join(';',@result)ifscalar@result;14031404# final transformation: trailing spaces must be escaped (URI-encoded)1405$href=~s/(\s+)$/CGI::escape($1)/e;14061407if($params{-anchor}) {1408$href.="#".esc_param($params{-anchor});1409}14101411return$href;1412}141314141415## ======================================================================1416## validation, quoting/unquoting and escaping14171418sub validate_action {1419my$input=shift||returnundef;1420returnundefunlessexists$actions{$input};1421return$input;1422}14231424sub validate_project {1425my$input=shift||returnundef;1426if(!validate_pathname($input) ||1427!(-d "$projectroot/$input") ||1428!check_export_ok("$projectroot/$input") ||1429($strict_export&& !project_in_list($input))) {1430returnundef;1431}else{1432return$input;1433}1434}14351436sub validate_pathname {1437my$input=shift||returnundef;14381439# no '.' or '..' as elements of path, i.e. no '.' nor '..'1440# at the beginning, at the end, and between slashes.1441# also this catches doubled slashes1442if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1443returnundef;1444}1445# no null characters1446if($input=~m!\0!) {1447returnundef;1448}1449return$input;1450}14511452sub validate_refname {1453my$input=shift||returnundef;14541455# textual hashes are O.K.1456if($input=~m/^[0-9a-fA-F]{40}$/) {1457return$input;1458}1459# it must be correct pathname1460$input= validate_pathname($input)1461orreturnundef;1462# restrictions on ref name according to git-check-ref-format1463if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1464returnundef;1465}1466return$input;1467}14681469# decode sequences of octets in utf8 into Perl's internal form,1470# which is utf-8 with utf8 flag set if needed. gitweb writes out1471# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1472sub to_utf8 {1473my$str=shift;1474returnundefunlessdefined$str;14751476if(utf8::is_utf8($str) || utf8::decode($str)) {1477return$str;1478}else{1479return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1480}1481}14821483# quote unsafe chars, but keep the slash, even when it's not1484# correct, but quoted slashes look too horrible in bookmarks1485sub esc_param {1486my$str=shift;1487returnundefunlessdefined$str;1488$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1489$str=~s/ /\+/g;1490return$str;1491}14921493# the quoting rules for path_info fragment are slightly different1494sub esc_path_info {1495my$str=shift;1496returnundefunlessdefined$str;14971498# path_info doesn't treat '+' as space (specially), but '?' must be escaped1499$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;15001501return$str;1502}15031504# quote unsafe chars in whole URL, so some characters cannot be quoted1505sub esc_url {1506my$str=shift;1507returnundefunlessdefined$str;1508$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1509$str=~s/ /\+/g;1510return$str;1511}15121513# quote unsafe characters in HTML attributes1514sub esc_attr {15151516# for XHTML conformance escaping '"' to '"' is not enough1517return esc_html(@_);1518}15191520# replace invalid utf8 character with SUBSTITUTION sequence1521sub esc_html {1522my$str=shift;1523my%opts=@_;15241525returnundefunlessdefined$str;15261527$str= to_utf8($str);1528$str=$cgi->escapeHTML($str);1529if($opts{'-nbsp'}) {1530$str=~s/ / /g;1531}1532$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1533return$str;1534}15351536# quote control characters and escape filename to HTML1537sub esc_path {1538my$str=shift;1539my%opts=@_;15401541returnundefunlessdefined$str;15421543$str= to_utf8($str);1544$str=$cgi->escapeHTML($str);1545if($opts{'-nbsp'}) {1546$str=~s/ / /g;1547}1548$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1549return$str;1550}15511552# Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)1553sub sanitize {1554my$str=shift;15551556returnundefunlessdefined$str;15571558$str= to_utf8($str);1559$str=~ s|([[:cntrl:]])|($1=~/[\t\n\r]/?$1: quot_cec($1))|eg;1560return$str;1561}15621563# Make control characters "printable", using character escape codes (CEC)1564sub quot_cec {1565my$cntrl=shift;1566my%opts=@_;1567my%es= (# character escape codes, aka escape sequences1568"\t"=>'\t',# tab (HT)1569"\n"=>'\n',# line feed (LF)1570"\r"=>'\r',# carrige return (CR)1571"\f"=>'\f',# form feed (FF)1572"\b"=>'\b',# backspace (BS)1573"\a"=>'\a',# alarm (bell) (BEL)1574"\e"=>'\e',# escape (ESC)1575"\013"=>'\v',# vertical tab (VT)1576"\000"=>'\0',# nul character (NUL)1577);1578my$chr= ( (exists$es{$cntrl})1579?$es{$cntrl}1580:sprintf('\%2x',ord($cntrl)) );1581if($opts{-nohtml}) {1582return$chr;1583}else{1584return"<span class=\"cntrl\">$chr</span>";1585}1586}15871588# Alternatively use unicode control pictures codepoints,1589# Unicode "printable representation" (PR)1590sub quot_upr {1591my$cntrl=shift;1592my%opts=@_;15931594my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1595if($opts{-nohtml}) {1596return$chr;1597}else{1598return"<span class=\"cntrl\">$chr</span>";1599}1600}16011602# git may return quoted and escaped filenames1603sub unquote {1604my$str=shift;16051606sub unq {1607my$seq=shift;1608my%es= (# character escape codes, aka escape sequences1609't'=>"\t",# tab (HT, TAB)1610'n'=>"\n",# newline (NL)1611'r'=>"\r",# return (CR)1612'f'=>"\f",# form feed (FF)1613'b'=>"\b",# backspace (BS)1614'a'=>"\a",# alarm (bell) (BEL)1615'e'=>"\e",# escape (ESC)1616'v'=>"\013",# vertical tab (VT)1617);16181619if($seq=~m/^[0-7]{1,3}$/) {1620# octal char sequence1621returnchr(oct($seq));1622}elsif(exists$es{$seq}) {1623# C escape sequence, aka character escape code1624return$es{$seq};1625}1626# quoted ordinary character1627return$seq;1628}16291630if($str=~m/^"(.*)"$/) {1631# needs unquoting1632$str=$1;1633$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1634}1635return$str;1636}16371638# escape tabs (convert tabs to spaces)1639sub untabify {1640my$line=shift;16411642while((my$pos=index($line,"\t")) != -1) {1643if(my$count= (8- ($pos%8))) {1644my$spaces=' ' x $count;1645$line=~s/\t/$spaces/;1646}1647}16481649return$line;1650}16511652sub project_in_list {1653my$project=shift;1654my@list= git_get_projects_list();1655return@list&&scalar(grep{$_->{'path'}eq$project}@list);1656}16571658## ----------------------------------------------------------------------1659## HTML aware string manipulation16601661# Try to chop given string on a word boundary between position1662# $len and $len+$add_len. If there is no word boundary there,1663# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1664# (marking chopped part) would be longer than given string.1665sub chop_str {1666my$str=shift;1667my$len=shift;1668my$add_len=shift||10;1669my$where=shift||'right';# 'left' | 'center' | 'right'16701671# Make sure perl knows it is utf8 encoded so we don't1672# cut in the middle of a utf8 multibyte char.1673$str= to_utf8($str);16741675# allow only $len chars, but don't cut a word if it would fit in $add_len1676# if it doesn't fit, cut it if it's still longer than the dots we would add1677# remove chopped character entities entirely16781679# when chopping in the middle, distribute $len into left and right part1680# return early if chopping wouldn't make string shorter1681if($whereeq'center') {1682return$strif($len+5>=length($str));# filler is length 51683$len=int($len/2);1684}else{1685return$strif($len+4>=length($str));# filler is length 41686}16871688# regexps: ending and beginning with word part up to $add_len1689my$endre=qr/.{$len}\w{0,$add_len}/;1690my$begre=qr/\w{0,$add_len}.{$len}/;16911692if($whereeq'left') {1693$str=~m/^(.*?)($begre)$/;1694my($lead,$body) = ($1,$2);1695if(length($lead) >4) {1696$lead=" ...";1697}1698return"$lead$body";16991700}elsif($whereeq'center') {1701$str=~m/^($endre)(.*)$/;1702my($left,$str) = ($1,$2);1703$str=~m/^(.*?)($begre)$/;1704my($mid,$right) = ($1,$2);1705if(length($mid) >5) {1706$mid=" ... ";1707}1708return"$left$mid$right";17091710}else{1711$str=~m/^($endre)(.*)$/;1712my$body=$1;1713my$tail=$2;1714if(length($tail) >4) {1715$tail="... ";1716}1717return"$body$tail";1718}1719}17201721# takes the same arguments as chop_str, but also wraps a <span> around the1722# result with a title attribute if it does get chopped. Additionally, the1723# string is HTML-escaped.1724sub chop_and_escape_str {1725my($str) =@_;17261727my$chopped= chop_str(@_);1728$str= to_utf8($str);1729if($choppedeq$str) {1730return esc_html($chopped);1731}else{1732$str=~s/[[:cntrl:]]/?/g;1733return$cgi->span({-title=>$str}, esc_html($chopped));1734}1735}17361737# Highlight selected fragments of string, using given CSS class,1738# and escape HTML. It is assumed that fragments do not overlap.1739# Regions are passed as list of pairs (array references).1740#1741# Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns1742# '<span class="mark">foo</span>bar'1743sub esc_html_hl_regions {1744my($str,$css_class,@sel) =@_;1745my%opts=grep{ref($_)ne'ARRAY'}@sel;1746@sel=grep{ref($_)eq'ARRAY'}@sel;1747return esc_html($str,%opts)unless@sel;17481749my$out='';1750my$pos=0;17511752formy$s(@sel) {1753my($begin,$end) =@$s;17541755# Don't create empty <span> elements.1756next if$end<=$begin;17571758my$escaped= esc_html(substr($str,$begin,$end-$begin),1759%opts);17601761$out.= esc_html(substr($str,$pos,$begin-$pos),%opts)1762if($begin-$pos>0);1763$out.=$cgi->span({-class=>$css_class},$escaped);17641765$pos=$end;1766}1767$out.= esc_html(substr($str,$pos),%opts)1768if($pos<length($str));17691770return$out;1771}17721773# return positions of beginning and end of each match1774sub matchpos_list {1775my($str,$regexp) =@_;1776return unless(defined$str&&defined$regexp);17771778my@matches;1779while($str=~/$regexp/g) {1780push@matches, [$-[0],$+[0]];1781}1782return@matches;1783}17841785# highlight match (if any), and escape HTML1786sub esc_html_match_hl {1787my($str,$regexp) =@_;1788return esc_html($str)unlessdefined$regexp;17891790my@matches= matchpos_list($str,$regexp);1791return esc_html($str)unless@matches;17921793return esc_html_hl_regions($str,'match',@matches);1794}179517961797# highlight match (if any) of shortened string, and escape HTML1798sub esc_html_match_hl_chopped {1799my($str,$chopped,$regexp) =@_;1800return esc_html_match_hl($str,$regexp)unlessdefined$chopped;18011802my@matches= matchpos_list($str,$regexp);1803return esc_html($chopped)unless@matches;18041805# filter matches so that we mark chopped string1806my$tail="... ";# see chop_str1807unless($chopped=~s/\Q$tail\E$//) {1808$tail='';1809}1810my$chop_len=length($chopped);1811my$tail_len=length($tail);1812my@filtered;18131814formy$m(@matches) {1815if($m->[0] >$chop_len) {1816push@filtered, [$chop_len,$chop_len+$tail_len]if($tail_len>0);1817last;1818}elsif($m->[1] >$chop_len) {1819push@filtered, [$m->[0],$chop_len+$tail_len];1820last;1821}1822push@filtered,$m;1823}18241825return esc_html_hl_regions($chopped.$tail,'match',@filtered);1826}18271828## ----------------------------------------------------------------------1829## functions returning short strings18301831# CSS class for given age value (in seconds)1832sub age_class {1833my$age=shift;18341835if(!defined$age) {1836return"noage";1837}elsif($age<60*60*2) {1838return"age0";1839}elsif($age<60*60*24*2) {1840return"age1";1841}else{1842return"age2";1843}1844}18451846# convert age in seconds to "nn units ago" string1847sub age_string {1848my$age=shift;1849my$age_str;18501851if($age>60*60*24*365*2) {1852$age_str= (int$age/60/60/24/365);1853$age_str.=" years ago";1854}elsif($age>60*60*24*(365/12)*2) {1855$age_str=int$age/60/60/24/(365/12);1856$age_str.=" months ago";1857}elsif($age>60*60*24*7*2) {1858$age_str=int$age/60/60/24/7;1859$age_str.=" weeks ago";1860}elsif($age>60*60*24*2) {1861$age_str=int$age/60/60/24;1862$age_str.=" days ago";1863}elsif($age>60*60*2) {1864$age_str=int$age/60/60;1865$age_str.=" hours ago";1866}elsif($age>60*2) {1867$age_str=int$age/60;1868$age_str.=" min ago";1869}elsif($age>2) {1870$age_str=int$age;1871$age_str.=" sec ago";1872}else{1873$age_str.=" right now";1874}1875return$age_str;1876}18771878useconstant{1879 S_IFINVALID =>0030000,1880 S_IFGITLINK =>0160000,1881};18821883# submodule/subproject, a commit object reference1884sub S_ISGITLINK {1885my$mode=shift;18861887return(($mode& S_IFMT) == S_IFGITLINK)1888}18891890# convert file mode in octal to symbolic file mode string1891sub mode_str {1892my$mode=oct shift;18931894if(S_ISGITLINK($mode)) {1895return'm---------';1896}elsif(S_ISDIR($mode& S_IFMT)) {1897return'drwxr-xr-x';1898}elsif(S_ISLNK($mode)) {1899return'lrwxrwxrwx';1900}elsif(S_ISREG($mode)) {1901# git cares only about the executable bit1902if($mode& S_IXUSR) {1903return'-rwxr-xr-x';1904}else{1905return'-rw-r--r--';1906};1907}else{1908return'----------';1909}1910}19111912# convert file mode in octal to file type string1913sub file_type {1914my$mode=shift;19151916if($mode!~m/^[0-7]+$/) {1917return$mode;1918}else{1919$mode=oct$mode;1920}19211922if(S_ISGITLINK($mode)) {1923return"submodule";1924}elsif(S_ISDIR($mode& S_IFMT)) {1925return"directory";1926}elsif(S_ISLNK($mode)) {1927return"symlink";1928}elsif(S_ISREG($mode)) {1929return"file";1930}else{1931return"unknown";1932}1933}19341935# convert file mode in octal to file type description string1936sub file_type_long {1937my$mode=shift;19381939if($mode!~m/^[0-7]+$/) {1940return$mode;1941}else{1942$mode=oct$mode;1943}19441945if(S_ISGITLINK($mode)) {1946return"submodule";1947}elsif(S_ISDIR($mode& S_IFMT)) {1948return"directory";1949}elsif(S_ISLNK($mode)) {1950return"symlink";1951}elsif(S_ISREG($mode)) {1952if($mode& S_IXUSR) {1953return"executable";1954}else{1955return"file";1956};1957}else{1958return"unknown";1959}1960}196119621963## ----------------------------------------------------------------------1964## functions returning short HTML fragments, or transforming HTML fragments1965## which don't belong to other sections19661967# format line of commit message.1968sub format_log_line_html {1969my$line=shift;19701971$line= esc_html($line, -nbsp=>1);1972$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1973$cgi->a({-href => href(action=>"object", hash=>$1),1974-class=>"text"},$1);1975}eg;19761977return$line;1978}19791980# format marker of refs pointing to given object19811982# the destination action is chosen based on object type and current context:1983# - for annotated tags, we choose the tag view unless it's the current view1984# already, in which case we go to shortlog view1985# - for other refs, we keep the current view if we're in history, shortlog or1986# log view, and select shortlog otherwise1987sub format_ref_marker {1988my($refs,$id) =@_;1989my$markers='';19901991if(defined$refs->{$id}) {1992foreachmy$ref(@{$refs->{$id}}) {1993# this code exploits the fact that non-lightweight tags are the1994# only indirect objects, and that they are the only objects for which1995# we want to use tag instead of shortlog as action1996my($type,$name) =qw();1997my$indirect= ($ref=~s/\^\{\}$//);1998# e.g. tags/v2.6.11 or heads/next1999if($ref=~m!^(.*?)s?/(.*)$!) {2000$type=$1;2001$name=$2;2002}else{2003$type="ref";2004$name=$ref;2005}20062007my$class=$type;2008$class.=" indirect"if$indirect;20092010my$dest_action="shortlog";20112012if($indirect) {2013$dest_action="tag"unless$actioneq"tag";2014}elsif($action=~/^(history|(short)?log)$/) {2015$dest_action=$action;2016}20172018my$dest="";2019$dest.="refs/"unless$ref=~ m!^refs/!;2020$dest.=$ref;20212022my$link=$cgi->a({2023-href => href(2024 action=>$dest_action,2025 hash=>$dest2026)},$name);20272028$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".2029$link."</span>";2030}2031}20322033if($markers) {2034return' <span class="refs">'.$markers.'</span>';2035}else{2036return"";2037}2038}20392040# format, perhaps shortened and with markers, title line2041sub format_subject_html {2042my($long,$short,$href,$extra) =@_;2043$extra=''unlessdefined($extra);20442045if(length($short) <length($long)) {2046$long=~s/[[:cntrl:]]/?/g;2047return$cgi->a({-href =>$href, -class=>"list subject",2048-title => to_utf8($long)},2049 esc_html($short)) .$extra;2050}else{2051return$cgi->a({-href =>$href, -class=>"list subject"},2052 esc_html($long)) .$extra;2053}2054}20552056# Rather than recomputing the url for an email multiple times, we cache it2057# after the first hit. This gives a visible benefit in views where the avatar2058# for the same email is used repeatedly (e.g. shortlog).2059# The cache is shared by all avatar engines (currently gravatar only), which2060# are free to use it as preferred. Since only one avatar engine is used for any2061# given page, there's no risk for cache conflicts.2062our%avatar_cache= ();20632064# Compute the picon url for a given email, by using the picon search service over at2065# http://www.cs.indiana.edu/picons/search.html2066sub picon_url {2067my$email=lc shift;2068if(!$avatar_cache{$email}) {2069my($user,$domain) =split('@',$email);2070$avatar_cache{$email} =2071"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".2072"$domain/$user/".2073"users+domains+unknown/up/single";2074}2075return$avatar_cache{$email};2076}20772078# Compute the gravatar url for a given email, if it's not in the cache already.2079# Gravatar stores only the part of the URL before the size, since that's the2080# one computationally more expensive. This also allows reuse of the cache for2081# different sizes (for this particular engine).2082sub gravatar_url {2083my$email=lc shift;2084my$size=shift;2085$avatar_cache{$email} ||=2086"http://www.gravatar.com/avatar/".2087 Digest::MD5::md5_hex($email) ."?s=";2088return$avatar_cache{$email} .$size;2089}20902091# Insert an avatar for the given $email at the given $size if the feature2092# is enabled.2093sub git_get_avatar {2094my($email,%opts) =@_;2095my$pre_white= ($opts{-pad_before} ?" ":"");2096my$post_white= ($opts{-pad_after} ?" ":"");2097$opts{-size} ||='default';2098my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};2099my$url="";2100if($git_avatareq'gravatar') {2101$url= gravatar_url($email,$size);2102}elsif($git_avatareq'picon') {2103$url= picon_url($email);2104}2105# Other providers can be added by extending the if chain, defining $url2106# as needed. If no variant puts something in $url, we assume avatars2107# are completely disabled/unavailable.2108if($url) {2109return$pre_white.2110"<img width=\"$size\"".2111"class=\"avatar\"".2112"src=\"".esc_url($url)."\"".2113"alt=\"\"".2114"/>".$post_white;2115}else{2116return"";2117}2118}21192120sub format_search_author {2121my($author,$searchtype,$displaytext) =@_;2122my$have_search= gitweb_check_feature('search');21232124if($have_search) {2125my$performed="";2126if($searchtypeeq'author') {2127$performed="authored";2128}elsif($searchtypeeq'committer') {2129$performed="committed";2130}21312132return$cgi->a({-href => href(action=>"search", hash=>$hash,2133 searchtext=>$author,2134 searchtype=>$searchtype),class=>"list",2135 title=>"Search for commits$performedby$author"},2136$displaytext);21372138}else{2139return$displaytext;2140}2141}21422143# format the author name of the given commit with the given tag2144# the author name is chopped and escaped according to the other2145# optional parameters (see chop_str).2146sub format_author_html {2147my$tag=shift;2148my$co=shift;2149my$author= chop_and_escape_str($co->{'author_name'},@_);2150return"<$tagclass=\"author\">".2151 format_search_author($co->{'author_name'},"author",2152 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2153$author) .2154"</$tag>";2155}21562157# format git diff header line, i.e. "diff --(git|combined|cc) ..."2158sub format_git_diff_header_line {2159my$line=shift;2160my$diffinfo=shift;2161my($from,$to) =@_;21622163if($diffinfo->{'nparents'}) {2164# combined diff2165$line=~s!^(diff (.*?) )"?.*$!$1!;2166if($to->{'href'}) {2167$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2168 esc_path($to->{'file'}));2169}else{# file was deleted (no href)2170$line.= esc_path($to->{'file'});2171}2172}else{2173# "ordinary" diff2174$line=~s!^(diff (.*?) )"?a/.*$!$1!;2175if($from->{'href'}) {2176$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2177'a/'. esc_path($from->{'file'}));2178}else{# file was added (no href)2179$line.='a/'. esc_path($from->{'file'});2180}2181$line.=' ';2182if($to->{'href'}) {2183$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2184'b/'. esc_path($to->{'file'}));2185}else{# file was deleted2186$line.='b/'. esc_path($to->{'file'});2187}2188}21892190return"<div class=\"diff header\">$line</div>\n";2191}21922193# format extended diff header line, before patch itself2194sub format_extended_diff_header_line {2195my$line=shift;2196my$diffinfo=shift;2197my($from,$to) =@_;21982199# match <path>2200if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2201$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2202 esc_path($from->{'file'}));2203}2204if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2205$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2206 esc_path($to->{'file'}));2207}2208# match single <mode>2209if($line=~m/\s(\d{6})$/) {2210$line.='<span class="info"> ('.2211 file_type_long($1) .2212')</span>';2213}2214# match <hash>2215if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2216# can match only for combined diff2217$line='index ';2218for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2219if($from->{'href'}[$i]) {2220$line.=$cgi->a({-href=>$from->{'href'}[$i],2221-class=>"hash"},2222substr($diffinfo->{'from_id'}[$i],0,7));2223}else{2224$line.='0' x 7;2225}2226# separator2227$line.=','if($i<$diffinfo->{'nparents'} -1);2228}2229$line.='..';2230if($to->{'href'}) {2231$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2232substr($diffinfo->{'to_id'},0,7));2233}else{2234$line.='0' x 7;2235}22362237}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2238# can match only for ordinary diff2239my($from_link,$to_link);2240if($from->{'href'}) {2241$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2242substr($diffinfo->{'from_id'},0,7));2243}else{2244$from_link='0' x 7;2245}2246if($to->{'href'}) {2247$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2248substr($diffinfo->{'to_id'},0,7));2249}else{2250$to_link='0' x 7;2251}2252my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2253$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2254}22552256return$line."<br/>\n";2257}22582259# format from-file/to-file diff header2260sub format_diff_from_to_header {2261my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2262my$line;2263my$result='';22642265$line=$from_line;2266#assert($line =~ m/^---/) if DEBUG;2267# no extra formatting for "^--- /dev/null"2268if(!$diffinfo->{'nparents'}) {2269# ordinary (single parent) diff2270if($line=~m!^--- "?a/!) {2271if($from->{'href'}) {2272$line='--- a/'.2273$cgi->a({-href=>$from->{'href'}, -class=>"path"},2274 esc_path($from->{'file'}));2275}else{2276$line='--- a/'.2277 esc_path($from->{'file'});2278}2279}2280$result.= qq!<div class="diff from_file">$line</div>\n!;22812282}else{2283# combined diff (merge commit)2284for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2285if($from->{'href'}[$i]) {2286$line='--- '.2287$cgi->a({-href=>href(action=>"blobdiff",2288 hash_parent=>$diffinfo->{'from_id'}[$i],2289 hash_parent_base=>$parents[$i],2290 file_parent=>$from->{'file'}[$i],2291 hash=>$diffinfo->{'to_id'},2292 hash_base=>$hash,2293 file_name=>$to->{'file'}),2294-class=>"path",2295-title=>"diff". ($i+1)},2296$i+1) .2297'/'.2298$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2299 esc_path($from->{'file'}[$i]));2300}else{2301$line='--- /dev/null';2302}2303$result.= qq!<div class="diff from_file">$line</div>\n!;2304}2305}23062307$line=$to_line;2308#assert($line =~ m/^\+\+\+/) if DEBUG;2309# no extra formatting for "^+++ /dev/null"2310if($line=~m!^\+\+\+ "?b/!) {2311if($to->{'href'}) {2312$line='+++ b/'.2313$cgi->a({-href=>$to->{'href'}, -class=>"path"},2314 esc_path($to->{'file'}));2315}else{2316$line='+++ b/'.2317 esc_path($to->{'file'});2318}2319}2320$result.= qq!<div class="diff to_file">$line</div>\n!;23212322return$result;2323}23242325# create note for patch simplified by combined diff2326sub format_diff_cc_simplified {2327my($diffinfo,@parents) =@_;2328my$result='';23292330$result.="<div class=\"diff header\">".2331"diff --cc ";2332if(!is_deleted($diffinfo)) {2333$result.=$cgi->a({-href => href(action=>"blob",2334 hash_base=>$hash,2335 hash=>$diffinfo->{'to_id'},2336 file_name=>$diffinfo->{'to_file'}),2337-class=>"path"},2338 esc_path($diffinfo->{'to_file'}));2339}else{2340$result.= esc_path($diffinfo->{'to_file'});2341}2342$result.="</div>\n".# class="diff header"2343"<div class=\"diff nodifferences\">".2344"Simple merge".2345"</div>\n";# class="diff nodifferences"23462347return$result;2348}23492350sub diff_line_class {2351my($line,$from,$to) =@_;23522353# ordinary diff2354my$num_sign=1;2355# combined diff2356if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2357$num_sign=scalar@{$from->{'href'}};2358}23592360my@diff_line_classifier= (2361{ regexp =>qr/^\@\@{$num_sign} /,class=>"chunk_header"},2362{ regexp =>qr/^\\/,class=>"incomplete"},2363{ regexp =>qr/^ {$num_sign}/,class=>"ctx"},2364# classifier for context must come before classifier add/rem,2365# or we would have to use more complicated regexp, for example2366# qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;2367{ regexp =>qr/^[+ ]{$num_sign}/,class=>"add"},2368{ regexp =>qr/^[- ]{$num_sign}/,class=>"rem"},2369);2370formy$clsfy(@diff_line_classifier) {2371return$clsfy->{'class'}2372if($line=~$clsfy->{'regexp'});2373}23742375# fallback2376return"";2377}23782379# assumes that $from and $to are defined and correctly filled,2380# and that $line holds a line of chunk header for unified diff2381sub format_unidiff_chunk_header {2382my($line,$from,$to) =@_;23832384my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2385$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;23862387$from_lines=0unlessdefined$from_lines;2388$to_lines=0unlessdefined$to_lines;23892390if($from->{'href'}) {2391$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2392-class=>"list"},$from_text);2393}2394if($to->{'href'}) {2395$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2396-class=>"list"},$to_text);2397}2398$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2399"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2400return$line;2401}24022403# assumes that $from and $to are defined and correctly filled,2404# and that $line holds a line of chunk header for combined diff2405sub format_cc_diff_chunk_header {2406my($line,$from,$to) =@_;24072408my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2409my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);24102411@from_text=split(' ',$ranges);2412for(my$i=0;$i<@from_text; ++$i) {2413($from_start[$i],$from_nlines[$i]) =2414(split(',',substr($from_text[$i],1)),0);2415}24162417$to_text=pop@from_text;2418$to_start=pop@from_start;2419$to_nlines=pop@from_nlines;24202421$line="<span class=\"chunk_info\">$prefix";2422for(my$i=0;$i<@from_text; ++$i) {2423if($from->{'href'}[$i]) {2424$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2425-class=>"list"},$from_text[$i]);2426}else{2427$line.=$from_text[$i];2428}2429$line.=" ";2430}2431if($to->{'href'}) {2432$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2433-class=>"list"},$to_text);2434}else{2435$line.=$to_text;2436}2437$line.="$prefix</span>".2438"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2439return$line;2440}24412442# process patch (diff) line (not to be used for diff headers),2443# returning HTML-formatted (but not wrapped) line.2444# If the line is passed as a reference, it is treated as HTML and not2445# esc_html()'ed.2446sub format_diff_line {2447my($line,$diff_class,$from,$to) =@_;24482449if(ref($line)) {2450$line=$$line;2451}else{2452chomp$line;2453$line= untabify($line);24542455if($from&&$to&&$line=~m/^\@{2} /) {2456$line= format_unidiff_chunk_header($line,$from,$to);2457}elsif($from&&$to&&$line=~m/^\@{3}/) {2458$line= format_cc_diff_chunk_header($line,$from,$to);2459}else{2460$line= esc_html($line, -nbsp=>1);2461}2462}24632464my$diff_classes="diff";2465$diff_classes.="$diff_class"if($diff_class);2466$line="<div class=\"$diff_classes\">$line</div>\n";24672468return$line;2469}24702471# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2472# linked. Pass the hash of the tree/commit to snapshot.2473sub format_snapshot_links {2474my($hash) =@_;2475my$num_fmts=@snapshot_fmts;2476if($num_fmts>1) {2477# A parenthesized list of links bearing format names.2478# e.g. "snapshot (_tar.gz_ _zip_)"2479return"snapshot (".join(' ',map2480$cgi->a({2481-href => href(2482 action=>"snapshot",2483 hash=>$hash,2484 snapshot_format=>$_2485)2486},$known_snapshot_formats{$_}{'display'})2487,@snapshot_fmts) .")";2488}elsif($num_fmts==1) {2489# A single "snapshot" link whose tooltip bears the format name.2490# i.e. "_snapshot_"2491my($fmt) =@snapshot_fmts;2492return2493$cgi->a({2494-href => href(2495 action=>"snapshot",2496 hash=>$hash,2497 snapshot_format=>$fmt2498),2499-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2500},"snapshot");2501}else{# $num_fmts == 02502returnundef;2503}2504}25052506## ......................................................................2507## functions returning values to be passed, perhaps after some2508## transformation, to other functions; e.g. returning arguments to href()25092510# returns hash to be passed to href to generate gitweb URL2511# in -title key it returns description of link2512sub get_feed_info {2513my$format=shift||'Atom';2514my%res= (action =>lc($format));25152516# feed links are possible only for project views2517return unless(defined$project);2518# some views should link to OPML, or to generic project feed,2519# or don't have specific feed yet (so they should use generic)2520return if(!$action||$action=~/^(?:tags|heads|forks|tag|search)$/x);25212522my$branch;2523# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2524# from tag links; this also makes possible to detect branch links2525if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2526(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2527$branch=$1;2528}2529# find log type for feed description (title)2530my$type='log';2531if(defined$file_name) {2532$type="history of$file_name";2533$type.="/"if($actioneq'tree');2534$type.=" on '$branch'"if(defined$branch);2535}else{2536$type="log of$branch"if(defined$branch);2537}25382539$res{-title} =$type;2540$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2541$res{'file_name'} =$file_name;25422543return%res;2544}25452546## ----------------------------------------------------------------------2547## git utility subroutines, invoking git commands25482549# returns path to the core git executable and the --git-dir parameter as list2550sub git_cmd {2551$number_of_git_cmds++;2552return$GIT,'--git-dir='.$git_dir;2553}25542555# quote the given arguments for passing them to the shell2556# quote_command("command", "arg 1", "arg with ' and ! characters")2557# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2558# Try to avoid using this function wherever possible.2559sub quote_command {2560returnjoin(' ',2561map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2562}25632564# get HEAD ref of given project as hash2565sub git_get_head_hash {2566return git_get_full_hash(shift,'HEAD');2567}25682569sub git_get_full_hash {2570return git_get_hash(@_);2571}25722573sub git_get_short_hash {2574return git_get_hash(@_,'--short=7');2575}25762577sub git_get_hash {2578my($project,$hash,@options) =@_;2579my$o_git_dir=$git_dir;2580my$retval=undef;2581$git_dir="$projectroot/$project";2582if(open my$fd,'-|', git_cmd(),'rev-parse',2583'--verify','-q',@options,$hash) {2584$retval= <$fd>;2585chomp$retvalifdefined$retval;2586close$fd;2587}2588if(defined$o_git_dir) {2589$git_dir=$o_git_dir;2590}2591return$retval;2592}25932594# get type of given object2595sub git_get_type {2596my$hash=shift;25972598open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2599my$type= <$fd>;2600close$fdorreturn;2601chomp$type;2602return$type;2603}26042605# repository configuration2606our$config_file='';2607our%config;26082609# store multiple values for single key as anonymous array reference2610# single values stored directly in the hash, not as [ <value> ]2611sub hash_set_multi {2612my($hash,$key,$value) =@_;26132614if(!exists$hash->{$key}) {2615$hash->{$key} =$value;2616}elsif(!ref$hash->{$key}) {2617$hash->{$key} = [$hash->{$key},$value];2618}else{2619push@{$hash->{$key}},$value;2620}2621}26222623# return hash of git project configuration2624# optionally limited to some section, e.g. 'gitweb'2625sub git_parse_project_config {2626my$section_regexp=shift;2627my%config;26282629local$/="\0";26302631open my$fh,"-|", git_cmd(),"config",'-z','-l',2632orreturn;26332634while(my$keyval= <$fh>) {2635chomp$keyval;2636my($key,$value) =split(/\n/,$keyval,2);26372638 hash_set_multi(\%config,$key,$value)2639if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2640}2641close$fh;26422643return%config;2644}26452646# convert config value to boolean: 'true' or 'false'2647# no value, number > 0, 'true' and 'yes' values are true2648# rest of values are treated as false (never as error)2649sub config_to_bool {2650my$val=shift;26512652return1if!defined$val;# section.key26532654# strip leading and trailing whitespace2655$val=~s/^\s+//;2656$val=~s/\s+$//;26572658return(($val=~/^\d+$/&&$val) ||# section.key = 12659($val=~/^(?:true|yes)$/i));# section.key = true2660}26612662# convert config value to simple decimal number2663# an optional value suffix of 'k', 'm', or 'g' will cause the value2664# to be multiplied by 1024, 1048576, or 10737418242665sub config_to_int {2666my$val=shift;26672668# strip leading and trailing whitespace2669$val=~s/^\s+//;2670$val=~s/\s+$//;26712672if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2673$unit=lc($unit);2674# unknown unit is treated as 12675return$num* ($uniteq'g'?1073741824:2676$uniteq'm'?1048576:2677$uniteq'k'?1024:1);2678}2679return$val;2680}26812682# convert config value to array reference, if needed2683sub config_to_multi {2684my$val=shift;26852686returnref($val) ?$val: (defined($val) ? [$val] : []);2687}26882689sub git_get_project_config {2690my($key,$type) =@_;26912692return unlessdefined$git_dir;26932694# key sanity check2695return unless($key);2696# only subsection, if exists, is case sensitive,2697# and not lowercased by 'git config -z -l'2698if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2699$key=join(".",lc($hi),$mi,lc($lo));2700}else{2701$key=lc($key);2702}2703$key=~s/^gitweb\.//;2704return if($key=~m/\W/);27052706# type sanity check2707if(defined$type) {2708$type=~s/^--//;2709$type=undef2710unless($typeeq'bool'||$typeeq'int');2711}27122713# get config2714if(!defined$config_file||2715$config_filene"$git_dir/config") {2716%config= git_parse_project_config('gitweb');2717$config_file="$git_dir/config";2718}27192720# check if config variable (key) exists2721return unlessexists$config{"gitweb.$key"};27222723# ensure given type2724if(!defined$type) {2725return$config{"gitweb.$key"};2726}elsif($typeeq'bool') {2727# backward compatibility: 'git config --bool' returns true/false2728return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2729}elsif($typeeq'int') {2730return config_to_int($config{"gitweb.$key"});2731}2732return$config{"gitweb.$key"};2733}27342735# get hash of given path at given ref2736sub git_get_hash_by_path {2737my$base=shift;2738my$path=shift||returnundef;2739my$type=shift;27402741$path=~ s,/+$,,;27422743open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2744or die_error(500,"Open git-ls-tree failed");2745my$line= <$fd>;2746close$fdorreturnundef;27472748if(!defined$line) {2749# there is no tree or hash given by $path at $base2750returnundef;2751}27522753#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2754$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2755if(defined$type&&$typene$2) {2756# type doesn't match2757returnundef;2758}2759return$3;2760}27612762# get path of entry with given hash at given tree-ish (ref)2763# used to get 'from' filename for combined diff (merge commit) for renames2764sub git_get_path_by_hash {2765my$base=shift||return;2766my$hash=shift||return;27672768local$/="\0";27692770open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2771orreturnundef;2772while(my$line= <$fd>) {2773chomp$line;27742775#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2776#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2777if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2778close$fd;2779return$1;2780}2781}2782close$fd;2783returnundef;2784}27852786## ......................................................................2787## git utility functions, directly accessing git repository27882789# get the value of config variable either from file named as the variable2790# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2791# configuration variable in the repository config file.2792sub git_get_file_or_project_config {2793my($path,$name) =@_;27942795$git_dir="$projectroot/$path";2796open my$fd,'<',"$git_dir/$name"2797orreturn git_get_project_config($name);2798my$conf= <$fd>;2799close$fd;2800if(defined$conf) {2801chomp$conf;2802}2803return$conf;2804}28052806sub git_get_project_description {2807my$path=shift;2808return git_get_file_or_project_config($path,'description');2809}28102811sub git_get_project_category {2812my$path=shift;2813return git_get_file_or_project_config($path,'category');2814}281528162817# supported formats:2818# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2819# - if its contents is a number, use it as tag weight,2820# - otherwise add a tag with weight 12821# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2822# the same value multiple times increases tag weight2823# * `gitweb.ctag' multi-valued repo config variable2824sub git_get_project_ctags {2825my$project=shift;2826my$ctags= {};28272828$git_dir="$projectroot/$project";2829if(opendir my$dh,"$git_dir/ctags") {2830my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2831foreachmy$tagfile(@files) {2832open my$ct,'<',$tagfile2833ornext;2834my$val= <$ct>;2835chomp$valif$val;2836close$ct;28372838(my$ctag=$tagfile) =~ s#.*/##;2839if($val=~/^\d+$/) {2840$ctags->{$ctag} =$val;2841}else{2842$ctags->{$ctag} =1;2843}2844}2845closedir$dh;28462847}elsif(open my$fh,'<',"$git_dir/ctags") {2848while(my$line= <$fh>) {2849chomp$line;2850$ctags->{$line}++if$line;2851}2852close$fh;28532854}else{2855my$taglist= config_to_multi(git_get_project_config('ctag'));2856foreachmy$tag(@$taglist) {2857$ctags->{$tag}++;2858}2859}28602861return$ctags;2862}28632864# return hash, where keys are content tags ('ctags'),2865# and values are sum of weights of given tag in every project2866sub git_gather_all_ctags {2867my$projects=shift;2868my$ctags= {};28692870foreachmy$p(@$projects) {2871foreachmy$ct(keys%{$p->{'ctags'}}) {2872$ctags->{$ct} +=$p->{'ctags'}->{$ct};2873}2874}28752876return$ctags;2877}28782879sub git_populate_project_tagcloud {2880my$ctags=shift;28812882# First, merge different-cased tags; tags vote on casing2883my%ctags_lc;2884foreach(keys%$ctags) {2885$ctags_lc{lc$_}->{count} +=$ctags->{$_};2886if(not$ctags_lc{lc$_}->{topcount}2887or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2888$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2889$ctags_lc{lc$_}->{topname} =$_;2890}2891}28922893my$cloud;2894my$matched=$input_params{'ctag'};2895if(eval{require HTML::TagCloud;1; }) {2896$cloud= HTML::TagCloud->new;2897foreachmy$ctag(sort keys%ctags_lc) {2898# Pad the title with spaces so that the cloud looks2899# less crammed.2900my$title= esc_html($ctags_lc{$ctag}->{topname});2901$title=~s/ / /g;2902$title=~s/^/ /g;2903$title=~s/$/ /g;2904if(defined$matched&&$matchedeq$ctag) {2905$title=qq(<span class="match">$title</span>);2906}2907$cloud->add($title, href(project=>undef, ctag=>$ctag),2908$ctags_lc{$ctag}->{count});2909}2910}else{2911$cloud= {};2912foreachmy$ctag(keys%ctags_lc) {2913my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2914if(defined$matched&&$matchedeq$ctag) {2915$title=qq(<span class="match">$title</span>);2916}2917$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2918$cloud->{$ctag}{ctag} =2919$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2920}2921}2922return$cloud;2923}29242925sub git_show_project_tagcloud {2926my($cloud,$count) =@_;2927if(ref$cloudeq'HTML::TagCloud') {2928return$cloud->html_and_css($count);2929}else{2930my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2931return2932'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2933join(', ',map{2934$cloud->{$_}->{'ctag'}2935}splice(@tags,0,$count)) .2936'</div>';2937}2938}29392940sub git_get_project_url_list {2941my$path=shift;29422943$git_dir="$projectroot/$path";2944open my$fd,'<',"$git_dir/cloneurl"2945orreturnwantarray?2946@{ config_to_multi(git_get_project_config('url')) } :2947 config_to_multi(git_get_project_config('url'));2948my@git_project_url_list=map{chomp;$_} <$fd>;2949close$fd;29502951returnwantarray?@git_project_url_list: \@git_project_url_list;2952}29532954sub git_get_projects_list {2955my$filter=shift||'';2956my$paranoid=shift;2957my@list;29582959if(-d $projects_list) {2960# search in directory2961my$dir=$projects_list;2962# remove the trailing "/"2963$dir=~s!/+$!!;2964my$pfxlen=length("$dir");2965my$pfxdepth= ($dir=~tr!/!!);2966# when filtering, search only given subdirectory2967if($filter&& !$paranoid) {2968$dir.="/$filter";2969$dir=~s!/+$!!;2970}29712972 File::Find::find({2973 follow_fast =>1,# follow symbolic links2974 follow_skip =>2,# ignore duplicates2975 dangling_symlinks =>0,# ignore dangling symlinks, silently2976 wanted =>sub{2977# global variables2978our$project_maxdepth;2979our$projectroot;2980# skip project-list toplevel, if we get it.2981return if(m!^[/.]$!);2982# only directories can be git repositories2983return unless(-d $_);2984# don't traverse too deep (Find is super slow on os x)2985# $project_maxdepth excludes depth of $projectroot2986if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2987$File::Find::prune =1;2988return;2989}29902991my$path=substr($File::Find::name,$pfxlen+1);2992# paranoidly only filter here2993if($paranoid&&$filter&&$path!~m!^\Q$filter\E/!) {2994next;2995}2996# we check related file in $projectroot2997if(check_export_ok("$projectroot/$path")) {2998push@list, { path =>$path};2999$File::Find::prune =1;3000}3001},3002},"$dir");30033004}elsif(-f $projects_list) {3005# read from file(url-encoded):3006# 'git%2Fgit.git Linus+Torvalds'3007# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3008# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3009open my$fd,'<',$projects_listorreturn;3010 PROJECT:3011while(my$line= <$fd>) {3012chomp$line;3013my($path,$owner) =split' ',$line;3014$path= unescape($path);3015$owner= unescape($owner);3016if(!defined$path) {3017next;3018}3019# if $filter is rpovided, check if $path begins with $filter3020if($filter&&$path!~m!^\Q$filter\E/!) {3021next;3022}3023if(check_export_ok("$projectroot/$path")) {3024my$pr= {3025 path =>$path3026};3027if($owner) {3028$pr->{'owner'} = to_utf8($owner);3029}3030push@list,$pr;3031}3032}3033close$fd;3034}3035return@list;3036}30373038# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)3039# as side effects it sets 'forks' field to list of forks for forked projects3040sub filter_forks_from_projects_list {3041my$projects=shift;30423043my%trie;# prefix tree of directories (path components)3044# generate trie out of those directories that might contain forks3045foreachmy$pr(@$projects) {3046my$path=$pr->{'path'};3047$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory3048next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'3049next unless($path);# skip '.git' repository: tests, git-instaweb3050next unless(-d "$projectroot/$path");# containing directory exists3051$pr->{'forks'} = [];# there can be 0 or more forks of project30523053# add to trie3054my@dirs=split('/',$path);3055# walk the trie, until either runs out of components or out of trie3056my$ref= \%trie;3057while(scalar@dirs&&3058exists($ref->{$dirs[0]})) {3059$ref=$ref->{shift@dirs};3060}3061# create rest of trie structure from rest of components3062foreachmy$dir(@dirs) {3063$ref=$ref->{$dir} = {};3064}3065# create end marker, store $pr as a data3066$ref->{''} =$prif(!exists$ref->{''});3067}30683069# filter out forks, by finding shortest prefix match for paths3070my@filtered;3071 PROJECT:3072foreachmy$pr(@$projects) {3073# trie lookup3074my$ref= \%trie;3075 DIR:3076foreachmy$dir(split('/',$pr->{'path'})) {3077if(exists$ref->{''}) {3078# found [shortest] prefix, is a fork - skip it3079push@{$ref->{''}{'forks'}},$pr;3080next PROJECT;3081}3082if(!exists$ref->{$dir}) {3083# not in trie, cannot have prefix, not a fork3084push@filtered,$pr;3085next PROJECT;3086}3087# If the dir is there, we just walk one step down the trie.3088$ref=$ref->{$dir};3089}3090# we ran out of trie3091# (shouldn't happen: it's either no match, or end marker)3092push@filtered,$pr;3093}30943095return@filtered;3096}30973098# note: fill_project_list_info must be run first,3099# for 'descr_long' and 'ctags' to be filled3100sub search_projects_list {3101my($projlist,%opts) =@_;3102my$tagfilter=$opts{'tagfilter'};3103my$search_re=$opts{'search_regexp'};31043105return@$projlist3106unless($tagfilter||$search_re);31073108# searching projects require filling to be run before it;3109 fill_project_list_info($projlist,3110$tagfilter?'ctags': (),3111$search_re? ('path','descr') : ());3112my@projects;3113 PROJECT:3114foreachmy$pr(@$projlist) {31153116if($tagfilter) {3117next unlessref($pr->{'ctags'})eq'HASH';3118next unless3119grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};3120}31213122if($search_re) {3123next unless3124$pr->{'path'} =~/$search_re/||3125$pr->{'descr_long'} =~/$search_re/;3126}31273128push@projects,$pr;3129}31303131return@projects;3132}31333134our$gitweb_project_owner=undef;3135sub git_get_project_list_from_file {31363137return if(defined$gitweb_project_owner);31383139$gitweb_project_owner= {};3140# read from file (url-encoded):3141# 'git%2Fgit.git Linus+Torvalds'3142# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3143# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3144if(-f $projects_list) {3145open(my$fd,'<',$projects_list);3146while(my$line= <$fd>) {3147chomp$line;3148my($pr,$ow) =split' ',$line;3149$pr= unescape($pr);3150$ow= unescape($ow);3151$gitweb_project_owner->{$pr} = to_utf8($ow);3152}3153close$fd;3154}3155}31563157sub git_get_project_owner {3158my$project=shift;3159my$owner;31603161returnundefunless$project;3162$git_dir="$projectroot/$project";31633164if(!defined$gitweb_project_owner) {3165 git_get_project_list_from_file();3166}31673168if(exists$gitweb_project_owner->{$project}) {3169$owner=$gitweb_project_owner->{$project};3170}3171if(!defined$owner){3172$owner= git_get_project_config('owner');3173}3174if(!defined$owner) {3175$owner= get_file_owner("$git_dir");3176}31773178return$owner;3179}31803181sub git_get_last_activity {3182my($path) =@_;3183my$fd;31843185$git_dir="$projectroot/$path";3186open($fd,"-|", git_cmd(),'for-each-ref',3187'--format=%(committer)',3188'--sort=-committerdate',3189'--count=1',3190'refs/heads')orreturn;3191my$most_recent= <$fd>;3192close$fdorreturn;3193if(defined$most_recent&&3194$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3195my$timestamp=$1;3196my$age=time-$timestamp;3197return($age, age_string($age));3198}3199return(undef,undef);3200}32013202# Implementation note: when a single remote is wanted, we cannot use 'git3203# remote show -n' because that command always work (assuming it's a remote URL3204# if it's not defined), and we cannot use 'git remote show' because that would3205# try to make a network roundtrip. So the only way to find if that particular3206# remote is defined is to walk the list provided by 'git remote -v' and stop if3207# and when we find what we want.3208sub git_get_remotes_list {3209my$wanted=shift;3210my%remotes= ();32113212open my$fd,'-|', git_cmd(),'remote','-v';3213return unless$fd;3214while(my$remote= <$fd>) {3215chomp$remote;3216$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3217next if$wantedand not$remoteeq$wanted;3218my($url,$key) = ($1,$2);32193220$remotes{$remote} ||= {'heads'=> () };3221$remotes{$remote}{$key} =$url;3222}3223close$fdorreturn;3224returnwantarray?%remotes: \%remotes;3225}32263227# Takes a hash of remotes as first parameter and fills it by adding the3228# available remote heads for each of the indicated remotes.3229sub fill_remote_heads {3230my$remotes=shift;3231my@heads=map{"remotes/$_"}keys%$remotes;3232my@remoteheads= git_get_heads_list(undef,@heads);3233foreachmy$remote(keys%$remotes) {3234$remotes->{$remote}{'heads'} = [grep{3235$_->{'name'} =~s!^$remote/!!3236}@remoteheads];3237}3238}32393240sub git_get_references {3241my$type=shift||"";3242my%refs;3243# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113244# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3245open my$fd,"-|", git_cmd(),"show-ref","--dereference",3246($type? ("--","refs/$type") : ())# use -- <pattern> if $type3247orreturn;32483249while(my$line= <$fd>) {3250chomp$line;3251if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3252if(defined$refs{$1}) {3253push@{$refs{$1}},$2;3254}else{3255$refs{$1} = [$2];3256}3257}3258}3259close$fdorreturn;3260return \%refs;3261}32623263sub git_get_rev_name_tags {3264my$hash=shift||returnundef;32653266open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3267orreturn;3268my$name_rev= <$fd>;3269close$fd;32703271if($name_rev=~ m|^$hash tags/(.*)$|) {3272return$1;3273}else{3274# catches also '$hash undefined' output3275returnundef;3276}3277}32783279## ----------------------------------------------------------------------3280## parse to hash functions32813282sub parse_date {3283my$epoch=shift;3284my$tz=shift||"-0000";32853286my%date;3287my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3288my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3289my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3290$date{'hour'} =$hour;3291$date{'minute'} =$min;3292$date{'mday'} =$mday;3293$date{'day'} =$days[$wday];3294$date{'month'} =$months[$mon];3295$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3296$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3297$date{'mday-time'} =sprintf"%d%s%02d:%02d",3298$mday,$months[$mon],$hour,$min;3299$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",33001900+$year,1+$mon,$mday,$hour,$min,$sec;33013302my($tz_sign,$tz_hour,$tz_min) =3303($tz=~m/^([-+])(\d\d)(\d\d)$/);3304$tz_sign= ($tz_signeq'-'? -1: +1);3305my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3306($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3307$date{'hour_local'} =$hour;3308$date{'minute_local'} =$min;3309$date{'tz_local'} =$tz;3310$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",33111900+$year,$mon+1,$mday,3312$hour,$min,$sec,$tz);3313return%date;3314}33153316sub parse_tag {3317my$tag_id=shift;3318my%tag;3319my@comment;33203321open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3322$tag{'id'} =$tag_id;3323while(my$line= <$fd>) {3324chomp$line;3325if($line=~m/^object ([0-9a-fA-F]{40})$/) {3326$tag{'object'} =$1;3327}elsif($line=~m/^type (.+)$/) {3328$tag{'type'} =$1;3329}elsif($line=~m/^tag (.+)$/) {3330$tag{'name'} =$1;3331}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3332$tag{'author'} =$1;3333$tag{'author_epoch'} =$2;3334$tag{'author_tz'} =$3;3335if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3336$tag{'author_name'} =$1;3337$tag{'author_email'} =$2;3338}else{3339$tag{'author_name'} =$tag{'author'};3340}3341}elsif($line=~m/--BEGIN/) {3342push@comment,$line;3343last;3344}elsif($lineeq"") {3345last;3346}3347}3348push@comment, <$fd>;3349$tag{'comment'} = \@comment;3350close$fdorreturn;3351if(!defined$tag{'name'}) {3352return3353};3354return%tag3355}33563357sub parse_commit_text {3358my($commit_text,$withparents) =@_;3359my@commit_lines=split'\n',$commit_text;3360my%co;33613362pop@commit_lines;# Remove '\0'33633364if(!@commit_lines) {3365return;3366}33673368my$header=shift@commit_lines;3369if($header!~m/^[0-9a-fA-F]{40}/) {3370return;3371}3372($co{'id'},my@parents) =split' ',$header;3373while(my$line=shift@commit_lines) {3374last if$lineeq"\n";3375if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3376$co{'tree'} =$1;3377}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3378push@parents,$1;3379}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3380$co{'author'} = to_utf8($1);3381$co{'author_epoch'} =$2;3382$co{'author_tz'} =$3;3383if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3384$co{'author_name'} =$1;3385$co{'author_email'} =$2;3386}else{3387$co{'author_name'} =$co{'author'};3388}3389}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3390$co{'committer'} = to_utf8($1);3391$co{'committer_epoch'} =$2;3392$co{'committer_tz'} =$3;3393if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3394$co{'committer_name'} =$1;3395$co{'committer_email'} =$2;3396}else{3397$co{'committer_name'} =$co{'committer'};3398}3399}3400}3401if(!defined$co{'tree'}) {3402return;3403};3404$co{'parents'} = \@parents;3405$co{'parent'} =$parents[0];34063407foreachmy$title(@commit_lines) {3408$title=~s/^ //;3409if($titlene"") {3410$co{'title'} = chop_str($title,80,5);3411# remove leading stuff of merges to make the interesting part visible3412if(length($title) >50) {3413$title=~s/^Automatic //;3414$title=~s/^merge (of|with) /Merge ... /i;3415if(length($title) >50) {3416$title=~s/(http|rsync):\/\///;3417}3418if(length($title) >50) {3419$title=~s/(master|www|rsync)\.//;3420}3421if(length($title) >50) {3422$title=~s/kernel.org:?//;3423}3424if(length($title) >50) {3425$title=~s/\/pub\/scm//;3426}3427}3428$co{'title_short'} = chop_str($title,50,5);3429last;3430}3431}3432if(!defined$co{'title'} ||$co{'title'}eq"") {3433$co{'title'} =$co{'title_short'} ='(no commit message)';3434}3435# remove added spaces3436foreachmy$line(@commit_lines) {3437$line=~s/^ //;3438}3439$co{'comment'} = \@commit_lines;34403441my$age=time-$co{'committer_epoch'};3442$co{'age'} =$age;3443$co{'age_string'} = age_string($age);3444my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3445if($age>60*60*24*7*2) {3446$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3447$co{'age_string_age'} =$co{'age_string'};3448}else{3449$co{'age_string_date'} =$co{'age_string'};3450$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3451}3452return%co;3453}34543455sub parse_commit {3456my($commit_id) =@_;3457my%co;34583459local$/="\0";34603461open my$fd,"-|", git_cmd(),"rev-list",3462"--parents",3463"--header",3464"--max-count=1",3465$commit_id,3466"--",3467or die_error(500,"Open git-rev-list failed");3468%co= parse_commit_text(<$fd>,1);3469close$fd;34703471return%co;3472}34733474sub parse_commits {3475my($commit_id,$maxcount,$skip,$filename,@args) =@_;3476my@cos;34773478$maxcount||=1;3479$skip||=0;34803481local$/="\0";34823483open my$fd,"-|", git_cmd(),"rev-list",3484"--header",3485@args,3486("--max-count=".$maxcount),3487("--skip=".$skip),3488@extra_options,3489$commit_id,3490"--",3491($filename? ($filename) : ())3492or die_error(500,"Open git-rev-list failed");3493while(my$line= <$fd>) {3494my%co= parse_commit_text($line);3495push@cos, \%co;3496}3497close$fd;34983499returnwantarray?@cos: \@cos;3500}35013502# parse line of git-diff-tree "raw" output3503sub parse_difftree_raw_line {3504my$line=shift;3505my%res;35063507# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3508# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3509if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3510$res{'from_mode'} =$1;3511$res{'to_mode'} =$2;3512$res{'from_id'} =$3;3513$res{'to_id'} =$4;3514$res{'status'} =$5;3515$res{'similarity'} =$6;3516if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3517($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3518}else{3519$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3520}3521}3522# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3523# combined diff (for merge commit)3524elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3525$res{'nparents'} =length($1);3526$res{'from_mode'} = [split(' ',$2) ];3527$res{'to_mode'} =pop@{$res{'from_mode'}};3528$res{'from_id'} = [split(' ',$3) ];3529$res{'to_id'} =pop@{$res{'from_id'}};3530$res{'status'} = [split('',$4) ];3531$res{'to_file'} = unquote($5);3532}3533# 'c512b523472485aef4fff9e57b229d9d243c967f'3534elsif($line=~m/^([0-9a-fA-F]{40})$/) {3535$res{'commit'} =$1;3536}35373538returnwantarray?%res: \%res;3539}35403541# wrapper: return parsed line of git-diff-tree "raw" output3542# (the argument might be raw line, or parsed info)3543sub parsed_difftree_line {3544my$line_or_ref=shift;35453546if(ref($line_or_ref)eq"HASH") {3547# pre-parsed (or generated by hand)3548return$line_or_ref;3549}else{3550return parse_difftree_raw_line($line_or_ref);3551}3552}35533554# parse line of git-ls-tree output3555sub parse_ls_tree_line {3556my$line=shift;3557my%opts=@_;3558my%res;35593560if($opts{'-l'}) {3561#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3562$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;35633564$res{'mode'} =$1;3565$res{'type'} =$2;3566$res{'hash'} =$3;3567$res{'size'} =$4;3568if($opts{'-z'}) {3569$res{'name'} =$5;3570}else{3571$res{'name'} = unquote($5);3572}3573}else{3574#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3575$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;35763577$res{'mode'} =$1;3578$res{'type'} =$2;3579$res{'hash'} =$3;3580if($opts{'-z'}) {3581$res{'name'} =$4;3582}else{3583$res{'name'} = unquote($4);3584}3585}35863587returnwantarray?%res: \%res;3588}35893590# generates _two_ hashes, references to which are passed as 2 and 3 argument3591sub parse_from_to_diffinfo {3592my($diffinfo,$from,$to,@parents) =@_;35933594if($diffinfo->{'nparents'}) {3595# combined diff3596$from->{'file'} = [];3597$from->{'href'} = [];3598 fill_from_file_info($diffinfo,@parents)3599unlessexists$diffinfo->{'from_file'};3600for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3601$from->{'file'}[$i] =3602defined$diffinfo->{'from_file'}[$i] ?3603$diffinfo->{'from_file'}[$i] :3604$diffinfo->{'to_file'};3605if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3606$from->{'href'}[$i] = href(action=>"blob",3607 hash_base=>$parents[$i],3608 hash=>$diffinfo->{'from_id'}[$i],3609 file_name=>$from->{'file'}[$i]);3610}else{3611$from->{'href'}[$i] =undef;3612}3613}3614}else{3615# ordinary (not combined) diff3616$from->{'file'} =$diffinfo->{'from_file'};3617if($diffinfo->{'status'}ne"A") {# not new (added) file3618$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3619 hash=>$diffinfo->{'from_id'},3620 file_name=>$from->{'file'});3621}else{3622delete$from->{'href'};3623}3624}36253626$to->{'file'} =$diffinfo->{'to_file'};3627if(!is_deleted($diffinfo)) {# file exists in result3628$to->{'href'} = href(action=>"blob", hash_base=>$hash,3629 hash=>$diffinfo->{'to_id'},3630 file_name=>$to->{'file'});3631}else{3632delete$to->{'href'};3633}3634}36353636## ......................................................................3637## parse to array of hashes functions36383639sub git_get_heads_list {3640my($limit,@classes) =@_;3641@classes= ('heads')unless@classes;3642my@patterns=map{"refs/$_"}@classes;3643my@headslist;36443645open my$fd,'-|', git_cmd(),'for-each-ref',3646($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3647'--format=%(objectname) %(refname) %(subject)%00%(committer)',3648@patterns3649orreturn;3650while(my$line= <$fd>) {3651my%ref_item;36523653chomp$line;3654my($refinfo,$committerinfo) =split(/\0/,$line);3655my($hash,$name,$title) =split(' ',$refinfo,3);3656my($committer,$epoch,$tz) =3657($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3658$ref_item{'fullname'} =$name;3659$name=~s!^refs/(?:head|remote)s/!!;36603661$ref_item{'name'} =$name;3662$ref_item{'id'} =$hash;3663$ref_item{'title'} =$title||'(no commit message)';3664$ref_item{'epoch'} =$epoch;3665if($epoch) {3666$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3667}else{3668$ref_item{'age'} ="unknown";3669}36703671push@headslist, \%ref_item;3672}3673close$fd;36743675returnwantarray?@headslist: \@headslist;3676}36773678sub git_get_tags_list {3679my$limit=shift;3680my@tagslist;36813682open my$fd,'-|', git_cmd(),'for-each-ref',3683($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3684'--format=%(objectname) %(objecttype) %(refname) '.3685'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3686'refs/tags'3687orreturn;3688while(my$line= <$fd>) {3689my%ref_item;36903691chomp$line;3692my($refinfo,$creatorinfo) =split(/\0/,$line);3693my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3694my($creator,$epoch,$tz) =3695($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3696$ref_item{'fullname'} =$name;3697$name=~s!^refs/tags/!!;36983699$ref_item{'type'} =$type;3700$ref_item{'id'} =$id;3701$ref_item{'name'} =$name;3702if($typeeq"tag") {3703$ref_item{'subject'} =$title;3704$ref_item{'reftype'} =$reftype;3705$ref_item{'refid'} =$refid;3706}else{3707$ref_item{'reftype'} =$type;3708$ref_item{'refid'} =$id;3709}37103711if($typeeq"tag"||$typeeq"commit") {3712$ref_item{'epoch'} =$epoch;3713if($epoch) {3714$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3715}else{3716$ref_item{'age'} ="unknown";3717}3718}37193720push@tagslist, \%ref_item;3721}3722close$fd;37233724returnwantarray?@tagslist: \@tagslist;3725}37263727## ----------------------------------------------------------------------3728## filesystem-related functions37293730sub get_file_owner {3731my$path=shift;37323733my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3734my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3735if(!defined$gcos) {3736returnundef;3737}3738my$owner=$gcos;3739$owner=~s/[,;].*$//;3740return to_utf8($owner);3741}37423743# assume that file exists3744sub insert_file {3745my$filename=shift;37463747open my$fd,'<',$filename;3748print map{ to_utf8($_) } <$fd>;3749close$fd;3750}37513752## ......................................................................3753## mimetype related functions37543755sub mimetype_guess_file {3756my$filename=shift;3757my$mimemap=shift;3758-r $mimemaporreturnundef;37593760my%mimemap;3761open(my$mh,'<',$mimemap)orreturnundef;3762while(<$mh>) {3763next ifm/^#/;# skip comments3764my($mimetype,@exts) =split(/\s+/);3765foreachmy$ext(@exts) {3766$mimemap{$ext} =$mimetype;3767}3768}3769close($mh);37703771$filename=~/\.([^.]*)$/;3772return$mimemap{$1};3773}37743775sub mimetype_guess {3776my$filename=shift;3777my$mime;3778$filename=~/\./orreturnundef;37793780if($mimetypes_file) {3781my$file=$mimetypes_file;3782if($file!~m!^/!) {# if it is relative path3783# it is relative to project3784$file="$projectroot/$project/$file";3785}3786$mime= mimetype_guess_file($filename,$file);3787}3788$mime||= mimetype_guess_file($filename,'/etc/mime.types');3789return$mime;3790}37913792sub blob_mimetype {3793my$fd=shift;3794my$filename=shift;37953796if($filename) {3797my$mime= mimetype_guess($filename);3798$mimeandreturn$mime;3799}38003801# just in case3802return$default_blob_plain_mimetypeunless$fd;38033804if(-T $fd) {3805return'text/plain';3806}elsif(!$filename) {3807return'application/octet-stream';3808}elsif($filename=~m/\.png$/i) {3809return'image/png';3810}elsif($filename=~m/\.gif$/i) {3811return'image/gif';3812}elsif($filename=~m/\.jpe?g$/i) {3813return'image/jpeg';3814}else{3815return'application/octet-stream';3816}3817}38183819sub blob_contenttype {3820my($fd,$file_name,$type) =@_;38213822$type||= blob_mimetype($fd,$file_name);3823if($typeeq'text/plain'&&defined$default_text_plain_charset) {3824$type.="; charset=$default_text_plain_charset";3825}38263827return$type;3828}38293830# guess file syntax for syntax highlighting; return undef if no highlighting3831# the name of syntax can (in the future) depend on syntax highlighter used3832sub guess_file_syntax {3833my($highlight,$mimetype,$file_name) =@_;3834returnundefunless($highlight&&defined$file_name);3835my$basename= basename($file_name,'.in');3836return$highlight_basename{$basename}3837ifexists$highlight_basename{$basename};38383839$basename=~/\.([^.]*)$/;3840my$ext=$1orreturnundef;3841return$highlight_ext{$ext}3842ifexists$highlight_ext{$ext};38433844returnundef;3845}38463847# run highlighter and return FD of its output,3848# or return original FD if no highlighting3849sub run_highlighter {3850my($fd,$highlight,$syntax) =@_;3851return$fdunless($highlight&&defined$syntax);38523853close$fd;3854open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3855 quote_command($highlight_bin).3856" --replace-tabs=8 --fragment --syntax$syntax|"3857or die_error(500,"Couldn't open file or run syntax highlighter");3858return$fd;3859}38603861## ======================================================================3862## functions printing HTML: header, footer, error page38633864sub get_page_title {3865my$title= to_utf8($site_name);38663867unless(defined$project) {3868if(defined$project_filter) {3869$title.=" - projects in '". esc_path($project_filter) ."'";3870}3871return$title;3872}3873$title.=" - ". to_utf8($project);38743875return$titleunless(defined$action);3876$title.="/$action";# $action is US-ASCII (7bit ASCII)38773878return$titleunless(defined$file_name);3879$title.=" - ". esc_path($file_name);3880if($actioneq"tree"&&$file_name!~ m|/$|) {3881$title.="/";3882}38833884return$title;3885}38863887sub get_content_type_html {3888# require explicit support from the UA if we are to send the page as3889# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3890# we have to do this because MSIE sometimes globs '*/*', pretending to3891# support xhtml+xml but choking when it gets what it asked for.3892if(defined$cgi->http('HTTP_ACCEPT') &&3893$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3894$cgi->Accept('application/xhtml+xml') !=0) {3895return'application/xhtml+xml';3896}else{3897return'text/html';3898}3899}39003901sub print_feed_meta {3902if(defined$project) {3903my%href_params= get_feed_info();3904if(!exists$href_params{'-title'}) {3905$href_params{'-title'} ='log';3906}39073908foreachmy$format(qw(RSS Atom)) {3909my$type=lc($format);3910my%link_attr= (3911'-rel'=>'alternate',3912'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3913'-type'=>"application/$type+xml"3914);39153916$href_params{'extra_options'} =undef;3917$href_params{'action'} =$type;3918$link_attr{'-href'} = href(%href_params);3919print"<link ".3920"rel=\"$link_attr{'-rel'}\"".3921"title=\"$link_attr{'-title'}\"".3922"href=\"$link_attr{'-href'}\"".3923"type=\"$link_attr{'-type'}\"".3924"/>\n";39253926$href_params{'extra_options'} ='--no-merges';3927$link_attr{'-href'} = href(%href_params);3928$link_attr{'-title'} .=' (no merges)';3929print"<link ".3930"rel=\"$link_attr{'-rel'}\"".3931"title=\"$link_attr{'-title'}\"".3932"href=\"$link_attr{'-href'}\"".3933"type=\"$link_attr{'-type'}\"".3934"/>\n";3935}39363937}else{3938printf('<link rel="alternate" title="%sprojects list" '.3939'href="%s" type="text/plain; charset=utf-8" />'."\n",3940 esc_attr($site_name), href(project=>undef, action=>"project_index"));3941printf('<link rel="alternate" title="%sprojects feeds" '.3942'href="%s" type="text/x-opml" />'."\n",3943 esc_attr($site_name), href(project=>undef, action=>"opml"));3944}3945}39463947sub print_header_links {3948my$status=shift;39493950# print out each stylesheet that exist, providing backwards capability3951# for those people who defined $stylesheet in a config file3952if(defined$stylesheet) {3953print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3954}else{3955foreachmy$stylesheet(@stylesheets) {3956next unless$stylesheet;3957print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3958}3959}3960 print_feed_meta()3961if($statuseq'200 OK');3962if(defined$favicon) {3963printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3964}3965}39663967sub print_nav_breadcrumbs_path {3968my$dirprefix=undef;3969while(my$part=shift) {3970$dirprefix.="/"ifdefined$dirprefix;3971$dirprefix.=$part;3972print$cgi->a({-href => href(project =>undef,3973 project_filter =>$dirprefix,3974 action =>"project_list")},3975 esc_html($part)) ." / ";3976}3977}39783979sub print_nav_breadcrumbs {3980my%opts=@_;39813982print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3983if(defined$project) {3984my@dirname=split'/',$project;3985my$projectbasename=pop@dirname;3986 print_nav_breadcrumbs_path(@dirname);3987print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));3988if(defined$action) {3989my$action_print=$action;3990if(defined$opts{-action_extra}) {3991$action_print=$cgi->a({-href => href(action=>$action)},3992$action);3993}3994print" /$action_print";3995}3996if(defined$opts{-action_extra}) {3997print" /$opts{-action_extra}";3998}3999print"\n";4000}elsif(defined$project_filter) {4001 print_nav_breadcrumbs_path(split'/',$project_filter);4002}4003}40044005sub print_search_form {4006if(!defined$searchtext) {4007$searchtext="";4008}4009my$search_hash;4010if(defined$hash_base) {4011$search_hash=$hash_base;4012}elsif(defined$hash) {4013$search_hash=$hash;4014}else{4015$search_hash="HEAD";4016}4017my$action=$my_uri;4018my$use_pathinfo= gitweb_check_feature('pathinfo');4019if($use_pathinfo) {4020$action.="/".esc_url($project);4021}4022print$cgi->startform(-method=>"get", -action =>$action) .4023"<div class=\"search\">\n".4024(!$use_pathinfo&&4025$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4026$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4027$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4028$cgi->popup_menu(-name =>'st', -default=>'commit',4029-values=> ['commit','grep','author','committer','pickaxe']) .4030$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .4031" search:\n",4032$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4033"<span title=\"Extended regular expression\">".4034$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4035-checked =>$search_use_regexp) .4036"</span>".4037"</div>".4038$cgi->end_form() ."\n";4039}40404041sub git_header_html {4042my$status=shift||"200 OK";4043my$expires=shift;4044my%opts=@_;40454046my$title= get_page_title();4047my$content_type= get_content_type_html();4048print$cgi->header(-type=>$content_type, -charset =>'utf-8',4049-status=>$status, -expires =>$expires)4050unless($opts{'-no_http_header'});4051my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4052print<<EOF;4053<?xml version="1.0" encoding="utf-8"?>4054<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4055<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4056<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4057<!-- git core binaries version$git_version-->4058<head>4059<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4060<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4061<meta name="robots" content="index, nofollow"/>4062<title>$title</title>4063EOF4064# the stylesheet, favicon etc urls won't work correctly with path_info4065# unless we set the appropriate base URL4066if($ENV{'PATH_INFO'}) {4067print"<base href=\"".esc_url($base_url)."\"/>\n";4068}4069 print_header_links($status);40704071if(defined$site_html_head_string) {4072print to_utf8($site_html_head_string);4073}40744075print"</head>\n".4076"<body>\n";40774078if(defined$site_header&& -f $site_header) {4079 insert_file($site_header);4080}40814082print"<div class=\"page_header\">\n";4083if(defined$logo) {4084print$cgi->a({-href => esc_url($logo_url),4085-title =>$logo_label},4086$cgi->img({-src => esc_url($logo),4087-width =>72, -height =>27,4088-alt =>"git",4089-class=>"logo"}));4090}4091 print_nav_breadcrumbs(%opts);4092print"</div>\n";40934094my$have_search= gitweb_check_feature('search');4095if(defined$project&&$have_search) {4096 print_search_form();4097}4098}40994100sub git_footer_html {4101my$feed_class='rss_logo';41024103print"<div class=\"page_footer\">\n";4104if(defined$project) {4105my$descr= git_get_project_description($project);4106if(defined$descr) {4107print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4108}41094110my%href_params= get_feed_info();4111if(!%href_params) {4112$feed_class.=' generic';4113}4114$href_params{'-title'} ||='log';41154116foreachmy$format(qw(RSS Atom)) {4117$href_params{'action'} =lc($format);4118print$cgi->a({-href => href(%href_params),4119-title =>"$href_params{'-title'}$formatfeed",4120-class=>$feed_class},$format)."\n";4121}41224123}else{4124print$cgi->a({-href => href(project=>undef, action=>"opml",4125 project_filter =>$project_filter),4126-class=>$feed_class},"OPML") ." ";4127print$cgi->a({-href => href(project=>undef, action=>"project_index",4128 project_filter =>$project_filter),4129-class=>$feed_class},"TXT") ."\n";4130}4131print"</div>\n";# class="page_footer"41324133if(defined$t0&& gitweb_check_feature('timed')) {4134print"<div id=\"generating_info\">\n";4135print'This page took '.4136'<span id="generating_time" class="time_span">'.4137 tv_interval($t0, [ gettimeofday() ]).4138' seconds </span>'.4139' and '.4140'<span id="generating_cmd">'.4141$number_of_git_cmds.4142'</span> git commands '.4143" to generate.\n";4144print"</div>\n";# class="page_footer"4145}41464147if(defined$site_footer&& -f $site_footer) {4148 insert_file($site_footer);4149}41504151print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4152if(defined$action&&4153$actioneq'blame_incremental') {4154print qq!<script type="text/javascript">\n!.4155 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4156 qq!"!. href() .qq!");\n!.4157 qq!</script>\n!;4158}else{4159my($jstimezone,$tz_cookie,$datetime_class) =4160 gitweb_get_feature('javascript-timezone');41614162print qq!<script type="text/javascript">\n!.4163 qq!window.onload = function () {\n!;4164if(gitweb_check_feature('javascript-actions')) {4165print qq! fixLinks();\n!;4166}4167if($jstimezone&&$tz_cookie&&$datetime_class) {4168print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4169 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4170}4171print qq!};\n!.4172 qq!</script>\n!;4173}41744175print"</body>\n".4176"</html>";4177}41784179# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4180# Example: die_error(404, 'Hash not found')4181# By convention, use the following status codes (as defined in RFC 2616):4182# 400: Invalid or missing CGI parameters, or4183# requested object exists but has wrong type.4184# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4185# this server or project.4186# 404: Requested object/revision/project doesn't exist.4187# 500: The server isn't configured properly, or4188# an internal error occurred (e.g. failed assertions caused by bugs), or4189# an unknown error occurred (e.g. the git binary died unexpectedly).4190# 503: The server is currently unavailable (because it is overloaded,4191# or down for maintenance). Generally, this is a temporary state.4192sub die_error {4193my$status=shift||500;4194my$error= esc_html(shift) ||"Internal Server Error";4195my$extra=shift;4196my%opts=@_;41974198my%http_responses= (4199400=>'400 Bad Request',4200403=>'403 Forbidden',4201404=>'404 Not Found',4202500=>'500 Internal Server Error',4203503=>'503 Service Unavailable',4204);4205 git_header_html($http_responses{$status},undef,%opts);4206print<<EOF;4207<div class="page_body">4208<br /><br />4209$status-$error4210<br />4211EOF4212if(defined$extra) {4213print"<hr />\n".4214"$extra\n";4215}4216print"</div>\n";42174218 git_footer_html();4219goto DONE_GITWEB4220unless($opts{'-error_handler'});4221}42224223## ----------------------------------------------------------------------4224## functions printing or outputting HTML: navigation42254226sub git_print_page_nav {4227my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4228$extra=''if!defined$extra;# pager or formats42294230my@navs=qw(summary shortlog log commit commitdiff tree);4231if($suppress) {4232@navs=grep{$_ne$suppress}@navs;4233}42344235my%arg=map{$_=> {action=>$_} }@navs;4236if(defined$head) {4237for(qw(commit commitdiff)) {4238$arg{$_}{'hash'} =$head;4239}4240if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4241for(qw(shortlog log)) {4242$arg{$_}{'hash'} =$head;4243}4244}4245}42464247$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4248$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;42494250my@actions= gitweb_get_feature('actions');4251my%repl= (4252'%'=>'%',4253'n'=>$project,# project name4254'f'=>$git_dir,# project path within filesystem4255'h'=>$treehead||'',# current hash ('h' parameter)4256'b'=>$treebase||'',# hash base ('hb' parameter)4257);4258while(@actions) {4259my($label,$link,$pos) =splice(@actions,0,3);4260# insert4261@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4262# munch munch4263$link=~s/%([%nfhb])/$repl{$1}/g;4264$arg{$label}{'_href'} =$link;4265}42664267print"<div class=\"page_nav\">\n".4268(join" | ",4269map{$_eq$current?4270$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4271}@navs);4272print"<br/>\n$extra<br/>\n".4273"</div>\n";4274}42754276# returns a submenu for the nagivation of the refs views (tags, heads,4277# remotes) with the current view disabled and the remotes view only4278# available if the feature is enabled4279sub format_ref_views {4280my($current) =@_;4281my@ref_views=qw{tags heads};4282push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4283returnjoin" | ",map{4284$_eq$current?$_:4285$cgi->a({-href => href(action=>$_)},$_)4286}@ref_views4287}42884289sub format_paging_nav {4290my($action,$page,$has_next_link) =@_;4291my$paging_nav;429242934294if($page>0) {4295$paging_nav.=4296$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4297" ⋅ ".4298$cgi->a({-href => href(-replay=>1, page=>$page-1),4299-accesskey =>"p", -title =>"Alt-p"},"prev");4300}else{4301$paging_nav.="first ⋅ prev";4302}43034304if($has_next_link) {4305$paging_nav.=" ⋅ ".4306$cgi->a({-href => href(-replay=>1, page=>$page+1),4307-accesskey =>"n", -title =>"Alt-n"},"next");4308}else{4309$paging_nav.=" ⋅ next";4310}43114312return$paging_nav;4313}43144315## ......................................................................4316## functions printing or outputting HTML: div43174318sub git_print_header_div {4319my($action,$title,$hash,$hash_base) =@_;4320my%args= ();43214322$args{'action'} =$action;4323$args{'hash'} =$hashif$hash;4324$args{'hash_base'} =$hash_baseif$hash_base;43254326print"<div class=\"header\">\n".4327$cgi->a({-href => href(%args), -class=>"title"},4328$title?$title:$action) .4329"\n</div>\n";4330}43314332sub format_repo_url {4333my($name,$url) =@_;4334return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4335}43364337# Group output by placing it in a DIV element and adding a header.4338# Options for start_div() can be provided by passing a hash reference as the4339# first parameter to the function.4340# Options to git_print_header_div() can be provided by passing an array4341# reference. This must follow the options to start_div if they are present.4342# The content can be a scalar, which is output as-is, a scalar reference, which4343# is output after html escaping, an IO handle passed either as *handle or4344# *handle{IO}, or a function reference. In the latter case all following4345# parameters will be taken as argument to the content function call.4346sub git_print_section {4347my($div_args,$header_args,$content);4348my$arg=shift;4349if(ref($arg)eq'HASH') {4350$div_args=$arg;4351$arg=shift;4352}4353if(ref($arg)eq'ARRAY') {4354$header_args=$arg;4355$arg=shift;4356}4357$content=$arg;43584359print$cgi->start_div($div_args);4360 git_print_header_div(@$header_args);43614362if(ref($content)eq'CODE') {4363$content->(@_);4364}elsif(ref($content)eq'SCALAR') {4365print esc_html($$content);4366}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4367print<$content>;4368}elsif(!ref($content) &&defined($content)) {4369print$content;4370}43714372print$cgi->end_div;4373}43744375sub format_timestamp_html {4376my$date=shift;4377my$strtime=$date->{'rfc2822'};43784379my(undef,undef,$datetime_class) =4380 gitweb_get_feature('javascript-timezone');4381if($datetime_class) {4382$strtime= qq!<span class="$datetime_class">$strtime</span>!;4383}43844385my$localtime_format='(%02d:%02d%s)';4386if($date->{'hour_local'} <6) {4387$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4388}4389$strtime.=' '.4390sprintf($localtime_format,4391$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});43924393return$strtime;4394}43954396# Outputs the author name and date in long form4397sub git_print_authorship {4398my$co=shift;4399my%opts=@_;4400my$tag=$opts{-tag} ||'div';4401my$author=$co->{'author_name'};44024403my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4404print"<$tagclass=\"author_date\">".4405 format_search_author($author,"author", esc_html($author)) .4406" [".format_timestamp_html(\%ad)."]".4407 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4408"</$tag>\n";4409}44104411# Outputs table rows containing the full author or committer information,4412# in the format expected for 'commit' view (& similar).4413# Parameters are a commit hash reference, followed by the list of people4414# to output information for. If the list is empty it defaults to both4415# author and committer.4416sub git_print_authorship_rows {4417my$co=shift;4418# too bad we can't use @people = @_ || ('author', 'committer')4419my@people=@_;4420@people= ('author','committer')unless@people;4421foreachmy$who(@people) {4422my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4423print"<tr><td>$who</td><td>".4424 format_search_author($co->{"${who}_name"},$who,4425 esc_html($co->{"${who}_name"})) ." ".4426 format_search_author($co->{"${who}_email"},$who,4427 esc_html("<".$co->{"${who}_email"} .">")) .4428"</td><td rowspan=\"2\">".4429 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4430"</td></tr>\n".4431"<tr>".4432"<td></td><td>".4433 format_timestamp_html(\%wd) .4434"</td>".4435"</tr>\n";4436}4437}44384439sub git_print_page_path {4440my$name=shift;4441my$type=shift;4442my$hb=shift;444344444445print"<div class=\"page_path\">";4446print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4447-title =>'tree root'}, to_utf8("[$project]"));4448print" / ";4449if(defined$name) {4450my@dirname=split'/',$name;4451my$basename=pop@dirname;4452my$fullname='';44534454foreachmy$dir(@dirname) {4455$fullname.= ($fullname?'/':'') .$dir;4456print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4457 hash_base=>$hb),4458-title =>$fullname}, esc_path($dir));4459print" / ";4460}4461if(defined$type&&$typeeq'blob') {4462print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4463 hash_base=>$hb),4464-title =>$name}, esc_path($basename));4465}elsif(defined$type&&$typeeq'tree') {4466print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4467 hash_base=>$hb),4468-title =>$name}, esc_path($basename));4469print" / ";4470}else{4471print esc_path($basename);4472}4473}4474print"<br/></div>\n";4475}44764477sub git_print_log {4478my$log=shift;4479my%opts=@_;44804481if($opts{'-remove_title'}) {4482# remove title, i.e. first line of log4483shift@$log;4484}4485# remove leading empty lines4486while(defined$log->[0] &&$log->[0]eq"") {4487shift@$log;4488}44894490# print log4491my$skip_blank_line=0;4492foreachmy$line(@$log) {4493if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4494if(!$opts{'-remove_signoff'}) {4495print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4496$skip_blank_line=1;4497}4498next;4499}45004501if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4502if(!$opts{'-remove_signoff'}) {4503print"<span class=\"signoff\">". esc_html($1) .": ".4504"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4505"</span><br/>\n";4506$skip_blank_line=1;4507}4508next;4509}45104511# print only one empty line4512# do not print empty line after signoff4513if($lineeq"") {4514next if($skip_blank_line);4515$skip_blank_line=1;4516}else{4517$skip_blank_line=0;4518}45194520print format_log_line_html($line) ."<br/>\n";4521}45224523if($opts{'-final_empty_line'}) {4524# end with single empty line4525print"<br/>\n"unless$skip_blank_line;4526}4527}45284529# return link target (what link points to)4530sub git_get_link_target {4531my$hash=shift;4532my$link_target;45334534# read link4535open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4536orreturn;4537{4538local$/=undef;4539$link_target= <$fd>;4540}4541close$fd4542orreturn;45434544return$link_target;4545}45464547# given link target, and the directory (basedir) the link is in,4548# return target of link relative to top directory (top tree);4549# return undef if it is not possible (including absolute links).4550sub normalize_link_target {4551my($link_target,$basedir) =@_;45524553# absolute symlinks (beginning with '/') cannot be normalized4554return if(substr($link_target,0,1)eq'/');45554556# normalize link target to path from top (root) tree (dir)4557my$path;4558if($basedir) {4559$path=$basedir.'/'.$link_target;4560}else{4561# we are in top (root) tree (dir)4562$path=$link_target;4563}45644565# remove //, /./, and /../4566my@path_parts;4567foreachmy$part(split('/',$path)) {4568# discard '.' and ''4569next if(!$part||$parteq'.');4570# handle '..'4571if($parteq'..') {4572if(@path_parts) {4573pop@path_parts;4574}else{4575# link leads outside repository (outside top dir)4576return;4577}4578}else{4579push@path_parts,$part;4580}4581}4582$path=join('/',@path_parts);45834584return$path;4585}45864587# print tree entry (row of git_tree), but without encompassing <tr> element4588sub git_print_tree_entry {4589my($t,$basedir,$hash_base,$have_blame) =@_;45904591my%base_key= ();4592$base_key{'hash_base'} =$hash_baseifdefined$hash_base;45934594# The format of a table row is: mode list link. Where mode is4595# the mode of the entry, list is the name of the entry, an href,4596# and link is the action links of the entry.45974598print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4599if(exists$t->{'size'}) {4600print"<td class=\"size\">$t->{'size'}</td>\n";4601}4602if($t->{'type'}eq"blob") {4603print"<td class=\"list\">".4604$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4605 file_name=>"$basedir$t->{'name'}",%base_key),4606-class=>"list"}, esc_path($t->{'name'}));4607if(S_ISLNK(oct$t->{'mode'})) {4608my$link_target= git_get_link_target($t->{'hash'});4609if($link_target) {4610my$norm_target= normalize_link_target($link_target,$basedir);4611if(defined$norm_target) {4612print" -> ".4613$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4614 file_name=>$norm_target),4615-title =>$norm_target}, esc_path($link_target));4616}else{4617print" -> ". esc_path($link_target);4618}4619}4620}4621print"</td>\n";4622print"<td class=\"link\">";4623print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4624 file_name=>"$basedir$t->{'name'}",%base_key)},4625"blob");4626if($have_blame) {4627print" | ".4628$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4629 file_name=>"$basedir$t->{'name'}",%base_key)},4630"blame");4631}4632if(defined$hash_base) {4633print" | ".4634$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4635 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4636"history");4637}4638print" | ".4639$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4640 file_name=>"$basedir$t->{'name'}")},4641"raw");4642print"</td>\n";46434644}elsif($t->{'type'}eq"tree") {4645print"<td class=\"list\">";4646print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4647 file_name=>"$basedir$t->{'name'}",4648%base_key)},4649 esc_path($t->{'name'}));4650print"</td>\n";4651print"<td class=\"link\">";4652print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4653 file_name=>"$basedir$t->{'name'}",4654%base_key)},4655"tree");4656if(defined$hash_base) {4657print" | ".4658$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4659 file_name=>"$basedir$t->{'name'}")},4660"history");4661}4662print"</td>\n";4663}else{4664# unknown object: we can only present history for it4665# (this includes 'commit' object, i.e. submodule support)4666print"<td class=\"list\">".4667 esc_path($t->{'name'}) .4668"</td>\n";4669print"<td class=\"link\">";4670if(defined$hash_base) {4671print$cgi->a({-href => href(action=>"history",4672 hash_base=>$hash_base,4673 file_name=>"$basedir$t->{'name'}")},4674"history");4675}4676print"</td>\n";4677}4678}46794680## ......................................................................4681## functions printing large fragments of HTML46824683# get pre-image filenames for merge (combined) diff4684sub fill_from_file_info {4685my($diff,@parents) =@_;46864687$diff->{'from_file'} = [ ];4688$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4689for(my$i=0;$i<$diff->{'nparents'};$i++) {4690if($diff->{'status'}[$i]eq'R'||4691$diff->{'status'}[$i]eq'C') {4692$diff->{'from_file'}[$i] =4693 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4694}4695}46964697return$diff;4698}46994700# is current raw difftree line of file deletion4701sub is_deleted {4702my$diffinfo=shift;47034704return$diffinfo->{'to_id'}eq('0' x 40);4705}47064707# does patch correspond to [previous] difftree raw line4708# $diffinfo - hashref of parsed raw diff format4709# $patchinfo - hashref of parsed patch diff format4710# (the same keys as in $diffinfo)4711sub is_patch_split {4712my($diffinfo,$patchinfo) =@_;47134714returndefined$diffinfo&&defined$patchinfo4715&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4716}471747184719sub git_difftree_body {4720my($difftree,$hash,@parents) =@_;4721my($parent) =$parents[0];4722my$have_blame= gitweb_check_feature('blame');4723print"<div class=\"list_head\">\n";4724if($#{$difftree} >10) {4725print(($#{$difftree} +1) ." files changed:\n");4726}4727print"</div>\n";47284729print"<table class=\"".4730(@parents>1?"combined ":"") .4731"diff_tree\">\n";47324733# header only for combined diff in 'commitdiff' view4734my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4735if($has_header) {4736# table header4737print"<thead><tr>\n".4738"<th></th><th></th>\n";# filename, patchN link4739for(my$i=0;$i<@parents;$i++) {4740my$par=$parents[$i];4741print"<th>".4742$cgi->a({-href => href(action=>"commitdiff",4743 hash=>$hash, hash_parent=>$par),4744-title =>'commitdiff to parent number '.4745($i+1) .': '.substr($par,0,7)},4746$i+1) .4747" </th>\n";4748}4749print"</tr></thead>\n<tbody>\n";4750}47514752my$alternate=1;4753my$patchno=0;4754foreachmy$line(@{$difftree}) {4755my$diff= parsed_difftree_line($line);47564757if($alternate) {4758print"<tr class=\"dark\">\n";4759}else{4760print"<tr class=\"light\">\n";4761}4762$alternate^=1;47634764if(exists$diff->{'nparents'}) {# combined diff47654766 fill_from_file_info($diff,@parents)4767unlessexists$diff->{'from_file'};47684769if(!is_deleted($diff)) {4770# file exists in the result (child) commit4771print"<td>".4772$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4773 file_name=>$diff->{'to_file'},4774 hash_base=>$hash),4775-class=>"list"}, esc_path($diff->{'to_file'})) .4776"</td>\n";4777}else{4778print"<td>".4779 esc_path($diff->{'to_file'}) .4780"</td>\n";4781}47824783if($actioneq'commitdiff') {4784# link to patch4785$patchno++;4786print"<td class=\"link\">".4787$cgi->a({-href => href(-anchor=>"patch$patchno")},4788"patch") .4789" | ".4790"</td>\n";4791}47924793my$has_history=0;4794my$not_deleted=0;4795for(my$i=0;$i<$diff->{'nparents'};$i++) {4796my$hash_parent=$parents[$i];4797my$from_hash=$diff->{'from_id'}[$i];4798my$from_path=$diff->{'from_file'}[$i];4799my$status=$diff->{'status'}[$i];48004801$has_history||= ($statusne'A');4802$not_deleted||= ($statusne'D');48034804if($statuseq'A') {4805print"<td class=\"link\"align=\"right\"> | </td>\n";4806}elsif($statuseq'D') {4807print"<td class=\"link\">".4808$cgi->a({-href => href(action=>"blob",4809 hash_base=>$hash,4810 hash=>$from_hash,4811 file_name=>$from_path)},4812"blob". ($i+1)) .4813" | </td>\n";4814}else{4815if($diff->{'to_id'}eq$from_hash) {4816print"<td class=\"link nochange\">";4817}else{4818print"<td class=\"link\">";4819}4820print$cgi->a({-href => href(action=>"blobdiff",4821 hash=>$diff->{'to_id'},4822 hash_parent=>$from_hash,4823 hash_base=>$hash,4824 hash_parent_base=>$hash_parent,4825 file_name=>$diff->{'to_file'},4826 file_parent=>$from_path)},4827"diff". ($i+1)) .4828" | </td>\n";4829}4830}48314832print"<td class=\"link\">";4833if($not_deleted) {4834print$cgi->a({-href => href(action=>"blob",4835 hash=>$diff->{'to_id'},4836 file_name=>$diff->{'to_file'},4837 hash_base=>$hash)},4838"blob");4839print" | "if($has_history);4840}4841if($has_history) {4842print$cgi->a({-href => href(action=>"history",4843 file_name=>$diff->{'to_file'},4844 hash_base=>$hash)},4845"history");4846}4847print"</td>\n";48484849print"</tr>\n";4850next;# instead of 'else' clause, to avoid extra indent4851}4852# else ordinary diff48534854my($to_mode_oct,$to_mode_str,$to_file_type);4855my($from_mode_oct,$from_mode_str,$from_file_type);4856if($diff->{'to_mode'}ne('0' x 6)) {4857$to_mode_oct=oct$diff->{'to_mode'};4858if(S_ISREG($to_mode_oct)) {# only for regular file4859$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4860}4861$to_file_type= file_type($diff->{'to_mode'});4862}4863if($diff->{'from_mode'}ne('0' x 6)) {4864$from_mode_oct=oct$diff->{'from_mode'};4865if(S_ISREG($from_mode_oct)) {# only for regular file4866$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4867}4868$from_file_type= file_type($diff->{'from_mode'});4869}48704871if($diff->{'status'}eq"A") {# created4872my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4873$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4874$mode_chng.="]</span>";4875print"<td>";4876print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4877 hash_base=>$hash, file_name=>$diff->{'file'}),4878-class=>"list"}, esc_path($diff->{'file'}));4879print"</td>\n";4880print"<td>$mode_chng</td>\n";4881print"<td class=\"link\">";4882if($actioneq'commitdiff') {4883# link to patch4884$patchno++;4885print$cgi->a({-href => href(-anchor=>"patch$patchno")},4886"patch") .4887" | ";4888}4889print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4890 hash_base=>$hash, file_name=>$diff->{'file'})},4891"blob");4892print"</td>\n";48934894}elsif($diff->{'status'}eq"D") {# deleted4895my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4896print"<td>";4897print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4898 hash_base=>$parent, file_name=>$diff->{'file'}),4899-class=>"list"}, esc_path($diff->{'file'}));4900print"</td>\n";4901print"<td>$mode_chng</td>\n";4902print"<td class=\"link\">";4903if($actioneq'commitdiff') {4904# link to patch4905$patchno++;4906print$cgi->a({-href => href(-anchor=>"patch$patchno")},4907"patch") .4908" | ";4909}4910print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4911 hash_base=>$parent, file_name=>$diff->{'file'})},4912"blob") ." | ";4913if($have_blame) {4914print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4915 file_name=>$diff->{'file'})},4916"blame") ." | ";4917}4918print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4919 file_name=>$diff->{'file'})},4920"history");4921print"</td>\n";49224923}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4924my$mode_chnge="";4925if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4926$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4927if($from_file_typene$to_file_type) {4928$mode_chnge.=" from$from_file_typeto$to_file_type";4929}4930if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4931if($from_mode_str&&$to_mode_str) {4932$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4933}elsif($to_mode_str) {4934$mode_chnge.=" mode:$to_mode_str";4935}4936}4937$mode_chnge.="]</span>\n";4938}4939print"<td>";4940print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4941 hash_base=>$hash, file_name=>$diff->{'file'}),4942-class=>"list"}, esc_path($diff->{'file'}));4943print"</td>\n";4944print"<td>$mode_chnge</td>\n";4945print"<td class=\"link\">";4946if($actioneq'commitdiff') {4947# link to patch4948$patchno++;4949print$cgi->a({-href => href(-anchor=>"patch$patchno")},4950"patch") .4951" | ";4952}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4953# "commit" view and modified file (not onlu mode changed)4954print$cgi->a({-href => href(action=>"blobdiff",4955 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4956 hash_base=>$hash, hash_parent_base=>$parent,4957 file_name=>$diff->{'file'})},4958"diff") .4959" | ";4960}4961print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4962 hash_base=>$hash, file_name=>$diff->{'file'})},4963"blob") ." | ";4964if($have_blame) {4965print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4966 file_name=>$diff->{'file'})},4967"blame") ." | ";4968}4969print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4970 file_name=>$diff->{'file'})},4971"history");4972print"</td>\n";49734974}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4975my%status_name= ('R'=>'moved','C'=>'copied');4976my$nstatus=$status_name{$diff->{'status'}};4977my$mode_chng="";4978if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4979# mode also for directories, so we cannot use $to_mode_str4980$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4981}4982print"<td>".4983$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4984 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4985-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4986"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4987$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4988 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4989-class=>"list"}, esc_path($diff->{'from_file'})) .4990" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4991"<td class=\"link\">";4992if($actioneq'commitdiff') {4993# link to patch4994$patchno++;4995print$cgi->a({-href => href(-anchor=>"patch$patchno")},4996"patch") .4997" | ";4998}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4999# "commit" view and modified file (not only pure rename or copy)5000print$cgi->a({-href => href(action=>"blobdiff",5001 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5002 hash_base=>$hash, hash_parent_base=>$parent,5003 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5004"diff") .5005" | ";5006}5007print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5008 hash_base=>$parent, file_name=>$diff->{'to_file'})},5009"blob") ." | ";5010if($have_blame) {5011print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5012 file_name=>$diff->{'to_file'})},5013"blame") ." | ";5014}5015print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5016 file_name=>$diff->{'to_file'})},5017"history");5018print"</td>\n";50195020}# we should not encounter Unmerged (U) or Unknown (X) status5021print"</tr>\n";5022}5023print"</tbody>"if$has_header;5024print"</table>\n";5025}50265027# Print context lines and then rem/add lines in a side-by-side manner.5028sub print_sidebyside_diff_lines {5029my($ctx,$rem,$add) =@_;50305031# print context block before add/rem block5032if(@$ctx) {5033print join'',5034'<div class="chunk_block ctx">',5035'<div class="old">',5036@$ctx,5037'</div>',5038'<div class="new">',5039@$ctx,5040'</div>',5041'</div>';5042}50435044if(!@$add) {5045# pure removal5046print join'',5047'<div class="chunk_block rem">',5048'<div class="old">',5049@$rem,5050'</div>',5051'</div>';5052}elsif(!@$rem) {5053# pure addition5054print join'',5055'<div class="chunk_block add">',5056'<div class="new">',5057@$add,5058'</div>',5059'</div>';5060}else{5061print join'',5062'<div class="chunk_block chg">',5063'<div class="old">',5064@$rem,5065'</div>',5066'<div class="new">',5067@$add,5068'</div>',5069'</div>';5070}5071}50725073# Print context lines and then rem/add lines in inline manner.5074sub print_inline_diff_lines {5075my($ctx,$rem,$add) =@_;50765077print@$ctx,@$rem,@$add;5078}50795080# Format removed and added line, mark changed part and HTML-format them.5081# Implementation is based on contrib/diff-highlight5082sub format_rem_add_lines_pair {5083my($rem,$add,$num_parents) =@_;50845085# We need to untabify lines before split()'ing them;5086# otherwise offsets would be invalid.5087chomp$rem;5088chomp$add;5089$rem= untabify($rem);5090$add= untabify($add);50915092my@rem=split(//,$rem);5093my@add=split(//,$add);5094my($esc_rem,$esc_add);5095# Ignore leading +/- characters for each parent.5096my($prefix_len,$suffix_len) = ($num_parents,0);5097my($prefix_has_nonspace,$suffix_has_nonspace);50985099my$shorter= (@rem<@add) ?@rem:@add;5100while($prefix_len<$shorter) {5101last if($rem[$prefix_len]ne$add[$prefix_len]);51025103$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5104$prefix_len++;5105}51065107while($prefix_len+$suffix_len<$shorter) {5108last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51095110$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5111$suffix_len++;5112}51135114# Mark lines that are different from each other, but have some common5115# part that isn't whitespace. If lines are completely different, don't5116# mark them because that would make output unreadable, especially if5117# diff consists of multiple lines.5118if($prefix_has_nonspace||$suffix_has_nonspace) {5119$esc_rem= esc_html_hl_regions($rem,'marked',5120[$prefix_len,@rem-$suffix_len], -nbsp=>1);5121$esc_add= esc_html_hl_regions($add,'marked',5122[$prefix_len,@add-$suffix_len], -nbsp=>1);5123}else{5124$esc_rem= esc_html($rem, -nbsp=>1);5125$esc_add= esc_html($add, -nbsp=>1);5126}51275128return format_diff_line(\$esc_rem,'rem'),5129 format_diff_line(\$esc_add,'add');5130}51315132# HTML-format diff context, removed and added lines.5133sub format_ctx_rem_add_lines {5134my($ctx,$rem,$add,$num_parents) =@_;5135my(@new_ctx,@new_rem,@new_add);5136my$can_highlight=0;5137my$is_combined= ($num_parents>1);51385139# Highlight if every removed line has a corresponding added line.5140if(@$add>0&&@$add==@$rem) {5141$can_highlight=1;51425143# Highlight lines in combined diff only if the chunk contains5144# diff between the same version, e.g.5145#5146# - a5147# - b5148# + c5149# + d5150#5151# Otherwise the highlightling would be confusing.5152if($is_combined) {5153for(my$i=0;$i<@$add;$i++) {5154my$prefix_rem=substr($rem->[$i],0,$num_parents);5155my$prefix_add=substr($add->[$i],0,$num_parents);51565157$prefix_rem=~s/-/+/g;51585159if($prefix_remne$prefix_add) {5160$can_highlight=0;5161last;5162}5163}5164}5165}51665167if($can_highlight) {5168for(my$i=0;$i<@$add;$i++) {5169my($line_rem,$line_add) = format_rem_add_lines_pair(5170$rem->[$i],$add->[$i],$num_parents);5171push@new_rem,$line_rem;5172push@new_add,$line_add;5173}5174}else{5175@new_rem=map{ format_diff_line($_,'rem') }@$rem;5176@new_add=map{ format_diff_line($_,'add') }@$add;5177}51785179@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;51805181return(\@new_ctx, \@new_rem, \@new_add);5182}51835184# Print context lines and then rem/add lines.5185sub print_diff_lines {5186my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5187my$is_combined=$num_parents>1;51885189($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5190$num_parents);51915192if($diff_styleeq'sidebyside'&& !$is_combined) {5193 print_sidebyside_diff_lines($ctx,$rem,$add);5194}else{5195# default 'inline' style and unknown styles5196 print_inline_diff_lines($ctx,$rem,$add);5197}5198}51995200sub print_diff_chunk {5201my($diff_style,$num_parents,$from,$to,@chunk) =@_;5202my(@ctx,@rem,@add);52035204# The class of the previous line.5205my$prev_class='';52065207return unless@chunk;52085209# incomplete last line might be among removed or added lines,5210# or both, or among context lines: find which5211for(my$i=1;$i<@chunk;$i++) {5212if($chunk[$i][0]eq'incomplete') {5213$chunk[$i][0] =$chunk[$i-1][0];5214}5215}52165217# guardian5218push@chunk, ["",""];52195220foreachmy$line_info(@chunk) {5221my($class,$line) =@$line_info;52225223# print chunk headers5224if($class&&$classeq'chunk_header') {5225print format_diff_line($line,$class,$from,$to);5226next;5227}52285229## print from accumulator when have some add/rem lines or end5230# of chunk (flush context lines), or when have add and rem5231# lines and new block is reached (otherwise add/rem lines could5232# be reordered)5233if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5234(@rem&&@add&&$classne$prev_class)) {5235 print_diff_lines(\@ctx, \@rem, \@add,5236$diff_style,$num_parents);5237@ctx=@rem=@add= ();5238}52395240## adding lines to accumulator5241# guardian value5242last unless$line;5243# rem, add or change5244if($classeq'rem') {5245push@rem,$line;5246}elsif($classeq'add') {5247push@add,$line;5248}5249# context line5250if($classeq'ctx') {5251push@ctx,$line;5252}52535254$prev_class=$class;5255}5256}52575258sub git_patchset_body {5259my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5260my($hash_parent) =$hash_parents[0];52615262my$is_combined= (@hash_parents>1);5263my$patch_idx=0;5264my$patch_number=0;5265my$patch_line;5266my$diffinfo;5267my$to_name;5268my(%from,%to);5269my@chunk;# for side-by-side diff52705271print"<div class=\"patchset\">\n";52725273# skip to first patch5274while($patch_line= <$fd>) {5275chomp$patch_line;52765277last if($patch_line=~m/^diff /);5278}52795280 PATCH:5281while($patch_line) {52825283# parse "git diff" header line5284if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5285# $1 is from_name, which we do not use5286$to_name= unquote($2);5287$to_name=~s!^b/!!;5288}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5289# $1 is 'cc' or 'combined', which we do not use5290$to_name= unquote($2);5291}else{5292$to_name=undef;5293}52945295# check if current patch belong to current raw line5296# and parse raw git-diff line if needed5297if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5298# this is continuation of a split patch5299print"<div class=\"patch cont\">\n";5300}else{5301# advance raw git-diff output if needed5302$patch_idx++ifdefined$diffinfo;53035304# read and prepare patch information5305$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53065307# compact combined diff output can have some patches skipped5308# find which patch (using pathname of result) we are at now;5309if($is_combined) {5310while($to_namene$diffinfo->{'to_file'}) {5311print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5312 format_diff_cc_simplified($diffinfo,@hash_parents) .5313"</div>\n";# class="patch"53145315$patch_idx++;5316$patch_number++;53175318last if$patch_idx>$#$difftree;5319$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5320}5321}53225323# modifies %from, %to hashes5324 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);53255326# this is first patch for raw difftree line with $patch_idx index5327# we index @$difftree array from 0, but number patches from 15328print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5329}53305331# git diff header5332#assert($patch_line =~ m/^diff /) if DEBUG;5333#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5334$patch_number++;5335# print "git diff" header5336print format_git_diff_header_line($patch_line,$diffinfo,5337 \%from, \%to);53385339# print extended diff header5340print"<div class=\"diff extended_header\">\n";5341 EXTENDED_HEADER:5342while($patch_line= <$fd>) {5343chomp$patch_line;53445345last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);53465347print format_extended_diff_header_line($patch_line,$diffinfo,5348 \%from, \%to);5349}5350print"</div>\n";# class="diff extended_header"53515352# from-file/to-file diff header5353if(!$patch_line) {5354print"</div>\n";# class="patch"5355last PATCH;5356}5357next PATCH if($patch_line=~m/^diff /);5358#assert($patch_line =~ m/^---/) if DEBUG;53595360my$last_patch_line=$patch_line;5361$patch_line= <$fd>;5362chomp$patch_line;5363#assert($patch_line =~ m/^\+\+\+/) if DEBUG;53645365print format_diff_from_to_header($last_patch_line,$patch_line,5366$diffinfo, \%from, \%to,5367@hash_parents);53685369# the patch itself5370 LINE:5371while($patch_line= <$fd>) {5372chomp$patch_line;53735374next PATCH if($patch_line=~m/^diff /);53755376my$class= diff_line_class($patch_line, \%from, \%to);53775378if($classeq'chunk_header') {5379 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5380@chunk= ();5381}53825383push@chunk, [$class,$patch_line];5384}53855386}continue{5387if(@chunk) {5388 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5389@chunk= ();5390}5391print"</div>\n";# class="patch"5392}53935394# for compact combined (--cc) format, with chunk and patch simplification5395# the patchset might be empty, but there might be unprocessed raw lines5396for(++$patch_idxif$patch_number>0;5397$patch_idx<@$difftree;5398++$patch_idx) {5399# read and prepare patch information5400$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54015402# generate anchor for "patch" links in difftree / whatchanged part5403print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5404 format_diff_cc_simplified($diffinfo,@hash_parents) .5405"</div>\n";# class="patch"54065407$patch_number++;5408}54095410if($patch_number==0) {5411if(@hash_parents>1) {5412print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5413}else{5414print"<div class=\"diff nodifferences\">No differences found</div>\n";5415}5416}54175418print"</div>\n";# class="patchset"5419}54205421# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54225423sub git_project_search_form {5424my($searchtext,$search_use_regexp) =@_;54255426my$limit='';5427if($project_filter) {5428$limit=" in '$project_filter/'";5429}54305431print"<div class=\"projsearch\">\n";5432print$cgi->startform(-method=>'get', -action =>$my_uri) .5433$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5434print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5435if(defined$project_filter);5436print$cgi->textfield(-name =>'s', -value =>$searchtext,5437-title =>"Search project by name and description$limit",5438-size =>60) ."\n".5439"<span title=\"Extended regular expression\">".5440$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5441-checked =>$search_use_regexp) .5442"</span>\n".5443$cgi->submit(-name =>'btnS', -value =>'Search') .5444$cgi->end_form() ."\n".5445$cgi->a({-href => href(project =>undef, searchtext =>undef,5446 project_filter =>$project_filter)},5447 esc_html("List all projects$limit")) ."<br />\n";5448print"</div>\n";5449}54505451# entry for given @keys needs filling if at least one of keys in list5452# is not present in %$project_info5453sub project_info_needs_filling {5454my($project_info,@keys) =@_;54555456# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5457foreachmy$key(@keys) {5458if(!exists$project_info->{$key}) {5459return1;5460}5461}5462return;5463}54645465# fills project list info (age, description, owner, category, forks, etc.)5466# for each project in the list, removing invalid projects from5467# returned list, or fill only specified info.5468#5469# Invalid projects are removed from the returned list if and only if you5470# ask 'age' or 'age_string' to be filled, because they are the only fields5471# that run unconditionally git command that requires repository, and5472# therefore do always check if project repository is invalid.5473#5474# USAGE:5475# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5476# ensures that 'descr_long' and 'ctags' fields are filled5477# * @project_list = fill_project_list_info(\@project_list)5478# ensures that all fields are filled (and invalid projects removed)5479#5480# NOTE: modifies $projlist, but does not remove entries from it5481sub fill_project_list_info {5482my($projlist,@wanted_keys) =@_;5483my@projects;5484my$filter_set=sub{return@_; };5485if(@wanted_keys) {5486my%wanted_keys=map{$_=>1}@wanted_keys;5487$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5488}54895490my$show_ctags= gitweb_check_feature('ctags');5491 PROJECT:5492foreachmy$pr(@$projlist) {5493if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5494my(@activity) = git_get_last_activity($pr->{'path'});5495unless(@activity) {5496next PROJECT;5497}5498($pr->{'age'},$pr->{'age_string'}) =@activity;5499}5500if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5501my$descr= git_get_project_description($pr->{'path'}) ||"";5502$descr= to_utf8($descr);5503$pr->{'descr_long'} =$descr;5504$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5505}5506if(project_info_needs_filling($pr,$filter_set->('owner'))) {5507$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5508}5509if($show_ctags&&5510 project_info_needs_filling($pr,$filter_set->('ctags'))) {5511$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5512}5513if($projects_list_group_categories&&5514 project_info_needs_filling($pr,$filter_set->('category'))) {5515my$cat= git_get_project_category($pr->{'path'}) ||5516$project_list_default_category;5517$pr->{'category'} = to_utf8($cat);5518}55195520push@projects,$pr;5521}55225523return@projects;5524}55255526sub sort_projects_list {5527my($projlist,$order) =@_;5528my@projects;55295530my%order_info= (5531 project => { key =>'path', type =>'str'},5532 descr => { key =>'descr_long', type =>'str'},5533 owner => { key =>'owner', type =>'str'},5534 age => { key =>'age', type =>'num'}5535);5536my$oi=$order_info{$order};5537return@$projlistunlessdefined$oi;5538if($oi->{'type'}eq'str') {5539@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5540}else{5541@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5542}55435544return@projects;5545}55465547# returns a hash of categories, containing the list of project5548# belonging to each category5549sub build_projlist_by_category {5550my($projlist,$from,$to) =@_;5551my%categories;55525553$from=0unlessdefined$from;5554$to=$#$projlistif(!defined$to||$#$projlist<$to);55555556for(my$i=$from;$i<=$to;$i++) {5557my$pr=$projlist->[$i];5558push@{$categories{$pr->{'category'} }},$pr;5559}55605561returnwantarray?%categories: \%categories;5562}55635564# print 'sort by' <th> element, generating 'sort by $name' replay link5565# if that order is not selected5566sub print_sort_th {5567print format_sort_th(@_);5568}55695570sub format_sort_th {5571my($name,$order,$header) =@_;5572my$sort_th="";5573$header||=ucfirst($name);55745575if($ordereq$name) {5576$sort_th.="<th>$header</th>\n";5577}else{5578$sort_th.="<th>".5579$cgi->a({-href => href(-replay=>1, order=>$name),5580-class=>"header"},$header) .5581"</th>\n";5582}55835584return$sort_th;5585}55865587sub git_project_list_rows {5588my($projlist,$from,$to,$check_forks) =@_;55895590$from=0unlessdefined$from;5591$to=$#$projlistif(!defined$to||$#$projlist<$to);55925593my$alternate=1;5594for(my$i=$from;$i<=$to;$i++) {5595my$pr=$projlist->[$i];55965597if($alternate) {5598print"<tr class=\"dark\">\n";5599}else{5600print"<tr class=\"light\">\n";5601}5602$alternate^=1;56035604if($check_forks) {5605print"<td>";5606if($pr->{'forks'}) {5607my$nforks=scalar@{$pr->{'forks'}};5608if($nforks>0) {5609print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5610-title =>"$nforksforks"},"+");5611}else{5612print$cgi->span({-title =>"$nforksforks"},"+");5613}5614}5615print"</td>\n";5616}5617print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5618-class=>"list"},5619 esc_html_match_hl($pr->{'path'},$search_regexp)) .5620"</td>\n".5621"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5622-class=>"list",5623-title =>$pr->{'descr_long'}},5624$search_regexp5625? esc_html_match_hl_chopped($pr->{'descr_long'},5626$pr->{'descr'},$search_regexp)5627: esc_html($pr->{'descr'})) .5628"</td>\n";5629unless($omit_owner) {5630print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5631}5632unless($omit_age_column) {5633print"<td class=\"". age_class($pr->{'age'}) ."\">".5634(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5635}5636print"<td class=\"link\">".5637$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5638$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5639$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5640$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5641($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5642"</td>\n".5643"</tr>\n";5644}5645}56465647sub git_project_list_body {5648# actually uses global variable $project5649my($projlist,$order,$from,$to,$extra,$no_header) =@_;5650my@projects=@$projlist;56515652my$check_forks= gitweb_check_feature('forks');5653my$show_ctags= gitweb_check_feature('ctags');5654my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5655$check_forks=undef5656if($tagfilter||$search_regexp);56575658# filtering out forks before filling info allows to do less work5659@projects= filter_forks_from_projects_list(\@projects)5660if($check_forks);5661# search_projects_list pre-fills required info5662@projects= search_projects_list(\@projects,5663'search_regexp'=>$search_regexp,5664'tagfilter'=>$tagfilter)5665if($tagfilter||$search_regexp);5666# fill the rest5667my@all_fields= ('descr','descr_long','ctags','category');5668push@all_fields, ('age','age_string')unless($omit_age_column);5669push@all_fields,'owner'unless($omit_owner);5670@projects= fill_project_list_info(\@projects,@all_fields);56715672$order||=$default_projects_order;5673$from=0unlessdefined$from;5674$to=$#projectsif(!defined$to||$#projects<$to);56755676# short circuit5677if($from>$to) {5678print"<center>\n".5679"<b>No such projects found</b><br />\n".5680"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5681"</center>\n<br />\n";5682return;5683}56845685@projects= sort_projects_list(\@projects,$order);56865687if($show_ctags) {5688my$ctags= git_gather_all_ctags(\@projects);5689my$cloud= git_populate_project_tagcloud($ctags);5690print git_show_project_tagcloud($cloud,64);5691}56925693print"<table class=\"project_list\">\n";5694unless($no_header) {5695print"<tr>\n";5696if($check_forks) {5697print"<th></th>\n";5698}5699 print_sort_th('project',$order,'Project');5700 print_sort_th('descr',$order,'Description');5701 print_sort_th('owner',$order,'Owner')unless$omit_owner;5702 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5703print"<th></th>\n".# for links5704"</tr>\n";5705}57065707if($projects_list_group_categories) {5708# only display categories with projects in the $from-$to window5709@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5710my%categories= build_projlist_by_category(\@projects,$from,$to);5711foreachmy$cat(sort keys%categories) {5712unless($cateq"") {5713print"<tr>\n";5714if($check_forks) {5715print"<td></td>\n";5716}5717print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5718print"</tr>\n";5719}57205721 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5722}5723}else{5724 git_project_list_rows(\@projects,$from,$to,$check_forks);5725}57265727if(defined$extra) {5728print"<tr>\n";5729if($check_forks) {5730print"<td></td>\n";5731}5732print"<td colspan=\"5\">$extra</td>\n".5733"</tr>\n";5734}5735print"</table>\n";5736}57375738sub git_log_body {5739# uses global variable $project5740my($commitlist,$from,$to,$refs,$extra) =@_;57415742$from=0unlessdefined$from;5743$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57445745for(my$i=0;$i<=$to;$i++) {5746my%co= %{$commitlist->[$i]};5747next if!%co;5748my$commit=$co{'id'};5749my$ref= format_ref_marker($refs,$commit);5750 git_print_header_div('commit',5751"<span class=\"age\">$co{'age_string'}</span>".5752 esc_html($co{'title'}) .$ref,5753$commit);5754print"<div class=\"title_text\">\n".5755"<div class=\"log_link\">\n".5756$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5757" | ".5758$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5759" | ".5760$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5761"<br/>\n".5762"</div>\n";5763 git_print_authorship(\%co, -tag =>'span');5764print"<br/>\n</div>\n";57655766print"<div class=\"log_body\">\n";5767 git_print_log($co{'comment'}, -final_empty_line=>1);5768print"</div>\n";5769}5770if($extra) {5771print"<div class=\"page_nav\">\n";5772print"$extra\n";5773print"</div>\n";5774}5775}57765777sub git_shortlog_body {5778# uses global variable $project5779my($commitlist,$from,$to,$refs,$extra) =@_;57805781$from=0unlessdefined$from;5782$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57835784print"<table class=\"shortlog\">\n";5785my$alternate=1;5786for(my$i=$from;$i<=$to;$i++) {5787my%co= %{$commitlist->[$i]};5788my$commit=$co{'id'};5789my$ref= format_ref_marker($refs,$commit);5790if($alternate) {5791print"<tr class=\"dark\">\n";5792}else{5793print"<tr class=\"light\">\n";5794}5795$alternate^=1;5796# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5797print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5798 format_author_html('td', \%co,10) ."<td>";5799print format_subject_html($co{'title'},$co{'title_short'},5800 href(action=>"commit", hash=>$commit),$ref);5801print"</td>\n".5802"<td class=\"link\">".5803$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5804$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5805$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5806my$snapshot_links= format_snapshot_links($commit);5807if(defined$snapshot_links) {5808print" | ".$snapshot_links;5809}5810print"</td>\n".5811"</tr>\n";5812}5813if(defined$extra) {5814print"<tr>\n".5815"<td colspan=\"4\">$extra</td>\n".5816"</tr>\n";5817}5818print"</table>\n";5819}58205821sub git_history_body {5822# Warning: assumes constant type (blob or tree) during history5823my($commitlist,$from,$to,$refs,$extra,5824$file_name,$file_hash,$ftype) =@_;58255826$from=0unlessdefined$from;5827$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});58285829print"<table class=\"history\">\n";5830my$alternate=1;5831for(my$i=$from;$i<=$to;$i++) {5832my%co= %{$commitlist->[$i]};5833if(!%co) {5834next;5835}5836my$commit=$co{'id'};58375838my$ref= format_ref_marker($refs,$commit);58395840if($alternate) {5841print"<tr class=\"dark\">\n";5842}else{5843print"<tr class=\"light\">\n";5844}5845$alternate^=1;5846print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5847# shortlog: format_author_html('td', \%co, 10)5848 format_author_html('td', \%co,15,3) ."<td>";5849# originally git_history used chop_str($co{'title'}, 50)5850print format_subject_html($co{'title'},$co{'title_short'},5851 href(action=>"commit", hash=>$commit),$ref);5852print"</td>\n".5853"<td class=\"link\">".5854$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5855$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");58565857if($ftypeeq'blob') {5858my$blob_current=$file_hash;5859my$blob_parent= git_get_hash_by_path($commit,$file_name);5860if(defined$blob_current&&defined$blob_parent&&5861$blob_currentne$blob_parent) {5862print" | ".5863$cgi->a({-href => href(action=>"blobdiff",5864 hash=>$blob_current, hash_parent=>$blob_parent,5865 hash_base=>$hash_base, hash_parent_base=>$commit,5866 file_name=>$file_name)},5867"diff to current");5868}5869}5870print"</td>\n".5871"</tr>\n";5872}5873if(defined$extra) {5874print"<tr>\n".5875"<td colspan=\"4\">$extra</td>\n".5876"</tr>\n";5877}5878print"</table>\n";5879}58805881sub git_tags_body {5882# uses global variable $project5883my($taglist,$from,$to,$extra) =@_;5884$from=0unlessdefined$from;5885$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);58865887print"<table class=\"tags\">\n";5888my$alternate=1;5889for(my$i=$from;$i<=$to;$i++) {5890my$entry=$taglist->[$i];5891my%tag=%$entry;5892my$comment=$tag{'subject'};5893my$comment_short;5894if(defined$comment) {5895$comment_short= chop_str($comment,30,5);5896}5897if($alternate) {5898print"<tr class=\"dark\">\n";5899}else{5900print"<tr class=\"light\">\n";5901}5902$alternate^=1;5903if(defined$tag{'age'}) {5904print"<td><i>$tag{'age'}</i></td>\n";5905}else{5906print"<td></td>\n";5907}5908print"<td>".5909$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5910-class=>"list name"}, esc_html($tag{'name'})) .5911"</td>\n".5912"<td>";5913if(defined$comment) {5914print format_subject_html($comment,$comment_short,5915 href(action=>"tag", hash=>$tag{'id'}));5916}5917print"</td>\n".5918"<td class=\"selflink\">";5919if($tag{'type'}eq"tag") {5920print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5921}else{5922print" ";5923}5924print"</td>\n".5925"<td class=\"link\">"." | ".5926$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5927if($tag{'reftype'}eq"commit") {5928print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5929" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5930}elsif($tag{'reftype'}eq"blob") {5931print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5932}5933print"</td>\n".5934"</tr>";5935}5936if(defined$extra) {5937print"<tr>\n".5938"<td colspan=\"5\">$extra</td>\n".5939"</tr>\n";5940}5941print"</table>\n";5942}59435944sub git_heads_body {5945# uses global variable $project5946my($headlist,$head_at,$from,$to,$extra) =@_;5947$from=0unlessdefined$from;5948$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);59495950print"<table class=\"heads\">\n";5951my$alternate=1;5952for(my$i=$from;$i<=$to;$i++) {5953my$entry=$headlist->[$i];5954my%ref=%$entry;5955my$curr=defined$head_at&&$ref{'id'}eq$head_at;5956if($alternate) {5957print"<tr class=\"dark\">\n";5958}else{5959print"<tr class=\"light\">\n";5960}5961$alternate^=1;5962print"<td><i>$ref{'age'}</i></td>\n".5963($curr?"<td class=\"current_head\">":"<td>") .5964$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5965-class=>"list name"},esc_html($ref{'name'})) .5966"</td>\n".5967"<td class=\"link\">".5968$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5969$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5970$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5971"</td>\n".5972"</tr>";5973}5974if(defined$extra) {5975print"<tr>\n".5976"<td colspan=\"3\">$extra</td>\n".5977"</tr>\n";5978}5979print"</table>\n";5980}59815982# Display a single remote block5983sub git_remote_block {5984my($remote,$rdata,$limit,$head) =@_;59855986my$heads=$rdata->{'heads'};5987my$fetch=$rdata->{'fetch'};5988my$push=$rdata->{'push'};59895990my$urls_table="<table class=\"projects_list\">\n";59915992if(defined$fetch) {5993if($fetcheq$push) {5994$urls_table.= format_repo_url("URL",$fetch);5995}else{5996$urls_table.= format_repo_url("Fetch URL",$fetch);5997$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5998}5999}elsif(defined$push) {6000$urls_table.= format_repo_url("Push URL",$push);6001}else{6002$urls_table.= format_repo_url("","No remote URL");6003}60046005$urls_table.="</table>\n";60066007my$dots;6008if(defined$limit&&$limit<@$heads) {6009$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6010}60116012print$urls_table;6013 git_heads_body($heads,$head,0,$limit,$dots);6014}60156016# Display a list of remote names with the respective fetch and push URLs6017sub git_remotes_list {6018my($remotedata,$limit) =@_;6019print"<table class=\"heads\">\n";6020my$alternate=1;6021my@remotes=sort keys%$remotedata;60226023my$limited=$limit&&$limit<@remotes;60246025$#remotes=$limit-1if$limited;60266027while(my$remote=shift@remotes) {6028my$rdata=$remotedata->{$remote};6029my$fetch=$rdata->{'fetch'};6030my$push=$rdata->{'push'};6031if($alternate) {6032print"<tr class=\"dark\">\n";6033}else{6034print"<tr class=\"light\">\n";6035}6036$alternate^=1;6037print"<td>".6038$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6039-class=>"list name"},esc_html($remote)) .6040"</td>";6041print"<td class=\"link\">".6042(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6043" | ".6044(defined$push?$cgi->a({-href=>$push},"push") :"push") .6045"</td>";60466047print"</tr>\n";6048}60496050if($limited) {6051print"<tr>\n".6052"<td colspan=\"3\">".6053$cgi->a({-href => href(action=>"remotes")},"...") .6054"</td>\n"."</tr>\n";6055}60566057print"</table>";6058}60596060# Display remote heads grouped by remote, unless there are too many6061# remotes, in which case we only display the remote names6062sub git_remotes_body {6063my($remotedata,$limit,$head) =@_;6064if($limitand$limit<keys%$remotedata) {6065 git_remotes_list($remotedata,$limit);6066}else{6067 fill_remote_heads($remotedata);6068while(my($remote,$rdata) =each%$remotedata) {6069 git_print_section({-class=>"remote", -id=>$remote},6070["remotes",$remote,$remote],sub{6071 git_remote_block($remote,$rdata,$limit,$head);6072});6073}6074}6075}60766077sub git_search_message {6078my%co=@_;60796080my$greptype;6081if($searchtypeeq'commit') {6082$greptype="--grep=";6083}elsif($searchtypeeq'author') {6084$greptype="--author=";6085}elsif($searchtypeeq'committer') {6086$greptype="--committer=";6087}6088$greptype.=$searchtext;6089my@commitlist= parse_commits($hash,101, (100*$page),undef,6090$greptype,'--regexp-ignore-case',6091$search_use_regexp?'--extended-regexp':'--fixed-strings');60926093my$paging_nav='';6094if($page>0) {6095$paging_nav.=6096$cgi->a({-href => href(-replay=>1, page=>undef)},6097"first") .6098" ⋅ ".6099$cgi->a({-href => href(-replay=>1, page=>$page-1),6100-accesskey =>"p", -title =>"Alt-p"},"prev");6101}else{6102$paging_nav.="first ⋅ prev";6103}6104my$next_link='';6105if($#commitlist>=100) {6106$next_link=6107$cgi->a({-href => href(-replay=>1, page=>$page+1),6108-accesskey =>"n", -title =>"Alt-n"},"next");6109$paging_nav.=" ⋅$next_link";6110}else{6111$paging_nav.=" ⋅ next";6112}61136114 git_header_html();61156116 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6117 git_print_header_div('commit', esc_html($co{'title'}),$hash);6118if($page==0&& !@commitlist) {6119print"<p>No match.</p>\n";6120}else{6121 git_search_grep_body(\@commitlist,0,99,$next_link);6122}61236124 git_footer_html();6125}61266127sub git_search_changes {6128my%co=@_;61296130local$/="\n";6131open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6132'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6133($search_use_regexp?'--pickaxe-regex': ())6134or die_error(500,"Open git-log failed");61356136 git_header_html();61376138 git_print_page_nav('','',$hash,$co{'tree'},$hash);6139 git_print_header_div('commit', esc_html($co{'title'}),$hash);61406141print"<table class=\"pickaxe search\">\n";6142my$alternate=1;6143undef%co;6144my@files;6145while(my$line= <$fd>) {6146chomp$line;6147next unless$line;61486149my%set= parse_difftree_raw_line($line);6150if(defined$set{'commit'}) {6151# finish previous commit6152if(%co) {6153print"</td>\n".6154"<td class=\"link\">".6155$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6156"commit") .6157" | ".6158$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6159 hash_base=>$co{'id'})},6160"tree") .6161"</td>\n".6162"</tr>\n";6163}61646165if($alternate) {6166print"<tr class=\"dark\">\n";6167}else{6168print"<tr class=\"light\">\n";6169}6170$alternate^=1;6171%co= parse_commit($set{'commit'});6172my$author= chop_and_escape_str($co{'author_name'},15,5);6173print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6174"<td><i>$author</i></td>\n".6175"<td>".6176$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6177-class=>"list subject"},6178 chop_and_escape_str($co{'title'},50) ."<br/>");6179}elsif(defined$set{'to_id'}) {6180next if($set{'to_id'} =~m/^0{40}$/);61816182print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6183 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6184-class=>"list"},6185"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6186"<br/>\n";6187}6188}6189close$fd;61906191# finish last commit (warning: repetition!)6192if(%co) {6193print"</td>\n".6194"<td class=\"link\">".6195$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6196"commit") .6197" | ".6198$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6199 hash_base=>$co{'id'})},6200"tree") .6201"</td>\n".6202"</tr>\n";6203}62046205print"</table>\n";62066207 git_footer_html();6208}62096210sub git_search_files {6211my%co=@_;62126213local$/="\n";6214open my$fd,"-|", git_cmd(),'grep','-n','-z',6215$search_use_regexp? ('-E','-i') :'-F',6216$searchtext,$co{'tree'}6217or die_error(500,"Open git-grep failed");62186219 git_header_html();62206221 git_print_page_nav('','',$hash,$co{'tree'},$hash);6222 git_print_header_div('commit', esc_html($co{'title'}),$hash);62236224print"<table class=\"grep_search\">\n";6225my$alternate=1;6226my$matches=0;6227my$lastfile='';6228my$file_href;6229while(my$line= <$fd>) {6230chomp$line;6231my($file,$lno,$ltext,$binary);6232last if($matches++>1000);6233if($line=~/^Binary file (.+) matches$/) {6234$file=$1;6235$binary=1;6236}else{6237($file,$lno,$ltext) =split(/\0/,$line,3);6238$file=~s/^$co{'tree'}://;6239}6240if($filene$lastfile) {6241$lastfileand print"</td></tr>\n";6242if($alternate++) {6243print"<tr class=\"dark\">\n";6244}else{6245print"<tr class=\"light\">\n";6246}6247$file_href= href(action=>"blob", hash_base=>$co{'id'},6248 file_name=>$file);6249print"<td class=\"list\">".6250$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6251print"</td><td>\n";6252$lastfile=$file;6253}6254if($binary) {6255print"<div class=\"binary\">Binary file</div>\n";6256}else{6257$ltext= untabify($ltext);6258if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6259$ltext= esc_html($1, -nbsp=>1);6260$ltext.='<span class="match">';6261$ltext.= esc_html($2, -nbsp=>1);6262$ltext.='</span>';6263$ltext.= esc_html($3, -nbsp=>1);6264}else{6265$ltext= esc_html($ltext, -nbsp=>1);6266}6267print"<div class=\"pre\">".6268$cgi->a({-href =>$file_href.'#l'.$lno,6269-class=>"linenr"},sprintf('%4i',$lno)) .6270' '.$ltext."</div>\n";6271}6272}6273if($lastfile) {6274print"</td></tr>\n";6275if($matches>1000) {6276print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6277}6278}else{6279print"<div class=\"diff nodifferences\">No matches found</div>\n";6280}6281close$fd;62826283print"</table>\n";62846285 git_footer_html();6286}62876288sub git_search_grep_body {6289my($commitlist,$from,$to,$extra) =@_;6290$from=0unlessdefined$from;6291$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);62926293print"<table class=\"commit_search\">\n";6294my$alternate=1;6295for(my$i=$from;$i<=$to;$i++) {6296my%co= %{$commitlist->[$i]};6297if(!%co) {6298next;6299}6300my$commit=$co{'id'};6301if($alternate) {6302print"<tr class=\"dark\">\n";6303}else{6304print"<tr class=\"light\">\n";6305}6306$alternate^=1;6307print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6308 format_author_html('td', \%co,15,5) .6309"<td>".6310$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6311-class=>"list subject"},6312 chop_and_escape_str($co{'title'},50) ."<br/>");6313my$comment=$co{'comment'};6314foreachmy$line(@$comment) {6315if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6316my($lead,$match,$trail) = ($1,$2,$3);6317$match= chop_str($match,70,5,'center');6318my$contextlen=int((80-length($match))/2);6319$contextlen=30if($contextlen>30);6320$lead= chop_str($lead,$contextlen,10,'left');6321$trail= chop_str($trail,$contextlen,10,'right');63226323$lead= esc_html($lead);6324$match= esc_html($match);6325$trail= esc_html($trail);63266327print"$lead<span class=\"match\">$match</span>$trail<br />";6328}6329}6330print"</td>\n".6331"<td class=\"link\">".6332$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6333" | ".6334$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6335" | ".6336$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6337print"</td>\n".6338"</tr>\n";6339}6340if(defined$extra) {6341print"<tr>\n".6342"<td colspan=\"3\">$extra</td>\n".6343"</tr>\n";6344}6345print"</table>\n";6346}63476348## ======================================================================6349## ======================================================================6350## actions63516352sub git_project_list {6353my$order=$input_params{'order'};6354if(defined$order&&$order!~m/none|project|descr|owner|age/) {6355 die_error(400,"Unknown order parameter");6356}63576358my@list= git_get_projects_list($project_filter,$strict_export);6359if(!@list) {6360 die_error(404,"No projects found");6361}63626363 git_header_html();6364if(defined$home_text&& -f $home_text) {6365print"<div class=\"index_include\">\n";6366 insert_file($home_text);6367print"</div>\n";6368}63696370 git_project_search_form($searchtext,$search_use_regexp);6371 git_project_list_body(\@list,$order);6372 git_footer_html();6373}63746375sub git_forks {6376my$order=$input_params{'order'};6377if(defined$order&&$order!~m/none|project|descr|owner|age/) {6378 die_error(400,"Unknown order parameter");6379}63806381my$filter=$project;6382$filter=~s/\.git$//;6383my@list= git_get_projects_list($filter);6384if(!@list) {6385 die_error(404,"No forks found");6386}63876388 git_header_html();6389 git_print_page_nav('','');6390 git_print_header_div('summary',"$projectforks");6391 git_project_list_body(\@list,$order);6392 git_footer_html();6393}63946395sub git_project_index {6396my@projects= git_get_projects_list($project_filter,$strict_export);6397if(!@projects) {6398 die_error(404,"No projects found");6399}64006401print$cgi->header(6402-type =>'text/plain',6403-charset =>'utf-8',6404-content_disposition =>'inline; filename="index.aux"');64056406foreachmy$pr(@projects) {6407if(!exists$pr->{'owner'}) {6408$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6409}64106411my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6412# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6413$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6414$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6415$path=~s/ /\+/g;6416$owner=~s/ /\+/g;64176418print"$path$owner\n";6419}6420}64216422sub git_summary {6423my$descr= git_get_project_description($project) ||"none";6424my%co= parse_commit("HEAD");6425my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6426my$head=$co{'id'};6427my$remote_heads= gitweb_check_feature('remote_heads');64286429my$owner= git_get_project_owner($project);64306431my$refs= git_get_references();6432# These get_*_list functions return one more to allow us to see if6433# there are more ...6434my@taglist= git_get_tags_list(16);6435my@headlist= git_get_heads_list(16);6436my%remotedata=$remote_heads? git_get_remotes_list() : ();6437my@forklist;6438my$check_forks= gitweb_check_feature('forks');64396440if($check_forks) {6441# find forks of a project6442my$filter=$project;6443$filter=~s/\.git$//;6444@forklist= git_get_projects_list($filter);6445# filter out forks of forks6446@forklist= filter_forks_from_projects_list(\@forklist)6447if(@forklist);6448}64496450 git_header_html();6451 git_print_page_nav('summary','',$head);64526453print"<div class=\"title\"> </div>\n";6454print"<table class=\"projects_list\">\n".6455"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6456unless($omit_owner) {6457print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6458}6459if(defined$cd{'rfc2822'}) {6460print"<tr id=\"metadata_lchange\"><td>last change</td>".6461"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6462}64636464# use per project git URL list in $projectroot/$project/cloneurl6465# or make project git URL from git base URL and project name6466my$url_tag="URL";6467my@url_list= git_get_project_url_list($project);6468@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6469foreachmy$git_url(@url_list) {6470next unless$git_url;6471print format_repo_url($url_tag,$git_url);6472$url_tag="";6473}64746475# Tag cloud6476my$show_ctags= gitweb_check_feature('ctags');6477if($show_ctags) {6478my$ctags= git_get_project_ctags($project);6479if(%$ctags) {6480# without ability to add tags, don't show if there are none6481my$cloud= git_populate_project_tagcloud($ctags);6482print"<tr id=\"metadata_ctags\">".6483"<td>content tags</td>".6484"<td>".git_show_project_tagcloud($cloud,48)."</td>".6485"</tr>\n";6486}6487}64886489print"</table>\n";64906491# If XSS prevention is on, we don't include README.html.6492# TODO: Allow a readme in some safe format.6493if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6494print"<div class=\"title\">readme</div>\n".6495"<div class=\"readme\">\n";6496 insert_file("$projectroot/$project/README.html");6497print"\n</div>\n";# class="readme"6498}64996500# we need to request one more than 16 (0..15) to check if6501# those 16 are all6502my@commitlist=$head? parse_commits($head,17) : ();6503if(@commitlist) {6504 git_print_header_div('shortlog');6505 git_shortlog_body(\@commitlist,0,15,$refs,6506$#commitlist<=15?undef:6507$cgi->a({-href => href(action=>"shortlog")},"..."));6508}65096510if(@taglist) {6511 git_print_header_div('tags');6512 git_tags_body(\@taglist,0,15,6513$#taglist<=15?undef:6514$cgi->a({-href => href(action=>"tags")},"..."));6515}65166517if(@headlist) {6518 git_print_header_div('heads');6519 git_heads_body(\@headlist,$head,0,15,6520$#headlist<=15?undef:6521$cgi->a({-href => href(action=>"heads")},"..."));6522}65236524if(%remotedata) {6525 git_print_header_div('remotes');6526 git_remotes_body(\%remotedata,15,$head);6527}65286529if(@forklist) {6530 git_print_header_div('forks');6531 git_project_list_body(\@forklist,'age',0,15,6532$#forklist<=15?undef:6533$cgi->a({-href => href(action=>"forks")},"..."),6534'no_header');6535}65366537 git_footer_html();6538}65396540sub git_tag {6541my%tag= parse_tag($hash);65426543if(!%tag) {6544 die_error(404,"Unknown tag object");6545}65466547my$head= git_get_head_hash($project);6548 git_header_html();6549 git_print_page_nav('','',$head,undef,$head);6550 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6551print"<div class=\"title_text\">\n".6552"<table class=\"object_header\">\n".6553"<tr>\n".6554"<td>object</td>\n".6555"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6556$tag{'object'}) ."</td>\n".6557"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6558$tag{'type'}) ."</td>\n".6559"</tr>\n";6560if(defined($tag{'author'})) {6561 git_print_authorship_rows(\%tag,'author');6562}6563print"</table>\n\n".6564"</div>\n";6565print"<div class=\"page_body\">";6566my$comment=$tag{'comment'};6567foreachmy$line(@$comment) {6568chomp$line;6569print esc_html($line, -nbsp=>1) ."<br/>\n";6570}6571print"</div>\n";6572 git_footer_html();6573}65746575sub git_blame_common {6576my$format=shift||'porcelain';6577if($formateq'porcelain'&&$input_params{'javascript'}) {6578$format='incremental';6579$action='blame_incremental';# for page title etc6580}65816582# permissions6583 gitweb_check_feature('blame')6584or die_error(403,"Blame view not allowed");65856586# error checking6587 die_error(400,"No file name given")unless$file_name;6588$hash_base||= git_get_head_hash($project);6589 die_error(404,"Couldn't find base commit")unless$hash_base;6590my%co= parse_commit($hash_base)6591or die_error(404,"Commit not found");6592my$ftype="blob";6593if(!defined$hash) {6594$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6595or die_error(404,"Error looking up file");6596}else{6597$ftype= git_get_type($hash);6598if($ftype!~"blob") {6599 die_error(400,"Object is not a blob");6600}6601}66026603my$fd;6604if($formateq'incremental') {6605# get file contents (as base)6606open$fd,"-|", git_cmd(),'cat-file','blob',$hash6607or die_error(500,"Open git-cat-file failed");6608}elsif($formateq'data') {6609# run git-blame --incremental6610open$fd,"-|", git_cmd(),"blame","--incremental",6611$hash_base,"--",$file_name6612or die_error(500,"Open git-blame --incremental failed");6613}else{6614# run git-blame --porcelain6615open$fd,"-|", git_cmd(),"blame",'-p',6616$hash_base,'--',$file_name6617or die_error(500,"Open git-blame --porcelain failed");6618}66196620# incremental blame data returns early6621if($formateq'data') {6622print$cgi->header(6623-type=>"text/plain", -charset =>"utf-8",6624-status=>"200 OK");6625local$| =1;# output autoflush6626while(my$line= <$fd>) {6627print to_utf8($line);6628}6629close$fd6630or print"ERROR$!\n";66316632print'END';6633if(defined$t0&& gitweb_check_feature('timed')) {6634print' '.6635 tv_interval($t0, [ gettimeofday() ]).6636' '.$number_of_git_cmds;6637}6638print"\n";66396640return;6641}66426643# page header6644 git_header_html();6645my$formats_nav=6646$cgi->a({-href => href(action=>"blob", -replay=>1)},6647"blob") .6648" | ";6649if($formateq'incremental') {6650$formats_nav.=6651$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6652"blame") ." (non-incremental)";6653}else{6654$formats_nav.=6655$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6656"blame") ." (incremental)";6657}6658$formats_nav.=6659" | ".6660$cgi->a({-href => href(action=>"history", -replay=>1)},6661"history") .6662" | ".6663$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6664"HEAD");6665 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6666 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6667 git_print_page_path($file_name,$ftype,$hash_base);66686669# page body6670if($formateq'incremental') {6671print"<noscript>\n<div class=\"error\"><center><b>\n".6672"This page requires JavaScript to run.\nUse ".6673$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6674'this page').6675" instead.\n".6676"</b></center></div>\n</noscript>\n";66776678print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6679}66806681print qq!<div class="page_body">\n!;6682print qq!<div id="progress_info">.../ ...</div>\n!6683if($formateq'incremental');6684print qq!<table id="blame_table"class="blame" width="100%">\n!.6685#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6686 qq!<thead>\n!.6687 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6688 qq!</thead>\n!.6689 qq!<tbody>\n!;66906691my@rev_color=qw(light dark);6692my$num_colors=scalar(@rev_color);6693my$current_color=0;66946695if($formateq'incremental') {6696my$color_class=$rev_color[$current_color];66976698#contents of a file6699my$linenr=0;6700 LINE:6701while(my$line= <$fd>) {6702chomp$line;6703$linenr++;67046705print qq!<tr id="l$linenr"class="$color_class">!.6706 qq!<td class="sha1"><a href=""> </a></td>!.6707 qq!<td class="linenr">!.6708 qq!<a class="linenr" href="">$linenr</a></td>!;6709print qq!<td class="pre">! . esc_html($line) ."</td>\n";6710print qq!</tr>\n!;6711}67126713}else{# porcelain, i.e. ordinary blame6714my%metainfo= ();# saves information about commits67156716# blame data6717 LINE:6718while(my$line= <$fd>) {6719chomp$line;6720# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6721# no <lines in group> for subsequent lines in group of lines6722my($full_rev,$orig_lineno,$lineno,$group_size) =6723($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6724if(!exists$metainfo{$full_rev}) {6725$metainfo{$full_rev} = {'nprevious'=>0};6726}6727my$meta=$metainfo{$full_rev};6728my$data;6729while($data= <$fd>) {6730chomp$data;6731last if($data=~s/^\t//);# contents of line6732if($data=~/^(\S+)(?: (.*))?$/) {6733$meta->{$1} =$2unlessexists$meta->{$1};6734}6735if($data=~/^previous /) {6736$meta->{'nprevious'}++;6737}6738}6739my$short_rev=substr($full_rev,0,8);6740my$author=$meta->{'author'};6741my%date=6742 parse_date($meta->{'author-time'},$meta->{'author-tz'});6743my$date=$date{'iso-tz'};6744if($group_size) {6745$current_color= ($current_color+1) %$num_colors;6746}6747my$tr_class=$rev_color[$current_color];6748$tr_class.=' boundary'if(exists$meta->{'boundary'});6749$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6750$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6751print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6752if($group_size) {6753print"<td class=\"sha1\"";6754print" title=\"". esc_html($author) .",$date\"";6755print" rowspan=\"$group_size\""if($group_size>1);6756print">";6757print$cgi->a({-href => href(action=>"commit",6758 hash=>$full_rev,6759 file_name=>$file_name)},6760 esc_html($short_rev));6761if($group_size>=2) {6762my@author_initials= ($author=~/\b([[:upper:]])\B/g);6763if(@author_initials) {6764print"<br />".6765 esc_html(join('',@author_initials));6766# or join('.', ...)6767}6768}6769print"</td>\n";6770}6771# 'previous' <sha1 of parent commit> <filename at commit>6772if(exists$meta->{'previous'} &&6773$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6774$meta->{'parent'} =$1;6775$meta->{'file_parent'} = unquote($2);6776}6777my$linenr_commit=6778exists($meta->{'parent'}) ?6779$meta->{'parent'} :$full_rev;6780my$linenr_filename=6781exists($meta->{'file_parent'}) ?6782$meta->{'file_parent'} : unquote($meta->{'filename'});6783my$blamed= href(action =>'blame',6784 file_name =>$linenr_filename,6785 hash_base =>$linenr_commit);6786print"<td class=\"linenr\">";6787print$cgi->a({ -href =>"$blamed#l$orig_lineno",6788-class=>"linenr"},6789 esc_html($lineno));6790print"</td>";6791print"<td class=\"pre\">". esc_html($data) ."</td>\n";6792print"</tr>\n";6793}# end while67946795}67966797# footer6798print"</tbody>\n".6799"</table>\n";# class="blame"6800print"</div>\n";# class="blame_body"6801close$fd6802or print"Reading blob failed\n";68036804 git_footer_html();6805}68066807sub git_blame {6808 git_blame_common();6809}68106811sub git_blame_incremental {6812 git_blame_common('incremental');6813}68146815sub git_blame_data {6816 git_blame_common('data');6817}68186819sub git_tags {6820my$head= git_get_head_hash($project);6821 git_header_html();6822 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6823 git_print_header_div('summary',$project);68246825my@tagslist= git_get_tags_list();6826if(@tagslist) {6827 git_tags_body(\@tagslist);6828}6829 git_footer_html();6830}68316832sub git_heads {6833my$head= git_get_head_hash($project);6834 git_header_html();6835 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6836 git_print_header_div('summary',$project);68376838my@headslist= git_get_heads_list();6839if(@headslist) {6840 git_heads_body(\@headslist,$head);6841}6842 git_footer_html();6843}68446845# used both for single remote view and for list of all the remotes6846sub git_remotes {6847 gitweb_check_feature('remote_heads')6848or die_error(403,"Remote heads view is disabled");68496850my$head= git_get_head_hash($project);6851my$remote=$input_params{'hash'};68526853my$remotedata= git_get_remotes_list($remote);6854 die_error(500,"Unable to get remote information")unlessdefined$remotedata;68556856unless(%$remotedata) {6857 die_error(404,defined$remote?6858"Remote$remotenot found":6859"No remotes found");6860}68616862 git_header_html(undef,undef, -action_extra =>$remote);6863 git_print_page_nav('','',$head,undef,$head,6864 format_ref_views($remote?'':'remotes'));68656866 fill_remote_heads($remotedata);6867if(defined$remote) {6868 git_print_header_div('remotes',"$remoteremote for$project");6869 git_remote_block($remote,$remotedata->{$remote},undef,$head);6870}else{6871 git_print_header_div('summary',"$projectremotes");6872 git_remotes_body($remotedata,undef,$head);6873}68746875 git_footer_html();6876}68776878sub git_blob_plain {6879my$type=shift;6880my$expires;68816882if(!defined$hash) {6883if(defined$file_name) {6884my$base=$hash_base|| git_get_head_hash($project);6885$hash= git_get_hash_by_path($base,$file_name,"blob")6886or die_error(404,"Cannot find file");6887}else{6888 die_error(400,"No file name defined");6889}6890}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6891# blobs defined by non-textual hash id's can be cached6892$expires="+1d";6893}68946895open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6896or die_error(500,"Open git-cat-file blob '$hash' failed");68976898# content-type (can include charset)6899$type= blob_contenttype($fd,$file_name,$type);69006901# "save as" filename, even when no $file_name is given6902my$save_as="$hash";6903if(defined$file_name) {6904$save_as=$file_name;6905}elsif($type=~m/^text\//) {6906$save_as.='.txt';6907}69086909# With XSS prevention on, blobs of all types except a few known safe6910# ones are served with "Content-Disposition: attachment" to make sure6911# they don't run in our security domain. For certain image types,6912# blob view writes an <img> tag referring to blob_plain view, and we6913# want to be sure not to break that by serving the image as an6914# attachment (though Firefox 3 doesn't seem to care).6915my$sandbox=$prevent_xss&&6916$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;69176918# serve text/* as text/plain6919if($prevent_xss&&6920($type=~m!^text/[a-z]+\b(.*)$!||6921($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6922my$rest=$1;6923$rest=defined$rest?$rest:'';6924$type="text/plain$rest";6925}69266927print$cgi->header(6928-type =>$type,6929-expires =>$expires,6930-content_disposition =>6931($sandbox?'attachment':'inline')6932.'; filename="'.$save_as.'"');6933local$/=undef;6934binmode STDOUT,':raw';6935print<$fd>;6936binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6937close$fd;6938}69396940sub git_blob {6941my$expires;69426943if(!defined$hash) {6944if(defined$file_name) {6945my$base=$hash_base|| git_get_head_hash($project);6946$hash= git_get_hash_by_path($base,$file_name,"blob")6947or die_error(404,"Cannot find file");6948}else{6949 die_error(400,"No file name defined");6950}6951}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6952# blobs defined by non-textual hash id's can be cached6953$expires="+1d";6954}69556956my$have_blame= gitweb_check_feature('blame');6957open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6958or die_error(500,"Couldn't cat$file_name,$hash");6959my$mimetype= blob_mimetype($fd,$file_name);6960# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6961if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6962close$fd;6963return git_blob_plain($mimetype);6964}6965# we can have blame only for text/* mimetype6966$have_blame&&= ($mimetype=~m!^text/!);69676968my$highlight= gitweb_check_feature('highlight');6969my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6970$fd= run_highlighter($fd,$highlight,$syntax)6971if$syntax;69726973 git_header_html(undef,$expires);6974my$formats_nav='';6975if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6976if(defined$file_name) {6977if($have_blame) {6978$formats_nav.=6979$cgi->a({-href => href(action=>"blame", -replay=>1)},6980"blame") .6981" | ";6982}6983$formats_nav.=6984$cgi->a({-href => href(action=>"history", -replay=>1)},6985"history") .6986" | ".6987$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6988"raw") .6989" | ".6990$cgi->a({-href => href(action=>"blob",6991 hash_base=>"HEAD", file_name=>$file_name)},6992"HEAD");6993}else{6994$formats_nav.=6995$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6996"raw");6997}6998 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6999 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7000}else{7001print"<div class=\"page_nav\">\n".7002"<br/><br/></div>\n".7003"<div class=\"title\">".esc_html($hash)."</div>\n";7004}7005 git_print_page_path($file_name,"blob",$hash_base);7006print"<div class=\"page_body\">\n";7007if($mimetype=~m!^image/!) {7008print qq!<img type="!.esc_attr($mimetype).qq!"!;7009if($file_name) {7010print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7011}7012print qq! src="! .7013 href(action=>"blob_plain", hash=>$hash,7014 hash_base=>$hash_base, file_name=>$file_name) .7015 qq!"/>\n!;7016}else{7017my$nr;7018while(my$line= <$fd>) {7019chomp$line;7020$nr++;7021$line= untabify($line);7022printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7023$nr, esc_attr(href(-replay =>1)),$nr,$nr,7024$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7025}7026}7027close$fd7028or print"Reading blob failed.\n";7029print"</div>";7030 git_footer_html();7031}70327033sub git_tree {7034if(!defined$hash_base) {7035$hash_base="HEAD";7036}7037if(!defined$hash) {7038if(defined$file_name) {7039$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7040}else{7041$hash=$hash_base;7042}7043}7044 die_error(404,"No such tree")unlessdefined($hash);70457046my$show_sizes= gitweb_check_feature('show-sizes');7047my$have_blame= gitweb_check_feature('blame');70487049my@entries= ();7050{7051local$/="\0";7052open my$fd,"-|", git_cmd(),"ls-tree",'-z',7053($show_sizes?'-l': ()),@extra_options,$hash7054or die_error(500,"Open git-ls-tree failed");7055@entries=map{chomp;$_} <$fd>;7056close$fd7057or die_error(404,"Reading tree failed");7058}70597060my$refs= git_get_references();7061my$ref= format_ref_marker($refs,$hash_base);7062 git_header_html();7063my$basedir='';7064if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7065my@views_nav= ();7066if(defined$file_name) {7067push@views_nav,7068$cgi->a({-href => href(action=>"history", -replay=>1)},7069"history"),7070$cgi->a({-href => href(action=>"tree",7071 hash_base=>"HEAD", file_name=>$file_name)},7072"HEAD"),7073}7074my$snapshot_links= format_snapshot_links($hash);7075if(defined$snapshot_links) {7076# FIXME: Should be available when we have no hash base as well.7077push@views_nav,$snapshot_links;7078}7079 git_print_page_nav('tree','',$hash_base,undef,undef,7080join(' | ',@views_nav));7081 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7082}else{7083undef$hash_base;7084print"<div class=\"page_nav\">\n";7085print"<br/><br/></div>\n";7086print"<div class=\"title\">".esc_html($hash)."</div>\n";7087}7088if(defined$file_name) {7089$basedir=$file_name;7090if($basedirne''&&substr($basedir, -1)ne'/') {7091$basedir.='/';7092}7093 git_print_page_path($file_name,'tree',$hash_base);7094}7095print"<div class=\"page_body\">\n";7096print"<table class=\"tree\">\n";7097my$alternate=1;7098# '..' (top directory) link if possible7099if(defined$hash_base&&7100defined$file_name&&$file_name=~m![^/]+$!) {7101if($alternate) {7102print"<tr class=\"dark\">\n";7103}else{7104print"<tr class=\"light\">\n";7105}7106$alternate^=1;71077108my$up=$file_name;7109$up=~s!/?[^/]+$!!;7110undef$upunless$up;7111# based on git_print_tree_entry7112print'<td class="mode">'. mode_str('040000') ."</td>\n";7113print'<td class="size"> </td>'."\n"if$show_sizes;7114print'<td class="list">';7115print$cgi->a({-href => href(action=>"tree",7116 hash_base=>$hash_base,7117 file_name=>$up)},7118"..");7119print"</td>\n";7120print"<td class=\"link\"></td>\n";71217122print"</tr>\n";7123}7124foreachmy$line(@entries) {7125my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);71267127if($alternate) {7128print"<tr class=\"dark\">\n";7129}else{7130print"<tr class=\"light\">\n";7131}7132$alternate^=1;71337134 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);71357136print"</tr>\n";7137}7138print"</table>\n".7139"</div>";7140 git_footer_html();7141}71427143sub snapshot_name {7144my($project,$hash) =@_;71457146# path/to/project.git -> project7147# path/to/project/.git -> project7148my$name= to_utf8($project);7149$name=~ s,([^/])/*\.git$,$1,;7150$name= basename($name);7151# sanitize name7152$name=~s/[[:cntrl:]]/?/g;71537154my$ver=$hash;7155if($hash=~/^[0-9a-fA-F]+$/) {7156# shorten SHA-1 hash7157my$full_hash= git_get_full_hash($project,$hash);7158if($full_hash=~/^$hash/&&length($hash) >7) {7159$ver= git_get_short_hash($project,$hash);7160}7161}elsif($hash=~m!^refs/tags/(.*)$!) {7162# tags don't need shortened SHA-1 hash7163$ver=$1;7164}else{7165# branches and other need shortened SHA-1 hash7166if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {7167$ver=$1;7168}7169$ver.='-'. git_get_short_hash($project,$hash);7170}7171# in case of hierarchical branch names7172$ver=~s!/!.!g;71737174# name = project-version_string7175$name="$name-$ver";71767177returnwantarray? ($name,$name) :$name;7178}71797180sub exit_if_unmodified_since {7181my($latest_epoch) =@_;7182our$cgi;71837184my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7185if(defined$if_modified) {7186my$since;7187if(eval{require HTTP::Date;1; }) {7188$since= HTTP::Date::str2time($if_modified);7189}elsif(eval{require Time::ParseDate;1; }) {7190$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7191}7192if(defined$since&&$latest_epoch<=$since) {7193my%latest_date= parse_date($latest_epoch);7194print$cgi->header(7195-last_modified =>$latest_date{'rfc2822'},7196-status =>'304 Not Modified');7197goto DONE_GITWEB;7198}7199}7200}72017202sub git_snapshot {7203my$format=$input_params{'snapshot_format'};7204if(!@snapshot_fmts) {7205 die_error(403,"Snapshots not allowed");7206}7207# default to first supported snapshot format7208$format||=$snapshot_fmts[0];7209if($format!~m/^[a-z0-9]+$/) {7210 die_error(400,"Invalid snapshot format parameter");7211}elsif(!exists($known_snapshot_formats{$format})) {7212 die_error(400,"Unknown snapshot format");7213}elsif($known_snapshot_formats{$format}{'disabled'}) {7214 die_error(403,"Snapshot format not allowed");7215}elsif(!grep($_eq$format,@snapshot_fmts)) {7216 die_error(403,"Unsupported snapshot format");7217}72187219my$type= git_get_type("$hash^{}");7220if(!$type) {7221 die_error(404,'Object does not exist');7222}elsif($typeeq'blob') {7223 die_error(400,'Object is not a tree-ish');7224}72257226my($name,$prefix) = snapshot_name($project,$hash);7227my$filename="$name$known_snapshot_formats{$format}{'suffix'}";72287229my%co= parse_commit($hash);7230 exit_if_unmodified_since($co{'committer_epoch'})if%co;72317232my$cmd= quote_command(7233 git_cmd(),'archive',7234"--format=$known_snapshot_formats{$format}{'format'}",7235"--prefix=$prefix/",$hash);7236if(exists$known_snapshot_formats{$format}{'compressor'}) {7237$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7238}72397240$filename=~s/(["\\])/\\$1/g;7241my%latest_date;7242if(%co) {7243%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7244}72457246print$cgi->header(7247-type =>$known_snapshot_formats{$format}{'type'},7248-content_disposition =>'inline; filename="'.$filename.'"',7249%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7250-status =>'200 OK');72517252open my$fd,"-|",$cmd7253or die_error(500,"Execute git-archive failed");7254binmode STDOUT,':raw';7255print<$fd>;7256binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7257close$fd;7258}72597260sub git_log_generic {7261my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;72627263my$head= git_get_head_hash($project);7264if(!defined$base) {7265$base=$head;7266}7267if(!defined$page) {7268$page=0;7269}7270my$refs= git_get_references();72717272my$commit_hash=$base;7273if(defined$parent) {7274$commit_hash="$parent..$base";7275}7276my@commitlist=7277 parse_commits($commit_hash,101, (100*$page),7278defined$file_name? ($file_name,"--full-history") : ());72797280my$ftype;7281if(!defined$file_hash&&defined$file_name) {7282# some commits could have deleted file in question,7283# and not have it in tree, but one of them has to have it7284for(my$i=0;$i<@commitlist;$i++) {7285$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7286last ifdefined$file_hash;7287}7288}7289if(defined$file_hash) {7290$ftype= git_get_type($file_hash);7291}7292if(defined$file_name&& !defined$ftype) {7293 die_error(500,"Unknown type of object");7294}7295my%co;7296if(defined$file_name) {7297%co= parse_commit($base)7298or die_error(404,"Unknown commit object");7299}730073017302my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7303my$next_link='';7304if($#commitlist>=100) {7305$next_link=7306$cgi->a({-href => href(-replay=>1, page=>$page+1),7307-accesskey =>"n", -title =>"Alt-n"},"next");7308}7309my$patch_max= gitweb_get_feature('patches');7310if($patch_max&& !defined$file_name) {7311if($patch_max<0||@commitlist<=$patch_max) {7312$paging_nav.=" ⋅ ".7313$cgi->a({-href => href(action=>"patches", -replay=>1)},7314"patches");7315}7316}73177318 git_header_html();7319 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7320if(defined$file_name) {7321 git_print_header_div('commit', esc_html($co{'title'}),$base);7322}else{7323 git_print_header_div('summary',$project)7324}7325 git_print_page_path($file_name,$ftype,$hash_base)7326if(defined$file_name);73277328$body_subr->(\@commitlist,0,99,$refs,$next_link,7329$file_name,$file_hash,$ftype);73307331 git_footer_html();7332}73337334sub git_log {7335 git_log_generic('log', \&git_log_body,7336$hash,$hash_parent);7337}73387339sub git_commit {7340$hash||=$hash_base||"HEAD";7341my%co= parse_commit($hash)7342or die_error(404,"Unknown commit object");73437344my$parent=$co{'parent'};7345my$parents=$co{'parents'};# listref73467347# we need to prepare $formats_nav before any parameter munging7348my$formats_nav;7349if(!defined$parent) {7350# --root commitdiff7351$formats_nav.='(initial)';7352}elsif(@$parents==1) {7353# single parent commit7354$formats_nav.=7355'(parent: '.7356$cgi->a({-href => href(action=>"commit",7357 hash=>$parent)},7358 esc_html(substr($parent,0,7))) .7359')';7360}else{7361# merge commit7362$formats_nav.=7363'(merge: '.7364join(' ',map{7365$cgi->a({-href => href(action=>"commit",7366 hash=>$_)},7367 esc_html(substr($_,0,7)));7368}@$parents) .7369')';7370}7371if(gitweb_check_feature('patches') &&@$parents<=1) {7372$formats_nav.=" | ".7373$cgi->a({-href => href(action=>"patch", -replay=>1)},7374"patch");7375}73767377if(!defined$parent) {7378$parent="--root";7379}7380my@difftree;7381open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7382@diff_opts,7383(@$parents<=1?$parent:'-c'),7384$hash,"--"7385or die_error(500,"Open git-diff-tree failed");7386@difftree=map{chomp;$_} <$fd>;7387close$fdor die_error(404,"Reading git-diff-tree failed");73887389# non-textual hash id's can be cached7390my$expires;7391if($hash=~m/^[0-9a-fA-F]{40}$/) {7392$expires="+1d";7393}7394my$refs= git_get_references();7395my$ref= format_ref_marker($refs,$co{'id'});73967397 git_header_html(undef,$expires);7398 git_print_page_nav('commit','',7399$hash,$co{'tree'},$hash,7400$formats_nav);74017402if(defined$co{'parent'}) {7403 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7404}else{7405 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7406}7407print"<div class=\"title_text\">\n".7408"<table class=\"object_header\">\n";7409 git_print_authorship_rows(\%co);7410print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7411print"<tr>".7412"<td>tree</td>".7413"<td class=\"sha1\">".7414$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7415class=>"list"},$co{'tree'}) .7416"</td>".7417"<td class=\"link\">".7418$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7419"tree");7420my$snapshot_links= format_snapshot_links($hash);7421if(defined$snapshot_links) {7422print" | ".$snapshot_links;7423}7424print"</td>".7425"</tr>\n";74267427foreachmy$par(@$parents) {7428print"<tr>".7429"<td>parent</td>".7430"<td class=\"sha1\">".7431$cgi->a({-href => href(action=>"commit", hash=>$par),7432class=>"list"},$par) .7433"</td>".7434"<td class=\"link\">".7435$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7436" | ".7437$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7438"</td>".7439"</tr>\n";7440}7441print"</table>".7442"</div>\n";74437444print"<div class=\"page_body\">\n";7445 git_print_log($co{'comment'});7446print"</div>\n";74477448 git_difftree_body(\@difftree,$hash,@$parents);74497450 git_footer_html();7451}74527453sub git_object {7454# object is defined by:7455# - hash or hash_base alone7456# - hash_base and file_name7457my$type;74587459# - hash or hash_base alone7460if($hash|| ($hash_base&& !defined$file_name)) {7461my$object_id=$hash||$hash_base;74627463open my$fd,"-|", quote_command(7464 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7465or die_error(404,"Object does not exist");7466$type= <$fd>;7467chomp$type;7468close$fd7469or die_error(404,"Object does not exist");74707471# - hash_base and file_name7472}elsif($hash_base&&defined$file_name) {7473$file_name=~ s,/+$,,;74747475system(git_cmd(),"cat-file",'-e',$hash_base) ==07476or die_error(404,"Base object does not exist");74777478# here errors should not hapen7479open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7480or die_error(500,"Open git-ls-tree failed");7481my$line= <$fd>;7482close$fd;74837484#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7485unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7486 die_error(404,"File or directory for given base does not exist");7487}7488$type=$2;7489$hash=$3;7490}else{7491 die_error(400,"Not enough information to find object");7492}74937494print$cgi->redirect(-uri => href(action=>$type, -full=>1,7495 hash=>$hash, hash_base=>$hash_base,7496 file_name=>$file_name),7497-status =>'302 Found');7498}74997500sub git_blobdiff {7501my$format=shift||'html';7502my$diff_style=$input_params{'diff_style'} ||'inline';75037504my$fd;7505my@difftree;7506my%diffinfo;7507my$expires;75087509# preparing $fd and %diffinfo for git_patchset_body7510# new style URI7511if(defined$hash_base&&defined$hash_parent_base) {7512if(defined$file_name) {7513# read raw output7514open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7515$hash_parent_base,$hash_base,7516"--", (defined$file_parent?$file_parent: ()),$file_name7517or die_error(500,"Open git-diff-tree failed");7518@difftree=map{chomp;$_} <$fd>;7519close$fd7520or die_error(404,"Reading git-diff-tree failed");7521@difftree7522or die_error(404,"Blob diff not found");75237524}elsif(defined$hash&&7525$hash=~/[0-9a-fA-F]{40}/) {7526# try to find filename from $hash75277528# read filtered raw output7529open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7530$hash_parent_base,$hash_base,"--"7531or die_error(500,"Open git-diff-tree failed");7532@difftree=7533# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7534# $hash == to_id7535grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7536map{chomp;$_} <$fd>;7537close$fd7538or die_error(404,"Reading git-diff-tree failed");7539@difftree7540or die_error(404,"Blob diff not found");75417542}else{7543 die_error(400,"Missing one of the blob diff parameters");7544}75457546if(@difftree>1) {7547 die_error(400,"Ambiguous blob diff specification");7548}75497550%diffinfo= parse_difftree_raw_line($difftree[0]);7551$file_parent||=$diffinfo{'from_file'} ||$file_name;7552$file_name||=$diffinfo{'to_file'};75537554$hash_parent||=$diffinfo{'from_id'};7555$hash||=$diffinfo{'to_id'};75567557# non-textual hash id's can be cached7558if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7559$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7560$expires='+1d';7561}75627563# open patch output7564open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7565'-p', ($formateq'html'?"--full-index": ()),7566$hash_parent_base,$hash_base,7567"--", (defined$file_parent?$file_parent: ()),$file_name7568or die_error(500,"Open git-diff-tree failed");7569}75707571# old/legacy style URI -- not generated anymore since 1.4.3.7572if(!%diffinfo) {7573 die_error('404 Not Found',"Missing one of the blob diff parameters")7574}75757576# header7577if($formateq'html') {7578my$formats_nav=7579$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7580"raw");7581$formats_nav.= diff_style_nav($diff_style);7582 git_header_html(undef,$expires);7583if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7584 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7585 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7586}else{7587print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7588print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7589}7590if(defined$file_name) {7591 git_print_page_path($file_name,"blob",$hash_base);7592}else{7593print"<div class=\"page_path\"></div>\n";7594}75957596}elsif($formateq'plain') {7597print$cgi->header(7598-type =>'text/plain',7599-charset =>'utf-8',7600-expires =>$expires,7601-content_disposition =>'inline; filename="'."$file_name".'.patch"');76027603print"X-Git-Url: ".$cgi->self_url() ."\n\n";76047605}else{7606 die_error(400,"Unknown blobdiff format");7607}76087609# patch7610if($formateq'html') {7611print"<div class=\"page_body\">\n";76127613 git_patchset_body($fd,$diff_style,7614[ \%diffinfo],$hash_base,$hash_parent_base);7615close$fd;76167617print"</div>\n";# class="page_body"7618 git_footer_html();76197620}else{7621while(my$line= <$fd>) {7622$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7623$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;76247625print$line;76267627last if$line=~m!^\+\+\+!;7628}7629local$/=undef;7630print<$fd>;7631close$fd;7632}7633}76347635sub git_blobdiff_plain {7636 git_blobdiff('plain');7637}76387639# assumes that it is added as later part of already existing navigation,7640# so it returns "| foo | bar" rather than just "foo | bar"7641sub diff_style_nav {7642my($diff_style,$is_combined) =@_;7643$diff_style||='inline';76447645return""if($is_combined);76467647my@styles= (inline =>'inline','sidebyside'=>'side by side');7648my%styles=@styles;7649@styles=7650@styles[map{$_*2}0..$#styles/2];76517652returnjoin'',7653map{" | ".$_}7654map{7655$_eq$diff_style?$styles{$_} :7656$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7657}@styles;7658}76597660sub git_commitdiff {7661my%params=@_;7662my$format=$params{-format} ||'html';7663my$diff_style=$input_params{'diff_style'} ||'inline';76647665my($patch_max) = gitweb_get_feature('patches');7666if($formateq'patch') {7667 die_error(403,"Patch view not allowed")unless$patch_max;7668}76697670$hash||=$hash_base||"HEAD";7671my%co= parse_commit($hash)7672or die_error(404,"Unknown commit object");76737674# choose format for commitdiff for merge7675if(!defined$hash_parent&& @{$co{'parents'}} >1) {7676$hash_parent='--cc';7677}7678# we need to prepare $formats_nav before almost any parameter munging7679my$formats_nav;7680if($formateq'html') {7681$formats_nav=7682$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7683"raw");7684if($patch_max&& @{$co{'parents'}} <=1) {7685$formats_nav.=" | ".7686$cgi->a({-href => href(action=>"patch", -replay=>1)},7687"patch");7688}7689$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);76907691if(defined$hash_parent&&7692$hash_parentne'-c'&&$hash_parentne'--cc') {7693# commitdiff with two commits given7694my$hash_parent_short=$hash_parent;7695if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7696$hash_parent_short=substr($hash_parent,0,7);7697}7698$formats_nav.=7699' (from';7700for(my$i=0;$i< @{$co{'parents'}};$i++) {7701if($co{'parents'}[$i]eq$hash_parent) {7702$formats_nav.=' parent '. ($i+1);7703last;7704}7705}7706$formats_nav.=': '.7707$cgi->a({-href => href(-replay=>1,7708 hash=>$hash_parent, hash_base=>undef)},7709 esc_html($hash_parent_short)) .7710')';7711}elsif(!$co{'parent'}) {7712# --root commitdiff7713$formats_nav.=' (initial)';7714}elsif(scalar@{$co{'parents'}} ==1) {7715# single parent commit7716$formats_nav.=7717' (parent: '.7718$cgi->a({-href => href(-replay=>1,7719 hash=>$co{'parent'}, hash_base=>undef)},7720 esc_html(substr($co{'parent'},0,7))) .7721')';7722}else{7723# merge commit7724if($hash_parenteq'--cc') {7725$formats_nav.=' | '.7726$cgi->a({-href => href(-replay=>1,7727 hash=>$hash, hash_parent=>'-c')},7728'combined');7729}else{# $hash_parent eq '-c'7730$formats_nav.=' | '.7731$cgi->a({-href => href(-replay=>1,7732 hash=>$hash, hash_parent=>'--cc')},7733'compact');7734}7735$formats_nav.=7736' (merge: '.7737join(' ',map{7738$cgi->a({-href => href(-replay=>1,7739 hash=>$_, hash_base=>undef)},7740 esc_html(substr($_,0,7)));7741} @{$co{'parents'}} ) .7742')';7743}7744}77457746my$hash_parent_param=$hash_parent;7747if(!defined$hash_parent_param) {7748# --cc for multiple parents, --root for parentless7749$hash_parent_param=7750@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7751}77527753# read commitdiff7754my$fd;7755my@difftree;7756if($formateq'html') {7757open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7758"--no-commit-id","--patch-with-raw","--full-index",7759$hash_parent_param,$hash,"--"7760or die_error(500,"Open git-diff-tree failed");77617762while(my$line= <$fd>) {7763chomp$line;7764# empty line ends raw part of diff-tree output7765last unless$line;7766push@difftree,scalar parse_difftree_raw_line($line);7767}77687769}elsif($formateq'plain') {7770open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7771'-p',$hash_parent_param,$hash,"--"7772or die_error(500,"Open git-diff-tree failed");7773}elsif($formateq'patch') {7774# For commit ranges, we limit the output to the number of7775# patches specified in the 'patches' feature.7776# For single commits, we limit the output to a single patch,7777# diverging from the git-format-patch default.7778my@commit_spec= ();7779if($hash_parent) {7780if($patch_max>0) {7781push@commit_spec,"-$patch_max";7782}7783push@commit_spec,'-n',"$hash_parent..$hash";7784}else{7785if($params{-single}) {7786push@commit_spec,'-1';7787}else{7788if($patch_max>0) {7789push@commit_spec,"-$patch_max";7790}7791push@commit_spec,"-n";7792}7793push@commit_spec,'--root',$hash;7794}7795open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7796'--encoding=utf8','--stdout',@commit_spec7797or die_error(500,"Open git-format-patch failed");7798}else{7799 die_error(400,"Unknown commitdiff format");7800}78017802# non-textual hash id's can be cached7803my$expires;7804if($hash=~m/^[0-9a-fA-F]{40}$/) {7805$expires="+1d";7806}78077808# write commit message7809if($formateq'html') {7810my$refs= git_get_references();7811my$ref= format_ref_marker($refs,$co{'id'});78127813 git_header_html(undef,$expires);7814 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7815 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7816print"<div class=\"title_text\">\n".7817"<table class=\"object_header\">\n";7818 git_print_authorship_rows(\%co);7819print"</table>".7820"</div>\n";7821print"<div class=\"page_body\">\n";7822if(@{$co{'comment'}} >1) {7823print"<div class=\"log\">\n";7824 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7825print"</div>\n";# class="log"7826}78277828}elsif($formateq'plain') {7829my$refs= git_get_references("tags");7830my$tagname= git_get_rev_name_tags($hash);7831my$filename= basename($project) ."-$hash.patch";78327833print$cgi->header(7834-type =>'text/plain',7835-charset =>'utf-8',7836-expires =>$expires,7837-content_disposition =>'inline; filename="'."$filename".'"');7838my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7839print"From: ". to_utf8($co{'author'}) ."\n";7840print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7841print"Subject: ". to_utf8($co{'title'}) ."\n";78427843print"X-Git-Tag:$tagname\n"if$tagname;7844print"X-Git-Url: ".$cgi->self_url() ."\n\n";78457846foreachmy$line(@{$co{'comment'}}) {7847print to_utf8($line) ."\n";7848}7849print"---\n\n";7850}elsif($formateq'patch') {7851my$filename= basename($project) ."-$hash.patch";78527853print$cgi->header(7854-type =>'text/plain',7855-charset =>'utf-8',7856-expires =>$expires,7857-content_disposition =>'inline; filename="'."$filename".'"');7858}78597860# write patch7861if($formateq'html') {7862my$use_parents= !defined$hash_parent||7863$hash_parenteq'-c'||$hash_parenteq'--cc';7864 git_difftree_body(\@difftree,$hash,7865$use_parents? @{$co{'parents'}} :$hash_parent);7866print"<br/>\n";78677868 git_patchset_body($fd,$diff_style,7869 \@difftree,$hash,7870$use_parents? @{$co{'parents'}} :$hash_parent);7871close$fd;7872print"</div>\n";# class="page_body"7873 git_footer_html();78747875}elsif($formateq'plain') {7876local$/=undef;7877print<$fd>;7878close$fd7879or print"Reading git-diff-tree failed\n";7880}elsif($formateq'patch') {7881local$/=undef;7882print<$fd>;7883close$fd7884or print"Reading git-format-patch failed\n";7885}7886}78877888sub git_commitdiff_plain {7889 git_commitdiff(-format =>'plain');7890}78917892# format-patch-style patches7893sub git_patch {7894 git_commitdiff(-format =>'patch', -single =>1);7895}78967897sub git_patches {7898 git_commitdiff(-format =>'patch');7899}79007901sub git_history {7902 git_log_generic('history', \&git_history_body,7903$hash_base,$hash_parent_base,7904$file_name,$hash);7905}79067907sub git_search {7908$searchtype||='commit';79097910# check if appropriate features are enabled7911 gitweb_check_feature('search')7912or die_error(403,"Search is disabled");7913if($searchtypeeq'pickaxe') {7914# pickaxe may take all resources of your box and run for several minutes7915# with every query - so decide by yourself how public you make this feature7916 gitweb_check_feature('pickaxe')7917or die_error(403,"Pickaxe search is disabled");7918}7919if($searchtypeeq'grep') {7920# grep search might be potentially CPU-intensive, too7921 gitweb_check_feature('grep')7922or die_error(403,"Grep search is disabled");7923}79247925if(!defined$searchtext) {7926 die_error(400,"Text field is empty");7927}7928if(!defined$hash) {7929$hash= git_get_head_hash($project);7930}7931my%co= parse_commit($hash);7932if(!%co) {7933 die_error(404,"Unknown commit object");7934}7935if(!defined$page) {7936$page=0;7937}79387939if($searchtypeeq'commit'||7940$searchtypeeq'author'||7941$searchtypeeq'committer') {7942 git_search_message(%co);7943}elsif($searchtypeeq'pickaxe') {7944 git_search_changes(%co);7945}elsif($searchtypeeq'grep') {7946 git_search_files(%co);7947}else{7948 die_error(400,"Unknown search type");7949}7950}79517952sub git_search_help {7953 git_header_html();7954 git_print_page_nav('','',$hash,$hash,$hash);7955print<<EOT;7956<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7957regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7958the pattern entered is recognized as the POSIX extended7959<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7960insensitive).</p>7961<dl>7962<dt><b>commit</b></dt>7963<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7964EOT7965my$have_grep= gitweb_check_feature('grep');7966if($have_grep) {7967print<<EOT;7968<dt><b>grep</b></dt>7969<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7970 a different one) are searched for the given pattern. On large trees, this search can take7971a while and put some strain on the server, so please use it with some consideration. Note that7972due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7973case-sensitive.</dd>7974EOT7975}7976print<<EOT;7977<dt><b>author</b></dt>7978<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7979<dt><b>committer</b></dt>7980<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7981EOT7982my$have_pickaxe= gitweb_check_feature('pickaxe');7983if($have_pickaxe) {7984print<<EOT;7985<dt><b>pickaxe</b></dt>7986<dd>All commits that caused the string to appear or disappear from any file (changes that7987added, removed or "modified" the string) will be listed. This search can take a while and7988takes a lot of strain on the server, so please use it wisely. Note that since you may be7989interested even in changes just changing the case as well, this search is case sensitive.</dd>7990EOT7991}7992print"</dl>\n";7993 git_footer_html();7994}79957996sub git_shortlog {7997 git_log_generic('shortlog', \&git_shortlog_body,7998$hash,$hash_parent);7999}80008001## ......................................................................8002## feeds (RSS, Atom; OPML)80038004sub git_feed {8005my$format=shift||'atom';8006my$have_blame= gitweb_check_feature('blame');80078008# Atom: http://www.atomenabled.org/developers/syndication/8009# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8010if($formatne'rss'&&$formatne'atom') {8011 die_error(400,"Unknown web feed format");8012}80138014# log/feed of current (HEAD) branch, log of given branch, history of file/directory8015my$head=$hash||'HEAD';8016my@commitlist= parse_commits($head,150,0,$file_name);80178018my%latest_commit;8019my%latest_date;8020my$content_type="application/$format+xml";8021if(defined$cgi->http('HTTP_ACCEPT') &&8022$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8023# browser (feed reader) prefers text/xml8024$content_type='text/xml';8025}8026if(defined($commitlist[0])) {8027%latest_commit= %{$commitlist[0]};8028my$latest_epoch=$latest_commit{'committer_epoch'};8029 exit_if_unmodified_since($latest_epoch);8030%latest_date= parse_date($latest_epoch,$latest_commit{'committer_tz'});8031}8032print$cgi->header(8033-type =>$content_type,8034-charset =>'utf-8',8035%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8036-status =>'200 OK');80378038# Optimization: skip generating the body if client asks only8039# for Last-Modified date.8040return if($cgi->request_method()eq'HEAD');80418042# header variables8043my$title="$site_name-$project/$action";8044my$feed_type='log';8045if(defined$hash) {8046$title.=" - '$hash'";8047$feed_type='branch log';8048if(defined$file_name) {8049$title.=" ::$file_name";8050$feed_type='history';8051}8052}elsif(defined$file_name) {8053$title.=" -$file_name";8054$feed_type='history';8055}8056$title.="$feed_type";8057$title= esc_html($title);8058my$descr= git_get_project_description($project);8059if(defined$descr) {8060$descr= esc_html($descr);8061}else{8062$descr="$project".8063($formateq'rss'?'RSS':'Atom') .8064" feed";8065}8066my$owner= git_get_project_owner($project);8067$owner= esc_html($owner);80688069#header8070my$alt_url;8071if(defined$file_name) {8072$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8073}elsif(defined$hash) {8074$alt_url= href(-full=>1, action=>"log", hash=>$hash);8075}else{8076$alt_url= href(-full=>1, action=>"summary");8077}8078print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8079if($formateq'rss') {8080print<<XML;8081<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8082<channel>8083XML8084print"<title>$title</title>\n".8085"<link>$alt_url</link>\n".8086"<description>$descr</description>\n".8087"<language>en</language>\n".8088# project owner is responsible for 'editorial' content8089"<managingEditor>$owner</managingEditor>\n";8090if(defined$logo||defined$favicon) {8091# prefer the logo to the favicon, since RSS8092# doesn't allow both8093my$img= esc_url($logo||$favicon);8094print"<image>\n".8095"<url>$img</url>\n".8096"<title>$title</title>\n".8097"<link>$alt_url</link>\n".8098"</image>\n";8099}8100if(%latest_date) {8101print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8102print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8103}8104print"<generator>gitweb v.$version/$git_version</generator>\n";8105}elsif($formateq'atom') {8106print<<XML;8107<feed xmlns="http://www.w3.org/2005/Atom">8108XML8109print"<title>$title</title>\n".8110"<subtitle>$descr</subtitle>\n".8111'<link rel="alternate" type="text/html" href="'.8112$alt_url.'" />'."\n".8113'<link rel="self" type="'.$content_type.'" href="'.8114$cgi->self_url() .'" />'."\n".8115"<id>". href(-full=>1) ."</id>\n".8116# use project owner for feed author8117"<author><name>$owner</name></author>\n";8118if(defined$favicon) {8119print"<icon>". esc_url($favicon) ."</icon>\n";8120}8121if(defined$logo) {8122# not twice as wide as tall: 72 x 27 pixels8123print"<logo>". esc_url($logo) ."</logo>\n";8124}8125if(!%latest_date) {8126# dummy date to keep the feed valid until commits trickle in:8127print"<updated>1970-01-01T00:00:00Z</updated>\n";8128}else{8129print"<updated>$latest_date{'iso-8601'}</updated>\n";8130}8131print"<generator version='$version/$git_version'>gitweb</generator>\n";8132}81338134# contents8135for(my$i=0;$i<=$#commitlist;$i++) {8136my%co= %{$commitlist[$i]};8137my$commit=$co{'id'};8138# we read 150, we always show 30 and the ones more recent than 48 hours8139if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8140last;8141}8142my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});81438144# get list of changed files8145open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8146$co{'parent'} ||"--root",8147$co{'id'},"--", (defined$file_name?$file_name: ())8148ornext;8149my@difftree=map{chomp;$_} <$fd>;8150close$fd8151ornext;81528153# print element (entry, item)8154my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8155if($formateq'rss') {8156print"<item>\n".8157"<title>". esc_html($co{'title'}) ."</title>\n".8158"<author>". esc_html($co{'author'}) ."</author>\n".8159"<pubDate>$cd{'rfc2822'}</pubDate>\n".8160"<guid isPermaLink=\"true\">$co_url</guid>\n".8161"<link>$co_url</link>\n".8162"<description>". esc_html($co{'title'}) ."</description>\n".8163"<content:encoded>".8164"<![CDATA[\n";8165}elsif($formateq'atom') {8166print"<entry>\n".8167"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8168"<updated>$cd{'iso-8601'}</updated>\n".8169"<author>\n".8170" <name>". esc_html($co{'author_name'}) ."</name>\n";8171if($co{'author_email'}) {8172print" <email>". esc_html($co{'author_email'}) ."</email>\n";8173}8174print"</author>\n".8175# use committer for contributor8176"<contributor>\n".8177" <name>". esc_html($co{'committer_name'}) ."</name>\n";8178if($co{'committer_email'}) {8179print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8180}8181print"</contributor>\n".8182"<published>$cd{'iso-8601'}</published>\n".8183"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8184"<id>$co_url</id>\n".8185"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8186"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8187}8188my$comment=$co{'comment'};8189print"<pre>\n";8190foreachmy$line(@$comment) {8191$line= esc_html($line);8192print"$line\n";8193}8194print"</pre><ul>\n";8195foreachmy$difftree_line(@difftree) {8196my%difftree= parse_difftree_raw_line($difftree_line);8197next if!$difftree{'from_id'};81988199my$file=$difftree{'file'} ||$difftree{'to_file'};82008201print"<li>".8202"[".8203$cgi->a({-href => href(-full=>1, action=>"blobdiff",8204 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8205 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8206 file_name=>$file, file_parent=>$difftree{'from_file'}),8207-title =>"diff"},'D');8208if($have_blame) {8209print$cgi->a({-href => href(-full=>1, action=>"blame",8210 file_name=>$file, hash_base=>$commit),8211-title =>"blame"},'B');8212}8213# if this is not a feed of a file history8214if(!defined$file_name||$file_namene$file) {8215print$cgi->a({-href => href(-full=>1, action=>"history",8216 file_name=>$file, hash=>$commit),8217-title =>"history"},'H');8218}8219$file= esc_path($file);8220print"] ".8221"$file</li>\n";8222}8223if($formateq'rss') {8224print"</ul>]]>\n".8225"</content:encoded>\n".8226"</item>\n";8227}elsif($formateq'atom') {8228print"</ul>\n</div>\n".8229"</content>\n".8230"</entry>\n";8231}8232}82338234# end of feed8235if($formateq'rss') {8236print"</channel>\n</rss>\n";8237}elsif($formateq'atom') {8238print"</feed>\n";8239}8240}82418242sub git_rss {8243 git_feed('rss');8244}82458246sub git_atom {8247 git_feed('atom');8248}82498250sub git_opml {8251my@list= git_get_projects_list($project_filter,$strict_export);8252if(!@list) {8253 die_error(404,"No projects found");8254}82558256print$cgi->header(8257-type =>'text/xml',8258-charset =>'utf-8',8259-content_disposition =>'inline; filename="opml.xml"');82608261my$title= esc_html($site_name);8262my$filter=" within subdirectory ";8263if(defined$project_filter) {8264$filter.= esc_html($project_filter);8265}else{8266$filter="";8267}8268print<<XML;8269<?xml version="1.0" encoding="utf-8"?>8270<opml version="1.0">8271<head>8272 <title>$titleOPML Export$filter</title>8273</head>8274<body>8275<outline text="git RSS feeds">8276XML82778278foreachmy$pr(@list) {8279my%proj=%$pr;8280my$head= git_get_head_hash($proj{'path'});8281if(!defined$head) {8282next;8283}8284$git_dir="$projectroot/$proj{'path'}";8285my%co= parse_commit($head);8286if(!%co) {8287next;8288}82898290my$path= esc_html(chop_str($proj{'path'},25,5));8291my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8292my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8293print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8294}8295print<<XML;8296</outline>8297</body>8298</opml>8299XML8300}