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.remoteheads = 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 against 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=undef;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 occurred 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:]])|(index("\t\n\r",$1) != -1?$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"//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"//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$lo=~s/_//g;2700$key=join(".",lc($hi),$mi,lc($lo));2701return if($lo=~/\W/||$hi=~/\W/);2702}else{2703$key=lc($key);2704$key=~s/_//g;2705return if($key=~/\W/);2706}2707$key=~s/^gitweb\.//;27082709# type sanity check2710if(defined$type) {2711$type=~s/^--//;2712$type=undef2713unless($typeeq'bool'||$typeeq'int');2714}27152716# get config2717if(!defined$config_file||2718$config_filene"$git_dir/config") {2719%config= git_parse_project_config('gitweb');2720$config_file="$git_dir/config";2721}27222723# check if config variable (key) exists2724return unlessexists$config{"gitweb.$key"};27252726# ensure given type2727if(!defined$type) {2728return$config{"gitweb.$key"};2729}elsif($typeeq'bool') {2730# backward compatibility: 'git config --bool' returns true/false2731return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2732}elsif($typeeq'int') {2733return config_to_int($config{"gitweb.$key"});2734}2735return$config{"gitweb.$key"};2736}27372738# get hash of given path at given ref2739sub git_get_hash_by_path {2740my$base=shift;2741my$path=shift||returnundef;2742my$type=shift;27432744$path=~ s,/+$,,;27452746open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2747or die_error(500,"Open git-ls-tree failed");2748my$line= <$fd>;2749close$fdorreturnundef;27502751if(!defined$line) {2752# there is no tree or hash given by $path at $base2753returnundef;2754}27552756#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2757$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2758if(defined$type&&$typene$2) {2759# type doesn't match2760returnundef;2761}2762return$3;2763}27642765# get path of entry with given hash at given tree-ish (ref)2766# used to get 'from' filename for combined diff (merge commit) for renames2767sub git_get_path_by_hash {2768my$base=shift||return;2769my$hash=shift||return;27702771local$/="\0";27722773open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2774orreturnundef;2775while(my$line= <$fd>) {2776chomp$line;27772778#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2779#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2780if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2781close$fd;2782return$1;2783}2784}2785close$fd;2786returnundef;2787}27882789## ......................................................................2790## git utility functions, directly accessing git repository27912792# get the value of config variable either from file named as the variable2793# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2794# configuration variable in the repository config file.2795sub git_get_file_or_project_config {2796my($path,$name) =@_;27972798$git_dir="$projectroot/$path";2799open my$fd,'<',"$git_dir/$name"2800orreturn git_get_project_config($name);2801my$conf= <$fd>;2802close$fd;2803if(defined$conf) {2804chomp$conf;2805}2806return$conf;2807}28082809sub git_get_project_description {2810my$path=shift;2811return git_get_file_or_project_config($path,'description');2812}28132814sub git_get_project_category {2815my$path=shift;2816return git_get_file_or_project_config($path,'category');2817}281828192820# supported formats:2821# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2822# - if its contents is a number, use it as tag weight,2823# - otherwise add a tag with weight 12824# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2825# the same value multiple times increases tag weight2826# * `gitweb.ctag' multi-valued repo config variable2827sub git_get_project_ctags {2828my$project=shift;2829my$ctags= {};28302831$git_dir="$projectroot/$project";2832if(opendir my$dh,"$git_dir/ctags") {2833my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2834foreachmy$tagfile(@files) {2835open my$ct,'<',$tagfile2836ornext;2837my$val= <$ct>;2838chomp$valif$val;2839close$ct;28402841(my$ctag=$tagfile) =~ s#.*/##;2842if($val=~/^\d+$/) {2843$ctags->{$ctag} =$val;2844}else{2845$ctags->{$ctag} =1;2846}2847}2848closedir$dh;28492850}elsif(open my$fh,'<',"$git_dir/ctags") {2851while(my$line= <$fh>) {2852chomp$line;2853$ctags->{$line}++if$line;2854}2855close$fh;28562857}else{2858my$taglist= config_to_multi(git_get_project_config('ctag'));2859foreachmy$tag(@$taglist) {2860$ctags->{$tag}++;2861}2862}28632864return$ctags;2865}28662867# return hash, where keys are content tags ('ctags'),2868# and values are sum of weights of given tag in every project2869sub git_gather_all_ctags {2870my$projects=shift;2871my$ctags= {};28722873foreachmy$p(@$projects) {2874foreachmy$ct(keys%{$p->{'ctags'}}) {2875$ctags->{$ct} +=$p->{'ctags'}->{$ct};2876}2877}28782879return$ctags;2880}28812882sub git_populate_project_tagcloud {2883my$ctags=shift;28842885# First, merge different-cased tags; tags vote on casing2886my%ctags_lc;2887foreach(keys%$ctags) {2888$ctags_lc{lc$_}->{count} +=$ctags->{$_};2889if(not$ctags_lc{lc$_}->{topcount}2890or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2891$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2892$ctags_lc{lc$_}->{topname} =$_;2893}2894}28952896my$cloud;2897my$matched=$input_params{'ctag'};2898if(eval{require HTML::TagCloud;1; }) {2899$cloud= HTML::TagCloud->new;2900foreachmy$ctag(sort keys%ctags_lc) {2901# Pad the title with spaces so that the cloud looks2902# less crammed.2903my$title= esc_html($ctags_lc{$ctag}->{topname});2904$title=~s/ / /g;2905$title=~s/^/ /g;2906$title=~s/$/ /g;2907if(defined$matched&&$matchedeq$ctag) {2908$title=qq(<span class="match">$title</span>);2909}2910$cloud->add($title, href(project=>undef, ctag=>$ctag),2911$ctags_lc{$ctag}->{count});2912}2913}else{2914$cloud= {};2915foreachmy$ctag(keys%ctags_lc) {2916my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2917if(defined$matched&&$matchedeq$ctag) {2918$title=qq(<span class="match">$title</span>);2919}2920$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2921$cloud->{$ctag}{ctag} =2922$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2923}2924}2925return$cloud;2926}29272928sub git_show_project_tagcloud {2929my($cloud,$count) =@_;2930if(ref$cloudeq'HTML::TagCloud') {2931return$cloud->html_and_css($count);2932}else{2933my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2934return2935'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2936join(', ',map{2937$cloud->{$_}->{'ctag'}2938}splice(@tags,0,$count)) .2939'</div>';2940}2941}29422943sub git_get_project_url_list {2944my$path=shift;29452946$git_dir="$projectroot/$path";2947open my$fd,'<',"$git_dir/cloneurl"2948orreturnwantarray?2949@{ config_to_multi(git_get_project_config('url')) } :2950 config_to_multi(git_get_project_config('url'));2951my@git_project_url_list=map{chomp;$_} <$fd>;2952close$fd;29532954returnwantarray?@git_project_url_list: \@git_project_url_list;2955}29562957sub git_get_projects_list {2958my$filter=shift||'';2959my$paranoid=shift;2960my@list;29612962if(-d $projects_list) {2963# search in directory2964my$dir=$projects_list;2965# remove the trailing "/"2966$dir=~s!/+$!!;2967my$pfxlen=length("$dir");2968my$pfxdepth= ($dir=~tr!/!!);2969# when filtering, search only given subdirectory2970if($filter&& !$paranoid) {2971$dir.="/$filter";2972$dir=~s!/+$!!;2973}29742975 File::Find::find({2976 follow_fast =>1,# follow symbolic links2977 follow_skip =>2,# ignore duplicates2978 dangling_symlinks =>0,# ignore dangling symlinks, silently2979 wanted =>sub{2980# global variables2981our$project_maxdepth;2982our$projectroot;2983# skip project-list toplevel, if we get it.2984return if(m!^[/.]$!);2985# only directories can be git repositories2986return unless(-d $_);2987# don't traverse too deep (Find is super slow on os x)2988# $project_maxdepth excludes depth of $projectroot2989if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2990$File::Find::prune =1;2991return;2992}29932994my$path=substr($File::Find::name,$pfxlen+1);2995# paranoidly only filter here2996if($paranoid&&$filter&&$path!~m!^\Q$filter\E/!) {2997next;2998}2999# we check related file in $projectroot3000if(check_export_ok("$projectroot/$path")) {3001push@list, { path =>$path};3002$File::Find::prune =1;3003}3004},3005},"$dir");30063007}elsif(-f $projects_list) {3008# read from file(url-encoded):3009# 'git%2Fgit.git Linus+Torvalds'3010# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3011# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3012open my$fd,'<',$projects_listorreturn;3013 PROJECT:3014while(my$line= <$fd>) {3015chomp$line;3016my($path,$owner) =split' ',$line;3017$path= unescape($path);3018$owner= unescape($owner);3019if(!defined$path) {3020next;3021}3022# if $filter is rpovided, check if $path begins with $filter3023if($filter&&$path!~m!^\Q$filter\E/!) {3024next;3025}3026if(check_export_ok("$projectroot/$path")) {3027my$pr= {3028 path =>$path3029};3030if($owner) {3031$pr->{'owner'} = to_utf8($owner);3032}3033push@list,$pr;3034}3035}3036close$fd;3037}3038return@list;3039}30403041# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)3042# as side effects it sets 'forks' field to list of forks for forked projects3043sub filter_forks_from_projects_list {3044my$projects=shift;30453046my%trie;# prefix tree of directories (path components)3047# generate trie out of those directories that might contain forks3048foreachmy$pr(@$projects) {3049my$path=$pr->{'path'};3050$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory3051next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'3052next unless($path);# skip '.git' repository: tests, git-instaweb3053next unless(-d "$projectroot/$path");# containing directory exists3054$pr->{'forks'} = [];# there can be 0 or more forks of project30553056# add to trie3057my@dirs=split('/',$path);3058# walk the trie, until either runs out of components or out of trie3059my$ref= \%trie;3060while(scalar@dirs&&3061exists($ref->{$dirs[0]})) {3062$ref=$ref->{shift@dirs};3063}3064# create rest of trie structure from rest of components3065foreachmy$dir(@dirs) {3066$ref=$ref->{$dir} = {};3067}3068# create end marker, store $pr as a data3069$ref->{''} =$prif(!exists$ref->{''});3070}30713072# filter out forks, by finding shortest prefix match for paths3073my@filtered;3074 PROJECT:3075foreachmy$pr(@$projects) {3076# trie lookup3077my$ref= \%trie;3078 DIR:3079foreachmy$dir(split('/',$pr->{'path'})) {3080if(exists$ref->{''}) {3081# found [shortest] prefix, is a fork - skip it3082push@{$ref->{''}{'forks'}},$pr;3083next PROJECT;3084}3085if(!exists$ref->{$dir}) {3086# not in trie, cannot have prefix, not a fork3087push@filtered,$pr;3088next PROJECT;3089}3090# If the dir is there, we just walk one step down the trie.3091$ref=$ref->{$dir};3092}3093# we ran out of trie3094# (shouldn't happen: it's either no match, or end marker)3095push@filtered,$pr;3096}30973098return@filtered;3099}31003101# note: fill_project_list_info must be run first,3102# for 'descr_long' and 'ctags' to be filled3103sub search_projects_list {3104my($projlist,%opts) =@_;3105my$tagfilter=$opts{'tagfilter'};3106my$search_re=$opts{'search_regexp'};31073108return@$projlist3109unless($tagfilter||$search_re);31103111# searching projects require filling to be run before it;3112 fill_project_list_info($projlist,3113$tagfilter?'ctags': (),3114$search_re? ('path','descr') : ());3115my@projects;3116 PROJECT:3117foreachmy$pr(@$projlist) {31183119if($tagfilter) {3120next unlessref($pr->{'ctags'})eq'HASH';3121next unless3122grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};3123}31243125if($search_re) {3126next unless3127$pr->{'path'} =~/$search_re/||3128$pr->{'descr_long'} =~/$search_re/;3129}31303131push@projects,$pr;3132}31333134return@projects;3135}31363137our$gitweb_project_owner=undef;3138sub git_get_project_list_from_file {31393140return if(defined$gitweb_project_owner);31413142$gitweb_project_owner= {};3143# read from file (url-encoded):3144# 'git%2Fgit.git Linus+Torvalds'3145# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3146# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3147if(-f $projects_list) {3148open(my$fd,'<',$projects_list);3149while(my$line= <$fd>) {3150chomp$line;3151my($pr,$ow) =split' ',$line;3152$pr= unescape($pr);3153$ow= unescape($ow);3154$gitweb_project_owner->{$pr} = to_utf8($ow);3155}3156close$fd;3157}3158}31593160sub git_get_project_owner {3161my$project=shift;3162my$owner;31633164returnundefunless$project;3165$git_dir="$projectroot/$project";31663167if(!defined$gitweb_project_owner) {3168 git_get_project_list_from_file();3169}31703171if(exists$gitweb_project_owner->{$project}) {3172$owner=$gitweb_project_owner->{$project};3173}3174if(!defined$owner){3175$owner= git_get_project_config('owner');3176}3177if(!defined$owner) {3178$owner= get_file_owner("$git_dir");3179}31803181return$owner;3182}31833184sub git_get_last_activity {3185my($path) =@_;3186my$fd;31873188$git_dir="$projectroot/$path";3189open($fd,"-|", git_cmd(),'for-each-ref',3190'--format=%(committer)',3191'--sort=-committerdate',3192'--count=1',3193'refs/heads')orreturn;3194my$most_recent= <$fd>;3195close$fdorreturn;3196if(defined$most_recent&&3197$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3198my$timestamp=$1;3199my$age=time-$timestamp;3200return($age, age_string($age));3201}3202return(undef,undef);3203}32043205# Implementation note: when a single remote is wanted, we cannot use 'git3206# remote show -n' because that command always work (assuming it's a remote URL3207# if it's not defined), and we cannot use 'git remote show' because that would3208# try to make a network roundtrip. So the only way to find if that particular3209# remote is defined is to walk the list provided by 'git remote -v' and stop if3210# and when we find what we want.3211sub git_get_remotes_list {3212my$wanted=shift;3213my%remotes= ();32143215open my$fd,'-|', git_cmd(),'remote','-v';3216return unless$fd;3217while(my$remote= <$fd>) {3218chomp$remote;3219$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3220next if$wantedand not$remoteeq$wanted;3221my($url,$key) = ($1,$2);32223223$remotes{$remote} ||= {'heads'=> () };3224$remotes{$remote}{$key} =$url;3225}3226close$fdorreturn;3227returnwantarray?%remotes: \%remotes;3228}32293230# Takes a hash of remotes as first parameter and fills it by adding the3231# available remote heads for each of the indicated remotes.3232sub fill_remote_heads {3233my$remotes=shift;3234my@heads=map{"remotes/$_"}keys%$remotes;3235my@remoteheads= git_get_heads_list(undef,@heads);3236foreachmy$remote(keys%$remotes) {3237$remotes->{$remote}{'heads'} = [grep{3238$_->{'name'} =~s!^$remote/!!3239}@remoteheads];3240}3241}32423243sub git_get_references {3244my$type=shift||"";3245my%refs;3246# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113247# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3248open my$fd,"-|", git_cmd(),"show-ref","--dereference",3249($type? ("--","refs/$type") : ())# use -- <pattern> if $type3250orreturn;32513252while(my$line= <$fd>) {3253chomp$line;3254if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3255if(defined$refs{$1}) {3256push@{$refs{$1}},$2;3257}else{3258$refs{$1} = [$2];3259}3260}3261}3262close$fdorreturn;3263return \%refs;3264}32653266sub git_get_rev_name_tags {3267my$hash=shift||returnundef;32683269open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3270orreturn;3271my$name_rev= <$fd>;3272close$fd;32733274if($name_rev=~ m|^$hash tags/(.*)$|) {3275return$1;3276}else{3277# catches also '$hash undefined' output3278returnundef;3279}3280}32813282## ----------------------------------------------------------------------3283## parse to hash functions32843285sub parse_date {3286my$epoch=shift;3287my$tz=shift||"-0000";32883289my%date;3290my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3291my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3292my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3293$date{'hour'} =$hour;3294$date{'minute'} =$min;3295$date{'mday'} =$mday;3296$date{'day'} =$days[$wday];3297$date{'month'} =$months[$mon];3298$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3299$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3300$date{'mday-time'} =sprintf"%d%s%02d:%02d",3301$mday,$months[$mon],$hour,$min;3302$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",33031900+$year,1+$mon,$mday,$hour,$min,$sec;33043305my($tz_sign,$tz_hour,$tz_min) =3306($tz=~m/^([-+])(\d\d)(\d\d)$/);3307$tz_sign= ($tz_signeq'-'? -1: +1);3308my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3309($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3310$date{'hour_local'} =$hour;3311$date{'minute_local'} =$min;3312$date{'tz_local'} =$tz;3313$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",33141900+$year,$mon+1,$mday,3315$hour,$min,$sec,$tz);3316return%date;3317}33183319sub parse_tag {3320my$tag_id=shift;3321my%tag;3322my@comment;33233324open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3325$tag{'id'} =$tag_id;3326while(my$line= <$fd>) {3327chomp$line;3328if($line=~m/^object ([0-9a-fA-F]{40})$/) {3329$tag{'object'} =$1;3330}elsif($line=~m/^type (.+)$/) {3331$tag{'type'} =$1;3332}elsif($line=~m/^tag (.+)$/) {3333$tag{'name'} =$1;3334}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3335$tag{'author'} =$1;3336$tag{'author_epoch'} =$2;3337$tag{'author_tz'} =$3;3338if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3339$tag{'author_name'} =$1;3340$tag{'author_email'} =$2;3341}else{3342$tag{'author_name'} =$tag{'author'};3343}3344}elsif($line=~m/--BEGIN/) {3345push@comment,$line;3346last;3347}elsif($lineeq"") {3348last;3349}3350}3351push@comment, <$fd>;3352$tag{'comment'} = \@comment;3353close$fdorreturn;3354if(!defined$tag{'name'}) {3355return3356};3357return%tag3358}33593360sub parse_commit_text {3361my($commit_text,$withparents) =@_;3362my@commit_lines=split'\n',$commit_text;3363my%co;33643365pop@commit_lines;# Remove '\0'33663367if(!@commit_lines) {3368return;3369}33703371my$header=shift@commit_lines;3372if($header!~m/^[0-9a-fA-F]{40}/) {3373return;3374}3375($co{'id'},my@parents) =split' ',$header;3376while(my$line=shift@commit_lines) {3377last if$lineeq"\n";3378if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3379$co{'tree'} =$1;3380}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3381push@parents,$1;3382}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3383$co{'author'} = to_utf8($1);3384$co{'author_epoch'} =$2;3385$co{'author_tz'} =$3;3386if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3387$co{'author_name'} =$1;3388$co{'author_email'} =$2;3389}else{3390$co{'author_name'} =$co{'author'};3391}3392}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3393$co{'committer'} = to_utf8($1);3394$co{'committer_epoch'} =$2;3395$co{'committer_tz'} =$3;3396if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3397$co{'committer_name'} =$1;3398$co{'committer_email'} =$2;3399}else{3400$co{'committer_name'} =$co{'committer'};3401}3402}3403}3404if(!defined$co{'tree'}) {3405return;3406};3407$co{'parents'} = \@parents;3408$co{'parent'} =$parents[0];34093410foreachmy$title(@commit_lines) {3411$title=~s/^ //;3412if($titlene"") {3413$co{'title'} = chop_str($title,80,5);3414# remove leading stuff of merges to make the interesting part visible3415if(length($title) >50) {3416$title=~s/^Automatic //;3417$title=~s/^merge (of|with) /Merge ... /i;3418if(length($title) >50) {3419$title=~s/(http|rsync):\/\///;3420}3421if(length($title) >50) {3422$title=~s/(master|www|rsync)\.//;3423}3424if(length($title) >50) {3425$title=~s/kernel.org:?//;3426}3427if(length($title) >50) {3428$title=~s/\/pub\/scm//;3429}3430}3431$co{'title_short'} = chop_str($title,50,5);3432last;3433}3434}3435if(!defined$co{'title'} ||$co{'title'}eq"") {3436$co{'title'} =$co{'title_short'} ='(no commit message)';3437}3438# remove added spaces3439foreachmy$line(@commit_lines) {3440$line=~s/^ //;3441}3442$co{'comment'} = \@commit_lines;34433444my$age=time-$co{'committer_epoch'};3445$co{'age'} =$age;3446$co{'age_string'} = age_string($age);3447my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3448if($age>60*60*24*7*2) {3449$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3450$co{'age_string_age'} =$co{'age_string'};3451}else{3452$co{'age_string_date'} =$co{'age_string'};3453$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3454}3455return%co;3456}34573458sub parse_commit {3459my($commit_id) =@_;3460my%co;34613462local$/="\0";34633464open my$fd,"-|", git_cmd(),"rev-list",3465"--parents",3466"--header",3467"--max-count=1",3468$commit_id,3469"--",3470or die_error(500,"Open git-rev-list failed");3471%co= parse_commit_text(<$fd>,1);3472close$fd;34733474return%co;3475}34763477sub parse_commits {3478my($commit_id,$maxcount,$skip,$filename,@args) =@_;3479my@cos;34803481$maxcount||=1;3482$skip||=0;34833484local$/="\0";34853486open my$fd,"-|", git_cmd(),"rev-list",3487"--header",3488@args,3489("--max-count=".$maxcount),3490("--skip=".$skip),3491@extra_options,3492$commit_id,3493"--",3494($filename? ($filename) : ())3495or die_error(500,"Open git-rev-list failed");3496while(my$line= <$fd>) {3497my%co= parse_commit_text($line);3498push@cos, \%co;3499}3500close$fd;35013502returnwantarray?@cos: \@cos;3503}35043505# parse line of git-diff-tree "raw" output3506sub parse_difftree_raw_line {3507my$line=shift;3508my%res;35093510# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3511# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3512if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3513$res{'from_mode'} =$1;3514$res{'to_mode'} =$2;3515$res{'from_id'} =$3;3516$res{'to_id'} =$4;3517$res{'status'} =$5;3518$res{'similarity'} =$6;3519if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3520($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3521}else{3522$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3523}3524}3525# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3526# combined diff (for merge commit)3527elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3528$res{'nparents'} =length($1);3529$res{'from_mode'} = [split(' ',$2) ];3530$res{'to_mode'} =pop@{$res{'from_mode'}};3531$res{'from_id'} = [split(' ',$3) ];3532$res{'to_id'} =pop@{$res{'from_id'}};3533$res{'status'} = [split('',$4) ];3534$res{'to_file'} = unquote($5);3535}3536# 'c512b523472485aef4fff9e57b229d9d243c967f'3537elsif($line=~m/^([0-9a-fA-F]{40})$/) {3538$res{'commit'} =$1;3539}35403541returnwantarray?%res: \%res;3542}35433544# wrapper: return parsed line of git-diff-tree "raw" output3545# (the argument might be raw line, or parsed info)3546sub parsed_difftree_line {3547my$line_or_ref=shift;35483549if(ref($line_or_ref)eq"HASH") {3550# pre-parsed (or generated by hand)3551return$line_or_ref;3552}else{3553return parse_difftree_raw_line($line_or_ref);3554}3555}35563557# parse line of git-ls-tree output3558sub parse_ls_tree_line {3559my$line=shift;3560my%opts=@_;3561my%res;35623563if($opts{'-l'}) {3564#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3565$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;35663567$res{'mode'} =$1;3568$res{'type'} =$2;3569$res{'hash'} =$3;3570$res{'size'} =$4;3571if($opts{'-z'}) {3572$res{'name'} =$5;3573}else{3574$res{'name'} = unquote($5);3575}3576}else{3577#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3578$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;35793580$res{'mode'} =$1;3581$res{'type'} =$2;3582$res{'hash'} =$3;3583if($opts{'-z'}) {3584$res{'name'} =$4;3585}else{3586$res{'name'} = unquote($4);3587}3588}35893590returnwantarray?%res: \%res;3591}35923593# generates _two_ hashes, references to which are passed as 2 and 3 argument3594sub parse_from_to_diffinfo {3595my($diffinfo,$from,$to,@parents) =@_;35963597if($diffinfo->{'nparents'}) {3598# combined diff3599$from->{'file'} = [];3600$from->{'href'} = [];3601 fill_from_file_info($diffinfo,@parents)3602unlessexists$diffinfo->{'from_file'};3603for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3604$from->{'file'}[$i] =3605defined$diffinfo->{'from_file'}[$i] ?3606$diffinfo->{'from_file'}[$i] :3607$diffinfo->{'to_file'};3608if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3609$from->{'href'}[$i] = href(action=>"blob",3610 hash_base=>$parents[$i],3611 hash=>$diffinfo->{'from_id'}[$i],3612 file_name=>$from->{'file'}[$i]);3613}else{3614$from->{'href'}[$i] =undef;3615}3616}3617}else{3618# ordinary (not combined) diff3619$from->{'file'} =$diffinfo->{'from_file'};3620if($diffinfo->{'status'}ne"A") {# not new (added) file3621$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3622 hash=>$diffinfo->{'from_id'},3623 file_name=>$from->{'file'});3624}else{3625delete$from->{'href'};3626}3627}36283629$to->{'file'} =$diffinfo->{'to_file'};3630if(!is_deleted($diffinfo)) {# file exists in result3631$to->{'href'} = href(action=>"blob", hash_base=>$hash,3632 hash=>$diffinfo->{'to_id'},3633 file_name=>$to->{'file'});3634}else{3635delete$to->{'href'};3636}3637}36383639## ......................................................................3640## parse to array of hashes functions36413642sub git_get_heads_list {3643my($limit,@classes) =@_;3644@classes= ('heads')unless@classes;3645my@patterns=map{"refs/$_"}@classes;3646my@headslist;36473648open my$fd,'-|', git_cmd(),'for-each-ref',3649($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3650'--format=%(objectname) %(refname) %(subject)%00%(committer)',3651@patterns3652orreturn;3653while(my$line= <$fd>) {3654my%ref_item;36553656chomp$line;3657my($refinfo,$committerinfo) =split(/\0/,$line);3658my($hash,$name,$title) =split(' ',$refinfo,3);3659my($committer,$epoch,$tz) =3660($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3661$ref_item{'fullname'} =$name;3662$name=~s!^refs/(?:head|remote)s/!!;36633664$ref_item{'name'} =$name;3665$ref_item{'id'} =$hash;3666$ref_item{'title'} =$title||'(no commit message)';3667$ref_item{'epoch'} =$epoch;3668if($epoch) {3669$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3670}else{3671$ref_item{'age'} ="unknown";3672}36733674push@headslist, \%ref_item;3675}3676close$fd;36773678returnwantarray?@headslist: \@headslist;3679}36803681sub git_get_tags_list {3682my$limit=shift;3683my@tagslist;36843685open my$fd,'-|', git_cmd(),'for-each-ref',3686($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3687'--format=%(objectname) %(objecttype) %(refname) '.3688'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3689'refs/tags'3690orreturn;3691while(my$line= <$fd>) {3692my%ref_item;36933694chomp$line;3695my($refinfo,$creatorinfo) =split(/\0/,$line);3696my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3697my($creator,$epoch,$tz) =3698($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3699$ref_item{'fullname'} =$name;3700$name=~s!^refs/tags/!!;37013702$ref_item{'type'} =$type;3703$ref_item{'id'} =$id;3704$ref_item{'name'} =$name;3705if($typeeq"tag") {3706$ref_item{'subject'} =$title;3707$ref_item{'reftype'} =$reftype;3708$ref_item{'refid'} =$refid;3709}else{3710$ref_item{'reftype'} =$type;3711$ref_item{'refid'} =$id;3712}37133714if($typeeq"tag"||$typeeq"commit") {3715$ref_item{'epoch'} =$epoch;3716if($epoch) {3717$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3718}else{3719$ref_item{'age'} ="unknown";3720}3721}37223723push@tagslist, \%ref_item;3724}3725close$fd;37263727returnwantarray?@tagslist: \@tagslist;3728}37293730## ----------------------------------------------------------------------3731## filesystem-related functions37323733sub get_file_owner {3734my$path=shift;37353736my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3737my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3738if(!defined$gcos) {3739returnundef;3740}3741my$owner=$gcos;3742$owner=~s/[,;].*$//;3743return to_utf8($owner);3744}37453746# assume that file exists3747sub insert_file {3748my$filename=shift;37493750open my$fd,'<',$filename;3751print map{ to_utf8($_) } <$fd>;3752close$fd;3753}37543755## ......................................................................3756## mimetype related functions37573758sub mimetype_guess_file {3759my$filename=shift;3760my$mimemap=shift;3761-r $mimemaporreturnundef;37623763my%mimemap;3764open(my$mh,'<',$mimemap)orreturnundef;3765while(<$mh>) {3766next ifm/^#/;# skip comments3767my($mimetype,@exts) =split(/\s+/);3768foreachmy$ext(@exts) {3769$mimemap{$ext} =$mimetype;3770}3771}3772close($mh);37733774$filename=~/\.([^.]*)$/;3775return$mimemap{$1};3776}37773778sub mimetype_guess {3779my$filename=shift;3780my$mime;3781$filename=~/\./orreturnundef;37823783if($mimetypes_file) {3784my$file=$mimetypes_file;3785if($file!~m!^/!) {# if it is relative path3786# it is relative to project3787$file="$projectroot/$project/$file";3788}3789$mime= mimetype_guess_file($filename,$file);3790}3791$mime||= mimetype_guess_file($filename,'/etc/mime.types');3792return$mime;3793}37943795sub blob_mimetype {3796my$fd=shift;3797my$filename=shift;37983799if($filename) {3800my$mime= mimetype_guess($filename);3801$mimeandreturn$mime;3802}38033804# just in case3805return$default_blob_plain_mimetypeunless$fd;38063807if(-T $fd) {3808return'text/plain';3809}elsif(!$filename) {3810return'application/octet-stream';3811}elsif($filename=~m/\.png$/i) {3812return'image/png';3813}elsif($filename=~m/\.gif$/i) {3814return'image/gif';3815}elsif($filename=~m/\.jpe?g$/i) {3816return'image/jpeg';3817}else{3818return'application/octet-stream';3819}3820}38213822sub blob_contenttype {3823my($fd,$file_name,$type) =@_;38243825$type||= blob_mimetype($fd,$file_name);3826if($typeeq'text/plain'&&defined$default_text_plain_charset) {3827$type.="; charset=$default_text_plain_charset";3828}38293830return$type;3831}38323833# guess file syntax for syntax highlighting; return undef if no highlighting3834# the name of syntax can (in the future) depend on syntax highlighter used3835sub guess_file_syntax {3836my($highlight,$mimetype,$file_name) =@_;3837returnundefunless($highlight&&defined$file_name);3838my$basename= basename($file_name,'.in');3839return$highlight_basename{$basename}3840ifexists$highlight_basename{$basename};38413842$basename=~/\.([^.]*)$/;3843my$ext=$1orreturnundef;3844return$highlight_ext{$ext}3845ifexists$highlight_ext{$ext};38463847returnundef;3848}38493850# run highlighter and return FD of its output,3851# or return original FD if no highlighting3852sub run_highlighter {3853my($fd,$highlight,$syntax) =@_;3854return$fdunless($highlight&&defined$syntax);38553856close$fd;3857open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3858 quote_command($highlight_bin).3859" --replace-tabs=8 --fragment --syntax$syntax|"3860or die_error(500,"Couldn't open file or run syntax highlighter");3861return$fd;3862}38633864## ======================================================================3865## functions printing HTML: header, footer, error page38663867sub get_page_title {3868my$title= to_utf8($site_name);38693870unless(defined$project) {3871if(defined$project_filter) {3872$title.=" - projects in '". esc_path($project_filter) ."'";3873}3874return$title;3875}3876$title.=" - ". to_utf8($project);38773878return$titleunless(defined$action);3879$title.="/$action";# $action is US-ASCII (7bit ASCII)38803881return$titleunless(defined$file_name);3882$title.=" - ". esc_path($file_name);3883if($actioneq"tree"&&$file_name!~ m|/$|) {3884$title.="/";3885}38863887return$title;3888}38893890sub get_content_type_html {3891# require explicit support from the UA if we are to send the page as3892# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3893# we have to do this because MSIE sometimes globs '*/*', pretending to3894# support xhtml+xml but choking when it gets what it asked for.3895if(defined$cgi->http('HTTP_ACCEPT') &&3896$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3897$cgi->Accept('application/xhtml+xml') !=0) {3898return'application/xhtml+xml';3899}else{3900return'text/html';3901}3902}39033904sub print_feed_meta {3905if(defined$project) {3906my%href_params= get_feed_info();3907if(!exists$href_params{'-title'}) {3908$href_params{'-title'} ='log';3909}39103911foreachmy$format(qw(RSS Atom)) {3912my$type=lc($format);3913my%link_attr= (3914'-rel'=>'alternate',3915'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3916'-type'=>"application/$type+xml"3917);39183919$href_params{'extra_options'} =undef;3920$href_params{'action'} =$type;3921$link_attr{'-href'} = href(%href_params);3922print"<link ".3923"rel=\"$link_attr{'-rel'}\"".3924"title=\"$link_attr{'-title'}\"".3925"href=\"$link_attr{'-href'}\"".3926"type=\"$link_attr{'-type'}\"".3927"/>\n";39283929$href_params{'extra_options'} ='--no-merges';3930$link_attr{'-href'} = href(%href_params);3931$link_attr{'-title'} .=' (no merges)';3932print"<link ".3933"rel=\"$link_attr{'-rel'}\"".3934"title=\"$link_attr{'-title'}\"".3935"href=\"$link_attr{'-href'}\"".3936"type=\"$link_attr{'-type'}\"".3937"/>\n";3938}39393940}else{3941printf('<link rel="alternate" title="%sprojects list" '.3942'href="%s" type="text/plain; charset=utf-8" />'."\n",3943 esc_attr($site_name), href(project=>undef, action=>"project_index"));3944printf('<link rel="alternate" title="%sprojects feeds" '.3945'href="%s" type="text/x-opml" />'."\n",3946 esc_attr($site_name), href(project=>undef, action=>"opml"));3947}3948}39493950sub print_header_links {3951my$status=shift;39523953# print out each stylesheet that exist, providing backwards capability3954# for those people who defined $stylesheet in a config file3955if(defined$stylesheet) {3956print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3957}else{3958foreachmy$stylesheet(@stylesheets) {3959next unless$stylesheet;3960print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3961}3962}3963 print_feed_meta()3964if($statuseq'200 OK');3965if(defined$favicon) {3966printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3967}3968}39693970sub print_nav_breadcrumbs_path {3971my$dirprefix=undef;3972while(my$part=shift) {3973$dirprefix.="/"ifdefined$dirprefix;3974$dirprefix.=$part;3975print$cgi->a({-href => href(project =>undef,3976 project_filter =>$dirprefix,3977 action =>"project_list")},3978 esc_html($part)) ." / ";3979}3980}39813982sub print_nav_breadcrumbs {3983my%opts=@_;39843985print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3986if(defined$project) {3987my@dirname=split'/',$project;3988my$projectbasename=pop@dirname;3989 print_nav_breadcrumbs_path(@dirname);3990print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));3991if(defined$action) {3992my$action_print=$action;3993if(defined$opts{-action_extra}) {3994$action_print=$cgi->a({-href => href(action=>$action)},3995$action);3996}3997print" /$action_print";3998}3999if(defined$opts{-action_extra}) {4000print" /$opts{-action_extra}";4001}4002print"\n";4003}elsif(defined$project_filter) {4004 print_nav_breadcrumbs_path(split'/',$project_filter);4005}4006}40074008sub print_search_form {4009if(!defined$searchtext) {4010$searchtext="";4011}4012my$search_hash;4013if(defined$hash_base) {4014$search_hash=$hash_base;4015}elsif(defined$hash) {4016$search_hash=$hash;4017}else{4018$search_hash="HEAD";4019}4020my$action=$my_uri;4021my$use_pathinfo= gitweb_check_feature('pathinfo');4022if($use_pathinfo) {4023$action.="/".esc_url($project);4024}4025print$cgi->startform(-method=>"get", -action =>$action) .4026"<div class=\"search\">\n".4027(!$use_pathinfo&&4028$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4029$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4030$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4031$cgi->popup_menu(-name =>'st', -default=>'commit',4032-values=> ['commit','grep','author','committer','pickaxe']) .4033$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .4034" search:\n",4035$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4036"<span title=\"Extended regular expression\">".4037$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4038-checked =>$search_use_regexp) .4039"</span>".4040"</div>".4041$cgi->end_form() ."\n";4042}40434044sub git_header_html {4045my$status=shift||"200 OK";4046my$expires=shift;4047my%opts=@_;40484049my$title= get_page_title();4050my$content_type= get_content_type_html();4051print$cgi->header(-type=>$content_type, -charset =>'utf-8',4052-status=>$status, -expires =>$expires)4053unless($opts{'-no_http_header'});4054my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4055print<<EOF;4056<?xml version="1.0" encoding="utf-8"?>4057<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4058<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4059<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4060<!-- git core binaries version$git_version-->4061<head>4062<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4063<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4064<meta name="robots" content="index, nofollow"/>4065<title>$title</title>4066EOF4067# the stylesheet, favicon etc urls won't work correctly with path_info4068# unless we set the appropriate base URL4069if($ENV{'PATH_INFO'}) {4070print"<base href=\"".esc_url($base_url)."\"/>\n";4071}4072 print_header_links($status);40734074if(defined$site_html_head_string) {4075print to_utf8($site_html_head_string);4076}40774078print"</head>\n".4079"<body>\n";40804081if(defined$site_header&& -f $site_header) {4082 insert_file($site_header);4083}40844085print"<div class=\"page_header\">\n";4086if(defined$logo) {4087print$cgi->a({-href => esc_url($logo_url),4088-title =>$logo_label},4089$cgi->img({-src => esc_url($logo),4090-width =>72, -height =>27,4091-alt =>"git",4092-class=>"logo"}));4093}4094 print_nav_breadcrumbs(%opts);4095print"</div>\n";40964097my$have_search= gitweb_check_feature('search');4098if(defined$project&&$have_search) {4099 print_search_form();4100}4101}41024103sub git_footer_html {4104my$feed_class='rss_logo';41054106print"<div class=\"page_footer\">\n";4107if(defined$project) {4108my$descr= git_get_project_description($project);4109if(defined$descr) {4110print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4111}41124113my%href_params= get_feed_info();4114if(!%href_params) {4115$feed_class.=' generic';4116}4117$href_params{'-title'} ||='log';41184119foreachmy$format(qw(RSS Atom)) {4120$href_params{'action'} =lc($format);4121print$cgi->a({-href => href(%href_params),4122-title =>"$href_params{'-title'}$formatfeed",4123-class=>$feed_class},$format)."\n";4124}41254126}else{4127print$cgi->a({-href => href(project=>undef, action=>"opml",4128 project_filter =>$project_filter),4129-class=>$feed_class},"OPML") ." ";4130print$cgi->a({-href => href(project=>undef, action=>"project_index",4131 project_filter =>$project_filter),4132-class=>$feed_class},"TXT") ."\n";4133}4134print"</div>\n";# class="page_footer"41354136if(defined$t0&& gitweb_check_feature('timed')) {4137print"<div id=\"generating_info\">\n";4138print'This page took '.4139'<span id="generating_time" class="time_span">'.4140 tv_interval($t0, [ gettimeofday() ]).4141' seconds </span>'.4142' and '.4143'<span id="generating_cmd">'.4144$number_of_git_cmds.4145'</span> git commands '.4146" to generate.\n";4147print"</div>\n";# class="page_footer"4148}41494150if(defined$site_footer&& -f $site_footer) {4151 insert_file($site_footer);4152}41534154print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4155if(defined$action&&4156$actioneq'blame_incremental') {4157print qq!<script type="text/javascript">\n!.4158 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4159 qq!"!. href() .qq!");\n!.4160 qq!</script>\n!;4161}else{4162my($jstimezone,$tz_cookie,$datetime_class) =4163 gitweb_get_feature('javascript-timezone');41644165print qq!<script type="text/javascript">\n!.4166 qq!window.onload = function () {\n!;4167if(gitweb_check_feature('javascript-actions')) {4168print qq! fixLinks();\n!;4169}4170if($jstimezone&&$tz_cookie&&$datetime_class) {4171print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4172 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4173}4174print qq!};\n!.4175 qq!</script>\n!;4176}41774178print"</body>\n".4179"</html>";4180}41814182# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4183# Example: die_error(404, 'Hash not found')4184# By convention, use the following status codes (as defined in RFC 2616):4185# 400: Invalid or missing CGI parameters, or4186# requested object exists but has wrong type.4187# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4188# this server or project.4189# 404: Requested object/revision/project doesn't exist.4190# 500: The server isn't configured properly, or4191# an internal error occurred (e.g. failed assertions caused by bugs), or4192# an unknown error occurred (e.g. the git binary died unexpectedly).4193# 503: The server is currently unavailable (because it is overloaded,4194# or down for maintenance). Generally, this is a temporary state.4195sub die_error {4196my$status=shift||500;4197my$error= esc_html(shift) ||"Internal Server Error";4198my$extra=shift;4199my%opts=@_;42004201my%http_responses= (4202400=>'400 Bad Request',4203403=>'403 Forbidden',4204404=>'404 Not Found',4205500=>'500 Internal Server Error',4206503=>'503 Service Unavailable',4207);4208 git_header_html($http_responses{$status},undef,%opts);4209print<<EOF;4210<div class="page_body">4211<br /><br />4212$status-$error4213<br />4214EOF4215if(defined$extra) {4216print"<hr />\n".4217"$extra\n";4218}4219print"</div>\n";42204221 git_footer_html();4222goto DONE_GITWEB4223unless($opts{'-error_handler'});4224}42254226## ----------------------------------------------------------------------4227## functions printing or outputting HTML: navigation42284229sub git_print_page_nav {4230my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4231$extra=''if!defined$extra;# pager or formats42324233my@navs=qw(summary shortlog log commit commitdiff tree);4234if($suppress) {4235@navs=grep{$_ne$suppress}@navs;4236}42374238my%arg=map{$_=> {action=>$_} }@navs;4239if(defined$head) {4240for(qw(commit commitdiff)) {4241$arg{$_}{'hash'} =$head;4242}4243if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4244for(qw(shortlog log)) {4245$arg{$_}{'hash'} =$head;4246}4247}4248}42494250$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4251$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;42524253my@actions= gitweb_get_feature('actions');4254my%repl= (4255'%'=>'%',4256'n'=>$project,# project name4257'f'=>$git_dir,# project path within filesystem4258'h'=>$treehead||'',# current hash ('h' parameter)4259'b'=>$treebase||'',# hash base ('hb' parameter)4260);4261while(@actions) {4262my($label,$link,$pos) =splice(@actions,0,3);4263# insert4264@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4265# munch munch4266$link=~s/%([%nfhb])/$repl{$1}/g;4267$arg{$label}{'_href'} =$link;4268}42694270print"<div class=\"page_nav\">\n".4271(join" | ",4272map{$_eq$current?4273$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4274}@navs);4275print"<br/>\n$extra<br/>\n".4276"</div>\n";4277}42784279# returns a submenu for the nagivation of the refs views (tags, heads,4280# remotes) with the current view disabled and the remotes view only4281# available if the feature is enabled4282sub format_ref_views {4283my($current) =@_;4284my@ref_views=qw{tags heads};4285push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4286returnjoin" | ",map{4287$_eq$current?$_:4288$cgi->a({-href => href(action=>$_)},$_)4289}@ref_views4290}42914292sub format_paging_nav {4293my($action,$page,$has_next_link) =@_;4294my$paging_nav;429542964297if($page>0) {4298$paging_nav.=4299$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4300" ⋅ ".4301$cgi->a({-href => href(-replay=>1, page=>$page-1),4302-accesskey =>"p", -title =>"Alt-p"},"prev");4303}else{4304$paging_nav.="first ⋅ prev";4305}43064307if($has_next_link) {4308$paging_nav.=" ⋅ ".4309$cgi->a({-href => href(-replay=>1, page=>$page+1),4310-accesskey =>"n", -title =>"Alt-n"},"next");4311}else{4312$paging_nav.=" ⋅ next";4313}43144315return$paging_nav;4316}43174318## ......................................................................4319## functions printing or outputting HTML: div43204321sub git_print_header_div {4322my($action,$title,$hash,$hash_base) =@_;4323my%args= ();43244325$args{'action'} =$action;4326$args{'hash'} =$hashif$hash;4327$args{'hash_base'} =$hash_baseif$hash_base;43284329print"<div class=\"header\">\n".4330$cgi->a({-href => href(%args), -class=>"title"},4331$title?$title:$action) .4332"\n</div>\n";4333}43344335sub format_repo_url {4336my($name,$url) =@_;4337return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4338}43394340# Group output by placing it in a DIV element and adding a header.4341# Options for start_div() can be provided by passing a hash reference as the4342# first parameter to the function.4343# Options to git_print_header_div() can be provided by passing an array4344# reference. This must follow the options to start_div if they are present.4345# The content can be a scalar, which is output as-is, a scalar reference, which4346# is output after html escaping, an IO handle passed either as *handle or4347# *handle{IO}, or a function reference. In the latter case all following4348# parameters will be taken as argument to the content function call.4349sub git_print_section {4350my($div_args,$header_args,$content);4351my$arg=shift;4352if(ref($arg)eq'HASH') {4353$div_args=$arg;4354$arg=shift;4355}4356if(ref($arg)eq'ARRAY') {4357$header_args=$arg;4358$arg=shift;4359}4360$content=$arg;43614362print$cgi->start_div($div_args);4363 git_print_header_div(@$header_args);43644365if(ref($content)eq'CODE') {4366$content->(@_);4367}elsif(ref($content)eq'SCALAR') {4368print esc_html($$content);4369}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4370print<$content>;4371}elsif(!ref($content) &&defined($content)) {4372print$content;4373}43744375print$cgi->end_div;4376}43774378sub format_timestamp_html {4379my$date=shift;4380my$strtime=$date->{'rfc2822'};43814382my(undef,undef,$datetime_class) =4383 gitweb_get_feature('javascript-timezone');4384if($datetime_class) {4385$strtime= qq!<span class="$datetime_class">$strtime</span>!;4386}43874388my$localtime_format='(%02d:%02d%s)';4389if($date->{'hour_local'} <6) {4390$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4391}4392$strtime.=' '.4393sprintf($localtime_format,4394$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});43954396return$strtime;4397}43984399# Outputs the author name and date in long form4400sub git_print_authorship {4401my$co=shift;4402my%opts=@_;4403my$tag=$opts{-tag} ||'div';4404my$author=$co->{'author_name'};44054406my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4407print"<$tagclass=\"author_date\">".4408 format_search_author($author,"author", esc_html($author)) .4409" [".format_timestamp_html(\%ad)."]".4410 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4411"</$tag>\n";4412}44134414# Outputs table rows containing the full author or committer information,4415# in the format expected for 'commit' view (& similar).4416# Parameters are a commit hash reference, followed by the list of people4417# to output information for. If the list is empty it defaults to both4418# author and committer.4419sub git_print_authorship_rows {4420my$co=shift;4421# too bad we can't use @people = @_ || ('author', 'committer')4422my@people=@_;4423@people= ('author','committer')unless@people;4424foreachmy$who(@people) {4425my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4426print"<tr><td>$who</td><td>".4427 format_search_author($co->{"${who}_name"},$who,4428 esc_html($co->{"${who}_name"})) ." ".4429 format_search_author($co->{"${who}_email"},$who,4430 esc_html("<".$co->{"${who}_email"} .">")) .4431"</td><td rowspan=\"2\">".4432 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4433"</td></tr>\n".4434"<tr>".4435"<td></td><td>".4436 format_timestamp_html(\%wd) .4437"</td>".4438"</tr>\n";4439}4440}44414442sub git_print_page_path {4443my$name=shift;4444my$type=shift;4445my$hb=shift;444644474448print"<div class=\"page_path\">";4449print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4450-title =>'tree root'}, to_utf8("[$project]"));4451print" / ";4452if(defined$name) {4453my@dirname=split'/',$name;4454my$basename=pop@dirname;4455my$fullname='';44564457foreachmy$dir(@dirname) {4458$fullname.= ($fullname?'/':'') .$dir;4459print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4460 hash_base=>$hb),4461-title =>$fullname}, esc_path($dir));4462print" / ";4463}4464if(defined$type&&$typeeq'blob') {4465print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4466 hash_base=>$hb),4467-title =>$name}, esc_path($basename));4468}elsif(defined$type&&$typeeq'tree') {4469print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4470 hash_base=>$hb),4471-title =>$name}, esc_path($basename));4472print" / ";4473}else{4474print esc_path($basename);4475}4476}4477print"<br/></div>\n";4478}44794480sub git_print_log {4481my$log=shift;4482my%opts=@_;44834484if($opts{'-remove_title'}) {4485# remove title, i.e. first line of log4486shift@$log;4487}4488# remove leading empty lines4489while(defined$log->[0] &&$log->[0]eq"") {4490shift@$log;4491}44924493# print log4494my$skip_blank_line=0;4495foreachmy$line(@$log) {4496if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4497if(!$opts{'-remove_signoff'}) {4498print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4499$skip_blank_line=1;4500}4501next;4502}45034504if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4505if(!$opts{'-remove_signoff'}) {4506print"<span class=\"signoff\">". esc_html($1) .": ".4507"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4508"</span><br/>\n";4509$skip_blank_line=1;4510}4511next;4512}45134514# print only one empty line4515# do not print empty line after signoff4516if($lineeq"") {4517next if($skip_blank_line);4518$skip_blank_line=1;4519}else{4520$skip_blank_line=0;4521}45224523print format_log_line_html($line) ."<br/>\n";4524}45254526if($opts{'-final_empty_line'}) {4527# end with single empty line4528print"<br/>\n"unless$skip_blank_line;4529}4530}45314532# return link target (what link points to)4533sub git_get_link_target {4534my$hash=shift;4535my$link_target;45364537# read link4538open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4539orreturn;4540{4541local$/=undef;4542$link_target= <$fd>;4543}4544close$fd4545orreturn;45464547return$link_target;4548}45494550# given link target, and the directory (basedir) the link is in,4551# return target of link relative to top directory (top tree);4552# return undef if it is not possible (including absolute links).4553sub normalize_link_target {4554my($link_target,$basedir) =@_;45554556# absolute symlinks (beginning with '/') cannot be normalized4557return if(substr($link_target,0,1)eq'/');45584559# normalize link target to path from top (root) tree (dir)4560my$path;4561if($basedir) {4562$path=$basedir.'/'.$link_target;4563}else{4564# we are in top (root) tree (dir)4565$path=$link_target;4566}45674568# remove //, /./, and /../4569my@path_parts;4570foreachmy$part(split('/',$path)) {4571# discard '.' and ''4572next if(!$part||$parteq'.');4573# handle '..'4574if($parteq'..') {4575if(@path_parts) {4576pop@path_parts;4577}else{4578# link leads outside repository (outside top dir)4579return;4580}4581}else{4582push@path_parts,$part;4583}4584}4585$path=join('/',@path_parts);45864587return$path;4588}45894590# print tree entry (row of git_tree), but without encompassing <tr> element4591sub git_print_tree_entry {4592my($t,$basedir,$hash_base,$have_blame) =@_;45934594my%base_key= ();4595$base_key{'hash_base'} =$hash_baseifdefined$hash_base;45964597# The format of a table row is: mode list link. Where mode is4598# the mode of the entry, list is the name of the entry, an href,4599# and link is the action links of the entry.46004601print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4602if(exists$t->{'size'}) {4603print"<td class=\"size\">$t->{'size'}</td>\n";4604}4605if($t->{'type'}eq"blob") {4606print"<td class=\"list\">".4607$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4608 file_name=>"$basedir$t->{'name'}",%base_key),4609-class=>"list"}, esc_path($t->{'name'}));4610if(S_ISLNK(oct$t->{'mode'})) {4611my$link_target= git_get_link_target($t->{'hash'});4612if($link_target) {4613my$norm_target= normalize_link_target($link_target,$basedir);4614if(defined$norm_target) {4615print" -> ".4616$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4617 file_name=>$norm_target),4618-title =>$norm_target}, esc_path($link_target));4619}else{4620print" -> ". esc_path($link_target);4621}4622}4623}4624print"</td>\n";4625print"<td class=\"link\">";4626print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4627 file_name=>"$basedir$t->{'name'}",%base_key)},4628"blob");4629if($have_blame) {4630print" | ".4631$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4632 file_name=>"$basedir$t->{'name'}",%base_key)},4633"blame");4634}4635if(defined$hash_base) {4636print" | ".4637$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4638 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4639"history");4640}4641print" | ".4642$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4643 file_name=>"$basedir$t->{'name'}")},4644"raw");4645print"</td>\n";46464647}elsif($t->{'type'}eq"tree") {4648print"<td class=\"list\">";4649print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4650 file_name=>"$basedir$t->{'name'}",4651%base_key)},4652 esc_path($t->{'name'}));4653print"</td>\n";4654print"<td class=\"link\">";4655print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4656 file_name=>"$basedir$t->{'name'}",4657%base_key)},4658"tree");4659if(defined$hash_base) {4660print" | ".4661$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4662 file_name=>"$basedir$t->{'name'}")},4663"history");4664}4665print"</td>\n";4666}else{4667# unknown object: we can only present history for it4668# (this includes 'commit' object, i.e. submodule support)4669print"<td class=\"list\">".4670 esc_path($t->{'name'}) .4671"</td>\n";4672print"<td class=\"link\">";4673if(defined$hash_base) {4674print$cgi->a({-href => href(action=>"history",4675 hash_base=>$hash_base,4676 file_name=>"$basedir$t->{'name'}")},4677"history");4678}4679print"</td>\n";4680}4681}46824683## ......................................................................4684## functions printing large fragments of HTML46854686# get pre-image filenames for merge (combined) diff4687sub fill_from_file_info {4688my($diff,@parents) =@_;46894690$diff->{'from_file'} = [ ];4691$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4692for(my$i=0;$i<$diff->{'nparents'};$i++) {4693if($diff->{'status'}[$i]eq'R'||4694$diff->{'status'}[$i]eq'C') {4695$diff->{'from_file'}[$i] =4696 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4697}4698}46994700return$diff;4701}47024703# is current raw difftree line of file deletion4704sub is_deleted {4705my$diffinfo=shift;47064707return$diffinfo->{'to_id'}eq('0' x 40);4708}47094710# does patch correspond to [previous] difftree raw line4711# $diffinfo - hashref of parsed raw diff format4712# $patchinfo - hashref of parsed patch diff format4713# (the same keys as in $diffinfo)4714sub is_patch_split {4715my($diffinfo,$patchinfo) =@_;47164717returndefined$diffinfo&&defined$patchinfo4718&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4719}472047214722sub git_difftree_body {4723my($difftree,$hash,@parents) =@_;4724my($parent) =$parents[0];4725my$have_blame= gitweb_check_feature('blame');4726print"<div class=\"list_head\">\n";4727if($#{$difftree} >10) {4728print(($#{$difftree} +1) ." files changed:\n");4729}4730print"</div>\n";47314732print"<table class=\"".4733(@parents>1?"combined ":"") .4734"diff_tree\">\n";47354736# header only for combined diff in 'commitdiff' view4737my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4738if($has_header) {4739# table header4740print"<thead><tr>\n".4741"<th></th><th></th>\n";# filename, patchN link4742for(my$i=0;$i<@parents;$i++) {4743my$par=$parents[$i];4744print"<th>".4745$cgi->a({-href => href(action=>"commitdiff",4746 hash=>$hash, hash_parent=>$par),4747-title =>'commitdiff to parent number '.4748($i+1) .': '.substr($par,0,7)},4749$i+1) .4750" </th>\n";4751}4752print"</tr></thead>\n<tbody>\n";4753}47544755my$alternate=1;4756my$patchno=0;4757foreachmy$line(@{$difftree}) {4758my$diff= parsed_difftree_line($line);47594760if($alternate) {4761print"<tr class=\"dark\">\n";4762}else{4763print"<tr class=\"light\">\n";4764}4765$alternate^=1;47664767if(exists$diff->{'nparents'}) {# combined diff47684769 fill_from_file_info($diff,@parents)4770unlessexists$diff->{'from_file'};47714772if(!is_deleted($diff)) {4773# file exists in the result (child) commit4774print"<td>".4775$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4776 file_name=>$diff->{'to_file'},4777 hash_base=>$hash),4778-class=>"list"}, esc_path($diff->{'to_file'})) .4779"</td>\n";4780}else{4781print"<td>".4782 esc_path($diff->{'to_file'}) .4783"</td>\n";4784}47854786if($actioneq'commitdiff') {4787# link to patch4788$patchno++;4789print"<td class=\"link\">".4790$cgi->a({-href => href(-anchor=>"patch$patchno")},4791"patch") .4792" | ".4793"</td>\n";4794}47954796my$has_history=0;4797my$not_deleted=0;4798for(my$i=0;$i<$diff->{'nparents'};$i++) {4799my$hash_parent=$parents[$i];4800my$from_hash=$diff->{'from_id'}[$i];4801my$from_path=$diff->{'from_file'}[$i];4802my$status=$diff->{'status'}[$i];48034804$has_history||= ($statusne'A');4805$not_deleted||= ($statusne'D');48064807if($statuseq'A') {4808print"<td class=\"link\"align=\"right\"> | </td>\n";4809}elsif($statuseq'D') {4810print"<td class=\"link\">".4811$cgi->a({-href => href(action=>"blob",4812 hash_base=>$hash,4813 hash=>$from_hash,4814 file_name=>$from_path)},4815"blob". ($i+1)) .4816" | </td>\n";4817}else{4818if($diff->{'to_id'}eq$from_hash) {4819print"<td class=\"link nochange\">";4820}else{4821print"<td class=\"link\">";4822}4823print$cgi->a({-href => href(action=>"blobdiff",4824 hash=>$diff->{'to_id'},4825 hash_parent=>$from_hash,4826 hash_base=>$hash,4827 hash_parent_base=>$hash_parent,4828 file_name=>$diff->{'to_file'},4829 file_parent=>$from_path)},4830"diff". ($i+1)) .4831" | </td>\n";4832}4833}48344835print"<td class=\"link\">";4836if($not_deleted) {4837print$cgi->a({-href => href(action=>"blob",4838 hash=>$diff->{'to_id'},4839 file_name=>$diff->{'to_file'},4840 hash_base=>$hash)},4841"blob");4842print" | "if($has_history);4843}4844if($has_history) {4845print$cgi->a({-href => href(action=>"history",4846 file_name=>$diff->{'to_file'},4847 hash_base=>$hash)},4848"history");4849}4850print"</td>\n";48514852print"</tr>\n";4853next;# instead of 'else' clause, to avoid extra indent4854}4855# else ordinary diff48564857my($to_mode_oct,$to_mode_str,$to_file_type);4858my($from_mode_oct,$from_mode_str,$from_file_type);4859if($diff->{'to_mode'}ne('0' x 6)) {4860$to_mode_oct=oct$diff->{'to_mode'};4861if(S_ISREG($to_mode_oct)) {# only for regular file4862$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4863}4864$to_file_type= file_type($diff->{'to_mode'});4865}4866if($diff->{'from_mode'}ne('0' x 6)) {4867$from_mode_oct=oct$diff->{'from_mode'};4868if(S_ISREG($from_mode_oct)) {# only for regular file4869$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4870}4871$from_file_type= file_type($diff->{'from_mode'});4872}48734874if($diff->{'status'}eq"A") {# created4875my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4876$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4877$mode_chng.="]</span>";4878print"<td>";4879print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4880 hash_base=>$hash, file_name=>$diff->{'file'}),4881-class=>"list"}, esc_path($diff->{'file'}));4882print"</td>\n";4883print"<td>$mode_chng</td>\n";4884print"<td class=\"link\">";4885if($actioneq'commitdiff') {4886# link to patch4887$patchno++;4888print$cgi->a({-href => href(-anchor=>"patch$patchno")},4889"patch") .4890" | ";4891}4892print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4893 hash_base=>$hash, file_name=>$diff->{'file'})},4894"blob");4895print"</td>\n";48964897}elsif($diff->{'status'}eq"D") {# deleted4898my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4899print"<td>";4900print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4901 hash_base=>$parent, file_name=>$diff->{'file'}),4902-class=>"list"}, esc_path($diff->{'file'}));4903print"</td>\n";4904print"<td>$mode_chng</td>\n";4905print"<td class=\"link\">";4906if($actioneq'commitdiff') {4907# link to patch4908$patchno++;4909print$cgi->a({-href => href(-anchor=>"patch$patchno")},4910"patch") .4911" | ";4912}4913print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4914 hash_base=>$parent, file_name=>$diff->{'file'})},4915"blob") ." | ";4916if($have_blame) {4917print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4918 file_name=>$diff->{'file'})},4919"blame") ." | ";4920}4921print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4922 file_name=>$diff->{'file'})},4923"history");4924print"</td>\n";49254926}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4927my$mode_chnge="";4928if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4929$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4930if($from_file_typene$to_file_type) {4931$mode_chnge.=" from$from_file_typeto$to_file_type";4932}4933if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4934if($from_mode_str&&$to_mode_str) {4935$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4936}elsif($to_mode_str) {4937$mode_chnge.=" mode:$to_mode_str";4938}4939}4940$mode_chnge.="]</span>\n";4941}4942print"<td>";4943print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4944 hash_base=>$hash, file_name=>$diff->{'file'}),4945-class=>"list"}, esc_path($diff->{'file'}));4946print"</td>\n";4947print"<td>$mode_chnge</td>\n";4948print"<td class=\"link\">";4949if($actioneq'commitdiff') {4950# link to patch4951$patchno++;4952print$cgi->a({-href => href(-anchor=>"patch$patchno")},4953"patch") .4954" | ";4955}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4956# "commit" view and modified file (not onlu mode changed)4957print$cgi->a({-href => href(action=>"blobdiff",4958 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4959 hash_base=>$hash, hash_parent_base=>$parent,4960 file_name=>$diff->{'file'})},4961"diff") .4962" | ";4963}4964print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4965 hash_base=>$hash, file_name=>$diff->{'file'})},4966"blob") ." | ";4967if($have_blame) {4968print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4969 file_name=>$diff->{'file'})},4970"blame") ." | ";4971}4972print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4973 file_name=>$diff->{'file'})},4974"history");4975print"</td>\n";49764977}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4978my%status_name= ('R'=>'moved','C'=>'copied');4979my$nstatus=$status_name{$diff->{'status'}};4980my$mode_chng="";4981if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4982# mode also for directories, so we cannot use $to_mode_str4983$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4984}4985print"<td>".4986$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4987 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4988-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4989"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4990$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4991 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4992-class=>"list"}, esc_path($diff->{'from_file'})) .4993" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4994"<td class=\"link\">";4995if($actioneq'commitdiff') {4996# link to patch4997$patchno++;4998print$cgi->a({-href => href(-anchor=>"patch$patchno")},4999"patch") .5000" | ";5001}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5002# "commit" view and modified file (not only pure rename or copy)5003print$cgi->a({-href => href(action=>"blobdiff",5004 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5005 hash_base=>$hash, hash_parent_base=>$parent,5006 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5007"diff") .5008" | ";5009}5010print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5011 hash_base=>$parent, file_name=>$diff->{'to_file'})},5012"blob") ." | ";5013if($have_blame) {5014print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5015 file_name=>$diff->{'to_file'})},5016"blame") ." | ";5017}5018print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5019 file_name=>$diff->{'to_file'})},5020"history");5021print"</td>\n";50225023}# we should not encounter Unmerged (U) or Unknown (X) status5024print"</tr>\n";5025}5026print"</tbody>"if$has_header;5027print"</table>\n";5028}50295030# Print context lines and then rem/add lines in a side-by-side manner.5031sub print_sidebyside_diff_lines {5032my($ctx,$rem,$add) =@_;50335034# print context block before add/rem block5035if(@$ctx) {5036print join'',5037'<div class="chunk_block ctx">',5038'<div class="old">',5039@$ctx,5040'</div>',5041'<div class="new">',5042@$ctx,5043'</div>',5044'</div>';5045}50465047if(!@$add) {5048# pure removal5049print join'',5050'<div class="chunk_block rem">',5051'<div class="old">',5052@$rem,5053'</div>',5054'</div>';5055}elsif(!@$rem) {5056# pure addition5057print join'',5058'<div class="chunk_block add">',5059'<div class="new">',5060@$add,5061'</div>',5062'</div>';5063}else{5064print join'',5065'<div class="chunk_block chg">',5066'<div class="old">',5067@$rem,5068'</div>',5069'<div class="new">',5070@$add,5071'</div>',5072'</div>';5073}5074}50755076# Print context lines and then rem/add lines in inline manner.5077sub print_inline_diff_lines {5078my($ctx,$rem,$add) =@_;50795080print@$ctx,@$rem,@$add;5081}50825083# Format removed and added line, mark changed part and HTML-format them.5084# Implementation is based on contrib/diff-highlight5085sub format_rem_add_lines_pair {5086my($rem,$add,$num_parents) =@_;50875088# We need to untabify lines before split()'ing them;5089# otherwise offsets would be invalid.5090chomp$rem;5091chomp$add;5092$rem= untabify($rem);5093$add= untabify($add);50945095my@rem=split(//,$rem);5096my@add=split(//,$add);5097my($esc_rem,$esc_add);5098# Ignore leading +/- characters for each parent.5099my($prefix_len,$suffix_len) = ($num_parents,0);5100my($prefix_has_nonspace,$suffix_has_nonspace);51015102my$shorter= (@rem<@add) ?@rem:@add;5103while($prefix_len<$shorter) {5104last if($rem[$prefix_len]ne$add[$prefix_len]);51055106$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5107$prefix_len++;5108}51095110while($prefix_len+$suffix_len<$shorter) {5111last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51125113$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5114$suffix_len++;5115}51165117# Mark lines that are different from each other, but have some common5118# part that isn't whitespace. If lines are completely different, don't5119# mark them because that would make output unreadable, especially if5120# diff consists of multiple lines.5121if($prefix_has_nonspace||$suffix_has_nonspace) {5122$esc_rem= esc_html_hl_regions($rem,'marked',5123[$prefix_len,@rem-$suffix_len], -nbsp=>1);5124$esc_add= esc_html_hl_regions($add,'marked',5125[$prefix_len,@add-$suffix_len], -nbsp=>1);5126}else{5127$esc_rem= esc_html($rem, -nbsp=>1);5128$esc_add= esc_html($add, -nbsp=>1);5129}51305131return format_diff_line(\$esc_rem,'rem'),5132 format_diff_line(\$esc_add,'add');5133}51345135# HTML-format diff context, removed and added lines.5136sub format_ctx_rem_add_lines {5137my($ctx,$rem,$add,$num_parents) =@_;5138my(@new_ctx,@new_rem,@new_add);5139my$can_highlight=0;5140my$is_combined= ($num_parents>1);51415142# Highlight if every removed line has a corresponding added line.5143if(@$add>0&&@$add==@$rem) {5144$can_highlight=1;51455146# Highlight lines in combined diff only if the chunk contains5147# diff between the same version, e.g.5148#5149# - a5150# - b5151# + c5152# + d5153#5154# Otherwise the highlightling would be confusing.5155if($is_combined) {5156for(my$i=0;$i<@$add;$i++) {5157my$prefix_rem=substr($rem->[$i],0,$num_parents);5158my$prefix_add=substr($add->[$i],0,$num_parents);51595160$prefix_rem=~s/-/+/g;51615162if($prefix_remne$prefix_add) {5163$can_highlight=0;5164last;5165}5166}5167}5168}51695170if($can_highlight) {5171for(my$i=0;$i<@$add;$i++) {5172my($line_rem,$line_add) = format_rem_add_lines_pair(5173$rem->[$i],$add->[$i],$num_parents);5174push@new_rem,$line_rem;5175push@new_add,$line_add;5176}5177}else{5178@new_rem=map{ format_diff_line($_,'rem') }@$rem;5179@new_add=map{ format_diff_line($_,'add') }@$add;5180}51815182@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;51835184return(\@new_ctx, \@new_rem, \@new_add);5185}51865187# Print context lines and then rem/add lines.5188sub print_diff_lines {5189my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5190my$is_combined=$num_parents>1;51915192($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5193$num_parents);51945195if($diff_styleeq'sidebyside'&& !$is_combined) {5196 print_sidebyside_diff_lines($ctx,$rem,$add);5197}else{5198# default 'inline' style and unknown styles5199 print_inline_diff_lines($ctx,$rem,$add);5200}5201}52025203sub print_diff_chunk {5204my($diff_style,$num_parents,$from,$to,@chunk) =@_;5205my(@ctx,@rem,@add);52065207# The class of the previous line.5208my$prev_class='';52095210return unless@chunk;52115212# incomplete last line might be among removed or added lines,5213# or both, or among context lines: find which5214for(my$i=1;$i<@chunk;$i++) {5215if($chunk[$i][0]eq'incomplete') {5216$chunk[$i][0] =$chunk[$i-1][0];5217}5218}52195220# guardian5221push@chunk, ["",""];52225223foreachmy$line_info(@chunk) {5224my($class,$line) =@$line_info;52255226# print chunk headers5227if($class&&$classeq'chunk_header') {5228print format_diff_line($line,$class,$from,$to);5229next;5230}52315232## print from accumulator when have some add/rem lines or end5233# of chunk (flush context lines), or when have add and rem5234# lines and new block is reached (otherwise add/rem lines could5235# be reordered)5236if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5237(@rem&&@add&&$classne$prev_class)) {5238 print_diff_lines(\@ctx, \@rem, \@add,5239$diff_style,$num_parents);5240@ctx=@rem=@add= ();5241}52425243## adding lines to accumulator5244# guardian value5245last unless$line;5246# rem, add or change5247if($classeq'rem') {5248push@rem,$line;5249}elsif($classeq'add') {5250push@add,$line;5251}5252# context line5253if($classeq'ctx') {5254push@ctx,$line;5255}52565257$prev_class=$class;5258}5259}52605261sub git_patchset_body {5262my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5263my($hash_parent) =$hash_parents[0];52645265my$is_combined= (@hash_parents>1);5266my$patch_idx=0;5267my$patch_number=0;5268my$patch_line;5269my$diffinfo;5270my$to_name;5271my(%from,%to);5272my@chunk;# for side-by-side diff52735274print"<div class=\"patchset\">\n";52755276# skip to first patch5277while($patch_line= <$fd>) {5278chomp$patch_line;52795280last if($patch_line=~m/^diff /);5281}52825283 PATCH:5284while($patch_line) {52855286# parse "git diff" header line5287if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5288# $1 is from_name, which we do not use5289$to_name= unquote($2);5290$to_name=~s!^b/!!;5291}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5292# $1 is 'cc' or 'combined', which we do not use5293$to_name= unquote($2);5294}else{5295$to_name=undef;5296}52975298# check if current patch belong to current raw line5299# and parse raw git-diff line if needed5300if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5301# this is continuation of a split patch5302print"<div class=\"patch cont\">\n";5303}else{5304# advance raw git-diff output if needed5305$patch_idx++ifdefined$diffinfo;53065307# read and prepare patch information5308$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53095310# compact combined diff output can have some patches skipped5311# find which patch (using pathname of result) we are at now;5312if($is_combined) {5313while($to_namene$diffinfo->{'to_file'}) {5314print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5315 format_diff_cc_simplified($diffinfo,@hash_parents) .5316"</div>\n";# class="patch"53175318$patch_idx++;5319$patch_number++;53205321last if$patch_idx>$#$difftree;5322$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5323}5324}53255326# modifies %from, %to hashes5327 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);53285329# this is first patch for raw difftree line with $patch_idx index5330# we index @$difftree array from 0, but number patches from 15331print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5332}53335334# git diff header5335#assert($patch_line =~ m/^diff /) if DEBUG;5336#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5337$patch_number++;5338# print "git diff" header5339print format_git_diff_header_line($patch_line,$diffinfo,5340 \%from, \%to);53415342# print extended diff header5343print"<div class=\"diff extended_header\">\n";5344 EXTENDED_HEADER:5345while($patch_line= <$fd>) {5346chomp$patch_line;53475348last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);53495350print format_extended_diff_header_line($patch_line,$diffinfo,5351 \%from, \%to);5352}5353print"</div>\n";# class="diff extended_header"53545355# from-file/to-file diff header5356if(!$patch_line) {5357print"</div>\n";# class="patch"5358last PATCH;5359}5360next PATCH if($patch_line=~m/^diff /);5361#assert($patch_line =~ m/^---/) if DEBUG;53625363my$last_patch_line=$patch_line;5364$patch_line= <$fd>;5365chomp$patch_line;5366#assert($patch_line =~ m/^\+\+\+/) if DEBUG;53675368print format_diff_from_to_header($last_patch_line,$patch_line,5369$diffinfo, \%from, \%to,5370@hash_parents);53715372# the patch itself5373 LINE:5374while($patch_line= <$fd>) {5375chomp$patch_line;53765377next PATCH if($patch_line=~m/^diff /);53785379my$class= diff_line_class($patch_line, \%from, \%to);53805381if($classeq'chunk_header') {5382 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5383@chunk= ();5384}53855386push@chunk, [$class,$patch_line];5387}53885389}continue{5390if(@chunk) {5391 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5392@chunk= ();5393}5394print"</div>\n";# class="patch"5395}53965397# for compact combined (--cc) format, with chunk and patch simplification5398# the patchset might be empty, but there might be unprocessed raw lines5399for(++$patch_idxif$patch_number>0;5400$patch_idx<@$difftree;5401++$patch_idx) {5402# read and prepare patch information5403$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54045405# generate anchor for "patch" links in difftree / whatchanged part5406print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5407 format_diff_cc_simplified($diffinfo,@hash_parents) .5408"</div>\n";# class="patch"54095410$patch_number++;5411}54125413if($patch_number==0) {5414if(@hash_parents>1) {5415print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5416}else{5417print"<div class=\"diff nodifferences\">No differences found</div>\n";5418}5419}54205421print"</div>\n";# class="patchset"5422}54235424# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54255426sub git_project_search_form {5427my($searchtext,$search_use_regexp) =@_;54285429my$limit='';5430if($project_filter) {5431$limit=" in '$project_filter/'";5432}54335434print"<div class=\"projsearch\">\n";5435print$cgi->startform(-method=>'get', -action =>$my_uri) .5436$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5437print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5438if(defined$project_filter);5439print$cgi->textfield(-name =>'s', -value =>$searchtext,5440-title =>"Search project by name and description$limit",5441-size =>60) ."\n".5442"<span title=\"Extended regular expression\">".5443$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5444-checked =>$search_use_regexp) .5445"</span>\n".5446$cgi->submit(-name =>'btnS', -value =>'Search') .5447$cgi->end_form() ."\n".5448$cgi->a({-href => href(project =>undef, searchtext =>undef,5449 project_filter =>$project_filter)},5450 esc_html("List all projects$limit")) ."<br />\n";5451print"</div>\n";5452}54535454# entry for given @keys needs filling if at least one of keys in list5455# is not present in %$project_info5456sub project_info_needs_filling {5457my($project_info,@keys) =@_;54585459# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5460foreachmy$key(@keys) {5461if(!exists$project_info->{$key}) {5462return1;5463}5464}5465return;5466}54675468# fills project list info (age, description, owner, category, forks, etc.)5469# for each project in the list, removing invalid projects from5470# returned list, or fill only specified info.5471#5472# Invalid projects are removed from the returned list if and only if you5473# ask 'age' or 'age_string' to be filled, because they are the only fields5474# that run unconditionally git command that requires repository, and5475# therefore do always check if project repository is invalid.5476#5477# USAGE:5478# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5479# ensures that 'descr_long' and 'ctags' fields are filled5480# * @project_list = fill_project_list_info(\@project_list)5481# ensures that all fields are filled (and invalid projects removed)5482#5483# NOTE: modifies $projlist, but does not remove entries from it5484sub fill_project_list_info {5485my($projlist,@wanted_keys) =@_;5486my@projects;5487my$filter_set=sub{return@_; };5488if(@wanted_keys) {5489my%wanted_keys=map{$_=>1}@wanted_keys;5490$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5491}54925493my$show_ctags= gitweb_check_feature('ctags');5494 PROJECT:5495foreachmy$pr(@$projlist) {5496if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5497my(@activity) = git_get_last_activity($pr->{'path'});5498unless(@activity) {5499next PROJECT;5500}5501($pr->{'age'},$pr->{'age_string'}) =@activity;5502}5503if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5504my$descr= git_get_project_description($pr->{'path'}) ||"";5505$descr= to_utf8($descr);5506$pr->{'descr_long'} =$descr;5507$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5508}5509if(project_info_needs_filling($pr,$filter_set->('owner'))) {5510$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5511}5512if($show_ctags&&5513 project_info_needs_filling($pr,$filter_set->('ctags'))) {5514$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5515}5516if($projects_list_group_categories&&5517 project_info_needs_filling($pr,$filter_set->('category'))) {5518my$cat= git_get_project_category($pr->{'path'}) ||5519$project_list_default_category;5520$pr->{'category'} = to_utf8($cat);5521}55225523push@projects,$pr;5524}55255526return@projects;5527}55285529sub sort_projects_list {5530my($projlist,$order) =@_;55315532sub order_str {5533my$key=shift;5534return sub{$a->{$key}cmp$b->{$key} };5535}55365537sub order_num_then_undef {5538my$key=shift;5539return sub{5540defined$a->{$key} ?5541(defined$b->{$key} ?$a->{$key} <=>$b->{$key} : -1) :5542(defined$b->{$key} ?1:0)5543};5544}55455546my%orderings= (5547 project => order_str('path'),5548 descr => order_str('descr_long'),5549 owner => order_str('owner'),5550 age => order_num_then_undef('age'),5551);55525553my$ordering=$orderings{$order};5554returndefined$ordering?sort$ordering @$projlist:@$projlist;5555}55565557# returns a hash of categories, containing the list of project5558# belonging to each category5559sub build_projlist_by_category {5560my($projlist,$from,$to) =@_;5561my%categories;55625563$from=0unlessdefined$from;5564$to=$#$projlistif(!defined$to||$#$projlist<$to);55655566for(my$i=$from;$i<=$to;$i++) {5567my$pr=$projlist->[$i];5568push@{$categories{$pr->{'category'} }},$pr;5569}55705571returnwantarray?%categories: \%categories;5572}55735574# print 'sort by' <th> element, generating 'sort by $name' replay link5575# if that order is not selected5576sub print_sort_th {5577print format_sort_th(@_);5578}55795580sub format_sort_th {5581my($name,$order,$header) =@_;5582my$sort_th="";5583$header||=ucfirst($name);55845585if($ordereq$name) {5586$sort_th.="<th>$header</th>\n";5587}else{5588$sort_th.="<th>".5589$cgi->a({-href => href(-replay=>1, order=>$name),5590-class=>"header"},$header) .5591"</th>\n";5592}55935594return$sort_th;5595}55965597sub git_project_list_rows {5598my($projlist,$from,$to,$check_forks) =@_;55995600$from=0unlessdefined$from;5601$to=$#$projlistif(!defined$to||$#$projlist<$to);56025603my$alternate=1;5604for(my$i=$from;$i<=$to;$i++) {5605my$pr=$projlist->[$i];56065607if($alternate) {5608print"<tr class=\"dark\">\n";5609}else{5610print"<tr class=\"light\">\n";5611}5612$alternate^=1;56135614if($check_forks) {5615print"<td>";5616if($pr->{'forks'}) {5617my$nforks=scalar@{$pr->{'forks'}};5618if($nforks>0) {5619print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5620-title =>"$nforksforks"},"+");5621}else{5622print$cgi->span({-title =>"$nforksforks"},"+");5623}5624}5625print"</td>\n";5626}5627print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5628-class=>"list"},5629 esc_html_match_hl($pr->{'path'},$search_regexp)) .5630"</td>\n".5631"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5632-class=>"list",5633-title =>$pr->{'descr_long'}},5634$search_regexp5635? esc_html_match_hl_chopped($pr->{'descr_long'},5636$pr->{'descr'},$search_regexp)5637: esc_html($pr->{'descr'})) .5638"</td>\n";5639unless($omit_owner) {5640print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5641}5642unless($omit_age_column) {5643print"<td class=\"". age_class($pr->{'age'}) ."\">".5644(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5645}5646print"<td class=\"link\">".5647$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5648$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5649$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5650$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5651($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5652"</td>\n".5653"</tr>\n";5654}5655}56565657sub git_project_list_body {5658# actually uses global variable $project5659my($projlist,$order,$from,$to,$extra,$no_header) =@_;5660my@projects=@$projlist;56615662my$check_forks= gitweb_check_feature('forks');5663my$show_ctags= gitweb_check_feature('ctags');5664my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5665$check_forks=undef5666if($tagfilter||$search_regexp);56675668# filtering out forks before filling info allows to do less work5669@projects= filter_forks_from_projects_list(\@projects)5670if($check_forks);5671# search_projects_list pre-fills required info5672@projects= search_projects_list(\@projects,5673'search_regexp'=>$search_regexp,5674'tagfilter'=>$tagfilter)5675if($tagfilter||$search_regexp);5676# fill the rest5677my@all_fields= ('descr','descr_long','ctags','category');5678push@all_fields, ('age','age_string')unless($omit_age_column);5679push@all_fields,'owner'unless($omit_owner);5680@projects= fill_project_list_info(\@projects,@all_fields);56815682$order||=$default_projects_order;5683$from=0unlessdefined$from;5684$to=$#projectsif(!defined$to||$#projects<$to);56855686# short circuit5687if($from>$to) {5688print"<center>\n".5689"<b>No such projects found</b><br />\n".5690"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5691"</center>\n<br />\n";5692return;5693}56945695@projects= sort_projects_list(\@projects,$order);56965697if($show_ctags) {5698my$ctags= git_gather_all_ctags(\@projects);5699my$cloud= git_populate_project_tagcloud($ctags);5700print git_show_project_tagcloud($cloud,64);5701}57025703print"<table class=\"project_list\">\n";5704unless($no_header) {5705print"<tr>\n";5706if($check_forks) {5707print"<th></th>\n";5708}5709 print_sort_th('project',$order,'Project');5710 print_sort_th('descr',$order,'Description');5711 print_sort_th('owner',$order,'Owner')unless$omit_owner;5712 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5713print"<th></th>\n".# for links5714"</tr>\n";5715}57165717if($projects_list_group_categories) {5718# only display categories with projects in the $from-$to window5719@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5720my%categories= build_projlist_by_category(\@projects,$from,$to);5721foreachmy$cat(sort keys%categories) {5722unless($cateq"") {5723print"<tr>\n";5724if($check_forks) {5725print"<td></td>\n";5726}5727print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5728print"</tr>\n";5729}57305731 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5732}5733}else{5734 git_project_list_rows(\@projects,$from,$to,$check_forks);5735}57365737if(defined$extra) {5738print"<tr>\n";5739if($check_forks) {5740print"<td></td>\n";5741}5742print"<td colspan=\"5\">$extra</td>\n".5743"</tr>\n";5744}5745print"</table>\n";5746}57475748sub git_log_body {5749# uses global variable $project5750my($commitlist,$from,$to,$refs,$extra) =@_;57515752$from=0unlessdefined$from;5753$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57545755for(my$i=0;$i<=$to;$i++) {5756my%co= %{$commitlist->[$i]};5757next if!%co;5758my$commit=$co{'id'};5759my$ref= format_ref_marker($refs,$commit);5760 git_print_header_div('commit',5761"<span class=\"age\">$co{'age_string'}</span>".5762 esc_html($co{'title'}) .$ref,5763$commit);5764print"<div class=\"title_text\">\n".5765"<div class=\"log_link\">\n".5766$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5767" | ".5768$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5769" | ".5770$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5771"<br/>\n".5772"</div>\n";5773 git_print_authorship(\%co, -tag =>'span');5774print"<br/>\n</div>\n";57755776print"<div class=\"log_body\">\n";5777 git_print_log($co{'comment'}, -final_empty_line=>1);5778print"</div>\n";5779}5780if($extra) {5781print"<div class=\"page_nav\">\n";5782print"$extra\n";5783print"</div>\n";5784}5785}57865787sub git_shortlog_body {5788# uses global variable $project5789my($commitlist,$from,$to,$refs,$extra) =@_;57905791$from=0unlessdefined$from;5792$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57935794print"<table class=\"shortlog\">\n";5795my$alternate=1;5796for(my$i=$from;$i<=$to;$i++) {5797my%co= %{$commitlist->[$i]};5798my$commit=$co{'id'};5799my$ref= format_ref_marker($refs,$commit);5800if($alternate) {5801print"<tr class=\"dark\">\n";5802}else{5803print"<tr class=\"light\">\n";5804}5805$alternate^=1;5806# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5807print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5808 format_author_html('td', \%co,10) ."<td>";5809print format_subject_html($co{'title'},$co{'title_short'},5810 href(action=>"commit", hash=>$commit),$ref);5811print"</td>\n".5812"<td class=\"link\">".5813$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5814$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5815$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5816my$snapshot_links= format_snapshot_links($commit);5817if(defined$snapshot_links) {5818print" | ".$snapshot_links;5819}5820print"</td>\n".5821"</tr>\n";5822}5823if(defined$extra) {5824print"<tr>\n".5825"<td colspan=\"4\">$extra</td>\n".5826"</tr>\n";5827}5828print"</table>\n";5829}58305831sub git_history_body {5832# Warning: assumes constant type (blob or tree) during history5833my($commitlist,$from,$to,$refs,$extra,5834$file_name,$file_hash,$ftype) =@_;58355836$from=0unlessdefined$from;5837$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});58385839print"<table class=\"history\">\n";5840my$alternate=1;5841for(my$i=$from;$i<=$to;$i++) {5842my%co= %{$commitlist->[$i]};5843if(!%co) {5844next;5845}5846my$commit=$co{'id'};58475848my$ref= format_ref_marker($refs,$commit);58495850if($alternate) {5851print"<tr class=\"dark\">\n";5852}else{5853print"<tr class=\"light\">\n";5854}5855$alternate^=1;5856print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5857# shortlog: format_author_html('td', \%co, 10)5858 format_author_html('td', \%co,15,3) ."<td>";5859# originally git_history used chop_str($co{'title'}, 50)5860print format_subject_html($co{'title'},$co{'title_short'},5861 href(action=>"commit", hash=>$commit),$ref);5862print"</td>\n".5863"<td class=\"link\">".5864$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5865$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");58665867if($ftypeeq'blob') {5868my$blob_current=$file_hash;5869my$blob_parent= git_get_hash_by_path($commit,$file_name);5870if(defined$blob_current&&defined$blob_parent&&5871$blob_currentne$blob_parent) {5872print" | ".5873$cgi->a({-href => href(action=>"blobdiff",5874 hash=>$blob_current, hash_parent=>$blob_parent,5875 hash_base=>$hash_base, hash_parent_base=>$commit,5876 file_name=>$file_name)},5877"diff to current");5878}5879}5880print"</td>\n".5881"</tr>\n";5882}5883if(defined$extra) {5884print"<tr>\n".5885"<td colspan=\"4\">$extra</td>\n".5886"</tr>\n";5887}5888print"</table>\n";5889}58905891sub git_tags_body {5892# uses global variable $project5893my($taglist,$from,$to,$extra) =@_;5894$from=0unlessdefined$from;5895$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);58965897print"<table class=\"tags\">\n";5898my$alternate=1;5899for(my$i=$from;$i<=$to;$i++) {5900my$entry=$taglist->[$i];5901my%tag=%$entry;5902my$comment=$tag{'subject'};5903my$comment_short;5904if(defined$comment) {5905$comment_short= chop_str($comment,30,5);5906}5907if($alternate) {5908print"<tr class=\"dark\">\n";5909}else{5910print"<tr class=\"light\">\n";5911}5912$alternate^=1;5913if(defined$tag{'age'}) {5914print"<td><i>$tag{'age'}</i></td>\n";5915}else{5916print"<td></td>\n";5917}5918print"<td>".5919$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5920-class=>"list name"}, esc_html($tag{'name'})) .5921"</td>\n".5922"<td>";5923if(defined$comment) {5924print format_subject_html($comment,$comment_short,5925 href(action=>"tag", hash=>$tag{'id'}));5926}5927print"</td>\n".5928"<td class=\"selflink\">";5929if($tag{'type'}eq"tag") {5930print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5931}else{5932print" ";5933}5934print"</td>\n".5935"<td class=\"link\">"." | ".5936$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5937if($tag{'reftype'}eq"commit") {5938print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5939" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5940}elsif($tag{'reftype'}eq"blob") {5941print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5942}5943print"</td>\n".5944"</tr>";5945}5946if(defined$extra) {5947print"<tr>\n".5948"<td colspan=\"5\">$extra</td>\n".5949"</tr>\n";5950}5951print"</table>\n";5952}59535954sub git_heads_body {5955# uses global variable $project5956my($headlist,$head_at,$from,$to,$extra) =@_;5957$from=0unlessdefined$from;5958$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);59595960print"<table class=\"heads\">\n";5961my$alternate=1;5962for(my$i=$from;$i<=$to;$i++) {5963my$entry=$headlist->[$i];5964my%ref=%$entry;5965my$curr=defined$head_at&&$ref{'id'}eq$head_at;5966if($alternate) {5967print"<tr class=\"dark\">\n";5968}else{5969print"<tr class=\"light\">\n";5970}5971$alternate^=1;5972print"<td><i>$ref{'age'}</i></td>\n".5973($curr?"<td class=\"current_head\">":"<td>") .5974$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5975-class=>"list name"},esc_html($ref{'name'})) .5976"</td>\n".5977"<td class=\"link\">".5978$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5979$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5980$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5981"</td>\n".5982"</tr>";5983}5984if(defined$extra) {5985print"<tr>\n".5986"<td colspan=\"3\">$extra</td>\n".5987"</tr>\n";5988}5989print"</table>\n";5990}59915992# Display a single remote block5993sub git_remote_block {5994my($remote,$rdata,$limit,$head) =@_;59955996my$heads=$rdata->{'heads'};5997my$fetch=$rdata->{'fetch'};5998my$push=$rdata->{'push'};59996000my$urls_table="<table class=\"projects_list\">\n";60016002if(defined$fetch) {6003if($fetcheq$push) {6004$urls_table.= format_repo_url("URL",$fetch);6005}else{6006$urls_table.= format_repo_url("Fetch URL",$fetch);6007$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;6008}6009}elsif(defined$push) {6010$urls_table.= format_repo_url("Push URL",$push);6011}else{6012$urls_table.= format_repo_url("","No remote URL");6013}60146015$urls_table.="</table>\n";60166017my$dots;6018if(defined$limit&&$limit<@$heads) {6019$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6020}60216022print$urls_table;6023 git_heads_body($heads,$head,0,$limit,$dots);6024}60256026# Display a list of remote names with the respective fetch and push URLs6027sub git_remotes_list {6028my($remotedata,$limit) =@_;6029print"<table class=\"heads\">\n";6030my$alternate=1;6031my@remotes=sort keys%$remotedata;60326033my$limited=$limit&&$limit<@remotes;60346035$#remotes=$limit-1if$limited;60366037while(my$remote=shift@remotes) {6038my$rdata=$remotedata->{$remote};6039my$fetch=$rdata->{'fetch'};6040my$push=$rdata->{'push'};6041if($alternate) {6042print"<tr class=\"dark\">\n";6043}else{6044print"<tr class=\"light\">\n";6045}6046$alternate^=1;6047print"<td>".6048$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6049-class=>"list name"},esc_html($remote)) .6050"</td>";6051print"<td class=\"link\">".6052(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6053" | ".6054(defined$push?$cgi->a({-href=>$push},"push") :"push") .6055"</td>";60566057print"</tr>\n";6058}60596060if($limited) {6061print"<tr>\n".6062"<td colspan=\"3\">".6063$cgi->a({-href => href(action=>"remotes")},"...") .6064"</td>\n"."</tr>\n";6065}60666067print"</table>";6068}60696070# Display remote heads grouped by remote, unless there are too many6071# remotes, in which case we only display the remote names6072sub git_remotes_body {6073my($remotedata,$limit,$head) =@_;6074if($limitand$limit<keys%$remotedata) {6075 git_remotes_list($remotedata,$limit);6076}else{6077 fill_remote_heads($remotedata);6078while(my($remote,$rdata) =each%$remotedata) {6079 git_print_section({-class=>"remote", -id=>$remote},6080["remotes",$remote,$remote],sub{6081 git_remote_block($remote,$rdata,$limit,$head);6082});6083}6084}6085}60866087sub git_search_message {6088my%co=@_;60896090my$greptype;6091if($searchtypeeq'commit') {6092$greptype="--grep=";6093}elsif($searchtypeeq'author') {6094$greptype="--author=";6095}elsif($searchtypeeq'committer') {6096$greptype="--committer=";6097}6098$greptype.=$searchtext;6099my@commitlist= parse_commits($hash,101, (100*$page),undef,6100$greptype,'--regexp-ignore-case',6101$search_use_regexp?'--extended-regexp':'--fixed-strings');61026103my$paging_nav='';6104if($page>0) {6105$paging_nav.=6106$cgi->a({-href => href(-replay=>1, page=>undef)},6107"first") .6108" ⋅ ".6109$cgi->a({-href => href(-replay=>1, page=>$page-1),6110-accesskey =>"p", -title =>"Alt-p"},"prev");6111}else{6112$paging_nav.="first ⋅ prev";6113}6114my$next_link='';6115if($#commitlist>=100) {6116$next_link=6117$cgi->a({-href => href(-replay=>1, page=>$page+1),6118-accesskey =>"n", -title =>"Alt-n"},"next");6119$paging_nav.=" ⋅$next_link";6120}else{6121$paging_nav.=" ⋅ next";6122}61236124 git_header_html();61256126 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6127 git_print_header_div('commit', esc_html($co{'title'}),$hash);6128if($page==0&& !@commitlist) {6129print"<p>No match.</p>\n";6130}else{6131 git_search_grep_body(\@commitlist,0,99,$next_link);6132}61336134 git_footer_html();6135}61366137sub git_search_changes {6138my%co=@_;61396140local$/="\n";6141open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6142'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6143($search_use_regexp?'--pickaxe-regex': ())6144or die_error(500,"Open git-log failed");61456146 git_header_html();61476148 git_print_page_nav('','',$hash,$co{'tree'},$hash);6149 git_print_header_div('commit', esc_html($co{'title'}),$hash);61506151print"<table class=\"pickaxe search\">\n";6152my$alternate=1;6153undef%co;6154my@files;6155while(my$line= <$fd>) {6156chomp$line;6157next unless$line;61586159my%set= parse_difftree_raw_line($line);6160if(defined$set{'commit'}) {6161# finish previous commit6162if(%co) {6163print"</td>\n".6164"<td class=\"link\">".6165$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6166"commit") .6167" | ".6168$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6169 hash_base=>$co{'id'})},6170"tree") .6171"</td>\n".6172"</tr>\n";6173}61746175if($alternate) {6176print"<tr class=\"dark\">\n";6177}else{6178print"<tr class=\"light\">\n";6179}6180$alternate^=1;6181%co= parse_commit($set{'commit'});6182my$author= chop_and_escape_str($co{'author_name'},15,5);6183print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6184"<td><i>$author</i></td>\n".6185"<td>".6186$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6187-class=>"list subject"},6188 chop_and_escape_str($co{'title'},50) ."<br/>");6189}elsif(defined$set{'to_id'}) {6190next if($set{'to_id'} =~m/^0{40}$/);61916192print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6193 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6194-class=>"list"},6195"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6196"<br/>\n";6197}6198}6199close$fd;62006201# finish last commit (warning: repetition!)6202if(%co) {6203print"</td>\n".6204"<td class=\"link\">".6205$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6206"commit") .6207" | ".6208$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6209 hash_base=>$co{'id'})},6210"tree") .6211"</td>\n".6212"</tr>\n";6213}62146215print"</table>\n";62166217 git_footer_html();6218}62196220sub git_search_files {6221my%co=@_;62226223local$/="\n";6224open my$fd,"-|", git_cmd(),'grep','-n','-z',6225$search_use_regexp? ('-E','-i') :'-F',6226$searchtext,$co{'tree'}6227or die_error(500,"Open git-grep failed");62286229 git_header_html();62306231 git_print_page_nav('','',$hash,$co{'tree'},$hash);6232 git_print_header_div('commit', esc_html($co{'title'}),$hash);62336234print"<table class=\"grep_search\">\n";6235my$alternate=1;6236my$matches=0;6237my$lastfile='';6238my$file_href;6239while(my$line= <$fd>) {6240chomp$line;6241my($file,$lno,$ltext,$binary);6242last if($matches++>1000);6243if($line=~/^Binary file (.+) matches$/) {6244$file=$1;6245$binary=1;6246}else{6247($file,$lno,$ltext) =split(/\0/,$line,3);6248$file=~s/^$co{'tree'}://;6249}6250if($filene$lastfile) {6251$lastfileand print"</td></tr>\n";6252if($alternate++) {6253print"<tr class=\"dark\">\n";6254}else{6255print"<tr class=\"light\">\n";6256}6257$file_href= href(action=>"blob", hash_base=>$co{'id'},6258 file_name=>$file);6259print"<td class=\"list\">".6260$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6261print"</td><td>\n";6262$lastfile=$file;6263}6264if($binary) {6265print"<div class=\"binary\">Binary file</div>\n";6266}else{6267$ltext= untabify($ltext);6268if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6269$ltext= esc_html($1, -nbsp=>1);6270$ltext.='<span class="match">';6271$ltext.= esc_html($2, -nbsp=>1);6272$ltext.='</span>';6273$ltext.= esc_html($3, -nbsp=>1);6274}else{6275$ltext= esc_html($ltext, -nbsp=>1);6276}6277print"<div class=\"pre\">".6278$cgi->a({-href =>$file_href.'#l'.$lno,6279-class=>"linenr"},sprintf('%4i',$lno)) .6280' '.$ltext."</div>\n";6281}6282}6283if($lastfile) {6284print"</td></tr>\n";6285if($matches>1000) {6286print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6287}6288}else{6289print"<div class=\"diff nodifferences\">No matches found</div>\n";6290}6291close$fd;62926293print"</table>\n";62946295 git_footer_html();6296}62976298sub git_search_grep_body {6299my($commitlist,$from,$to,$extra) =@_;6300$from=0unlessdefined$from;6301$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);63026303print"<table class=\"commit_search\">\n";6304my$alternate=1;6305for(my$i=$from;$i<=$to;$i++) {6306my%co= %{$commitlist->[$i]};6307if(!%co) {6308next;6309}6310my$commit=$co{'id'};6311if($alternate) {6312print"<tr class=\"dark\">\n";6313}else{6314print"<tr class=\"light\">\n";6315}6316$alternate^=1;6317print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6318 format_author_html('td', \%co,15,5) .6319"<td>".6320$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6321-class=>"list subject"},6322 chop_and_escape_str($co{'title'},50) ."<br/>");6323my$comment=$co{'comment'};6324foreachmy$line(@$comment) {6325if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6326my($lead,$match,$trail) = ($1,$2,$3);6327$match= chop_str($match,70,5,'center');6328my$contextlen=int((80-length($match))/2);6329$contextlen=30if($contextlen>30);6330$lead= chop_str($lead,$contextlen,10,'left');6331$trail= chop_str($trail,$contextlen,10,'right');63326333$lead= esc_html($lead);6334$match= esc_html($match);6335$trail= esc_html($trail);63366337print"$lead<span class=\"match\">$match</span>$trail<br />";6338}6339}6340print"</td>\n".6341"<td class=\"link\">".6342$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6343" | ".6344$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6345" | ".6346$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6347print"</td>\n".6348"</tr>\n";6349}6350if(defined$extra) {6351print"<tr>\n".6352"<td colspan=\"3\">$extra</td>\n".6353"</tr>\n";6354}6355print"</table>\n";6356}63576358## ======================================================================6359## ======================================================================6360## actions63616362sub git_project_list {6363my$order=$input_params{'order'};6364if(defined$order&&$order!~m/none|project|descr|owner|age/) {6365 die_error(400,"Unknown order parameter");6366}63676368my@list= git_get_projects_list($project_filter,$strict_export);6369if(!@list) {6370 die_error(404,"No projects found");6371}63726373 git_header_html();6374if(defined$home_text&& -f $home_text) {6375print"<div class=\"index_include\">\n";6376 insert_file($home_text);6377print"</div>\n";6378}63796380 git_project_search_form($searchtext,$search_use_regexp);6381 git_project_list_body(\@list,$order);6382 git_footer_html();6383}63846385sub git_forks {6386my$order=$input_params{'order'};6387if(defined$order&&$order!~m/none|project|descr|owner|age/) {6388 die_error(400,"Unknown order parameter");6389}63906391my$filter=$project;6392$filter=~s/\.git$//;6393my@list= git_get_projects_list($filter);6394if(!@list) {6395 die_error(404,"No forks found");6396}63976398 git_header_html();6399 git_print_page_nav('','');6400 git_print_header_div('summary',"$projectforks");6401 git_project_list_body(\@list,$order);6402 git_footer_html();6403}64046405sub git_project_index {6406my@projects= git_get_projects_list($project_filter,$strict_export);6407if(!@projects) {6408 die_error(404,"No projects found");6409}64106411print$cgi->header(6412-type =>'text/plain',6413-charset =>'utf-8',6414-content_disposition =>'inline; filename="index.aux"');64156416foreachmy$pr(@projects) {6417if(!exists$pr->{'owner'}) {6418$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6419}64206421my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6422# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6423$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6424$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6425$path=~s/ /\+/g;6426$owner=~s/ /\+/g;64276428print"$path$owner\n";6429}6430}64316432sub git_summary {6433my$descr= git_get_project_description($project) ||"none";6434my%co= parse_commit("HEAD");6435my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6436my$head=$co{'id'};6437my$remote_heads= gitweb_check_feature('remote_heads');64386439my$owner= git_get_project_owner($project);64406441my$refs= git_get_references();6442# These get_*_list functions return one more to allow us to see if6443# there are more ...6444my@taglist= git_get_tags_list(16);6445my@headlist= git_get_heads_list(16);6446my%remotedata=$remote_heads? git_get_remotes_list() : ();6447my@forklist;6448my$check_forks= gitweb_check_feature('forks');64496450if($check_forks) {6451# find forks of a project6452my$filter=$project;6453$filter=~s/\.git$//;6454@forklist= git_get_projects_list($filter);6455# filter out forks of forks6456@forklist= filter_forks_from_projects_list(\@forklist)6457if(@forklist);6458}64596460 git_header_html();6461 git_print_page_nav('summary','',$head);64626463print"<div class=\"title\"> </div>\n";6464print"<table class=\"projects_list\">\n".6465"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6466unless($omit_owner) {6467print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6468}6469if(defined$cd{'rfc2822'}) {6470print"<tr id=\"metadata_lchange\"><td>last change</td>".6471"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6472}64736474# use per project git URL list in $projectroot/$project/cloneurl6475# or make project git URL from git base URL and project name6476my$url_tag="URL";6477my@url_list= git_get_project_url_list($project);6478@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6479foreachmy$git_url(@url_list) {6480next unless$git_url;6481print format_repo_url($url_tag,$git_url);6482$url_tag="";6483}64846485# Tag cloud6486my$show_ctags= gitweb_check_feature('ctags');6487if($show_ctags) {6488my$ctags= git_get_project_ctags($project);6489if(%$ctags) {6490# without ability to add tags, don't show if there are none6491my$cloud= git_populate_project_tagcloud($ctags);6492print"<tr id=\"metadata_ctags\">".6493"<td>content tags</td>".6494"<td>".git_show_project_tagcloud($cloud,48)."</td>".6495"</tr>\n";6496}6497}64986499print"</table>\n";65006501# If XSS prevention is on, we don't include README.html.6502# TODO: Allow a readme in some safe format.6503if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6504print"<div class=\"title\">readme</div>\n".6505"<div class=\"readme\">\n";6506 insert_file("$projectroot/$project/README.html");6507print"\n</div>\n";# class="readme"6508}65096510# we need to request one more than 16 (0..15) to check if6511# those 16 are all6512my@commitlist=$head? parse_commits($head,17) : ();6513if(@commitlist) {6514 git_print_header_div('shortlog');6515 git_shortlog_body(\@commitlist,0,15,$refs,6516$#commitlist<=15?undef:6517$cgi->a({-href => href(action=>"shortlog")},"..."));6518}65196520if(@taglist) {6521 git_print_header_div('tags');6522 git_tags_body(\@taglist,0,15,6523$#taglist<=15?undef:6524$cgi->a({-href => href(action=>"tags")},"..."));6525}65266527if(@headlist) {6528 git_print_header_div('heads');6529 git_heads_body(\@headlist,$head,0,15,6530$#headlist<=15?undef:6531$cgi->a({-href => href(action=>"heads")},"..."));6532}65336534if(%remotedata) {6535 git_print_header_div('remotes');6536 git_remotes_body(\%remotedata,15,$head);6537}65386539if(@forklist) {6540 git_print_header_div('forks');6541 git_project_list_body(\@forklist,'age',0,15,6542$#forklist<=15?undef:6543$cgi->a({-href => href(action=>"forks")},"..."),6544'no_header');6545}65466547 git_footer_html();6548}65496550sub git_tag {6551my%tag= parse_tag($hash);65526553if(!%tag) {6554 die_error(404,"Unknown tag object");6555}65566557my$head= git_get_head_hash($project);6558 git_header_html();6559 git_print_page_nav('','',$head,undef,$head);6560 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6561print"<div class=\"title_text\">\n".6562"<table class=\"object_header\">\n".6563"<tr>\n".6564"<td>object</td>\n".6565"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6566$tag{'object'}) ."</td>\n".6567"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6568$tag{'type'}) ."</td>\n".6569"</tr>\n";6570if(defined($tag{'author'})) {6571 git_print_authorship_rows(\%tag,'author');6572}6573print"</table>\n\n".6574"</div>\n";6575print"<div class=\"page_body\">";6576my$comment=$tag{'comment'};6577foreachmy$line(@$comment) {6578chomp$line;6579print esc_html($line, -nbsp=>1) ."<br/>\n";6580}6581print"</div>\n";6582 git_footer_html();6583}65846585sub git_blame_common {6586my$format=shift||'porcelain';6587if($formateq'porcelain'&&$input_params{'javascript'}) {6588$format='incremental';6589$action='blame_incremental';# for page title etc6590}65916592# permissions6593 gitweb_check_feature('blame')6594or die_error(403,"Blame view not allowed");65956596# error checking6597 die_error(400,"No file name given")unless$file_name;6598$hash_base||= git_get_head_hash($project);6599 die_error(404,"Couldn't find base commit")unless$hash_base;6600my%co= parse_commit($hash_base)6601or die_error(404,"Commit not found");6602my$ftype="blob";6603if(!defined$hash) {6604$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6605or die_error(404,"Error looking up file");6606}else{6607$ftype= git_get_type($hash);6608if($ftype!~"blob") {6609 die_error(400,"Object is not a blob");6610}6611}66126613my$fd;6614if($formateq'incremental') {6615# get file contents (as base)6616open$fd,"-|", git_cmd(),'cat-file','blob',$hash6617or die_error(500,"Open git-cat-file failed");6618}elsif($formateq'data') {6619# run git-blame --incremental6620open$fd,"-|", git_cmd(),"blame","--incremental",6621$hash_base,"--",$file_name6622or die_error(500,"Open git-blame --incremental failed");6623}else{6624# run git-blame --porcelain6625open$fd,"-|", git_cmd(),"blame",'-p',6626$hash_base,'--',$file_name6627or die_error(500,"Open git-blame --porcelain failed");6628}66296630# incremental blame data returns early6631if($formateq'data') {6632print$cgi->header(6633-type=>"text/plain", -charset =>"utf-8",6634-status=>"200 OK");6635local$| =1;# output autoflush6636while(my$line= <$fd>) {6637print to_utf8($line);6638}6639close$fd6640or print"ERROR$!\n";66416642print'END';6643if(defined$t0&& gitweb_check_feature('timed')) {6644print' '.6645 tv_interval($t0, [ gettimeofday() ]).6646' '.$number_of_git_cmds;6647}6648print"\n";66496650return;6651}66526653# page header6654 git_header_html();6655my$formats_nav=6656$cgi->a({-href => href(action=>"blob", -replay=>1)},6657"blob") .6658" | ";6659if($formateq'incremental') {6660$formats_nav.=6661$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6662"blame") ." (non-incremental)";6663}else{6664$formats_nav.=6665$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6666"blame") ." (incremental)";6667}6668$formats_nav.=6669" | ".6670$cgi->a({-href => href(action=>"history", -replay=>1)},6671"history") .6672" | ".6673$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6674"HEAD");6675 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6676 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6677 git_print_page_path($file_name,$ftype,$hash_base);66786679# page body6680if($formateq'incremental') {6681print"<noscript>\n<div class=\"error\"><center><b>\n".6682"This page requires JavaScript to run.\nUse ".6683$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6684'this page').6685" instead.\n".6686"</b></center></div>\n</noscript>\n";66876688print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6689}66906691print qq!<div class="page_body">\n!;6692print qq!<div id="progress_info">.../ ...</div>\n!6693if($formateq'incremental');6694print qq!<table id="blame_table"class="blame" width="100%">\n!.6695#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6696 qq!<thead>\n!.6697 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6698 qq!</thead>\n!.6699 qq!<tbody>\n!;67006701my@rev_color=qw(light dark);6702my$num_colors=scalar(@rev_color);6703my$current_color=0;67046705if($formateq'incremental') {6706my$color_class=$rev_color[$current_color];67076708#contents of a file6709my$linenr=0;6710 LINE:6711while(my$line= <$fd>) {6712chomp$line;6713$linenr++;67146715print qq!<tr id="l$linenr"class="$color_class">!.6716 qq!<td class="sha1"><a href=""> </a></td>!.6717 qq!<td class="linenr">!.6718 qq!<a class="linenr" href="">$linenr</a></td>!;6719print qq!<td class="pre">! . esc_html($line) ."</td>\n";6720print qq!</tr>\n!;6721}67226723}else{# porcelain, i.e. ordinary blame6724my%metainfo= ();# saves information about commits67256726# blame data6727 LINE:6728while(my$line= <$fd>) {6729chomp$line;6730# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6731# no <lines in group> for subsequent lines in group of lines6732my($full_rev,$orig_lineno,$lineno,$group_size) =6733($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6734if(!exists$metainfo{$full_rev}) {6735$metainfo{$full_rev} = {'nprevious'=>0};6736}6737my$meta=$metainfo{$full_rev};6738my$data;6739while($data= <$fd>) {6740chomp$data;6741last if($data=~s/^\t//);# contents of line6742if($data=~/^(\S+)(?: (.*))?$/) {6743$meta->{$1} =$2unlessexists$meta->{$1};6744}6745if($data=~/^previous /) {6746$meta->{'nprevious'}++;6747}6748}6749my$short_rev=substr($full_rev,0,8);6750my$author=$meta->{'author'};6751my%date=6752 parse_date($meta->{'author-time'},$meta->{'author-tz'});6753my$date=$date{'iso-tz'};6754if($group_size) {6755$current_color= ($current_color+1) %$num_colors;6756}6757my$tr_class=$rev_color[$current_color];6758$tr_class.=' boundary'if(exists$meta->{'boundary'});6759$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6760$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6761print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6762if($group_size) {6763print"<td class=\"sha1\"";6764print" title=\"". esc_html($author) .",$date\"";6765print" rowspan=\"$group_size\""if($group_size>1);6766print">";6767print$cgi->a({-href => href(action=>"commit",6768 hash=>$full_rev,6769 file_name=>$file_name)},6770 esc_html($short_rev));6771if($group_size>=2) {6772my@author_initials= ($author=~/\b([[:upper:]])\B/g);6773if(@author_initials) {6774print"<br />".6775 esc_html(join('',@author_initials));6776# or join('.', ...)6777}6778}6779print"</td>\n";6780}6781# 'previous' <sha1 of parent commit> <filename at commit>6782if(exists$meta->{'previous'} &&6783$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6784$meta->{'parent'} =$1;6785$meta->{'file_parent'} = unquote($2);6786}6787my$linenr_commit=6788exists($meta->{'parent'}) ?6789$meta->{'parent'} :$full_rev;6790my$linenr_filename=6791exists($meta->{'file_parent'}) ?6792$meta->{'file_parent'} : unquote($meta->{'filename'});6793my$blamed= href(action =>'blame',6794 file_name =>$linenr_filename,6795 hash_base =>$linenr_commit);6796print"<td class=\"linenr\">";6797print$cgi->a({ -href =>"$blamed#l$orig_lineno",6798-class=>"linenr"},6799 esc_html($lineno));6800print"</td>";6801print"<td class=\"pre\">". esc_html($data) ."</td>\n";6802print"</tr>\n";6803}# end while68046805}68066807# footer6808print"</tbody>\n".6809"</table>\n";# class="blame"6810print"</div>\n";# class="blame_body"6811close$fd6812or print"Reading blob failed\n";68136814 git_footer_html();6815}68166817sub git_blame {6818 git_blame_common();6819}68206821sub git_blame_incremental {6822 git_blame_common('incremental');6823}68246825sub git_blame_data {6826 git_blame_common('data');6827}68286829sub git_tags {6830my$head= git_get_head_hash($project);6831 git_header_html();6832 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6833 git_print_header_div('summary',$project);68346835my@tagslist= git_get_tags_list();6836if(@tagslist) {6837 git_tags_body(\@tagslist);6838}6839 git_footer_html();6840}68416842sub git_heads {6843my$head= git_get_head_hash($project);6844 git_header_html();6845 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6846 git_print_header_div('summary',$project);68476848my@headslist= git_get_heads_list();6849if(@headslist) {6850 git_heads_body(\@headslist,$head);6851}6852 git_footer_html();6853}68546855# used both for single remote view and for list of all the remotes6856sub git_remotes {6857 gitweb_check_feature('remote_heads')6858or die_error(403,"Remote heads view is disabled");68596860my$head= git_get_head_hash($project);6861my$remote=$input_params{'hash'};68626863my$remotedata= git_get_remotes_list($remote);6864 die_error(500,"Unable to get remote information")unlessdefined$remotedata;68656866unless(%$remotedata) {6867 die_error(404,defined$remote?6868"Remote$remotenot found":6869"No remotes found");6870}68716872 git_header_html(undef,undef, -action_extra =>$remote);6873 git_print_page_nav('','',$head,undef,$head,6874 format_ref_views($remote?'':'remotes'));68756876 fill_remote_heads($remotedata);6877if(defined$remote) {6878 git_print_header_div('remotes',"$remoteremote for$project");6879 git_remote_block($remote,$remotedata->{$remote},undef,$head);6880}else{6881 git_print_header_div('summary',"$projectremotes");6882 git_remotes_body($remotedata,undef,$head);6883}68846885 git_footer_html();6886}68876888sub git_blob_plain {6889my$type=shift;6890my$expires;68916892if(!defined$hash) {6893if(defined$file_name) {6894my$base=$hash_base|| git_get_head_hash($project);6895$hash= git_get_hash_by_path($base,$file_name,"blob")6896or die_error(404,"Cannot find file");6897}else{6898 die_error(400,"No file name defined");6899}6900}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6901# blobs defined by non-textual hash id's can be cached6902$expires="+1d";6903}69046905open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6906or die_error(500,"Open git-cat-file blob '$hash' failed");69076908# content-type (can include charset)6909$type= blob_contenttype($fd,$file_name,$type);69106911# "save as" filename, even when no $file_name is given6912my$save_as="$hash";6913if(defined$file_name) {6914$save_as=$file_name;6915}elsif($type=~m/^text\//) {6916$save_as.='.txt';6917}69186919# With XSS prevention on, blobs of all types except a few known safe6920# ones are served with "Content-Disposition: attachment" to make sure6921# they don't run in our security domain. For certain image types,6922# blob view writes an <img> tag referring to blob_plain view, and we6923# want to be sure not to break that by serving the image as an6924# attachment (though Firefox 3 doesn't seem to care).6925my$sandbox=$prevent_xss&&6926$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;69276928# serve text/* as text/plain6929if($prevent_xss&&6930($type=~m!^text/[a-z]+\b(.*)$!||6931($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6932my$rest=$1;6933$rest=defined$rest?$rest:'';6934$type="text/plain$rest";6935}69366937print$cgi->header(6938-type =>$type,6939-expires =>$expires,6940-content_disposition =>6941($sandbox?'attachment':'inline')6942.'; filename="'.$save_as.'"');6943local$/=undef;6944binmode STDOUT,':raw';6945print<$fd>;6946binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6947close$fd;6948}69496950sub git_blob {6951my$expires;69526953if(!defined$hash) {6954if(defined$file_name) {6955my$base=$hash_base|| git_get_head_hash($project);6956$hash= git_get_hash_by_path($base,$file_name,"blob")6957or die_error(404,"Cannot find file");6958}else{6959 die_error(400,"No file name defined");6960}6961}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6962# blobs defined by non-textual hash id's can be cached6963$expires="+1d";6964}69656966my$have_blame= gitweb_check_feature('blame');6967open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6968or die_error(500,"Couldn't cat$file_name,$hash");6969my$mimetype= blob_mimetype($fd,$file_name);6970# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6971if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6972close$fd;6973return git_blob_plain($mimetype);6974}6975# we can have blame only for text/* mimetype6976$have_blame&&= ($mimetype=~m!^text/!);69776978my$highlight= gitweb_check_feature('highlight');6979my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6980$fd= run_highlighter($fd,$highlight,$syntax)6981if$syntax;69826983 git_header_html(undef,$expires);6984my$formats_nav='';6985if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6986if(defined$file_name) {6987if($have_blame) {6988$formats_nav.=6989$cgi->a({-href => href(action=>"blame", -replay=>1)},6990"blame") .6991" | ";6992}6993$formats_nav.=6994$cgi->a({-href => href(action=>"history", -replay=>1)},6995"history") .6996" | ".6997$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6998"raw") .6999" | ".7000$cgi->a({-href => href(action=>"blob",7001 hash_base=>"HEAD", file_name=>$file_name)},7002"HEAD");7003}else{7004$formats_nav.=7005$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},7006"raw");7007}7008 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7009 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7010}else{7011print"<div class=\"page_nav\">\n".7012"<br/><br/></div>\n".7013"<div class=\"title\">".esc_html($hash)."</div>\n";7014}7015 git_print_page_path($file_name,"blob",$hash_base);7016print"<div class=\"page_body\">\n";7017if($mimetype=~m!^image/!) {7018print qq!<img type="!.esc_attr($mimetype).qq!"!;7019if($file_name) {7020print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7021}7022print qq! src="! .7023 href(action=>"blob_plain", hash=>$hash,7024 hash_base=>$hash_base, file_name=>$file_name) .7025 qq!"/>\n!;7026}else{7027my$nr;7028while(my$line= <$fd>) {7029chomp$line;7030$nr++;7031$line= untabify($line);7032printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7033$nr, esc_attr(href(-replay =>1)),$nr,$nr,7034$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7035}7036}7037close$fd7038or print"Reading blob failed.\n";7039print"</div>";7040 git_footer_html();7041}70427043sub git_tree {7044if(!defined$hash_base) {7045$hash_base="HEAD";7046}7047if(!defined$hash) {7048if(defined$file_name) {7049$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7050}else{7051$hash=$hash_base;7052}7053}7054 die_error(404,"No such tree")unlessdefined($hash);70557056my$show_sizes= gitweb_check_feature('show-sizes');7057my$have_blame= gitweb_check_feature('blame');70587059my@entries= ();7060{7061local$/="\0";7062open my$fd,"-|", git_cmd(),"ls-tree",'-z',7063($show_sizes?'-l': ()),@extra_options,$hash7064or die_error(500,"Open git-ls-tree failed");7065@entries=map{chomp;$_} <$fd>;7066close$fd7067or die_error(404,"Reading tree failed");7068}70697070my$refs= git_get_references();7071my$ref= format_ref_marker($refs,$hash_base);7072 git_header_html();7073my$basedir='';7074if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7075my@views_nav= ();7076if(defined$file_name) {7077push@views_nav,7078$cgi->a({-href => href(action=>"history", -replay=>1)},7079"history"),7080$cgi->a({-href => href(action=>"tree",7081 hash_base=>"HEAD", file_name=>$file_name)},7082"HEAD"),7083}7084my$snapshot_links= format_snapshot_links($hash);7085if(defined$snapshot_links) {7086# FIXME: Should be available when we have no hash base as well.7087push@views_nav,$snapshot_links;7088}7089 git_print_page_nav('tree','',$hash_base,undef,undef,7090join(' | ',@views_nav));7091 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7092}else{7093undef$hash_base;7094print"<div class=\"page_nav\">\n";7095print"<br/><br/></div>\n";7096print"<div class=\"title\">".esc_html($hash)."</div>\n";7097}7098if(defined$file_name) {7099$basedir=$file_name;7100if($basedirne''&&substr($basedir, -1)ne'/') {7101$basedir.='/';7102}7103 git_print_page_path($file_name,'tree',$hash_base);7104}7105print"<div class=\"page_body\">\n";7106print"<table class=\"tree\">\n";7107my$alternate=1;7108# '..' (top directory) link if possible7109if(defined$hash_base&&7110defined$file_name&&$file_name=~m![^/]+$!) {7111if($alternate) {7112print"<tr class=\"dark\">\n";7113}else{7114print"<tr class=\"light\">\n";7115}7116$alternate^=1;71177118my$up=$file_name;7119$up=~s!/?[^/]+$!!;7120undef$upunless$up;7121# based on git_print_tree_entry7122print'<td class="mode">'. mode_str('040000') ."</td>\n";7123print'<td class="size"> </td>'."\n"if$show_sizes;7124print'<td class="list">';7125print$cgi->a({-href => href(action=>"tree",7126 hash_base=>$hash_base,7127 file_name=>$up)},7128"..");7129print"</td>\n";7130print"<td class=\"link\"></td>\n";71317132print"</tr>\n";7133}7134foreachmy$line(@entries) {7135my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);71367137if($alternate) {7138print"<tr class=\"dark\">\n";7139}else{7140print"<tr class=\"light\">\n";7141}7142$alternate^=1;71437144 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);71457146print"</tr>\n";7147}7148print"</table>\n".7149"</div>";7150 git_footer_html();7151}71527153sub snapshot_name {7154my($project,$hash) =@_;71557156# path/to/project.git -> project7157# path/to/project/.git -> project7158my$name= to_utf8($project);7159$name=~ s,([^/])/*\.git$,$1,;7160$name= basename($name);7161# sanitize name7162$name=~s/[[:cntrl:]]/?/g;71637164my$ver=$hash;7165if($hash=~/^[0-9a-fA-F]+$/) {7166# shorten SHA-1 hash7167my$full_hash= git_get_full_hash($project,$hash);7168if($full_hash=~/^$hash/&&length($hash) >7) {7169$ver= git_get_short_hash($project,$hash);7170}7171}elsif($hash=~m!^refs/tags/(.*)$!) {7172# tags don't need shortened SHA-1 hash7173$ver=$1;7174}else{7175# branches and other need shortened SHA-1 hash7176if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {7177$ver=$1;7178}7179$ver.='-'. git_get_short_hash($project,$hash);7180}7181# in case of hierarchical branch names7182$ver=~s!/!.!g;71837184# name = project-version_string7185$name="$name-$ver";71867187returnwantarray? ($name,$name) :$name;7188}71897190sub exit_if_unmodified_since {7191my($latest_epoch) =@_;7192our$cgi;71937194my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7195if(defined$if_modified) {7196my$since;7197if(eval{require HTTP::Date;1; }) {7198$since= HTTP::Date::str2time($if_modified);7199}elsif(eval{require Time::ParseDate;1; }) {7200$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7201}7202if(defined$since&&$latest_epoch<=$since) {7203my%latest_date= parse_date($latest_epoch);7204print$cgi->header(7205-last_modified =>$latest_date{'rfc2822'},7206-status =>'304 Not Modified');7207goto DONE_GITWEB;7208}7209}7210}72117212sub git_snapshot {7213my$format=$input_params{'snapshot_format'};7214if(!@snapshot_fmts) {7215 die_error(403,"Snapshots not allowed");7216}7217# default to first supported snapshot format7218$format||=$snapshot_fmts[0];7219if($format!~m/^[a-z0-9]+$/) {7220 die_error(400,"Invalid snapshot format parameter");7221}elsif(!exists($known_snapshot_formats{$format})) {7222 die_error(400,"Unknown snapshot format");7223}elsif($known_snapshot_formats{$format}{'disabled'}) {7224 die_error(403,"Snapshot format not allowed");7225}elsif(!grep($_eq$format,@snapshot_fmts)) {7226 die_error(403,"Unsupported snapshot format");7227}72287229my$type= git_get_type("$hash^{}");7230if(!$type) {7231 die_error(404,'Object does not exist');7232}elsif($typeeq'blob') {7233 die_error(400,'Object is not a tree-ish');7234}72357236my($name,$prefix) = snapshot_name($project,$hash);7237my$filename="$name$known_snapshot_formats{$format}{'suffix'}";72387239my%co= parse_commit($hash);7240 exit_if_unmodified_since($co{'committer_epoch'})if%co;72417242my$cmd= quote_command(7243 git_cmd(),'archive',7244"--format=$known_snapshot_formats{$format}{'format'}",7245"--prefix=$prefix/",$hash);7246if(exists$known_snapshot_formats{$format}{'compressor'}) {7247$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7248}72497250$filename=~s/(["\\])/\\$1/g;7251my%latest_date;7252if(%co) {7253%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7254}72557256print$cgi->header(7257-type =>$known_snapshot_formats{$format}{'type'},7258-content_disposition =>'inline; filename="'.$filename.'"',7259%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7260-status =>'200 OK');72617262open my$fd,"-|",$cmd7263or die_error(500,"Execute git-archive failed");7264binmode STDOUT,':raw';7265print<$fd>;7266binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7267close$fd;7268}72697270sub git_log_generic {7271my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;72727273my$head= git_get_head_hash($project);7274if(!defined$base) {7275$base=$head;7276}7277if(!defined$page) {7278$page=0;7279}7280my$refs= git_get_references();72817282my$commit_hash=$base;7283if(defined$parent) {7284$commit_hash="$parent..$base";7285}7286my@commitlist=7287 parse_commits($commit_hash,101, (100*$page),7288defined$file_name? ($file_name,"--full-history") : ());72897290my$ftype;7291if(!defined$file_hash&&defined$file_name) {7292# some commits could have deleted file in question,7293# and not have it in tree, but one of them has to have it7294for(my$i=0;$i<@commitlist;$i++) {7295$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7296last ifdefined$file_hash;7297}7298}7299if(defined$file_hash) {7300$ftype= git_get_type($file_hash);7301}7302if(defined$file_name&& !defined$ftype) {7303 die_error(500,"Unknown type of object");7304}7305my%co;7306if(defined$file_name) {7307%co= parse_commit($base)7308or die_error(404,"Unknown commit object");7309}731073117312my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7313my$next_link='';7314if($#commitlist>=100) {7315$next_link=7316$cgi->a({-href => href(-replay=>1, page=>$page+1),7317-accesskey =>"n", -title =>"Alt-n"},"next");7318}7319my$patch_max= gitweb_get_feature('patches');7320if($patch_max&& !defined$file_name) {7321if($patch_max<0||@commitlist<=$patch_max) {7322$paging_nav.=" ⋅ ".7323$cgi->a({-href => href(action=>"patches", -replay=>1)},7324"patches");7325}7326}73277328 git_header_html();7329 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7330if(defined$file_name) {7331 git_print_header_div('commit', esc_html($co{'title'}),$base);7332}else{7333 git_print_header_div('summary',$project)7334}7335 git_print_page_path($file_name,$ftype,$hash_base)7336if(defined$file_name);73377338$body_subr->(\@commitlist,0,99,$refs,$next_link,7339$file_name,$file_hash,$ftype);73407341 git_footer_html();7342}73437344sub git_log {7345 git_log_generic('log', \&git_log_body,7346$hash,$hash_parent);7347}73487349sub git_commit {7350$hash||=$hash_base||"HEAD";7351my%co= parse_commit($hash)7352or die_error(404,"Unknown commit object");73537354my$parent=$co{'parent'};7355my$parents=$co{'parents'};# listref73567357# we need to prepare $formats_nav before any parameter munging7358my$formats_nav;7359if(!defined$parent) {7360# --root commitdiff7361$formats_nav.='(initial)';7362}elsif(@$parents==1) {7363# single parent commit7364$formats_nav.=7365'(parent: '.7366$cgi->a({-href => href(action=>"commit",7367 hash=>$parent)},7368 esc_html(substr($parent,0,7))) .7369')';7370}else{7371# merge commit7372$formats_nav.=7373'(merge: '.7374join(' ',map{7375$cgi->a({-href => href(action=>"commit",7376 hash=>$_)},7377 esc_html(substr($_,0,7)));7378}@$parents) .7379')';7380}7381if(gitweb_check_feature('patches') &&@$parents<=1) {7382$formats_nav.=" | ".7383$cgi->a({-href => href(action=>"patch", -replay=>1)},7384"patch");7385}73867387if(!defined$parent) {7388$parent="--root";7389}7390my@difftree;7391open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7392@diff_opts,7393(@$parents<=1?$parent:'-c'),7394$hash,"--"7395or die_error(500,"Open git-diff-tree failed");7396@difftree=map{chomp;$_} <$fd>;7397close$fdor die_error(404,"Reading git-diff-tree failed");73987399# non-textual hash id's can be cached7400my$expires;7401if($hash=~m/^[0-9a-fA-F]{40}$/) {7402$expires="+1d";7403}7404my$refs= git_get_references();7405my$ref= format_ref_marker($refs,$co{'id'});74067407 git_header_html(undef,$expires);7408 git_print_page_nav('commit','',7409$hash,$co{'tree'},$hash,7410$formats_nav);74117412if(defined$co{'parent'}) {7413 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7414}else{7415 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7416}7417print"<div class=\"title_text\">\n".7418"<table class=\"object_header\">\n";7419 git_print_authorship_rows(\%co);7420print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7421print"<tr>".7422"<td>tree</td>".7423"<td class=\"sha1\">".7424$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7425class=>"list"},$co{'tree'}) .7426"</td>".7427"<td class=\"link\">".7428$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7429"tree");7430my$snapshot_links= format_snapshot_links($hash);7431if(defined$snapshot_links) {7432print" | ".$snapshot_links;7433}7434print"</td>".7435"</tr>\n";74367437foreachmy$par(@$parents) {7438print"<tr>".7439"<td>parent</td>".7440"<td class=\"sha1\">".7441$cgi->a({-href => href(action=>"commit", hash=>$par),7442class=>"list"},$par) .7443"</td>".7444"<td class=\"link\">".7445$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7446" | ".7447$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7448"</td>".7449"</tr>\n";7450}7451print"</table>".7452"</div>\n";74537454print"<div class=\"page_body\">\n";7455 git_print_log($co{'comment'});7456print"</div>\n";74577458 git_difftree_body(\@difftree,$hash,@$parents);74597460 git_footer_html();7461}74627463sub git_object {7464# object is defined by:7465# - hash or hash_base alone7466# - hash_base and file_name7467my$type;74687469# - hash or hash_base alone7470if($hash|| ($hash_base&& !defined$file_name)) {7471my$object_id=$hash||$hash_base;74727473open my$fd,"-|", quote_command(7474 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7475or die_error(404,"Object does not exist");7476$type= <$fd>;7477chomp$type;7478close$fd7479or die_error(404,"Object does not exist");74807481# - hash_base and file_name7482}elsif($hash_base&&defined$file_name) {7483$file_name=~ s,/+$,,;74847485system(git_cmd(),"cat-file",'-e',$hash_base) ==07486or die_error(404,"Base object does not exist");74877488# here errors should not happen7489open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7490or die_error(500,"Open git-ls-tree failed");7491my$line= <$fd>;7492close$fd;74937494#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7495unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7496 die_error(404,"File or directory for given base does not exist");7497}7498$type=$2;7499$hash=$3;7500}else{7501 die_error(400,"Not enough information to find object");7502}75037504print$cgi->redirect(-uri => href(action=>$type, -full=>1,7505 hash=>$hash, hash_base=>$hash_base,7506 file_name=>$file_name),7507-status =>'302 Found');7508}75097510sub git_blobdiff {7511my$format=shift||'html';7512my$diff_style=$input_params{'diff_style'} ||'inline';75137514my$fd;7515my@difftree;7516my%diffinfo;7517my$expires;75187519# preparing $fd and %diffinfo for git_patchset_body7520# new style URI7521if(defined$hash_base&&defined$hash_parent_base) {7522if(defined$file_name) {7523# read raw output7524open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7525$hash_parent_base,$hash_base,7526"--", (defined$file_parent?$file_parent: ()),$file_name7527or die_error(500,"Open git-diff-tree failed");7528@difftree=map{chomp;$_} <$fd>;7529close$fd7530or die_error(404,"Reading git-diff-tree failed");7531@difftree7532or die_error(404,"Blob diff not found");75337534}elsif(defined$hash&&7535$hash=~/[0-9a-fA-F]{40}/) {7536# try to find filename from $hash75377538# read filtered raw output7539open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7540$hash_parent_base,$hash_base,"--"7541or die_error(500,"Open git-diff-tree failed");7542@difftree=7543# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7544# $hash == to_id7545grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7546map{chomp;$_} <$fd>;7547close$fd7548or die_error(404,"Reading git-diff-tree failed");7549@difftree7550or die_error(404,"Blob diff not found");75517552}else{7553 die_error(400,"Missing one of the blob diff parameters");7554}75557556if(@difftree>1) {7557 die_error(400,"Ambiguous blob diff specification");7558}75597560%diffinfo= parse_difftree_raw_line($difftree[0]);7561$file_parent||=$diffinfo{'from_file'} ||$file_name;7562$file_name||=$diffinfo{'to_file'};75637564$hash_parent||=$diffinfo{'from_id'};7565$hash||=$diffinfo{'to_id'};75667567# non-textual hash id's can be cached7568if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7569$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7570$expires='+1d';7571}75727573# open patch output7574open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7575'-p', ($formateq'html'?"--full-index": ()),7576$hash_parent_base,$hash_base,7577"--", (defined$file_parent?$file_parent: ()),$file_name7578or die_error(500,"Open git-diff-tree failed");7579}75807581# old/legacy style URI -- not generated anymore since 1.4.3.7582if(!%diffinfo) {7583 die_error('404 Not Found',"Missing one of the blob diff parameters")7584}75857586# header7587if($formateq'html') {7588my$formats_nav=7589$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7590"raw");7591$formats_nav.= diff_style_nav($diff_style);7592 git_header_html(undef,$expires);7593if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7594 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7595 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7596}else{7597print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7598print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7599}7600if(defined$file_name) {7601 git_print_page_path($file_name,"blob",$hash_base);7602}else{7603print"<div class=\"page_path\"></div>\n";7604}76057606}elsif($formateq'plain') {7607print$cgi->header(7608-type =>'text/plain',7609-charset =>'utf-8',7610-expires =>$expires,7611-content_disposition =>'inline; filename="'."$file_name".'.patch"');76127613print"X-Git-Url: ".$cgi->self_url() ."\n\n";76147615}else{7616 die_error(400,"Unknown blobdiff format");7617}76187619# patch7620if($formateq'html') {7621print"<div class=\"page_body\">\n";76227623 git_patchset_body($fd,$diff_style,7624[ \%diffinfo],$hash_base,$hash_parent_base);7625close$fd;76267627print"</div>\n";# class="page_body"7628 git_footer_html();76297630}else{7631while(my$line= <$fd>) {7632$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7633$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;76347635print$line;76367637last if$line=~m!^\+\+\+!;7638}7639local$/=undef;7640print<$fd>;7641close$fd;7642}7643}76447645sub git_blobdiff_plain {7646 git_blobdiff('plain');7647}76487649# assumes that it is added as later part of already existing navigation,7650# so it returns "| foo | bar" rather than just "foo | bar"7651sub diff_style_nav {7652my($diff_style,$is_combined) =@_;7653$diff_style||='inline';76547655return""if($is_combined);76567657my@styles= (inline =>'inline','sidebyside'=>'side by side');7658my%styles=@styles;7659@styles=7660@styles[map{$_*2}0..$#styles/2];76617662returnjoin'',7663map{" | ".$_}7664map{7665$_eq$diff_style?$styles{$_} :7666$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7667}@styles;7668}76697670sub git_commitdiff {7671my%params=@_;7672my$format=$params{-format} ||'html';7673my$diff_style=$input_params{'diff_style'} ||'inline';76747675my($patch_max) = gitweb_get_feature('patches');7676if($formateq'patch') {7677 die_error(403,"Patch view not allowed")unless$patch_max;7678}76797680$hash||=$hash_base||"HEAD";7681my%co= parse_commit($hash)7682or die_error(404,"Unknown commit object");76837684# choose format for commitdiff for merge7685if(!defined$hash_parent&& @{$co{'parents'}} >1) {7686$hash_parent='--cc';7687}7688# we need to prepare $formats_nav before almost any parameter munging7689my$formats_nav;7690if($formateq'html') {7691$formats_nav=7692$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7693"raw");7694if($patch_max&& @{$co{'parents'}} <=1) {7695$formats_nav.=" | ".7696$cgi->a({-href => href(action=>"patch", -replay=>1)},7697"patch");7698}7699$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);77007701if(defined$hash_parent&&7702$hash_parentne'-c'&&$hash_parentne'--cc') {7703# commitdiff with two commits given7704my$hash_parent_short=$hash_parent;7705if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7706$hash_parent_short=substr($hash_parent,0,7);7707}7708$formats_nav.=7709' (from';7710for(my$i=0;$i< @{$co{'parents'}};$i++) {7711if($co{'parents'}[$i]eq$hash_parent) {7712$formats_nav.=' parent '. ($i+1);7713last;7714}7715}7716$formats_nav.=': '.7717$cgi->a({-href => href(-replay=>1,7718 hash=>$hash_parent, hash_base=>undef)},7719 esc_html($hash_parent_short)) .7720')';7721}elsif(!$co{'parent'}) {7722# --root commitdiff7723$formats_nav.=' (initial)';7724}elsif(scalar@{$co{'parents'}} ==1) {7725# single parent commit7726$formats_nav.=7727' (parent: '.7728$cgi->a({-href => href(-replay=>1,7729 hash=>$co{'parent'}, hash_base=>undef)},7730 esc_html(substr($co{'parent'},0,7))) .7731')';7732}else{7733# merge commit7734if($hash_parenteq'--cc') {7735$formats_nav.=' | '.7736$cgi->a({-href => href(-replay=>1,7737 hash=>$hash, hash_parent=>'-c')},7738'combined');7739}else{# $hash_parent eq '-c'7740$formats_nav.=' | '.7741$cgi->a({-href => href(-replay=>1,7742 hash=>$hash, hash_parent=>'--cc')},7743'compact');7744}7745$formats_nav.=7746' (merge: '.7747join(' ',map{7748$cgi->a({-href => href(-replay=>1,7749 hash=>$_, hash_base=>undef)},7750 esc_html(substr($_,0,7)));7751} @{$co{'parents'}} ) .7752')';7753}7754}77557756my$hash_parent_param=$hash_parent;7757if(!defined$hash_parent_param) {7758# --cc for multiple parents, --root for parentless7759$hash_parent_param=7760@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7761}77627763# read commitdiff7764my$fd;7765my@difftree;7766if($formateq'html') {7767open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7768"--no-commit-id","--patch-with-raw","--full-index",7769$hash_parent_param,$hash,"--"7770or die_error(500,"Open git-diff-tree failed");77717772while(my$line= <$fd>) {7773chomp$line;7774# empty line ends raw part of diff-tree output7775last unless$line;7776push@difftree,scalar parse_difftree_raw_line($line);7777}77787779}elsif($formateq'plain') {7780open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7781'-p',$hash_parent_param,$hash,"--"7782or die_error(500,"Open git-diff-tree failed");7783}elsif($formateq'patch') {7784# For commit ranges, we limit the output to the number of7785# patches specified in the 'patches' feature.7786# For single commits, we limit the output to a single patch,7787# diverging from the git-format-patch default.7788my@commit_spec= ();7789if($hash_parent) {7790if($patch_max>0) {7791push@commit_spec,"-$patch_max";7792}7793push@commit_spec,'-n',"$hash_parent..$hash";7794}else{7795if($params{-single}) {7796push@commit_spec,'-1';7797}else{7798if($patch_max>0) {7799push@commit_spec,"-$patch_max";7800}7801push@commit_spec,"-n";7802}7803push@commit_spec,'--root',$hash;7804}7805open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7806'--encoding=utf8','--stdout',@commit_spec7807or die_error(500,"Open git-format-patch failed");7808}else{7809 die_error(400,"Unknown commitdiff format");7810}78117812# non-textual hash id's can be cached7813my$expires;7814if($hash=~m/^[0-9a-fA-F]{40}$/) {7815$expires="+1d";7816}78177818# write commit message7819if($formateq'html') {7820my$refs= git_get_references();7821my$ref= format_ref_marker($refs,$co{'id'});78227823 git_header_html(undef,$expires);7824 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7825 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7826print"<div class=\"title_text\">\n".7827"<table class=\"object_header\">\n";7828 git_print_authorship_rows(\%co);7829print"</table>".7830"</div>\n";7831print"<div class=\"page_body\">\n";7832if(@{$co{'comment'}} >1) {7833print"<div class=\"log\">\n";7834 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7835print"</div>\n";# class="log"7836}78377838}elsif($formateq'plain') {7839my$refs= git_get_references("tags");7840my$tagname= git_get_rev_name_tags($hash);7841my$filename= basename($project) ."-$hash.patch";78427843print$cgi->header(7844-type =>'text/plain',7845-charset =>'utf-8',7846-expires =>$expires,7847-content_disposition =>'inline; filename="'."$filename".'"');7848my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7849print"From: ". to_utf8($co{'author'}) ."\n";7850print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7851print"Subject: ". to_utf8($co{'title'}) ."\n";78527853print"X-Git-Tag:$tagname\n"if$tagname;7854print"X-Git-Url: ".$cgi->self_url() ."\n\n";78557856foreachmy$line(@{$co{'comment'}}) {7857print to_utf8($line) ."\n";7858}7859print"---\n\n";7860}elsif($formateq'patch') {7861my$filename= basename($project) ."-$hash.patch";78627863print$cgi->header(7864-type =>'text/plain',7865-charset =>'utf-8',7866-expires =>$expires,7867-content_disposition =>'inline; filename="'."$filename".'"');7868}78697870# write patch7871if($formateq'html') {7872my$use_parents= !defined$hash_parent||7873$hash_parenteq'-c'||$hash_parenteq'--cc';7874 git_difftree_body(\@difftree,$hash,7875$use_parents? @{$co{'parents'}} :$hash_parent);7876print"<br/>\n";78777878 git_patchset_body($fd,$diff_style,7879 \@difftree,$hash,7880$use_parents? @{$co{'parents'}} :$hash_parent);7881close$fd;7882print"</div>\n";# class="page_body"7883 git_footer_html();78847885}elsif($formateq'plain') {7886local$/=undef;7887print<$fd>;7888close$fd7889or print"Reading git-diff-tree failed\n";7890}elsif($formateq'patch') {7891local$/=undef;7892print<$fd>;7893close$fd7894or print"Reading git-format-patch failed\n";7895}7896}78977898sub git_commitdiff_plain {7899 git_commitdiff(-format =>'plain');7900}79017902# format-patch-style patches7903sub git_patch {7904 git_commitdiff(-format =>'patch', -single =>1);7905}79067907sub git_patches {7908 git_commitdiff(-format =>'patch');7909}79107911sub git_history {7912 git_log_generic('history', \&git_history_body,7913$hash_base,$hash_parent_base,7914$file_name,$hash);7915}79167917sub git_search {7918$searchtype||='commit';79197920# check if appropriate features are enabled7921 gitweb_check_feature('search')7922or die_error(403,"Search is disabled");7923if($searchtypeeq'pickaxe') {7924# pickaxe may take all resources of your box and run for several minutes7925# with every query - so decide by yourself how public you make this feature7926 gitweb_check_feature('pickaxe')7927or die_error(403,"Pickaxe search is disabled");7928}7929if($searchtypeeq'grep') {7930# grep search might be potentially CPU-intensive, too7931 gitweb_check_feature('grep')7932or die_error(403,"Grep search is disabled");7933}79347935if(!defined$searchtext) {7936 die_error(400,"Text field is empty");7937}7938if(!defined$hash) {7939$hash= git_get_head_hash($project);7940}7941my%co= parse_commit($hash);7942if(!%co) {7943 die_error(404,"Unknown commit object");7944}7945if(!defined$page) {7946$page=0;7947}79487949if($searchtypeeq'commit'||7950$searchtypeeq'author'||7951$searchtypeeq'committer') {7952 git_search_message(%co);7953}elsif($searchtypeeq'pickaxe') {7954 git_search_changes(%co);7955}elsif($searchtypeeq'grep') {7956 git_search_files(%co);7957}else{7958 die_error(400,"Unknown search type");7959}7960}79617962sub git_search_help {7963 git_header_html();7964 git_print_page_nav('','',$hash,$hash,$hash);7965print<<EOT;7966<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7967regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7968the pattern entered is recognized as the POSIX extended7969<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7970insensitive).</p>7971<dl>7972<dt><b>commit</b></dt>7973<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7974EOT7975my$have_grep= gitweb_check_feature('grep');7976if($have_grep) {7977print<<EOT;7978<dt><b>grep</b></dt>7979<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7980 a different one) are searched for the given pattern. On large trees, this search can take7981a while and put some strain on the server, so please use it with some consideration. Note that7982due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7983case-sensitive.</dd>7984EOT7985}7986print<<EOT;7987<dt><b>author</b></dt>7988<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7989<dt><b>committer</b></dt>7990<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7991EOT7992my$have_pickaxe= gitweb_check_feature('pickaxe');7993if($have_pickaxe) {7994print<<EOT;7995<dt><b>pickaxe</b></dt>7996<dd>All commits that caused the string to appear or disappear from any file (changes that7997added, removed or "modified" the string) will be listed. This search can take a while and7998takes a lot of strain on the server, so please use it wisely. Note that since you may be7999interested even in changes just changing the case as well, this search is case sensitive.</dd>8000EOT8001}8002print"</dl>\n";8003 git_footer_html();8004}80058006sub git_shortlog {8007 git_log_generic('shortlog', \&git_shortlog_body,8008$hash,$hash_parent);8009}80108011## ......................................................................8012## feeds (RSS, Atom; OPML)80138014sub git_feed {8015my$format=shift||'atom';8016my$have_blame= gitweb_check_feature('blame');80178018# Atom: http://www.atomenabled.org/developers/syndication/8019# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8020if($formatne'rss'&&$formatne'atom') {8021 die_error(400,"Unknown web feed format");8022}80238024# log/feed of current (HEAD) branch, log of given branch, history of file/directory8025my$head=$hash||'HEAD';8026my@commitlist= parse_commits($head,150,0,$file_name);80278028my%latest_commit;8029my%latest_date;8030my$content_type="application/$format+xml";8031if(defined$cgi->http('HTTP_ACCEPT') &&8032$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8033# browser (feed reader) prefers text/xml8034$content_type='text/xml';8035}8036if(defined($commitlist[0])) {8037%latest_commit= %{$commitlist[0]};8038my$latest_epoch=$latest_commit{'committer_epoch'};8039 exit_if_unmodified_since($latest_epoch);8040%latest_date= parse_date($latest_epoch,$latest_commit{'committer_tz'});8041}8042print$cgi->header(8043-type =>$content_type,8044-charset =>'utf-8',8045%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8046-status =>'200 OK');80478048# Optimization: skip generating the body if client asks only8049# for Last-Modified date.8050return if($cgi->request_method()eq'HEAD');80518052# header variables8053my$title="$site_name-$project/$action";8054my$feed_type='log';8055if(defined$hash) {8056$title.=" - '$hash'";8057$feed_type='branch log';8058if(defined$file_name) {8059$title.=" ::$file_name";8060$feed_type='history';8061}8062}elsif(defined$file_name) {8063$title.=" -$file_name";8064$feed_type='history';8065}8066$title.="$feed_type";8067$title= esc_html($title);8068my$descr= git_get_project_description($project);8069if(defined$descr) {8070$descr= esc_html($descr);8071}else{8072$descr="$project".8073($formateq'rss'?'RSS':'Atom') .8074" feed";8075}8076my$owner= git_get_project_owner($project);8077$owner= esc_html($owner);80788079#header8080my$alt_url;8081if(defined$file_name) {8082$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8083}elsif(defined$hash) {8084$alt_url= href(-full=>1, action=>"log", hash=>$hash);8085}else{8086$alt_url= href(-full=>1, action=>"summary");8087}8088print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8089if($formateq'rss') {8090print<<XML;8091<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8092<channel>8093XML8094print"<title>$title</title>\n".8095"<link>$alt_url</link>\n".8096"<description>$descr</description>\n".8097"<language>en</language>\n".8098# project owner is responsible for 'editorial' content8099"<managingEditor>$owner</managingEditor>\n";8100if(defined$logo||defined$favicon) {8101# prefer the logo to the favicon, since RSS8102# doesn't allow both8103my$img= esc_url($logo||$favicon);8104print"<image>\n".8105"<url>$img</url>\n".8106"<title>$title</title>\n".8107"<link>$alt_url</link>\n".8108"</image>\n";8109}8110if(%latest_date) {8111print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8112print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8113}8114print"<generator>gitweb v.$version/$git_version</generator>\n";8115}elsif($formateq'atom') {8116print<<XML;8117<feed xmlns="http://www.w3.org/2005/Atom">8118XML8119print"<title>$title</title>\n".8120"<subtitle>$descr</subtitle>\n".8121'<link rel="alternate" type="text/html" href="'.8122$alt_url.'" />'."\n".8123'<link rel="self" type="'.$content_type.'" href="'.8124$cgi->self_url() .'" />'."\n".8125"<id>". href(-full=>1) ."</id>\n".8126# use project owner for feed author8127"<author><name>$owner</name></author>\n";8128if(defined$favicon) {8129print"<icon>". esc_url($favicon) ."</icon>\n";8130}8131if(defined$logo) {8132# not twice as wide as tall: 72 x 27 pixels8133print"<logo>". esc_url($logo) ."</logo>\n";8134}8135if(!%latest_date) {8136# dummy date to keep the feed valid until commits trickle in:8137print"<updated>1970-01-01T00:00:00Z</updated>\n";8138}else{8139print"<updated>$latest_date{'iso-8601'}</updated>\n";8140}8141print"<generator version='$version/$git_version'>gitweb</generator>\n";8142}81438144# contents8145for(my$i=0;$i<=$#commitlist;$i++) {8146my%co= %{$commitlist[$i]};8147my$commit=$co{'id'};8148# we read 150, we always show 30 and the ones more recent than 48 hours8149if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8150last;8151}8152my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});81538154# get list of changed files8155open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8156$co{'parent'} ||"--root",8157$co{'id'},"--", (defined$file_name?$file_name: ())8158ornext;8159my@difftree=map{chomp;$_} <$fd>;8160close$fd8161ornext;81628163# print element (entry, item)8164my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8165if($formateq'rss') {8166print"<item>\n".8167"<title>". esc_html($co{'title'}) ."</title>\n".8168"<author>". esc_html($co{'author'}) ."</author>\n".8169"<pubDate>$cd{'rfc2822'}</pubDate>\n".8170"<guid isPermaLink=\"true\">$co_url</guid>\n".8171"<link>$co_url</link>\n".8172"<description>". esc_html($co{'title'}) ."</description>\n".8173"<content:encoded>".8174"<![CDATA[\n";8175}elsif($formateq'atom') {8176print"<entry>\n".8177"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8178"<updated>$cd{'iso-8601'}</updated>\n".8179"<author>\n".8180" <name>". esc_html($co{'author_name'}) ."</name>\n";8181if($co{'author_email'}) {8182print" <email>". esc_html($co{'author_email'}) ."</email>\n";8183}8184print"</author>\n".8185# use committer for contributor8186"<contributor>\n".8187" <name>". esc_html($co{'committer_name'}) ."</name>\n";8188if($co{'committer_email'}) {8189print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8190}8191print"</contributor>\n".8192"<published>$cd{'iso-8601'}</published>\n".8193"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8194"<id>$co_url</id>\n".8195"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8196"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8197}8198my$comment=$co{'comment'};8199print"<pre>\n";8200foreachmy$line(@$comment) {8201$line= esc_html($line);8202print"$line\n";8203}8204print"</pre><ul>\n";8205foreachmy$difftree_line(@difftree) {8206my%difftree= parse_difftree_raw_line($difftree_line);8207next if!$difftree{'from_id'};82088209my$file=$difftree{'file'} ||$difftree{'to_file'};82108211print"<li>".8212"[".8213$cgi->a({-href => href(-full=>1, action=>"blobdiff",8214 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8215 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8216 file_name=>$file, file_parent=>$difftree{'from_file'}),8217-title =>"diff"},'D');8218if($have_blame) {8219print$cgi->a({-href => href(-full=>1, action=>"blame",8220 file_name=>$file, hash_base=>$commit),8221-title =>"blame"},'B');8222}8223# if this is not a feed of a file history8224if(!defined$file_name||$file_namene$file) {8225print$cgi->a({-href => href(-full=>1, action=>"history",8226 file_name=>$file, hash=>$commit),8227-title =>"history"},'H');8228}8229$file= esc_path($file);8230print"] ".8231"$file</li>\n";8232}8233if($formateq'rss') {8234print"</ul>]]>\n".8235"</content:encoded>\n".8236"</item>\n";8237}elsif($formateq'atom') {8238print"</ul>\n</div>\n".8239"</content>\n".8240"</entry>\n";8241}8242}82438244# end of feed8245if($formateq'rss') {8246print"</channel>\n</rss>\n";8247}elsif($formateq'atom') {8248print"</feed>\n";8249}8250}82518252sub git_rss {8253 git_feed('rss');8254}82558256sub git_atom {8257 git_feed('atom');8258}82598260sub git_opml {8261my@list= git_get_projects_list($project_filter,$strict_export);8262if(!@list) {8263 die_error(404,"No projects found");8264}82658266print$cgi->header(8267-type =>'text/xml',8268-charset =>'utf-8',8269-content_disposition =>'inline; filename="opml.xml"');82708271my$title= esc_html($site_name);8272my$filter=" within subdirectory ";8273if(defined$project_filter) {8274$filter.= esc_html($project_filter);8275}else{8276$filter="";8277}8278print<<XML;8279<?xml version="1.0" encoding="utf-8"?>8280<opml version="1.0">8281<head>8282 <title>$titleOPML Export$filter</title>8283</head>8284<body>8285<outline text="git RSS feeds">8286XML82878288foreachmy$pr(@list) {8289my%proj=%$pr;8290my$head= git_get_head_hash($proj{'path'});8291if(!defined$head) {8292next;8293}8294$git_dir="$projectroot/$proj{'path'}";8295my%co= parse_commit($head);8296if(!%co) {8297next;8298}82998300my$path= esc_html(chop_str($proj{'path'},25,5));8301my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8302my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8303print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8304}8305print<<XML;8306</outline>8307</body>8308</opml>8309XML8310}