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 273map{$_=>$_} 274qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make), 275# alternate extensions, see /etc/highlight/filetypes.conf 276'h'=>'c', 277map{$_=>'sh'}qw(bash zsh ksh), 278map{$_=>'cpp'}qw(cxx c++ cc), 279map{$_=>'php'}qw(php3 php4 php5 phps), 280map{$_=>'pl'}qw(perl pm),# perhaps also 'cgi' 281map{$_=>'make'}qw(mak mk), 282map{$_=>'xml'}qw(xhtml html htm), 283); 284 285# You define site-wide feature defaults here; override them with 286# $GITWEB_CONFIG as necessary. 287our%feature= ( 288# feature => { 289# 'sub' => feature-sub (subroutine), 290# 'override' => allow-override (boolean), 291# 'default' => [ default options...] (array reference)} 292# 293# if feature is overridable (it means that allow-override has true value), 294# then feature-sub will be called with default options as parameters; 295# return value of feature-sub indicates if to enable specified feature 296# 297# if there is no 'sub' key (no feature-sub), then feature cannot be 298# overridden 299# 300# use gitweb_get_feature(<feature>) to retrieve the <feature> value 301# (an array) or gitweb_check_feature(<feature>) to check if <feature> 302# is enabled 303 304# Enable the 'blame' blob view, showing the last commit that modified 305# each line in the file. This can be very CPU-intensive. 306 307# To enable system wide have in $GITWEB_CONFIG 308# $feature{'blame'}{'default'} = [1]; 309# To have project specific config enable override in $GITWEB_CONFIG 310# $feature{'blame'}{'override'} = 1; 311# and in project config gitweb.blame = 0|1; 312'blame'=> { 313'sub'=>sub{ feature_bool('blame',@_) }, 314'override'=>0, 315'default'=> [0]}, 316 317# Enable the 'snapshot' link, providing a compressed archive of any 318# tree. This can potentially generate high traffic if you have large 319# project. 320 321# Value is a list of formats defined in %known_snapshot_formats that 322# you wish to offer. 323# To disable system wide have in $GITWEB_CONFIG 324# $feature{'snapshot'}{'default'} = []; 325# To have project specific config enable override in $GITWEB_CONFIG 326# $feature{'snapshot'}{'override'} = 1; 327# and in project config, a comma-separated list of formats or "none" 328# to disable. Example: gitweb.snapshot = tbz2,zip; 329'snapshot'=> { 330'sub'=> \&feature_snapshot, 331'override'=>0, 332'default'=> ['tgz']}, 333 334# Enable text search, which will list the commits which match author, 335# committer or commit text to a given string. Enabled by default. 336# Project specific override is not supported. 337# 338# Note that this controls all search features, which means that if 339# it is disabled, then 'grep' and 'pickaxe' search would also be 340# disabled. 341'search'=> { 342'override'=>0, 343'default'=> [1]}, 344 345# Enable grep search, which will list the files in currently selected 346# tree containing the given string. Enabled by default. This can be 347# potentially CPU-intensive, of course. 348# Note that you need to have 'search' feature enabled too. 349 350# To enable system wide have in $GITWEB_CONFIG 351# $feature{'grep'}{'default'} = [1]; 352# To have project specific config enable override in $GITWEB_CONFIG 353# $feature{'grep'}{'override'} = 1; 354# and in project config gitweb.grep = 0|1; 355'grep'=> { 356'sub'=>sub{ feature_bool('grep',@_) }, 357'override'=>0, 358'default'=> [1]}, 359 360# Enable the pickaxe search, which will list the commits that modified 361# a given string in a file. This can be practical and quite faster 362# alternative to 'blame', but still potentially CPU-intensive. 363# Note that you need to have 'search' feature enabled too. 364 365# To enable system wide have in $GITWEB_CONFIG 366# $feature{'pickaxe'}{'default'} = [1]; 367# To have project specific config enable override in $GITWEB_CONFIG 368# $feature{'pickaxe'}{'override'} = 1; 369# and in project config gitweb.pickaxe = 0|1; 370'pickaxe'=> { 371'sub'=>sub{ feature_bool('pickaxe',@_) }, 372'override'=>0, 373'default'=> [1]}, 374 375# Enable showing size of blobs in a 'tree' view, in a separate 376# column, similar to what 'ls -l' does. This cost a bit of IO. 377 378# To disable system wide have in $GITWEB_CONFIG 379# $feature{'show-sizes'}{'default'} = [0]; 380# To have project specific config enable override in $GITWEB_CONFIG 381# $feature{'show-sizes'}{'override'} = 1; 382# and in project config gitweb.showsizes = 0|1; 383'show-sizes'=> { 384'sub'=>sub{ feature_bool('showsizes',@_) }, 385'override'=>0, 386'default'=> [1]}, 387 388# Make gitweb use an alternative format of the URLs which can be 389# more readable and natural-looking: project name is embedded 390# directly in the path and the query string contains other 391# auxiliary information. All gitweb installations recognize 392# URL in either format; this configures in which formats gitweb 393# generates links. 394 395# To enable system wide have in $GITWEB_CONFIG 396# $feature{'pathinfo'}{'default'} = [1]; 397# Project specific override is not supported. 398 399# Note that you will need to change the default location of CSS, 400# favicon, logo and possibly other files to an absolute URL. Also, 401# if gitweb.cgi serves as your indexfile, you will need to force 402# $my_uri to contain the script name in your $GITWEB_CONFIG. 403'pathinfo'=> { 404'override'=>0, 405'default'=> [0]}, 406 407# Make gitweb consider projects in project root subdirectories 408# to be forks of existing projects. Given project $projname.git, 409# projects matching $projname/*.git will not be shown in the main 410# projects list, instead a '+' mark will be added to $projname 411# there and a 'forks' view will be enabled for the project, listing 412# all the forks. If project list is taken from a file, forks have 413# to be listed after the main project. 414 415# To enable system wide have in $GITWEB_CONFIG 416# $feature{'forks'}{'default'} = [1]; 417# Project specific override is not supported. 418'forks'=> { 419'override'=>0, 420'default'=> [0]}, 421 422# Insert custom links to the action bar of all project pages. 423# This enables you mainly to link to third-party scripts integrating 424# into gitweb; e.g. git-browser for graphical history representation 425# or custom web-based repository administration interface. 426 427# The 'default' value consists of a list of triplets in the form 428# (label, link, position) where position is the label after which 429# to insert the link and link is a format string where %n expands 430# to the project name, %f to the project path within the filesystem, 431# %h to the current hash (h gitweb parameter) and %b to the current 432# hash base (hb gitweb parameter); %% expands to %. 433 434# To enable system wide have in $GITWEB_CONFIG e.g. 435# $feature{'actions'}{'default'} = [('graphiclog', 436# '/git-browser/by-commit.html?r=%n', 'summary')]; 437# Project specific override is not supported. 438'actions'=> { 439'override'=>0, 440'default'=> []}, 441 442# Allow gitweb scan project content tags of project repository, 443# and display the popular Web 2.0-ish "tag cloud" near the projects 444# list. Note that this is something COMPLETELY different from the 445# normal Git tags. 446 447# gitweb by itself can show existing tags, but it does not handle 448# tagging itself; you need to do it externally, outside gitweb. 449# The format is described in git_get_project_ctags() subroutine. 450# You may want to install the HTML::TagCloud Perl module to get 451# a pretty tag cloud instead of just a list of tags. 452 453# To enable system wide have in $GITWEB_CONFIG 454# $feature{'ctags'}{'default'} = [1]; 455# Project specific override is not supported. 456 457# In the future whether ctags editing is enabled might depend 458# on the value, but using 1 should always mean no editing of ctags. 459'ctags'=> { 460'override'=>0, 461'default'=> [0]}, 462 463# The maximum number of patches in a patchset generated in patch 464# view. Set this to 0 or undef to disable patch view, or to a 465# negative number to remove any limit. 466 467# To disable system wide have in $GITWEB_CONFIG 468# $feature{'patches'}{'default'} = [0]; 469# To have project specific config enable override in $GITWEB_CONFIG 470# $feature{'patches'}{'override'} = 1; 471# and in project config gitweb.patches = 0|n; 472# where n is the maximum number of patches allowed in a patchset. 473'patches'=> { 474'sub'=> \&feature_patches, 475'override'=>0, 476'default'=> [16]}, 477 478# Avatar support. When this feature is enabled, views such as 479# shortlog or commit will display an avatar associated with 480# the email of the committer(s) and/or author(s). 481 482# Currently available providers are gravatar and picon. 483# If an unknown provider is specified, the feature is disabled. 484 485# Gravatar depends on Digest::MD5. 486# Picon currently relies on the indiana.edu database. 487 488# To enable system wide have in $GITWEB_CONFIG 489# $feature{'avatar'}{'default'} = ['<provider>']; 490# where <provider> is either gravatar or picon. 491# To have project specific config enable override in $GITWEB_CONFIG 492# $feature{'avatar'}{'override'} = 1; 493# and in project config gitweb.avatar = <provider>; 494'avatar'=> { 495'sub'=> \&feature_avatar, 496'override'=>0, 497'default'=> ['']}, 498 499# Enable displaying how much time and how many git commands 500# it took to generate and display page. Disabled by default. 501# Project specific override is not supported. 502'timed'=> { 503'override'=>0, 504'default'=> [0]}, 505 506# Enable turning some links into links to actions which require 507# JavaScript to run (like 'blame_incremental'). Not enabled by 508# default. Project specific override is currently not supported. 509'javascript-actions'=> { 510'override'=>0, 511'default'=> [0]}, 512 513# Enable and configure ability to change common timezone for dates 514# in gitweb output via JavaScript. Enabled by default. 515# Project specific override is not supported. 516'javascript-timezone'=> { 517'override'=>0, 518'default'=> [ 519'local',# default timezone: 'utc', 'local', or '(-|+)HHMM' format, 520# or undef to turn off this feature 521'gitweb_tz',# name of cookie where to store selected timezone 522'datetime',# CSS class used to mark up dates for manipulation 523]}, 524 525# Syntax highlighting support. This is based on Daniel Svensson's 526# and Sham Chukoury's work in gitweb-xmms2.git. 527# It requires the 'highlight' program present in $PATH, 528# and therefore is disabled by default. 529 530# To enable system wide have in $GITWEB_CONFIG 531# $feature{'highlight'}{'default'} = [1]; 532 533'highlight'=> { 534'sub'=>sub{ feature_bool('highlight',@_) }, 535'override'=>0, 536'default'=> [0]}, 537 538# Enable displaying of remote heads in the heads list 539 540# To enable system wide have in $GITWEB_CONFIG 541# $feature{'remote_heads'}{'default'} = [1]; 542# To have project specific config enable override in $GITWEB_CONFIG 543# $feature{'remote_heads'}{'override'} = 1; 544# and in project config gitweb.remote_heads = 0|1; 545'remote_heads'=> { 546'sub'=>sub{ feature_bool('remote_heads',@_) }, 547'override'=>0, 548'default'=> [0]}, 549); 550 551sub gitweb_get_feature { 552my($name) =@_; 553return unlessexists$feature{$name}; 554my($sub,$override,@defaults) = ( 555$feature{$name}{'sub'}, 556$feature{$name}{'override'}, 557@{$feature{$name}{'default'}}); 558# project specific override is possible only if we have project 559our$git_dir;# global variable, declared later 560if(!$override|| !defined$git_dir) { 561return@defaults; 562} 563if(!defined$sub) { 564warn"feature$nameis not overridable"; 565return@defaults; 566} 567return$sub->(@defaults); 568} 569 570# A wrapper to check if a given feature is enabled. 571# With this, you can say 572# 573# my $bool_feat = gitweb_check_feature('bool_feat'); 574# gitweb_check_feature('bool_feat') or somecode; 575# 576# instead of 577# 578# my ($bool_feat) = gitweb_get_feature('bool_feat'); 579# (gitweb_get_feature('bool_feat'))[0] or somecode; 580# 581sub gitweb_check_feature { 582return(gitweb_get_feature(@_))[0]; 583} 584 585 586sub feature_bool { 587my$key=shift; 588my($val) = git_get_project_config($key,'--bool'); 589 590if(!defined$val) { 591return($_[0]); 592}elsif($valeq'true') { 593return(1); 594}elsif($valeq'false') { 595return(0); 596} 597} 598 599sub feature_snapshot { 600my(@fmts) =@_; 601 602my($val) = git_get_project_config('snapshot'); 603 604if($val) { 605@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 606} 607 608return@fmts; 609} 610 611sub feature_patches { 612my@val= (git_get_project_config('patches','--int')); 613 614if(@val) { 615return@val; 616} 617 618return($_[0]); 619} 620 621sub feature_avatar { 622my@val= (git_get_project_config('avatar')); 623 624return@val?@val:@_; 625} 626 627# checking HEAD file with -e is fragile if the repository was 628# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 629# and then pruned. 630sub check_head_link { 631my($dir) =@_; 632my$headfile="$dir/HEAD"; 633return((-e $headfile) || 634(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 635} 636 637sub check_export_ok { 638my($dir) =@_; 639return(check_head_link($dir) && 640(!$export_ok|| -e "$dir/$export_ok") && 641(!$export_auth_hook||$export_auth_hook->($dir))); 642} 643 644# process alternate names for backward compatibility 645# filter out unsupported (unknown) snapshot formats 646sub filter_snapshot_fmts { 647my@fmts=@_; 648 649@fmts=map{ 650exists$known_snapshot_format_aliases{$_} ? 651$known_snapshot_format_aliases{$_} :$_}@fmts; 652@fmts=grep{ 653exists$known_snapshot_formats{$_} && 654!$known_snapshot_formats{$_}{'disabled'}}@fmts; 655} 656 657# If it is set to code reference, it is code that it is to be run once per 658# request, allowing updating configurations that change with each request, 659# while running other code in config file only once. 660# 661# Otherwise, if it is false then gitweb would process config file only once; 662# if it is true then gitweb config would be run for each request. 663our$per_request_config=1; 664 665# read and parse gitweb config file given by its parameter. 666# returns true on success, false on recoverable error, allowing 667# to chain this subroutine, using first file that exists. 668# dies on errors during parsing config file, as it is unrecoverable. 669sub read_config_file { 670my$filename=shift; 671return unlessdefined$filename; 672# die if there are errors parsing config file 673if(-e $filename) { 674do$filename; 675die$@if$@; 676return1; 677} 678return; 679} 680 681our($GITWEB_CONFIG,$GITWEB_CONFIG_SYSTEM,$GITWEB_CONFIG_COMMON); 682sub evaluate_gitweb_config { 683our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 684our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 685our$GITWEB_CONFIG_COMMON=$ENV{'GITWEB_CONFIG_COMMON'} ||"++GITWEB_CONFIG_COMMON++"; 686 687# Protect agains duplications of file names, to not read config twice. 688# Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so 689# there possibility of duplication of filename there doesn't matter. 690$GITWEB_CONFIG=""if($GITWEB_CONFIGeq$GITWEB_CONFIG_COMMON); 691$GITWEB_CONFIG_SYSTEM=""if($GITWEB_CONFIG_SYSTEMeq$GITWEB_CONFIG_COMMON); 692 693# Common system-wide settings for convenience. 694# Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM. 695 read_config_file($GITWEB_CONFIG_COMMON); 696 697# Use first config file that exists. This means use the per-instance 698# GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG. 699 read_config_file($GITWEB_CONFIG)andreturn; 700 read_config_file($GITWEB_CONFIG_SYSTEM); 701} 702 703# Get loadavg of system, to compare against $maxload. 704# Currently it requires '/proc/loadavg' present to get loadavg; 705# if it is not present it returns 0, which means no load checking. 706sub get_loadavg { 707if( -e '/proc/loadavg'){ 708open my$fd,'<','/proc/loadavg' 709orreturn0; 710my@load=split(/\s+/,scalar<$fd>); 711close$fd; 712 713# The first three columns measure CPU and IO utilization of the last one, 714# five, and 10 minute periods. The fourth column shows the number of 715# currently running processes and the total number of processes in the m/n 716# format. The last column displays the last process ID used. 717return$load[0] ||0; 718} 719# additional checks for load average should go here for things that don't export 720# /proc/loadavg 721 722return0; 723} 724 725# version of the core git binary 726our$git_version; 727sub evaluate_git_version { 728our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 729$number_of_git_cmds++; 730} 731 732sub check_loadavg { 733if(defined$maxload&& get_loadavg() >$maxload) { 734 die_error(503,"The load average on the server is too high"); 735} 736} 737 738# ====================================================================== 739# input validation and dispatch 740 741# input parameters can be collected from a variety of sources (presently, CGI 742# and PATH_INFO), so we define an %input_params hash that collects them all 743# together during validation: this allows subsequent uses (e.g. href()) to be 744# agnostic of the parameter origin 745 746our%input_params= (); 747 748# input parameters are stored with the long parameter name as key. This will 749# also be used in the href subroutine to convert parameters to their CGI 750# equivalent, and since the href() usage is the most frequent one, we store 751# the name -> CGI key mapping here, instead of the reverse. 752# 753# XXX: Warning: If you touch this, check the search form for updating, 754# too. 755 756our@cgi_param_mapping= ( 757 project =>"p", 758 action =>"a", 759 file_name =>"f", 760 file_parent =>"fp", 761 hash =>"h", 762 hash_parent =>"hp", 763 hash_base =>"hb", 764 hash_parent_base =>"hpb", 765 page =>"pg", 766 order =>"o", 767 searchtext =>"s", 768 searchtype =>"st", 769 snapshot_format =>"sf", 770 extra_options =>"opt", 771 search_use_regexp =>"sr", 772 ctag =>"by_tag", 773 diff_style =>"ds", 774 project_filter =>"pf", 775# this must be last entry (for manipulation from JavaScript) 776 javascript =>"js" 777); 778our%cgi_param_mapping=@cgi_param_mapping; 779 780# we will also need to know the possible actions, for validation 781our%actions= ( 782"blame"=> \&git_blame, 783"blame_incremental"=> \&git_blame_incremental, 784"blame_data"=> \&git_blame_data, 785"blobdiff"=> \&git_blobdiff, 786"blobdiff_plain"=> \&git_blobdiff_plain, 787"blob"=> \&git_blob, 788"blob_plain"=> \&git_blob_plain, 789"commitdiff"=> \&git_commitdiff, 790"commitdiff_plain"=> \&git_commitdiff_plain, 791"commit"=> \&git_commit, 792"forks"=> \&git_forks, 793"heads"=> \&git_heads, 794"history"=> \&git_history, 795"log"=> \&git_log, 796"patch"=> \&git_patch, 797"patches"=> \&git_patches, 798"remotes"=> \&git_remotes, 799"rss"=> \&git_rss, 800"atom"=> \&git_atom, 801"search"=> \&git_search, 802"search_help"=> \&git_search_help, 803"shortlog"=> \&git_shortlog, 804"summary"=> \&git_summary, 805"tag"=> \&git_tag, 806"tags"=> \&git_tags, 807"tree"=> \&git_tree, 808"snapshot"=> \&git_snapshot, 809"object"=> \&git_object, 810# those below don't need $project 811"opml"=> \&git_opml, 812"project_list"=> \&git_project_list, 813"project_index"=> \&git_project_index, 814); 815 816# finally, we have the hash of allowed extra_options for the commands that 817# allow them 818our%allowed_options= ( 819"--no-merges"=> [qw(rss atom log shortlog history)], 820); 821 822# fill %input_params with the CGI parameters. All values except for 'opt' 823# should be single values, but opt can be an array. We should probably 824# build an array of parameters that can be multi-valued, but since for the time 825# being it's only this one, we just single it out 826sub evaluate_query_params { 827our$cgi; 828 829while(my($name,$symbol) =each%cgi_param_mapping) { 830if($symboleq'opt') { 831$input_params{$name} = [map{ decode_utf8($_) }$cgi->param($symbol) ]; 832}else{ 833$input_params{$name} = decode_utf8($cgi->param($symbol)); 834} 835} 836} 837 838# now read PATH_INFO and update the parameter list for missing parameters 839sub evaluate_path_info { 840return ifdefined$input_params{'project'}; 841return if!$path_info; 842$path_info=~ s,^/+,,; 843return if!$path_info; 844 845# find which part of PATH_INFO is project 846my$project=$path_info; 847$project=~ s,/+$,,; 848while($project&& !check_head_link("$projectroot/$project")) { 849$project=~ s,/*[^/]*$,,; 850} 851return unless$project; 852$input_params{'project'} =$project; 853 854# do not change any parameters if an action is given using the query string 855return if$input_params{'action'}; 856$path_info=~ s,^\Q$project\E/*,,; 857 858# next, check if we have an action 859my$action=$path_info; 860$action=~ s,/.*$,,; 861if(exists$actions{$action}) { 862$path_info=~ s,^$action/*,,; 863$input_params{'action'} =$action; 864} 865 866# list of actions that want hash_base instead of hash, but can have no 867# pathname (f) parameter 868my@wants_base= ( 869'tree', 870'history', 871); 872 873# we want to catch, among others 874# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 875my($parentrefname,$parentpathname,$refname,$pathname) = 876($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/); 877 878# first, analyze the 'current' part 879if(defined$pathname) { 880# we got "branch:filename" or "branch:dir/" 881# we could use git_get_type(branch:pathname), but: 882# - it needs $git_dir 883# - it does a git() call 884# - the convention of terminating directories with a slash 885# makes it superfluous 886# - embedding the action in the PATH_INFO would make it even 887# more superfluous 888$pathname=~ s,^/+,,; 889if(!$pathname||substr($pathname, -1)eq"/") { 890$input_params{'action'} ||="tree"; 891$pathname=~ s,/$,,; 892}else{ 893# the default action depends on whether we had parent info 894# or not 895if($parentrefname) { 896$input_params{'action'} ||="blobdiff_plain"; 897}else{ 898$input_params{'action'} ||="blob_plain"; 899} 900} 901$input_params{'hash_base'} ||=$refname; 902$input_params{'file_name'} ||=$pathname; 903}elsif(defined$refname) { 904# we got "branch". In this case we have to choose if we have to 905# set hash or hash_base. 906# 907# Most of the actions without a pathname only want hash to be 908# set, except for the ones specified in @wants_base that want 909# hash_base instead. It should also be noted that hand-crafted 910# links having 'history' as an action and no pathname or hash 911# set will fail, but that happens regardless of PATH_INFO. 912if(defined$parentrefname) { 913# if there is parent let the default be 'shortlog' action 914# (for http://git.example.com/repo.git/A..B links); if there 915# is no parent, dispatch will detect type of object and set 916# action appropriately if required (if action is not set) 917$input_params{'action'} ||="shortlog"; 918} 919if($input_params{'action'} && 920grep{$_eq$input_params{'action'} }@wants_base) { 921$input_params{'hash_base'} ||=$refname; 922}else{ 923$input_params{'hash'} ||=$refname; 924} 925} 926 927# next, handle the 'parent' part, if present 928if(defined$parentrefname) { 929# a missing pathspec defaults to the 'current' filename, allowing e.g. 930# someproject/blobdiff/oldrev..newrev:/filename 931if($parentpathname) { 932$parentpathname=~ s,^/+,,; 933$parentpathname=~ s,/$,,; 934$input_params{'file_parent'} ||=$parentpathname; 935}else{ 936$input_params{'file_parent'} ||=$input_params{'file_name'}; 937} 938# we assume that hash_parent_base is wanted if a path was specified, 939# or if the action wants hash_base instead of hash 940if(defined$input_params{'file_parent'} || 941grep{$_eq$input_params{'action'} }@wants_base) { 942$input_params{'hash_parent_base'} ||=$parentrefname; 943}else{ 944$input_params{'hash_parent'} ||=$parentrefname; 945} 946} 947 948# for the snapshot action, we allow URLs in the form 949# $project/snapshot/$hash.ext 950# where .ext determines the snapshot and gets removed from the 951# passed $refname to provide the $hash. 952# 953# To be able to tell that $refname includes the format extension, we 954# require the following two conditions to be satisfied: 955# - the hash input parameter MUST have been set from the $refname part 956# of the URL (i.e. they must be equal) 957# - the snapshot format MUST NOT have been defined already (e.g. from 958# CGI parameter sf) 959# It's also useless to try any matching unless $refname has a dot, 960# so we check for that too 961if(defined$input_params{'action'} && 962$input_params{'action'}eq'snapshot'&& 963defined$refname&&index($refname,'.') != -1&& 964$refnameeq$input_params{'hash'} && 965!defined$input_params{'snapshot_format'}) { 966# We loop over the known snapshot formats, checking for 967# extensions. Allowed extensions are both the defined suffix 968# (which includes the initial dot already) and the snapshot 969# format key itself, with a prepended dot 970while(my($fmt,$opt) =each%known_snapshot_formats) { 971my$hash=$refname; 972unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 973next; 974} 975my$sfx=$1; 976# a valid suffix was found, so set the snapshot format 977# and reset the hash parameter 978$input_params{'snapshot_format'} =$fmt; 979$input_params{'hash'} =$hash; 980# we also set the format suffix to the one requested 981# in the URL: this way a request for e.g. .tgz returns 982# a .tgz instead of a .tar.gz 983$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 984last; 985} 986} 987} 988 989our($action,$project,$file_name,$file_parent,$hash,$hash_parent,$hash_base, 990$hash_parent_base,@extra_options,$page,$searchtype,$search_use_regexp, 991$searchtext,$search_regexp,$project_filter); 992sub evaluate_and_validate_params { 993our$action=$input_params{'action'}; 994if(defined$action) { 995if(!validate_action($action)) { 996 die_error(400,"Invalid action parameter"); 997} 998} 9991000# parameters which are pathnames1001our$project=$input_params{'project'};1002if(defined$project) {1003if(!validate_project($project)) {1004undef$project;1005 die_error(404,"No such project");1006}1007}10081009our$project_filter=$input_params{'project_filter'};1010if(defined$project_filter) {1011if(!validate_pathname($project_filter)) {1012 die_error(404,"Invalid project_filter parameter");1013}1014}10151016our$file_name=$input_params{'file_name'};1017if(defined$file_name) {1018if(!validate_pathname($file_name)) {1019 die_error(400,"Invalid file parameter");1020}1021}10221023our$file_parent=$input_params{'file_parent'};1024if(defined$file_parent) {1025if(!validate_pathname($file_parent)) {1026 die_error(400,"Invalid file parent parameter");1027}1028}10291030# parameters which are refnames1031our$hash=$input_params{'hash'};1032if(defined$hash) {1033if(!validate_refname($hash)) {1034 die_error(400,"Invalid hash parameter");1035}1036}10371038our$hash_parent=$input_params{'hash_parent'};1039if(defined$hash_parent) {1040if(!validate_refname($hash_parent)) {1041 die_error(400,"Invalid hash parent parameter");1042}1043}10441045our$hash_base=$input_params{'hash_base'};1046if(defined$hash_base) {1047if(!validate_refname($hash_base)) {1048 die_error(400,"Invalid hash base parameter");1049}1050}10511052our@extra_options= @{$input_params{'extra_options'}};1053# @extra_options is always defined, since it can only be (currently) set from1054# CGI, and $cgi->param() returns the empty array in array context if the param1055# is not set1056foreachmy$opt(@extra_options) {1057if(not exists$allowed_options{$opt}) {1058 die_error(400,"Invalid option parameter");1059}1060if(not grep(/^$action$/, @{$allowed_options{$opt}})) {1061 die_error(400,"Invalid option parameter for this action");1062}1063}10641065our$hash_parent_base=$input_params{'hash_parent_base'};1066if(defined$hash_parent_base) {1067if(!validate_refname($hash_parent_base)) {1068 die_error(400,"Invalid hash parent base parameter");1069}1070}10711072# other parameters1073our$page=$input_params{'page'};1074if(defined$page) {1075if($page=~m/[^0-9]/) {1076 die_error(400,"Invalid page parameter");1077}1078}10791080our$searchtype=$input_params{'searchtype'};1081if(defined$searchtype) {1082if($searchtype=~m/[^a-z]/) {1083 die_error(400,"Invalid searchtype parameter");1084}1085}10861087our$search_use_regexp=$input_params{'search_use_regexp'};10881089our$searchtext=$input_params{'searchtext'};1090our$search_regexp;1091if(defined$searchtext) {1092if(length($searchtext) <2) {1093 die_error(403,"At least two characters are required for search parameter");1094}1095if($search_use_regexp) {1096$search_regexp=$searchtext;1097if(!eval{qr/$search_regexp/;1; }) {1098(my$error=$@) =~s/ at \S+ line \d+.*\n?//;1099 die_error(400,"Invalid search regexp '$search_regexp'",1100 esc_html($error));1101}1102}else{1103$search_regexp=quotemeta$searchtext;1104}1105}1106}11071108# path to the current git repository1109our$git_dir;1110sub evaluate_git_dir {1111our$git_dir="$projectroot/$project"if$project;1112}11131114our(@snapshot_fmts,$git_avatar);1115sub configure_gitweb_features {1116# list of supported snapshot formats1117our@snapshot_fmts= gitweb_get_feature('snapshot');1118@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts);11191120# check that the avatar feature is set to a known provider name,1121# and for each provider check if the dependencies are satisfied.1122# if the provider name is invalid or the dependencies are not met,1123# reset $git_avatar to the empty string.1124our($git_avatar) = gitweb_get_feature('avatar');1125if($git_avatareq'gravatar') {1126$git_avatar=''unless(eval{require Digest::MD5;1; });1127}elsif($git_avatareq'picon') {1128# no dependencies1129}else{1130$git_avatar='';1131}1132}11331134# custom error handler: 'die <message>' is Internal Server Error1135sub handle_errors_html {1136my$msg=shift;# it is already HTML escaped11371138# to avoid infinite loop where error occurs in die_error,1139# change handler to default handler, disabling handle_errors_html1140 set_message("Error occured when inside die_error:\n$msg");11411142# you cannot jump out of die_error when called as error handler;1143# the subroutine set via CGI::Carp::set_message is called _after_1144# HTTP headers are already written, so it cannot write them itself1145 die_error(undef,undef,$msg, -error_handler =>1, -no_http_header =>1);1146}1147set_message(\&handle_errors_html);11481149# dispatch1150sub dispatch {1151if(!defined$action) {1152if(defined$hash) {1153$action= git_get_type($hash);1154$actionor die_error(404,"Object does not exist");1155}elsif(defined$hash_base&&defined$file_name) {1156$action= git_get_type("$hash_base:$file_name");1157$actionor die_error(404,"File or directory does not exist");1158}elsif(defined$project) {1159$action='summary';1160}else{1161$action='project_list';1162}1163}1164if(!defined($actions{$action})) {1165 die_error(400,"Unknown action");1166}1167if($action!~m/^(?:opml|project_list|project_index)$/&&1168!$project) {1169 die_error(400,"Project needed");1170}1171$actions{$action}->();1172}11731174sub reset_timer {1175our$t0= [ gettimeofday() ]1176ifdefined$t0;1177our$number_of_git_cmds=0;1178}11791180our$first_request=1;1181sub run_request {1182 reset_timer();11831184 evaluate_uri();1185if($first_request) {1186 evaluate_gitweb_config();1187 evaluate_git_version();1188}1189if($per_request_config) {1190if(ref($per_request_config)eq'CODE') {1191$per_request_config->();1192}elsif(!$first_request) {1193 evaluate_gitweb_config();1194}1195}1196 check_loadavg();11971198# $projectroot and $projects_list might be set in gitweb config file1199$projects_list||=$projectroot;12001201 evaluate_query_params();1202 evaluate_path_info();1203 evaluate_and_validate_params();1204 evaluate_git_dir();12051206 configure_gitweb_features();12071208 dispatch();1209}12101211our$is_last_request=sub{1};1212our($pre_dispatch_hook,$post_dispatch_hook,$pre_listen_hook);1213our$CGI='CGI';1214our$cgi;1215sub configure_as_fcgi {1216require CGI::Fast;1217our$CGI='CGI::Fast';12181219my$request_number=0;1220# let each child service 100 requests1221our$is_last_request=sub{ ++$request_number>100};1222}1223sub evaluate_argv {1224my$script_name=$ENV{'SCRIPT_NAME'} ||$ENV{'SCRIPT_FILENAME'} || __FILE__;1225 configure_as_fcgi()1226if$script_name=~/\.fcgi$/;12271228return unless(@ARGV);12291230require Getopt::Long;1231 Getopt::Long::GetOptions(1232'fastcgi|fcgi|f'=> \&configure_as_fcgi,1233'nproc|n=i'=>sub{1234my($arg,$val) =@_;1235return unlesseval{require FCGI::ProcManager;1; };1236my$proc_manager= FCGI::ProcManager->new({1237 n_processes =>$val,1238});1239our$pre_listen_hook=sub{$proc_manager->pm_manage() };1240our$pre_dispatch_hook=sub{$proc_manager->pm_pre_dispatch() };1241our$post_dispatch_hook=sub{$proc_manager->pm_post_dispatch() };1242},1243);1244}12451246sub run {1247 evaluate_argv();12481249$first_request=1;1250$pre_listen_hook->()1251if$pre_listen_hook;12521253 REQUEST:1254while($cgi=$CGI->new()) {1255$pre_dispatch_hook->()1256if$pre_dispatch_hook;12571258 run_request();12591260$post_dispatch_hook->()1261if$post_dispatch_hook;1262$first_request=0;12631264last REQUEST if($is_last_request->());1265}12661267 DONE_GITWEB:12681;1269}12701271run();12721273if(defined caller) {1274# wrapped in a subroutine processing requests,1275# e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI1276return;1277}else{1278# pure CGI script, serving single request1279exit;1280}12811282## ======================================================================1283## action links12841285# possible values of extra options1286# -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)1287# -replay => 1 - start from a current view (replay with modifications)1288# -path_info => 0|1 - don't use/use path_info URL (if possible)1289# -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone1290sub href {1291my%params=@_;1292# default is to use -absolute url() i.e. $my_uri1293my$href=$params{-full} ?$my_url:$my_uri;12941295# implicit -replay, must be first of implicit params1296$params{-replay} =1if(keys%params==1&&$params{-anchor});12971298$params{'project'} =$projectunlessexists$params{'project'};12991300if($params{-replay}) {1301while(my($name,$symbol) =each%cgi_param_mapping) {1302if(!exists$params{$name}) {1303$params{$name} =$input_params{$name};1304}1305}1306}13071308my$use_pathinfo= gitweb_check_feature('pathinfo');1309if(defined$params{'project'} &&1310(exists$params{-path_info} ?$params{-path_info} :$use_pathinfo)) {1311# try to put as many parameters as possible in PATH_INFO:1312# - project name1313# - action1314# - hash_parent or hash_parent_base:/file_parent1315# - hash or hash_base:/filename1316# - the snapshot_format as an appropriate suffix13171318# When the script is the root DirectoryIndex for the domain,1319# $href here would be something like http://gitweb.example.com/1320# Thus, we strip any trailing / from $href, to spare us double1321# slashes in the final URL1322$href=~ s,/$,,;13231324# Then add the project name, if present1325$href.="/".esc_path_info($params{'project'});1326delete$params{'project'};13271328# since we destructively absorb parameters, we keep this1329# boolean that remembers if we're handling a snapshot1330my$is_snapshot=$params{'action'}eq'snapshot';13311332# Summary just uses the project path URL, any other action is1333# added to the URL1334if(defined$params{'action'}) {1335$href.="/".esc_path_info($params{'action'})1336unless$params{'action'}eq'summary';1337delete$params{'action'};1338}13391340# Next, we put hash_parent_base:/file_parent..hash_base:/file_name,1341# stripping nonexistent or useless pieces1342$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'}1343||$params{'hash_parent'} ||$params{'hash'});1344if(defined$params{'hash_base'}) {1345if(defined$params{'hash_parent_base'}) {1346$href.= esc_path_info($params{'hash_parent_base'});1347# skip the file_parent if it's the same as the file_name1348if(defined$params{'file_parent'}) {1349if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) {1350delete$params{'file_parent'};1351}elsif($params{'file_parent'} !~/\.\./) {1352$href.=":/".esc_path_info($params{'file_parent'});1353delete$params{'file_parent'};1354}1355}1356$href.="..";1357delete$params{'hash_parent'};1358delete$params{'hash_parent_base'};1359}elsif(defined$params{'hash_parent'}) {1360$href.= esc_path_info($params{'hash_parent'})."..";1361delete$params{'hash_parent'};1362}13631364$href.= esc_path_info($params{'hash_base'});1365if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) {1366$href.=":/".esc_path_info($params{'file_name'});1367delete$params{'file_name'};1368}1369delete$params{'hash'};1370delete$params{'hash_base'};1371}elsif(defined$params{'hash'}) {1372$href.= esc_path_info($params{'hash'});1373delete$params{'hash'};1374}13751376# If the action was a snapshot, we can absorb the1377# snapshot_format parameter too1378if($is_snapshot) {1379my$fmt=$params{'snapshot_format'};1380# snapshot_format should always be defined when href()1381# is called, but just in case some code forgets, we1382# fall back to the default1383$fmt||=$snapshot_fmts[0];1384$href.=$known_snapshot_formats{$fmt}{'suffix'};1385delete$params{'snapshot_format'};1386}1387}13881389# now encode the parameters explicitly1390my@result= ();1391for(my$i=0;$i<@cgi_param_mapping;$i+=2) {1392my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]);1393if(defined$params{$name}) {1394if(ref($params{$name})eq"ARRAY") {1395foreachmy$par(@{$params{$name}}) {1396push@result,$symbol."=". esc_param($par);1397}1398}else{1399push@result,$symbol."=". esc_param($params{$name});1400}1401}1402}1403$href.="?".join(';',@result)ifscalar@result;14041405# final transformation: trailing spaces must be escaped (URI-encoded)1406$href=~s/(\s+)$/CGI::escape($1)/e;14071408if($params{-anchor}) {1409$href.="#".esc_param($params{-anchor});1410}14111412return$href;1413}141414151416## ======================================================================1417## validation, quoting/unquoting and escaping14181419sub validate_action {1420my$input=shift||returnundef;1421returnundefunlessexists$actions{$input};1422return$input;1423}14241425sub validate_project {1426my$input=shift||returnundef;1427if(!validate_pathname($input) ||1428!(-d "$projectroot/$input") ||1429!check_export_ok("$projectroot/$input") ||1430($strict_export&& !project_in_list($input))) {1431returnundef;1432}else{1433return$input;1434}1435}14361437sub validate_pathname {1438my$input=shift||returnundef;14391440# no '.' or '..' as elements of path, i.e. no '.' nor '..'1441# at the beginning, at the end, and between slashes.1442# also this catches doubled slashes1443if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1444returnundef;1445}1446# no null characters1447if($input=~m!\0!) {1448returnundef;1449}1450return$input;1451}14521453sub validate_refname {1454my$input=shift||returnundef;14551456# textual hashes are O.K.1457if($input=~m/^[0-9a-fA-F]{40}$/) {1458return$input;1459}1460# it must be correct pathname1461$input= validate_pathname($input)1462orreturnundef;1463# restrictions on ref name according to git-check-ref-format1464if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1465returnundef;1466}1467return$input;1468}14691470# decode sequences of octets in utf8 into Perl's internal form,1471# which is utf-8 with utf8 flag set if needed. gitweb writes out1472# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1473sub to_utf8 {1474my$str=shift;1475returnundefunlessdefined$str;14761477if(utf8::is_utf8($str) || utf8::decode($str)) {1478return$str;1479}else{1480return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1481}1482}14831484# quote unsafe chars, but keep the slash, even when it's not1485# correct, but quoted slashes look too horrible in bookmarks1486sub esc_param {1487my$str=shift;1488returnundefunlessdefined$str;1489$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1490$str=~s/ /\+/g;1491return$str;1492}14931494# the quoting rules for path_info fragment are slightly different1495sub esc_path_info {1496my$str=shift;1497returnundefunlessdefined$str;14981499# path_info doesn't treat '+' as space (specially), but '?' must be escaped1500$str=~s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;15011502return$str;1503}15041505# quote unsafe chars in whole URL, so some characters cannot be quoted1506sub esc_url {1507my$str=shift;1508returnundefunlessdefined$str;1509$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;1510$str=~s/ /\+/g;1511return$str;1512}15131514# quote unsafe characters in HTML attributes1515sub esc_attr {15161517# for XHTML conformance escaping '"' to '"' is not enough1518return esc_html(@_);1519}15201521# replace invalid utf8 character with SUBSTITUTION sequence1522sub esc_html {1523my$str=shift;1524my%opts=@_;15251526returnundefunlessdefined$str;15271528$str= to_utf8($str);1529$str=$cgi->escapeHTML($str);1530if($opts{'-nbsp'}) {1531$str=~s/ / /g;1532}1533$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1534return$str;1535}15361537# quote control characters and escape filename to HTML1538sub esc_path {1539my$str=shift;1540my%opts=@_;15411542returnundefunlessdefined$str;15431544$str= to_utf8($str);1545$str=$cgi->escapeHTML($str);1546if($opts{'-nbsp'}) {1547$str=~s/ / /g;1548}1549$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1550return$str;1551}15521553# Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)1554sub sanitize {1555my$str=shift;15561557returnundefunlessdefined$str;15581559$str= to_utf8($str);1560$str=~ s|([[:cntrl:]])|($1=~/[\t\n\r]/?$1: quot_cec($1))|eg;1561return$str;1562}15631564# Make control characters "printable", using character escape codes (CEC)1565sub quot_cec {1566my$cntrl=shift;1567my%opts=@_;1568my%es= (# character escape codes, aka escape sequences1569"\t"=>'\t',# tab (HT)1570"\n"=>'\n',# line feed (LF)1571"\r"=>'\r',# carrige return (CR)1572"\f"=>'\f',# form feed (FF)1573"\b"=>'\b',# backspace (BS)1574"\a"=>'\a',# alarm (bell) (BEL)1575"\e"=>'\e',# escape (ESC)1576"\013"=>'\v',# vertical tab (VT)1577"\000"=>'\0',# nul character (NUL)1578);1579my$chr= ( (exists$es{$cntrl})1580?$es{$cntrl}1581:sprintf('\%2x',ord($cntrl)) );1582if($opts{-nohtml}) {1583return$chr;1584}else{1585return"<span class=\"cntrl\">$chr</span>";1586}1587}15881589# Alternatively use unicode control pictures codepoints,1590# Unicode "printable representation" (PR)1591sub quot_upr {1592my$cntrl=shift;1593my%opts=@_;15941595my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1596if($opts{-nohtml}) {1597return$chr;1598}else{1599return"<span class=\"cntrl\">$chr</span>";1600}1601}16021603# git may return quoted and escaped filenames1604sub unquote {1605my$str=shift;16061607sub unq {1608my$seq=shift;1609my%es= (# character escape codes, aka escape sequences1610't'=>"\t",# tab (HT, TAB)1611'n'=>"\n",# newline (NL)1612'r'=>"\r",# return (CR)1613'f'=>"\f",# form feed (FF)1614'b'=>"\b",# backspace (BS)1615'a'=>"\a",# alarm (bell) (BEL)1616'e'=>"\e",# escape (ESC)1617'v'=>"\013",# vertical tab (VT)1618);16191620if($seq=~m/^[0-7]{1,3}$/) {1621# octal char sequence1622returnchr(oct($seq));1623}elsif(exists$es{$seq}) {1624# C escape sequence, aka character escape code1625return$es{$seq};1626}1627# quoted ordinary character1628return$seq;1629}16301631if($str=~m/^"(.*)"$/) {1632# needs unquoting1633$str=$1;1634$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1635}1636return$str;1637}16381639# escape tabs (convert tabs to spaces)1640sub untabify {1641my$line=shift;16421643while((my$pos=index($line,"\t")) != -1) {1644if(my$count= (8- ($pos%8))) {1645my$spaces=' ' x $count;1646$line=~s/\t/$spaces/;1647}1648}16491650return$line;1651}16521653sub project_in_list {1654my$project=shift;1655my@list= git_get_projects_list();1656return@list&&scalar(grep{$_->{'path'}eq$project}@list);1657}16581659## ----------------------------------------------------------------------1660## HTML aware string manipulation16611662# Try to chop given string on a word boundary between position1663# $len and $len+$add_len. If there is no word boundary there,1664# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1665# (marking chopped part) would be longer than given string.1666sub chop_str {1667my$str=shift;1668my$len=shift;1669my$add_len=shift||10;1670my$where=shift||'right';# 'left' | 'center' | 'right'16711672# Make sure perl knows it is utf8 encoded so we don't1673# cut in the middle of a utf8 multibyte char.1674$str= to_utf8($str);16751676# allow only $len chars, but don't cut a word if it would fit in $add_len1677# if it doesn't fit, cut it if it's still longer than the dots we would add1678# remove chopped character entities entirely16791680# when chopping in the middle, distribute $len into left and right part1681# return early if chopping wouldn't make string shorter1682if($whereeq'center') {1683return$strif($len+5>=length($str));# filler is length 51684$len=int($len/2);1685}else{1686return$strif($len+4>=length($str));# filler is length 41687}16881689# regexps: ending and beginning with word part up to $add_len1690my$endre=qr/.{$len}\w{0,$add_len}/;1691my$begre=qr/\w{0,$add_len}.{$len}/;16921693if($whereeq'left') {1694$str=~m/^(.*?)($begre)$/;1695my($lead,$body) = ($1,$2);1696if(length($lead) >4) {1697$lead=" ...";1698}1699return"$lead$body";17001701}elsif($whereeq'center') {1702$str=~m/^($endre)(.*)$/;1703my($left,$str) = ($1,$2);1704$str=~m/^(.*?)($begre)$/;1705my($mid,$right) = ($1,$2);1706if(length($mid) >5) {1707$mid=" ... ";1708}1709return"$left$mid$right";17101711}else{1712$str=~m/^($endre)(.*)$/;1713my$body=$1;1714my$tail=$2;1715if(length($tail) >4) {1716$tail="... ";1717}1718return"$body$tail";1719}1720}17211722# takes the same arguments as chop_str, but also wraps a <span> around the1723# result with a title attribute if it does get chopped. Additionally, the1724# string is HTML-escaped.1725sub chop_and_escape_str {1726my($str) =@_;17271728my$chopped= chop_str(@_);1729$str= to_utf8($str);1730if($choppedeq$str) {1731return esc_html($chopped);1732}else{1733$str=~s/[[:cntrl:]]/?/g;1734return$cgi->span({-title=>$str}, esc_html($chopped));1735}1736}17371738# Highlight selected fragments of string, using given CSS class,1739# and escape HTML. It is assumed that fragments do not overlap.1740# Regions are passed as list of pairs (array references).1741#1742# Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns1743# '<span class="mark">foo</span>bar'1744sub esc_html_hl_regions {1745my($str,$css_class,@sel) =@_;1746my%opts=grep{ref($_)ne'ARRAY'}@sel;1747@sel=grep{ref($_)eq'ARRAY'}@sel;1748return esc_html($str,%opts)unless@sel;17491750my$out='';1751my$pos=0;17521753formy$s(@sel) {1754my($begin,$end) =@$s;17551756# Don't create empty <span> elements.1757next if$end<=$begin;17581759my$escaped= esc_html(substr($str,$begin,$end-$begin),1760%opts);17611762$out.= esc_html(substr($str,$pos,$begin-$pos),%opts)1763if($begin-$pos>0);1764$out.=$cgi->span({-class=>$css_class},$escaped);17651766$pos=$end;1767}1768$out.= esc_html(substr($str,$pos),%opts)1769if($pos<length($str));17701771return$out;1772}17731774# return positions of beginning and end of each match1775sub matchpos_list {1776my($str,$regexp) =@_;1777return unless(defined$str&&defined$regexp);17781779my@matches;1780while($str=~/$regexp/g) {1781push@matches, [$-[0],$+[0]];1782}1783return@matches;1784}17851786# highlight match (if any), and escape HTML1787sub esc_html_match_hl {1788my($str,$regexp) =@_;1789return esc_html($str)unlessdefined$regexp;17901791my@matches= matchpos_list($str,$regexp);1792return esc_html($str)unless@matches;17931794return esc_html_hl_regions($str,'match',@matches);1795}179617971798# highlight match (if any) of shortened string, and escape HTML1799sub esc_html_match_hl_chopped {1800my($str,$chopped,$regexp) =@_;1801return esc_html_match_hl($str,$regexp)unlessdefined$chopped;18021803my@matches= matchpos_list($str,$regexp);1804return esc_html($chopped)unless@matches;18051806# filter matches so that we mark chopped string1807my$tail="... ";# see chop_str1808unless($chopped=~s/\Q$tail\E$//) {1809$tail='';1810}1811my$chop_len=length($chopped);1812my$tail_len=length($tail);1813my@filtered;18141815formy$m(@matches) {1816if($m->[0] >$chop_len) {1817push@filtered, [$chop_len,$chop_len+$tail_len]if($tail_len>0);1818last;1819}elsif($m->[1] >$chop_len) {1820push@filtered, [$m->[0],$chop_len+$tail_len];1821last;1822}1823push@filtered,$m;1824}18251826return esc_html_hl_regions($chopped.$tail,'match',@filtered);1827}18281829## ----------------------------------------------------------------------1830## functions returning short strings18311832# CSS class for given age value (in seconds)1833sub age_class {1834my$age=shift;18351836if(!defined$age) {1837return"noage";1838}elsif($age<60*60*2) {1839return"age0";1840}elsif($age<60*60*24*2) {1841return"age1";1842}else{1843return"age2";1844}1845}18461847# convert age in seconds to "nn units ago" string1848sub age_string {1849my$age=shift;1850my$age_str;18511852if($age>60*60*24*365*2) {1853$age_str= (int$age/60/60/24/365);1854$age_str.=" years ago";1855}elsif($age>60*60*24*(365/12)*2) {1856$age_str=int$age/60/60/24/(365/12);1857$age_str.=" months ago";1858}elsif($age>60*60*24*7*2) {1859$age_str=int$age/60/60/24/7;1860$age_str.=" weeks ago";1861}elsif($age>60*60*24*2) {1862$age_str=int$age/60/60/24;1863$age_str.=" days ago";1864}elsif($age>60*60*2) {1865$age_str=int$age/60/60;1866$age_str.=" hours ago";1867}elsif($age>60*2) {1868$age_str=int$age/60;1869$age_str.=" min ago";1870}elsif($age>2) {1871$age_str=int$age;1872$age_str.=" sec ago";1873}else{1874$age_str.=" right now";1875}1876return$age_str;1877}18781879useconstant{1880 S_IFINVALID =>0030000,1881 S_IFGITLINK =>0160000,1882};18831884# submodule/subproject, a commit object reference1885sub S_ISGITLINK {1886my$mode=shift;18871888return(($mode& S_IFMT) == S_IFGITLINK)1889}18901891# convert file mode in octal to symbolic file mode string1892sub mode_str {1893my$mode=oct shift;18941895if(S_ISGITLINK($mode)) {1896return'm---------';1897}elsif(S_ISDIR($mode& S_IFMT)) {1898return'drwxr-xr-x';1899}elsif(S_ISLNK($mode)) {1900return'lrwxrwxrwx';1901}elsif(S_ISREG($mode)) {1902# git cares only about the executable bit1903if($mode& S_IXUSR) {1904return'-rwxr-xr-x';1905}else{1906return'-rw-r--r--';1907};1908}else{1909return'----------';1910}1911}19121913# convert file mode in octal to file type string1914sub file_type {1915my$mode=shift;19161917if($mode!~m/^[0-7]+$/) {1918return$mode;1919}else{1920$mode=oct$mode;1921}19221923if(S_ISGITLINK($mode)) {1924return"submodule";1925}elsif(S_ISDIR($mode& S_IFMT)) {1926return"directory";1927}elsif(S_ISLNK($mode)) {1928return"symlink";1929}elsif(S_ISREG($mode)) {1930return"file";1931}else{1932return"unknown";1933}1934}19351936# convert file mode in octal to file type description string1937sub file_type_long {1938my$mode=shift;19391940if($mode!~m/^[0-7]+$/) {1941return$mode;1942}else{1943$mode=oct$mode;1944}19451946if(S_ISGITLINK($mode)) {1947return"submodule";1948}elsif(S_ISDIR($mode& S_IFMT)) {1949return"directory";1950}elsif(S_ISLNK($mode)) {1951return"symlink";1952}elsif(S_ISREG($mode)) {1953if($mode& S_IXUSR) {1954return"executable";1955}else{1956return"file";1957};1958}else{1959return"unknown";1960}1961}196219631964## ----------------------------------------------------------------------1965## functions returning short HTML fragments, or transforming HTML fragments1966## which don't belong to other sections19671968# format line of commit message.1969sub format_log_line_html {1970my$line=shift;19711972$line= esc_html($line, -nbsp=>1);1973$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1974$cgi->a({-href => href(action=>"object", hash=>$1),1975-class=>"text"},$1);1976}eg;19771978return$line;1979}19801981# format marker of refs pointing to given object19821983# the destination action is chosen based on object type and current context:1984# - for annotated tags, we choose the tag view unless it's the current view1985# already, in which case we go to shortlog view1986# - for other refs, we keep the current view if we're in history, shortlog or1987# log view, and select shortlog otherwise1988sub format_ref_marker {1989my($refs,$id) =@_;1990my$markers='';19911992if(defined$refs->{$id}) {1993foreachmy$ref(@{$refs->{$id}}) {1994# this code exploits the fact that non-lightweight tags are the1995# only indirect objects, and that they are the only objects for which1996# we want to use tag instead of shortlog as action1997my($type,$name) =qw();1998my$indirect= ($ref=~s/\^\{\}$//);1999# e.g. tags/v2.6.11 or heads/next2000if($ref=~m!^(.*?)s?/(.*)$!) {2001$type=$1;2002$name=$2;2003}else{2004$type="ref";2005$name=$ref;2006}20072008my$class=$type;2009$class.=" indirect"if$indirect;20102011my$dest_action="shortlog";20122013if($indirect) {2014$dest_action="tag"unless$actioneq"tag";2015}elsif($action=~/^(history|(short)?log)$/) {2016$dest_action=$action;2017}20182019my$dest="";2020$dest.="refs/"unless$ref=~ m!^refs/!;2021$dest.=$ref;20222023my$link=$cgi->a({2024-href => href(2025 action=>$dest_action,2026 hash=>$dest2027)},$name);20282029$markers.=" <span class=\"".esc_attr($class)."\"title=\"".esc_attr($ref)."\">".2030$link."</span>";2031}2032}20332034if($markers) {2035return' <span class="refs">'.$markers.'</span>';2036}else{2037return"";2038}2039}20402041# format, perhaps shortened and with markers, title line2042sub format_subject_html {2043my($long,$short,$href,$extra) =@_;2044$extra=''unlessdefined($extra);20452046if(length($short) <length($long)) {2047$long=~s/[[:cntrl:]]/?/g;2048return$cgi->a({-href =>$href, -class=>"list subject",2049-title => to_utf8($long)},2050 esc_html($short)) .$extra;2051}else{2052return$cgi->a({-href =>$href, -class=>"list subject"},2053 esc_html($long)) .$extra;2054}2055}20562057# Rather than recomputing the url for an email multiple times, we cache it2058# after the first hit. This gives a visible benefit in views where the avatar2059# for the same email is used repeatedly (e.g. shortlog).2060# The cache is shared by all avatar engines (currently gravatar only), which2061# are free to use it as preferred. Since only one avatar engine is used for any2062# given page, there's no risk for cache conflicts.2063our%avatar_cache= ();20642065# Compute the picon url for a given email, by using the picon search service over at2066# http://www.cs.indiana.edu/picons/search.html2067sub picon_url {2068my$email=lc shift;2069if(!$avatar_cache{$email}) {2070my($user,$domain) =split('@',$email);2071$avatar_cache{$email} =2072"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".2073"$domain/$user/".2074"users+domains+unknown/up/single";2075}2076return$avatar_cache{$email};2077}20782079# Compute the gravatar url for a given email, if it's not in the cache already.2080# Gravatar stores only the part of the URL before the size, since that's the2081# one computationally more expensive. This also allows reuse of the cache for2082# different sizes (for this particular engine).2083sub gravatar_url {2084my$email=lc shift;2085my$size=shift;2086$avatar_cache{$email} ||=2087"http://www.gravatar.com/avatar/".2088 Digest::MD5::md5_hex($email) ."?s=";2089return$avatar_cache{$email} .$size;2090}20912092# Insert an avatar for the given $email at the given $size if the feature2093# is enabled.2094sub git_get_avatar {2095my($email,%opts) =@_;2096my$pre_white= ($opts{-pad_before} ?" ":"");2097my$post_white= ($opts{-pad_after} ?" ":"");2098$opts{-size} ||='default';2099my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};2100my$url="";2101if($git_avatareq'gravatar') {2102$url= gravatar_url($email,$size);2103}elsif($git_avatareq'picon') {2104$url= picon_url($email);2105}2106# Other providers can be added by extending the if chain, defining $url2107# as needed. If no variant puts something in $url, we assume avatars2108# are completely disabled/unavailable.2109if($url) {2110return$pre_white.2111"<img width=\"$size\"".2112"class=\"avatar\"".2113"src=\"".esc_url($url)."\"".2114"alt=\"\"".2115"/>".$post_white;2116}else{2117return"";2118}2119}21202121sub format_search_author {2122my($author,$searchtype,$displaytext) =@_;2123my$have_search= gitweb_check_feature('search');21242125if($have_search) {2126my$performed="";2127if($searchtypeeq'author') {2128$performed="authored";2129}elsif($searchtypeeq'committer') {2130$performed="committed";2131}21322133return$cgi->a({-href => href(action=>"search", hash=>$hash,2134 searchtext=>$author,2135 searchtype=>$searchtype),class=>"list",2136 title=>"Search for commits$performedby$author"},2137$displaytext);21382139}else{2140return$displaytext;2141}2142}21432144# format the author name of the given commit with the given tag2145# the author name is chopped and escaped according to the other2146# optional parameters (see chop_str).2147sub format_author_html {2148my$tag=shift;2149my$co=shift;2150my$author= chop_and_escape_str($co->{'author_name'},@_);2151return"<$tagclass=\"author\">".2152 format_search_author($co->{'author_name'},"author",2153 git_get_avatar($co->{'author_email'}, -pad_after =>1) .2154$author) .2155"</$tag>";2156}21572158# format git diff header line, i.e. "diff --(git|combined|cc) ..."2159sub format_git_diff_header_line {2160my$line=shift;2161my$diffinfo=shift;2162my($from,$to) =@_;21632164if($diffinfo->{'nparents'}) {2165# combined diff2166$line=~s!^(diff (.*?) )"?.*$!$1!;2167if($to->{'href'}) {2168$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2169 esc_path($to->{'file'}));2170}else{# file was deleted (no href)2171$line.= esc_path($to->{'file'});2172}2173}else{2174# "ordinary" diff2175$line=~s!^(diff (.*?) )"?a/.*$!$1!;2176if($from->{'href'}) {2177$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},2178'a/'. esc_path($from->{'file'}));2179}else{# file was added (no href)2180$line.='a/'. esc_path($from->{'file'});2181}2182$line.=' ';2183if($to->{'href'}) {2184$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},2185'b/'. esc_path($to->{'file'}));2186}else{# file was deleted2187$line.='b/'. esc_path($to->{'file'});2188}2189}21902191return"<div class=\"diff header\">$line</div>\n";2192}21932194# format extended diff header line, before patch itself2195sub format_extended_diff_header_line {2196my$line=shift;2197my$diffinfo=shift;2198my($from,$to) =@_;21992200# match <path>2201if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {2202$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},2203 esc_path($from->{'file'}));2204}2205if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {2206$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},2207 esc_path($to->{'file'}));2208}2209# match single <mode>2210if($line=~m/\s(\d{6})$/) {2211$line.='<span class="info"> ('.2212 file_type_long($1) .2213')</span>';2214}2215# match <hash>2216if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {2217# can match only for combined diff2218$line='index ';2219for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2220if($from->{'href'}[$i]) {2221$line.=$cgi->a({-href=>$from->{'href'}[$i],2222-class=>"hash"},2223substr($diffinfo->{'from_id'}[$i],0,7));2224}else{2225$line.='0' x 7;2226}2227# separator2228$line.=','if($i<$diffinfo->{'nparents'} -1);2229}2230$line.='..';2231if($to->{'href'}) {2232$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2233substr($diffinfo->{'to_id'},0,7));2234}else{2235$line.='0' x 7;2236}22372238}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {2239# can match only for ordinary diff2240my($from_link,$to_link);2241if($from->{'href'}) {2242$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},2243substr($diffinfo->{'from_id'},0,7));2244}else{2245$from_link='0' x 7;2246}2247if($to->{'href'}) {2248$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},2249substr($diffinfo->{'to_id'},0,7));2250}else{2251$to_link='0' x 7;2252}2253my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});2254$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;2255}22562257return$line."<br/>\n";2258}22592260# format from-file/to-file diff header2261sub format_diff_from_to_header {2262my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;2263my$line;2264my$result='';22652266$line=$from_line;2267#assert($line =~ m/^---/) if DEBUG;2268# no extra formatting for "^--- /dev/null"2269if(!$diffinfo->{'nparents'}) {2270# ordinary (single parent) diff2271if($line=~m!^--- "?a/!) {2272if($from->{'href'}) {2273$line='--- a/'.2274$cgi->a({-href=>$from->{'href'}, -class=>"path"},2275 esc_path($from->{'file'}));2276}else{2277$line='--- a/'.2278 esc_path($from->{'file'});2279}2280}2281$result.= qq!<div class="diff from_file">$line</div>\n!;22822283}else{2284# combined diff (merge commit)2285for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2286if($from->{'href'}[$i]) {2287$line='--- '.2288$cgi->a({-href=>href(action=>"blobdiff",2289 hash_parent=>$diffinfo->{'from_id'}[$i],2290 hash_parent_base=>$parents[$i],2291 file_parent=>$from->{'file'}[$i],2292 hash=>$diffinfo->{'to_id'},2293 hash_base=>$hash,2294 file_name=>$to->{'file'}),2295-class=>"path",2296-title=>"diff". ($i+1)},2297$i+1) .2298'/'.2299$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},2300 esc_path($from->{'file'}[$i]));2301}else{2302$line='--- /dev/null';2303}2304$result.= qq!<div class="diff from_file">$line</div>\n!;2305}2306}23072308$line=$to_line;2309#assert($line =~ m/^\+\+\+/) if DEBUG;2310# no extra formatting for "^+++ /dev/null"2311if($line=~m!^\+\+\+ "?b/!) {2312if($to->{'href'}) {2313$line='+++ b/'.2314$cgi->a({-href=>$to->{'href'}, -class=>"path"},2315 esc_path($to->{'file'}));2316}else{2317$line='+++ b/'.2318 esc_path($to->{'file'});2319}2320}2321$result.= qq!<div class="diff to_file">$line</div>\n!;23222323return$result;2324}23252326# create note for patch simplified by combined diff2327sub format_diff_cc_simplified {2328my($diffinfo,@parents) =@_;2329my$result='';23302331$result.="<div class=\"diff header\">".2332"diff --cc ";2333if(!is_deleted($diffinfo)) {2334$result.=$cgi->a({-href => href(action=>"blob",2335 hash_base=>$hash,2336 hash=>$diffinfo->{'to_id'},2337 file_name=>$diffinfo->{'to_file'}),2338-class=>"path"},2339 esc_path($diffinfo->{'to_file'}));2340}else{2341$result.= esc_path($diffinfo->{'to_file'});2342}2343$result.="</div>\n".# class="diff header"2344"<div class=\"diff nodifferences\">".2345"Simple merge".2346"</div>\n";# class="diff nodifferences"23472348return$result;2349}23502351sub diff_line_class {2352my($line,$from,$to) =@_;23532354# ordinary diff2355my$num_sign=1;2356# combined diff2357if($from&&$to&&ref($from->{'href'})eq"ARRAY") {2358$num_sign=scalar@{$from->{'href'}};2359}23602361my@diff_line_classifier= (2362{ regexp =>qr/^\@\@{$num_sign} /,class=>"chunk_header"},2363{ regexp =>qr/^\\/,class=>"incomplete"},2364{ regexp =>qr/^ {$num_sign}/,class=>"ctx"},2365# classifier for context must come before classifier add/rem,2366# or we would have to use more complicated regexp, for example2367# qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;2368{ regexp =>qr/^[+ ]{$num_sign}/,class=>"add"},2369{ regexp =>qr/^[- ]{$num_sign}/,class=>"rem"},2370);2371formy$clsfy(@diff_line_classifier) {2372return$clsfy->{'class'}2373if($line=~$clsfy->{'regexp'});2374}23752376# fallback2377return"";2378}23792380# assumes that $from and $to are defined and correctly filled,2381# and that $line holds a line of chunk header for unified diff2382sub format_unidiff_chunk_header {2383my($line,$from,$to) =@_;23842385my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =2386$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;23872388$from_lines=0unlessdefined$from_lines;2389$to_lines=0unlessdefined$to_lines;23902391if($from->{'href'}) {2392$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",2393-class=>"list"},$from_text);2394}2395if($to->{'href'}) {2396$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",2397-class=>"list"},$to_text);2398}2399$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".2400"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2401return$line;2402}24032404# assumes that $from and $to are defined and correctly filled,2405# and that $line holds a line of chunk header for combined diff2406sub format_cc_diff_chunk_header {2407my($line,$from,$to) =@_;24082409my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;2410my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);24112412@from_text=split(' ',$ranges);2413for(my$i=0;$i<@from_text; ++$i) {2414($from_start[$i],$from_nlines[$i]) =2415(split(',',substr($from_text[$i],1)),0);2416}24172418$to_text=pop@from_text;2419$to_start=pop@from_start;2420$to_nlines=pop@from_nlines;24212422$line="<span class=\"chunk_info\">$prefix";2423for(my$i=0;$i<@from_text; ++$i) {2424if($from->{'href'}[$i]) {2425$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",2426-class=>"list"},$from_text[$i]);2427}else{2428$line.=$from_text[$i];2429}2430$line.=" ";2431}2432if($to->{'href'}) {2433$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",2434-class=>"list"},$to_text);2435}else{2436$line.=$to_text;2437}2438$line.="$prefix</span>".2439"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";2440return$line;2441}24422443# process patch (diff) line (not to be used for diff headers),2444# returning HTML-formatted (but not wrapped) line.2445# If the line is passed as a reference, it is treated as HTML and not2446# esc_html()'ed.2447sub format_diff_line {2448my($line,$diff_class,$from,$to) =@_;24492450if(ref($line)) {2451$line=$$line;2452}else{2453chomp$line;2454$line= untabify($line);24552456if($from&&$to&&$line=~m/^\@{2} /) {2457$line= format_unidiff_chunk_header($line,$from,$to);2458}elsif($from&&$to&&$line=~m/^\@{3}/) {2459$line= format_cc_diff_chunk_header($line,$from,$to);2460}else{2461$line= esc_html($line, -nbsp=>1);2462}2463}24642465my$diff_classes="diff";2466$diff_classes.="$diff_class"if($diff_class);2467$line="<div class=\"$diff_classes\">$line</div>\n";24682469return$line;2470}24712472# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",2473# linked. Pass the hash of the tree/commit to snapshot.2474sub format_snapshot_links {2475my($hash) =@_;2476my$num_fmts=@snapshot_fmts;2477if($num_fmts>1) {2478# A parenthesized list of links bearing format names.2479# e.g. "snapshot (_tar.gz_ _zip_)"2480return"snapshot (".join(' ',map2481$cgi->a({2482-href => href(2483 action=>"snapshot",2484 hash=>$hash,2485 snapshot_format=>$_2486)2487},$known_snapshot_formats{$_}{'display'})2488,@snapshot_fmts) .")";2489}elsif($num_fmts==1) {2490# A single "snapshot" link whose tooltip bears the format name.2491# i.e. "_snapshot_"2492my($fmt) =@snapshot_fmts;2493return2494$cgi->a({2495-href => href(2496 action=>"snapshot",2497 hash=>$hash,2498 snapshot_format=>$fmt2499),2500-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"2501},"snapshot");2502}else{# $num_fmts == 02503returnundef;2504}2505}25062507## ......................................................................2508## functions returning values to be passed, perhaps after some2509## transformation, to other functions; e.g. returning arguments to href()25102511# returns hash to be passed to href to generate gitweb URL2512# in -title key it returns description of link2513sub get_feed_info {2514my$format=shift||'Atom';2515my%res= (action =>lc($format));25162517# feed links are possible only for project views2518return unless(defined$project);2519# some views should link to OPML, or to generic project feed,2520# or don't have specific feed yet (so they should use generic)2521return if(!$action||$action=~/^(?:tags|heads|forks|tag|search)$/x);25222523my$branch;2524# branches refs uses 'refs/heads/' prefix (fullname) to differentiate2525# from tag links; this also makes possible to detect branch links2526if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||2527(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {2528$branch=$1;2529}2530# find log type for feed description (title)2531my$type='log';2532if(defined$file_name) {2533$type="history of$file_name";2534$type.="/"if($actioneq'tree');2535$type.=" on '$branch'"if(defined$branch);2536}else{2537$type="log of$branch"if(defined$branch);2538}25392540$res{-title} =$type;2541$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);2542$res{'file_name'} =$file_name;25432544return%res;2545}25462547## ----------------------------------------------------------------------2548## git utility subroutines, invoking git commands25492550# returns path to the core git executable and the --git-dir parameter as list2551sub git_cmd {2552$number_of_git_cmds++;2553return$GIT,'--git-dir='.$git_dir;2554}25552556# quote the given arguments for passing them to the shell2557# quote_command("command", "arg 1", "arg with ' and ! characters")2558# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"2559# Try to avoid using this function wherever possible.2560sub quote_command {2561returnjoin(' ',2562map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);2563}25642565# get HEAD ref of given project as hash2566sub git_get_head_hash {2567return git_get_full_hash(shift,'HEAD');2568}25692570sub git_get_full_hash {2571return git_get_hash(@_);2572}25732574sub git_get_short_hash {2575return git_get_hash(@_,'--short=7');2576}25772578sub git_get_hash {2579my($project,$hash,@options) =@_;2580my$o_git_dir=$git_dir;2581my$retval=undef;2582$git_dir="$projectroot/$project";2583if(open my$fd,'-|', git_cmd(),'rev-parse',2584'--verify','-q',@options,$hash) {2585$retval= <$fd>;2586chomp$retvalifdefined$retval;2587close$fd;2588}2589if(defined$o_git_dir) {2590$git_dir=$o_git_dir;2591}2592return$retval;2593}25942595# get type of given object2596sub git_get_type {2597my$hash=shift;25982599open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2600my$type= <$fd>;2601close$fdorreturn;2602chomp$type;2603return$type;2604}26052606# repository configuration2607our$config_file='';2608our%config;26092610# store multiple values for single key as anonymous array reference2611# single values stored directly in the hash, not as [ <value> ]2612sub hash_set_multi {2613my($hash,$key,$value) =@_;26142615if(!exists$hash->{$key}) {2616$hash->{$key} =$value;2617}elsif(!ref$hash->{$key}) {2618$hash->{$key} = [$hash->{$key},$value];2619}else{2620push@{$hash->{$key}},$value;2621}2622}26232624# return hash of git project configuration2625# optionally limited to some section, e.g. 'gitweb'2626sub git_parse_project_config {2627my$section_regexp=shift;2628my%config;26292630local$/="\0";26312632open my$fh,"-|", git_cmd(),"config",'-z','-l',2633orreturn;26342635while(my$keyval= <$fh>) {2636chomp$keyval;2637my($key,$value) =split(/\n/,$keyval,2);26382639 hash_set_multi(\%config,$key,$value)2640if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2641}2642close$fh;26432644return%config;2645}26462647# convert config value to boolean: 'true' or 'false'2648# no value, number > 0, 'true' and 'yes' values are true2649# rest of values are treated as false (never as error)2650sub config_to_bool {2651my$val=shift;26522653return1if!defined$val;# section.key26542655# strip leading and trailing whitespace2656$val=~s/^\s+//;2657$val=~s/\s+$//;26582659return(($val=~/^\d+$/&&$val) ||# section.key = 12660($val=~/^(?:true|yes)$/i));# section.key = true2661}26622663# convert config value to simple decimal number2664# an optional value suffix of 'k', 'm', or 'g' will cause the value2665# to be multiplied by 1024, 1048576, or 10737418242666sub config_to_int {2667my$val=shift;26682669# strip leading and trailing whitespace2670$val=~s/^\s+//;2671$val=~s/\s+$//;26722673if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2674$unit=lc($unit);2675# unknown unit is treated as 12676return$num* ($uniteq'g'?1073741824:2677$uniteq'm'?1048576:2678$uniteq'k'?1024:1);2679}2680return$val;2681}26822683# convert config value to array reference, if needed2684sub config_to_multi {2685my$val=shift;26862687returnref($val) ?$val: (defined($val) ? [$val] : []);2688}26892690sub git_get_project_config {2691my($key,$type) =@_;26922693return unlessdefined$git_dir;26942695# key sanity check2696return unless($key);2697# only subsection, if exists, is case sensitive,2698# and not lowercased by 'git config -z -l'2699if(my($hi,$mi,$lo) = ($key=~/^([^.]*)\.(.*)\.([^.]*)$/)) {2700$key=join(".",lc($hi),$mi,lc($lo));2701}else{2702$key=lc($key);2703}2704$key=~s/^gitweb\.//;2705return if($key=~m/\W/);27062707# type sanity check2708if(defined$type) {2709$type=~s/^--//;2710$type=undef2711unless($typeeq'bool'||$typeeq'int');2712}27132714# get config2715if(!defined$config_file||2716$config_filene"$git_dir/config") {2717%config= git_parse_project_config('gitweb');2718$config_file="$git_dir/config";2719}27202721# check if config variable (key) exists2722return unlessexists$config{"gitweb.$key"};27232724# ensure given type2725if(!defined$type) {2726return$config{"gitweb.$key"};2727}elsif($typeeq'bool') {2728# backward compatibility: 'git config --bool' returns true/false2729return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2730}elsif($typeeq'int') {2731return config_to_int($config{"gitweb.$key"});2732}2733return$config{"gitweb.$key"};2734}27352736# get hash of given path at given ref2737sub git_get_hash_by_path {2738my$base=shift;2739my$path=shift||returnundef;2740my$type=shift;27412742$path=~ s,/+$,,;27432744open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2745or die_error(500,"Open git-ls-tree failed");2746my$line= <$fd>;2747close$fdorreturnundef;27482749if(!defined$line) {2750# there is no tree or hash given by $path at $base2751returnundef;2752}27532754#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2755$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2756if(defined$type&&$typene$2) {2757# type doesn't match2758returnundef;2759}2760return$3;2761}27622763# get path of entry with given hash at given tree-ish (ref)2764# used to get 'from' filename for combined diff (merge commit) for renames2765sub git_get_path_by_hash {2766my$base=shift||return;2767my$hash=shift||return;27682769local$/="\0";27702771open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2772orreturnundef;2773while(my$line= <$fd>) {2774chomp$line;27752776#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2777#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2778if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2779close$fd;2780return$1;2781}2782}2783close$fd;2784returnundef;2785}27862787## ......................................................................2788## git utility functions, directly accessing git repository27892790# get the value of config variable either from file named as the variable2791# itself in the repository ($GIT_DIR/$name file), or from gitweb.$name2792# configuration variable in the repository config file.2793sub git_get_file_or_project_config {2794my($path,$name) =@_;27952796$git_dir="$projectroot/$path";2797open my$fd,'<',"$git_dir/$name"2798orreturn git_get_project_config($name);2799my$conf= <$fd>;2800close$fd;2801if(defined$conf) {2802chomp$conf;2803}2804return$conf;2805}28062807sub git_get_project_description {2808my$path=shift;2809return git_get_file_or_project_config($path,'description');2810}28112812sub git_get_project_category {2813my$path=shift;2814return git_get_file_or_project_config($path,'category');2815}281628172818# supported formats:2819# * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)2820# - if its contents is a number, use it as tag weight,2821# - otherwise add a tag with weight 12822# * $GIT_DIR/ctags file, each line is a tag (with weight 1)2823# the same value multiple times increases tag weight2824# * `gitweb.ctag' multi-valued repo config variable2825sub git_get_project_ctags {2826my$project=shift;2827my$ctags= {};28282829$git_dir="$projectroot/$project";2830if(opendir my$dh,"$git_dir/ctags") {2831my@files=grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh);2832foreachmy$tagfile(@files) {2833open my$ct,'<',$tagfile2834ornext;2835my$val= <$ct>;2836chomp$valif$val;2837close$ct;28382839(my$ctag=$tagfile) =~ s#.*/##;2840if($val=~/^\d+$/) {2841$ctags->{$ctag} =$val;2842}else{2843$ctags->{$ctag} =1;2844}2845}2846closedir$dh;28472848}elsif(open my$fh,'<',"$git_dir/ctags") {2849while(my$line= <$fh>) {2850chomp$line;2851$ctags->{$line}++if$line;2852}2853close$fh;28542855}else{2856my$taglist= config_to_multi(git_get_project_config('ctag'));2857foreachmy$tag(@$taglist) {2858$ctags->{$tag}++;2859}2860}28612862return$ctags;2863}28642865# return hash, where keys are content tags ('ctags'),2866# and values are sum of weights of given tag in every project2867sub git_gather_all_ctags {2868my$projects=shift;2869my$ctags= {};28702871foreachmy$p(@$projects) {2872foreachmy$ct(keys%{$p->{'ctags'}}) {2873$ctags->{$ct} +=$p->{'ctags'}->{$ct};2874}2875}28762877return$ctags;2878}28792880sub git_populate_project_tagcloud {2881my$ctags=shift;28822883# First, merge different-cased tags; tags vote on casing2884my%ctags_lc;2885foreach(keys%$ctags) {2886$ctags_lc{lc$_}->{count} +=$ctags->{$_};2887if(not$ctags_lc{lc$_}->{topcount}2888or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2889$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2890$ctags_lc{lc$_}->{topname} =$_;2891}2892}28932894my$cloud;2895my$matched=$input_params{'ctag'};2896if(eval{require HTML::TagCloud;1; }) {2897$cloud= HTML::TagCloud->new;2898foreachmy$ctag(sort keys%ctags_lc) {2899# Pad the title with spaces so that the cloud looks2900# less crammed.2901my$title= esc_html($ctags_lc{$ctag}->{topname});2902$title=~s/ / /g;2903$title=~s/^/ /g;2904$title=~s/$/ /g;2905if(defined$matched&&$matchedeq$ctag) {2906$title=qq(<span class="match">$title</span>);2907}2908$cloud->add($title, href(project=>undef, ctag=>$ctag),2909$ctags_lc{$ctag}->{count});2910}2911}else{2912$cloud= {};2913foreachmy$ctag(keys%ctags_lc) {2914my$title= esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);2915if(defined$matched&&$matchedeq$ctag) {2916$title=qq(<span class="match">$title</span>);2917}2918$cloud->{$ctag}{count} =$ctags_lc{$ctag}->{count};2919$cloud->{$ctag}{ctag} =2920$cgi->a({-href=>href(project=>undef, ctag=>$ctag)},$title);2921}2922}2923return$cloud;2924}29252926sub git_show_project_tagcloud {2927my($cloud,$count) =@_;2928if(ref$cloudeq'HTML::TagCloud') {2929return$cloud->html_and_css($count);2930}else{2931my@tags=sort{$cloud->{$a}->{'count'} <=>$cloud->{$b}->{'count'} }keys%$cloud;2932return2933'<div id="htmltagcloud"'.($project?'':' align="center"').'>'.2934join(', ',map{2935$cloud->{$_}->{'ctag'}2936}splice(@tags,0,$count)) .2937'</div>';2938}2939}29402941sub git_get_project_url_list {2942my$path=shift;29432944$git_dir="$projectroot/$path";2945open my$fd,'<',"$git_dir/cloneurl"2946orreturnwantarray?2947@{ config_to_multi(git_get_project_config('url')) } :2948 config_to_multi(git_get_project_config('url'));2949my@git_project_url_list=map{chomp;$_} <$fd>;2950close$fd;29512952returnwantarray?@git_project_url_list: \@git_project_url_list;2953}29542955sub git_get_projects_list {2956my$filter=shift||'';2957my$paranoid=shift;2958my@list;29592960if(-d $projects_list) {2961# search in directory2962my$dir=$projects_list;2963# remove the trailing "/"2964$dir=~s!/+$!!;2965my$pfxlen=length("$dir");2966my$pfxdepth= ($dir=~tr!/!!);2967# when filtering, search only given subdirectory2968if($filter&& !$paranoid) {2969$dir.="/$filter";2970$dir=~s!/+$!!;2971}29722973 File::Find::find({2974 follow_fast =>1,# follow symbolic links2975 follow_skip =>2,# ignore duplicates2976 dangling_symlinks =>0,# ignore dangling symlinks, silently2977 wanted =>sub{2978# global variables2979our$project_maxdepth;2980our$projectroot;2981# skip project-list toplevel, if we get it.2982return if(m!^[/.]$!);2983# only directories can be git repositories2984return unless(-d $_);2985# don't traverse too deep (Find is super slow on os x)2986# $project_maxdepth excludes depth of $projectroot2987if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2988$File::Find::prune =1;2989return;2990}29912992my$path=substr($File::Find::name,$pfxlen+1);2993# paranoidly only filter here2994if($paranoid&&$filter&&$path!~m!^\Q$filter\E/!) {2995next;2996}2997# we check related file in $projectroot2998if(check_export_ok("$projectroot/$path")) {2999push@list, { path =>$path};3000$File::Find::prune =1;3001}3002},3003},"$dir");30043005}elsif(-f $projects_list) {3006# read from file(url-encoded):3007# 'git%2Fgit.git Linus+Torvalds'3008# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3009# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3010open my$fd,'<',$projects_listorreturn;3011 PROJECT:3012while(my$line= <$fd>) {3013chomp$line;3014my($path,$owner) =split' ',$line;3015$path= unescape($path);3016$owner= unescape($owner);3017if(!defined$path) {3018next;3019}3020# if $filter is rpovided, check if $path begins with $filter3021if($filter&&$path!~m!^\Q$filter\E/!) {3022next;3023}3024if(check_export_ok("$projectroot/$path")) {3025my$pr= {3026 path =>$path3027};3028if($owner) {3029$pr->{'owner'} = to_utf8($owner);3030}3031push@list,$pr;3032}3033}3034close$fd;3035}3036return@list;3037}30383039# written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)3040# as side effects it sets 'forks' field to list of forks for forked projects3041sub filter_forks_from_projects_list {3042my$projects=shift;30433044my%trie;# prefix tree of directories (path components)3045# generate trie out of those directories that might contain forks3046foreachmy$pr(@$projects) {3047my$path=$pr->{'path'};3048$path=~s/\.git$//;# forks of 'repo.git' are in 'repo/' directory3049next if($path=~m!/$!);# skip non-bare repositories, e.g. 'repo/.git'3050next unless($path);# skip '.git' repository: tests, git-instaweb3051next unless(-d "$projectroot/$path");# containing directory exists3052$pr->{'forks'} = [];# there can be 0 or more forks of project30533054# add to trie3055my@dirs=split('/',$path);3056# walk the trie, until either runs out of components or out of trie3057my$ref= \%trie;3058while(scalar@dirs&&3059exists($ref->{$dirs[0]})) {3060$ref=$ref->{shift@dirs};3061}3062# create rest of trie structure from rest of components3063foreachmy$dir(@dirs) {3064$ref=$ref->{$dir} = {};3065}3066# create end marker, store $pr as a data3067$ref->{''} =$prif(!exists$ref->{''});3068}30693070# filter out forks, by finding shortest prefix match for paths3071my@filtered;3072 PROJECT:3073foreachmy$pr(@$projects) {3074# trie lookup3075my$ref= \%trie;3076 DIR:3077foreachmy$dir(split('/',$pr->{'path'})) {3078if(exists$ref->{''}) {3079# found [shortest] prefix, is a fork - skip it3080push@{$ref->{''}{'forks'}},$pr;3081next PROJECT;3082}3083if(!exists$ref->{$dir}) {3084# not in trie, cannot have prefix, not a fork3085push@filtered,$pr;3086next PROJECT;3087}3088# If the dir is there, we just walk one step down the trie.3089$ref=$ref->{$dir};3090}3091# we ran out of trie3092# (shouldn't happen: it's either no match, or end marker)3093push@filtered,$pr;3094}30953096return@filtered;3097}30983099# note: fill_project_list_info must be run first,3100# for 'descr_long' and 'ctags' to be filled3101sub search_projects_list {3102my($projlist,%opts) =@_;3103my$tagfilter=$opts{'tagfilter'};3104my$search_re=$opts{'search_regexp'};31053106return@$projlist3107unless($tagfilter||$search_re);31083109# searching projects require filling to be run before it;3110 fill_project_list_info($projlist,3111$tagfilter?'ctags': (),3112$search_re? ('path','descr') : ());3113my@projects;3114 PROJECT:3115foreachmy$pr(@$projlist) {31163117if($tagfilter) {3118next unlessref($pr->{'ctags'})eq'HASH';3119next unless3120grep{lc($_)eq lc($tagfilter) }keys%{$pr->{'ctags'}};3121}31223123if($search_re) {3124next unless3125$pr->{'path'} =~/$search_re/||3126$pr->{'descr_long'} =~/$search_re/;3127}31283129push@projects,$pr;3130}31313132return@projects;3133}31343135our$gitweb_project_owner=undef;3136sub git_get_project_list_from_file {31373138return if(defined$gitweb_project_owner);31393140$gitweb_project_owner= {};3141# read from file (url-encoded):3142# 'git%2Fgit.git Linus+Torvalds'3143# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'3144# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'3145if(-f $projects_list) {3146open(my$fd,'<',$projects_list);3147while(my$line= <$fd>) {3148chomp$line;3149my($pr,$ow) =split' ',$line;3150$pr= unescape($pr);3151$ow= unescape($ow);3152$gitweb_project_owner->{$pr} = to_utf8($ow);3153}3154close$fd;3155}3156}31573158sub git_get_project_owner {3159my$project=shift;3160my$owner;31613162returnundefunless$project;3163$git_dir="$projectroot/$project";31643165if(!defined$gitweb_project_owner) {3166 git_get_project_list_from_file();3167}31683169if(exists$gitweb_project_owner->{$project}) {3170$owner=$gitweb_project_owner->{$project};3171}3172if(!defined$owner){3173$owner= git_get_project_config('owner');3174}3175if(!defined$owner) {3176$owner= get_file_owner("$git_dir");3177}31783179return$owner;3180}31813182sub git_get_last_activity {3183my($path) =@_;3184my$fd;31853186$git_dir="$projectroot/$path";3187open($fd,"-|", git_cmd(),'for-each-ref',3188'--format=%(committer)',3189'--sort=-committerdate',3190'--count=1',3191'refs/heads')orreturn;3192my$most_recent= <$fd>;3193close$fdorreturn;3194if(defined$most_recent&&3195$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {3196my$timestamp=$1;3197my$age=time-$timestamp;3198return($age, age_string($age));3199}3200return(undef,undef);3201}32023203# Implementation note: when a single remote is wanted, we cannot use 'git3204# remote show -n' because that command always work (assuming it's a remote URL3205# if it's not defined), and we cannot use 'git remote show' because that would3206# try to make a network roundtrip. So the only way to find if that particular3207# remote is defined is to walk the list provided by 'git remote -v' and stop if3208# and when we find what we want.3209sub git_get_remotes_list {3210my$wanted=shift;3211my%remotes= ();32123213open my$fd,'-|', git_cmd(),'remote','-v';3214return unless$fd;3215while(my$remote= <$fd>) {3216chomp$remote;3217$remote=~s!\t(.*?)\s+\((\w+)\)$!!;3218next if$wantedand not$remoteeq$wanted;3219my($url,$key) = ($1,$2);32203221$remotes{$remote} ||= {'heads'=> () };3222$remotes{$remote}{$key} =$url;3223}3224close$fdorreturn;3225returnwantarray?%remotes: \%remotes;3226}32273228# Takes a hash of remotes as first parameter and fills it by adding the3229# available remote heads for each of the indicated remotes.3230sub fill_remote_heads {3231my$remotes=shift;3232my@heads=map{"remotes/$_"}keys%$remotes;3233my@remoteheads= git_get_heads_list(undef,@heads);3234foreachmy$remote(keys%$remotes) {3235$remotes->{$remote}{'heads'} = [grep{3236$_->{'name'} =~s!^$remote/!!3237}@remoteheads];3238}3239}32403241sub git_get_references {3242my$type=shift||"";3243my%refs;3244# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.113245# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}3246open my$fd,"-|", git_cmd(),"show-ref","--dereference",3247($type? ("--","refs/$type") : ())# use -- <pattern> if $type3248orreturn;32493250while(my$line= <$fd>) {3251chomp$line;3252if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {3253if(defined$refs{$1}) {3254push@{$refs{$1}},$2;3255}else{3256$refs{$1} = [$2];3257}3258}3259}3260close$fdorreturn;3261return \%refs;3262}32633264sub git_get_rev_name_tags {3265my$hash=shift||returnundef;32663267open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash3268orreturn;3269my$name_rev= <$fd>;3270close$fd;32713272if($name_rev=~ m|^$hash tags/(.*)$|) {3273return$1;3274}else{3275# catches also '$hash undefined' output3276returnundef;3277}3278}32793280## ----------------------------------------------------------------------3281## parse to hash functions32823283sub parse_date {3284my$epoch=shift;3285my$tz=shift||"-0000";32863287my%date;3288my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");3289my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");3290my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);3291$date{'hour'} =$hour;3292$date{'minute'} =$min;3293$date{'mday'} =$mday;3294$date{'day'} =$days[$wday];3295$date{'month'} =$months[$mon];3296$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",3297$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;3298$date{'mday-time'} =sprintf"%d%s%02d:%02d",3299$mday,$months[$mon],$hour,$min;3300$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",33011900+$year,1+$mon,$mday,$hour,$min,$sec;33023303my($tz_sign,$tz_hour,$tz_min) =3304($tz=~m/^([-+])(\d\d)(\d\d)$/);3305$tz_sign= ($tz_signeq'-'? -1: +1);3306my$local=$epoch+$tz_sign*((($tz_hour*60) +$tz_min)*60);3307($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);3308$date{'hour_local'} =$hour;3309$date{'minute_local'} =$min;3310$date{'tz_local'} =$tz;3311$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",33121900+$year,$mon+1,$mday,3313$hour,$min,$sec,$tz);3314return%date;3315}33163317sub parse_tag {3318my$tag_id=shift;3319my%tag;3320my@comment;33213322open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;3323$tag{'id'} =$tag_id;3324while(my$line= <$fd>) {3325chomp$line;3326if($line=~m/^object ([0-9a-fA-F]{40})$/) {3327$tag{'object'} =$1;3328}elsif($line=~m/^type (.+)$/) {3329$tag{'type'} =$1;3330}elsif($line=~m/^tag (.+)$/) {3331$tag{'name'} =$1;3332}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {3333$tag{'author'} =$1;3334$tag{'author_epoch'} =$2;3335$tag{'author_tz'} =$3;3336if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {3337$tag{'author_name'} =$1;3338$tag{'author_email'} =$2;3339}else{3340$tag{'author_name'} =$tag{'author'};3341}3342}elsif($line=~m/--BEGIN/) {3343push@comment,$line;3344last;3345}elsif($lineeq"") {3346last;3347}3348}3349push@comment, <$fd>;3350$tag{'comment'} = \@comment;3351close$fdorreturn;3352if(!defined$tag{'name'}) {3353return3354};3355return%tag3356}33573358sub parse_commit_text {3359my($commit_text,$withparents) =@_;3360my@commit_lines=split'\n',$commit_text;3361my%co;33623363pop@commit_lines;# Remove '\0'33643365if(!@commit_lines) {3366return;3367}33683369my$header=shift@commit_lines;3370if($header!~m/^[0-9a-fA-F]{40}/) {3371return;3372}3373($co{'id'},my@parents) =split' ',$header;3374while(my$line=shift@commit_lines) {3375last if$lineeq"\n";3376if($line=~m/^tree ([0-9a-fA-F]{40})$/) {3377$co{'tree'} =$1;3378}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {3379push@parents,$1;3380}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {3381$co{'author'} = to_utf8($1);3382$co{'author_epoch'} =$2;3383$co{'author_tz'} =$3;3384if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {3385$co{'author_name'} =$1;3386$co{'author_email'} =$2;3387}else{3388$co{'author_name'} =$co{'author'};3389}3390}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {3391$co{'committer'} = to_utf8($1);3392$co{'committer_epoch'} =$2;3393$co{'committer_tz'} =$3;3394if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {3395$co{'committer_name'} =$1;3396$co{'committer_email'} =$2;3397}else{3398$co{'committer_name'} =$co{'committer'};3399}3400}3401}3402if(!defined$co{'tree'}) {3403return;3404};3405$co{'parents'} = \@parents;3406$co{'parent'} =$parents[0];34073408foreachmy$title(@commit_lines) {3409$title=~s/^ //;3410if($titlene"") {3411$co{'title'} = chop_str($title,80,5);3412# remove leading stuff of merges to make the interesting part visible3413if(length($title) >50) {3414$title=~s/^Automatic //;3415$title=~s/^merge (of|with) /Merge ... /i;3416if(length($title) >50) {3417$title=~s/(http|rsync):\/\///;3418}3419if(length($title) >50) {3420$title=~s/(master|www|rsync)\.//;3421}3422if(length($title) >50) {3423$title=~s/kernel.org:?//;3424}3425if(length($title) >50) {3426$title=~s/\/pub\/scm//;3427}3428}3429$co{'title_short'} = chop_str($title,50,5);3430last;3431}3432}3433if(!defined$co{'title'} ||$co{'title'}eq"") {3434$co{'title'} =$co{'title_short'} ='(no commit message)';3435}3436# remove added spaces3437foreachmy$line(@commit_lines) {3438$line=~s/^ //;3439}3440$co{'comment'} = \@commit_lines;34413442my$age=time-$co{'committer_epoch'};3443$co{'age'} =$age;3444$co{'age_string'} = age_string($age);3445my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});3446if($age>60*60*24*7*2) {3447$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3448$co{'age_string_age'} =$co{'age_string'};3449}else{3450$co{'age_string_date'} =$co{'age_string'};3451$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;3452}3453return%co;3454}34553456sub parse_commit {3457my($commit_id) =@_;3458my%co;34593460local$/="\0";34613462open my$fd,"-|", git_cmd(),"rev-list",3463"--parents",3464"--header",3465"--max-count=1",3466$commit_id,3467"--",3468or die_error(500,"Open git-rev-list failed");3469%co= parse_commit_text(<$fd>,1);3470close$fd;34713472return%co;3473}34743475sub parse_commits {3476my($commit_id,$maxcount,$skip,$filename,@args) =@_;3477my@cos;34783479$maxcount||=1;3480$skip||=0;34813482local$/="\0";34833484open my$fd,"-|", git_cmd(),"rev-list",3485"--header",3486@args,3487("--max-count=".$maxcount),3488("--skip=".$skip),3489@extra_options,3490$commit_id,3491"--",3492($filename? ($filename) : ())3493or die_error(500,"Open git-rev-list failed");3494while(my$line= <$fd>) {3495my%co= parse_commit_text($line);3496push@cos, \%co;3497}3498close$fd;34993500returnwantarray?@cos: \@cos;3501}35023503# parse line of git-diff-tree "raw" output3504sub parse_difftree_raw_line {3505my$line=shift;3506my%res;35073508# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'3509# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'3510if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {3511$res{'from_mode'} =$1;3512$res{'to_mode'} =$2;3513$res{'from_id'} =$3;3514$res{'to_id'} =$4;3515$res{'status'} =$5;3516$res{'similarity'} =$6;3517if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied3518($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);3519}else{3520$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);3521}3522}3523# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'3524# combined diff (for merge commit)3525elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {3526$res{'nparents'} =length($1);3527$res{'from_mode'} = [split(' ',$2) ];3528$res{'to_mode'} =pop@{$res{'from_mode'}};3529$res{'from_id'} = [split(' ',$3) ];3530$res{'to_id'} =pop@{$res{'from_id'}};3531$res{'status'} = [split('',$4) ];3532$res{'to_file'} = unquote($5);3533}3534# 'c512b523472485aef4fff9e57b229d9d243c967f'3535elsif($line=~m/^([0-9a-fA-F]{40})$/) {3536$res{'commit'} =$1;3537}35383539returnwantarray?%res: \%res;3540}35413542# wrapper: return parsed line of git-diff-tree "raw" output3543# (the argument might be raw line, or parsed info)3544sub parsed_difftree_line {3545my$line_or_ref=shift;35463547if(ref($line_or_ref)eq"HASH") {3548# pre-parsed (or generated by hand)3549return$line_or_ref;3550}else{3551return parse_difftree_raw_line($line_or_ref);3552}3553}35543555# parse line of git-ls-tree output3556sub parse_ls_tree_line {3557my$line=shift;3558my%opts=@_;3559my%res;35603561if($opts{'-l'}) {3562#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'3563$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;35643565$res{'mode'} =$1;3566$res{'type'} =$2;3567$res{'hash'} =$3;3568$res{'size'} =$4;3569if($opts{'-z'}) {3570$res{'name'} =$5;3571}else{3572$res{'name'} = unquote($5);3573}3574}else{3575#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'3576$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;35773578$res{'mode'} =$1;3579$res{'type'} =$2;3580$res{'hash'} =$3;3581if($opts{'-z'}) {3582$res{'name'} =$4;3583}else{3584$res{'name'} = unquote($4);3585}3586}35873588returnwantarray?%res: \%res;3589}35903591# generates _two_ hashes, references to which are passed as 2 and 3 argument3592sub parse_from_to_diffinfo {3593my($diffinfo,$from,$to,@parents) =@_;35943595if($diffinfo->{'nparents'}) {3596# combined diff3597$from->{'file'} = [];3598$from->{'href'} = [];3599 fill_from_file_info($diffinfo,@parents)3600unlessexists$diffinfo->{'from_file'};3601for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {3602$from->{'file'}[$i] =3603defined$diffinfo->{'from_file'}[$i] ?3604$diffinfo->{'from_file'}[$i] :3605$diffinfo->{'to_file'};3606if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file3607$from->{'href'}[$i] = href(action=>"blob",3608 hash_base=>$parents[$i],3609 hash=>$diffinfo->{'from_id'}[$i],3610 file_name=>$from->{'file'}[$i]);3611}else{3612$from->{'href'}[$i] =undef;3613}3614}3615}else{3616# ordinary (not combined) diff3617$from->{'file'} =$diffinfo->{'from_file'};3618if($diffinfo->{'status'}ne"A") {# not new (added) file3619$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,3620 hash=>$diffinfo->{'from_id'},3621 file_name=>$from->{'file'});3622}else{3623delete$from->{'href'};3624}3625}36263627$to->{'file'} =$diffinfo->{'to_file'};3628if(!is_deleted($diffinfo)) {# file exists in result3629$to->{'href'} = href(action=>"blob", hash_base=>$hash,3630 hash=>$diffinfo->{'to_id'},3631 file_name=>$to->{'file'});3632}else{3633delete$to->{'href'};3634}3635}36363637## ......................................................................3638## parse to array of hashes functions36393640sub git_get_heads_list {3641my($limit,@classes) =@_;3642@classes= ('heads')unless@classes;3643my@patterns=map{"refs/$_"}@classes;3644my@headslist;36453646open my$fd,'-|', git_cmd(),'for-each-ref',3647($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',3648'--format=%(objectname) %(refname) %(subject)%00%(committer)',3649@patterns3650orreturn;3651while(my$line= <$fd>) {3652my%ref_item;36533654chomp$line;3655my($refinfo,$committerinfo) =split(/\0/,$line);3656my($hash,$name,$title) =split(' ',$refinfo,3);3657my($committer,$epoch,$tz) =3658($committerinfo=~/^(.*) ([0-9]+) (.*)$/);3659$ref_item{'fullname'} =$name;3660$name=~s!^refs/(?:head|remote)s/!!;36613662$ref_item{'name'} =$name;3663$ref_item{'id'} =$hash;3664$ref_item{'title'} =$title||'(no commit message)';3665$ref_item{'epoch'} =$epoch;3666if($epoch) {3667$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3668}else{3669$ref_item{'age'} ="unknown";3670}36713672push@headslist, \%ref_item;3673}3674close$fd;36753676returnwantarray?@headslist: \@headslist;3677}36783679sub git_get_tags_list {3680my$limit=shift;3681my@tagslist;36823683open my$fd,'-|', git_cmd(),'for-each-ref',3684($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',3685'--format=%(objectname) %(objecttype) %(refname) '.3686'%(*objectname) %(*objecttype) %(subject)%00%(creator)',3687'refs/tags'3688orreturn;3689while(my$line= <$fd>) {3690my%ref_item;36913692chomp$line;3693my($refinfo,$creatorinfo) =split(/\0/,$line);3694my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);3695my($creator,$epoch,$tz) =3696($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);3697$ref_item{'fullname'} =$name;3698$name=~s!^refs/tags/!!;36993700$ref_item{'type'} =$type;3701$ref_item{'id'} =$id;3702$ref_item{'name'} =$name;3703if($typeeq"tag") {3704$ref_item{'subject'} =$title;3705$ref_item{'reftype'} =$reftype;3706$ref_item{'refid'} =$refid;3707}else{3708$ref_item{'reftype'} =$type;3709$ref_item{'refid'} =$id;3710}37113712if($typeeq"tag"||$typeeq"commit") {3713$ref_item{'epoch'} =$epoch;3714if($epoch) {3715$ref_item{'age'} = age_string(time-$ref_item{'epoch'});3716}else{3717$ref_item{'age'} ="unknown";3718}3719}37203721push@tagslist, \%ref_item;3722}3723close$fd;37243725returnwantarray?@tagslist: \@tagslist;3726}37273728## ----------------------------------------------------------------------3729## filesystem-related functions37303731sub get_file_owner {3732my$path=shift;37333734my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);3735my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);3736if(!defined$gcos) {3737returnundef;3738}3739my$owner=$gcos;3740$owner=~s/[,;].*$//;3741return to_utf8($owner);3742}37433744# assume that file exists3745sub insert_file {3746my$filename=shift;37473748open my$fd,'<',$filename;3749print map{ to_utf8($_) } <$fd>;3750close$fd;3751}37523753## ......................................................................3754## mimetype related functions37553756sub mimetype_guess_file {3757my$filename=shift;3758my$mimemap=shift;3759-r $mimemaporreturnundef;37603761my%mimemap;3762open(my$mh,'<',$mimemap)orreturnundef;3763while(<$mh>) {3764next ifm/^#/;# skip comments3765my($mimetype,@exts) =split(/\s+/);3766foreachmy$ext(@exts) {3767$mimemap{$ext} =$mimetype;3768}3769}3770close($mh);37713772$filename=~/\.([^.]*)$/;3773return$mimemap{$1};3774}37753776sub mimetype_guess {3777my$filename=shift;3778my$mime;3779$filename=~/\./orreturnundef;37803781if($mimetypes_file) {3782my$file=$mimetypes_file;3783if($file!~m!^/!) {# if it is relative path3784# it is relative to project3785$file="$projectroot/$project/$file";3786}3787$mime= mimetype_guess_file($filename,$file);3788}3789$mime||= mimetype_guess_file($filename,'/etc/mime.types');3790return$mime;3791}37923793sub blob_mimetype {3794my$fd=shift;3795my$filename=shift;37963797if($filename) {3798my$mime= mimetype_guess($filename);3799$mimeandreturn$mime;3800}38013802# just in case3803return$default_blob_plain_mimetypeunless$fd;38043805if(-T $fd) {3806return'text/plain';3807}elsif(!$filename) {3808return'application/octet-stream';3809}elsif($filename=~m/\.png$/i) {3810return'image/png';3811}elsif($filename=~m/\.gif$/i) {3812return'image/gif';3813}elsif($filename=~m/\.jpe?g$/i) {3814return'image/jpeg';3815}else{3816return'application/octet-stream';3817}3818}38193820sub blob_contenttype {3821my($fd,$file_name,$type) =@_;38223823$type||= blob_mimetype($fd,$file_name);3824if($typeeq'text/plain'&&defined$default_text_plain_charset) {3825$type.="; charset=$default_text_plain_charset";3826}38273828return$type;3829}38303831# guess file syntax for syntax highlighting; return undef if no highlighting3832# the name of syntax can (in the future) depend on syntax highlighter used3833sub guess_file_syntax {3834my($highlight,$mimetype,$file_name) =@_;3835returnundefunless($highlight&&defined$file_name);3836my$basename= basename($file_name,'.in');3837return$highlight_basename{$basename}3838ifexists$highlight_basename{$basename};38393840$basename=~/\.([^.]*)$/;3841my$ext=$1orreturnundef;3842return$highlight_ext{$ext}3843ifexists$highlight_ext{$ext};38443845returnundef;3846}38473848# run highlighter and return FD of its output,3849# or return original FD if no highlighting3850sub run_highlighter {3851my($fd,$highlight,$syntax) =@_;3852return$fdunless($highlight&&defined$syntax);38533854close$fd;3855open$fd, quote_command(git_cmd(),"cat-file","blob",$hash)." | ".3856 quote_command($highlight_bin).3857" --replace-tabs=8 --fragment --syntax$syntax|"3858or die_error(500,"Couldn't open file or run syntax highlighter");3859return$fd;3860}38613862## ======================================================================3863## functions printing HTML: header, footer, error page38643865sub get_page_title {3866my$title= to_utf8($site_name);38673868unless(defined$project) {3869if(defined$project_filter) {3870$title.=" - projects in '". esc_path($project_filter) ."'";3871}3872return$title;3873}3874$title.=" - ". to_utf8($project);38753876return$titleunless(defined$action);3877$title.="/$action";# $action is US-ASCII (7bit ASCII)38783879return$titleunless(defined$file_name);3880$title.=" - ". esc_path($file_name);3881if($actioneq"tree"&&$file_name!~ m|/$|) {3882$title.="/";3883}38843885return$title;3886}38873888sub get_content_type_html {3889# require explicit support from the UA if we are to send the page as3890# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3891# we have to do this because MSIE sometimes globs '*/*', pretending to3892# support xhtml+xml but choking when it gets what it asked for.3893if(defined$cgi->http('HTTP_ACCEPT') &&3894$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3895$cgi->Accept('application/xhtml+xml') !=0) {3896return'application/xhtml+xml';3897}else{3898return'text/html';3899}3900}39013902sub print_feed_meta {3903if(defined$project) {3904my%href_params= get_feed_info();3905if(!exists$href_params{'-title'}) {3906$href_params{'-title'} ='log';3907}39083909foreachmy$format(qw(RSS Atom)) {3910my$type=lc($format);3911my%link_attr= (3912'-rel'=>'alternate',3913'-title'=> esc_attr("$project-$href_params{'-title'} -$formatfeed"),3914'-type'=>"application/$type+xml"3915);39163917$href_params{'extra_options'} =undef;3918$href_params{'action'} =$type;3919$link_attr{'-href'} = href(%href_params);3920print"<link ".3921"rel=\"$link_attr{'-rel'}\"".3922"title=\"$link_attr{'-title'}\"".3923"href=\"$link_attr{'-href'}\"".3924"type=\"$link_attr{'-type'}\"".3925"/>\n";39263927$href_params{'extra_options'} ='--no-merges';3928$link_attr{'-href'} = href(%href_params);3929$link_attr{'-title'} .=' (no merges)';3930print"<link ".3931"rel=\"$link_attr{'-rel'}\"".3932"title=\"$link_attr{'-title'}\"".3933"href=\"$link_attr{'-href'}\"".3934"type=\"$link_attr{'-type'}\"".3935"/>\n";3936}39373938}else{3939printf('<link rel="alternate" title="%sprojects list" '.3940'href="%s" type="text/plain; charset=utf-8" />'."\n",3941 esc_attr($site_name), href(project=>undef, action=>"project_index"));3942printf('<link rel="alternate" title="%sprojects feeds" '.3943'href="%s" type="text/x-opml" />'."\n",3944 esc_attr($site_name), href(project=>undef, action=>"opml"));3945}3946}39473948sub print_header_links {3949my$status=shift;39503951# print out each stylesheet that exist, providing backwards capability3952# for those people who defined $stylesheet in a config file3953if(defined$stylesheet) {3954print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3955}else{3956foreachmy$stylesheet(@stylesheets) {3957next unless$stylesheet;3958print'<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";3959}3960}3961 print_feed_meta()3962if($statuseq'200 OK');3963if(defined$favicon) {3964printqq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);3965}3966}39673968sub print_nav_breadcrumbs_path {3969my$dirprefix=undef;3970while(my$part=shift) {3971$dirprefix.="/"ifdefined$dirprefix;3972$dirprefix.=$part;3973print$cgi->a({-href => href(project =>undef,3974 project_filter =>$dirprefix,3975 action =>"project_list")},3976 esc_html($part)) ." / ";3977}3978}39793980sub print_nav_breadcrumbs {3981my%opts=@_;39823983print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3984if(defined$project) {3985my@dirname=split'/',$project;3986my$projectbasename=pop@dirname;3987 print_nav_breadcrumbs_path(@dirname);3988print$cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));3989if(defined$action) {3990my$action_print=$action;3991if(defined$opts{-action_extra}) {3992$action_print=$cgi->a({-href => href(action=>$action)},3993$action);3994}3995print" /$action_print";3996}3997if(defined$opts{-action_extra}) {3998print" /$opts{-action_extra}";3999}4000print"\n";4001}elsif(defined$project_filter) {4002 print_nav_breadcrumbs_path(split'/',$project_filter);4003}4004}40054006sub print_search_form {4007if(!defined$searchtext) {4008$searchtext="";4009}4010my$search_hash;4011if(defined$hash_base) {4012$search_hash=$hash_base;4013}elsif(defined$hash) {4014$search_hash=$hash;4015}else{4016$search_hash="HEAD";4017}4018my$action=$my_uri;4019my$use_pathinfo= gitweb_check_feature('pathinfo');4020if($use_pathinfo) {4021$action.="/".esc_url($project);4022}4023print$cgi->startform(-method=>"get", -action =>$action) .4024"<div class=\"search\">\n".4025(!$use_pathinfo&&4026$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .4027$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".4028$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".4029$cgi->popup_menu(-name =>'st', -default=>'commit',4030-values=> ['commit','grep','author','committer','pickaxe']) .4031$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .4032" search:\n",4033$cgi->textfield(-name =>"s", -value =>$searchtext, -override =>1) ."\n".4034"<span title=\"Extended regular expression\">".4035$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',4036-checked =>$search_use_regexp) .4037"</span>".4038"</div>".4039$cgi->end_form() ."\n";4040}40414042sub git_header_html {4043my$status=shift||"200 OK";4044my$expires=shift;4045my%opts=@_;40464047my$title= get_page_title();4048my$content_type= get_content_type_html();4049print$cgi->header(-type=>$content_type, -charset =>'utf-8',4050-status=>$status, -expires =>$expires)4051unless($opts{'-no_http_header'});4052my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';4053print<<EOF;4054<?xml version="1.0" encoding="utf-8"?>4055<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4056<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">4057<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->4058<!-- git core binaries version$git_version-->4059<head>4060<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>4061<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>4062<meta name="robots" content="index, nofollow"/>4063<title>$title</title>4064EOF4065# the stylesheet, favicon etc urls won't work correctly with path_info4066# unless we set the appropriate base URL4067if($ENV{'PATH_INFO'}) {4068print"<base href=\"".esc_url($base_url)."\"/>\n";4069}4070 print_header_links($status);40714072if(defined$site_html_head_string) {4073print to_utf8($site_html_head_string);4074}40754076print"</head>\n".4077"<body>\n";40784079if(defined$site_header&& -f $site_header) {4080 insert_file($site_header);4081}40824083print"<div class=\"page_header\">\n";4084if(defined$logo) {4085print$cgi->a({-href => esc_url($logo_url),4086-title =>$logo_label},4087$cgi->img({-src => esc_url($logo),4088-width =>72, -height =>27,4089-alt =>"git",4090-class=>"logo"}));4091}4092 print_nav_breadcrumbs(%opts);4093print"</div>\n";40944095my$have_search= gitweb_check_feature('search');4096if(defined$project&&$have_search) {4097 print_search_form();4098}4099}41004101sub git_footer_html {4102my$feed_class='rss_logo';41034104print"<div class=\"page_footer\">\n";4105if(defined$project) {4106my$descr= git_get_project_description($project);4107if(defined$descr) {4108print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";4109}41104111my%href_params= get_feed_info();4112if(!%href_params) {4113$feed_class.=' generic';4114}4115$href_params{'-title'} ||='log';41164117foreachmy$format(qw(RSS Atom)) {4118$href_params{'action'} =lc($format);4119print$cgi->a({-href => href(%href_params),4120-title =>"$href_params{'-title'}$formatfeed",4121-class=>$feed_class},$format)."\n";4122}41234124}else{4125print$cgi->a({-href => href(project=>undef, action=>"opml",4126 project_filter =>$project_filter),4127-class=>$feed_class},"OPML") ." ";4128print$cgi->a({-href => href(project=>undef, action=>"project_index",4129 project_filter =>$project_filter),4130-class=>$feed_class},"TXT") ."\n";4131}4132print"</div>\n";# class="page_footer"41334134if(defined$t0&& gitweb_check_feature('timed')) {4135print"<div id=\"generating_info\">\n";4136print'This page took '.4137'<span id="generating_time" class="time_span">'.4138 tv_interval($t0, [ gettimeofday() ]).4139' seconds </span>'.4140' and '.4141'<span id="generating_cmd">'.4142$number_of_git_cmds.4143'</span> git commands '.4144" to generate.\n";4145print"</div>\n";# class="page_footer"4146}41474148if(defined$site_footer&& -f $site_footer) {4149 insert_file($site_footer);4150}41514152print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;4153if(defined$action&&4154$actioneq'blame_incremental') {4155print qq!<script type="text/javascript">\n!.4156 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.4157 qq!"!. href() .qq!");\n!.4158 qq!</script>\n!;4159}else{4160my($jstimezone,$tz_cookie,$datetime_class) =4161 gitweb_get_feature('javascript-timezone');41624163print qq!<script type="text/javascript">\n!.4164 qq!window.onload = function () {\n!;4165if(gitweb_check_feature('javascript-actions')) {4166print qq! fixLinks();\n!;4167}4168if($jstimezone&&$tz_cookie&&$datetime_class) {4169print qq! var tz_cookie = { name:'$tz_cookie', expires:14, path:'/'};\n!.# in days4170 qq! onloadTZSetup('$jstimezone', tz_cookie,'$datetime_class');\n!;4171}4172print qq!};\n!.4173 qq!</script>\n!;4174}41754176print"</body>\n".4177"</html>";4178}41794180# die_error(<http_status_code>, <error_message>[, <detailed_html_description>])4181# Example: die_error(404, 'Hash not found')4182# By convention, use the following status codes (as defined in RFC 2616):4183# 400: Invalid or missing CGI parameters, or4184# requested object exists but has wrong type.4185# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on4186# this server or project.4187# 404: Requested object/revision/project doesn't exist.4188# 500: The server isn't configured properly, or4189# an internal error occurred (e.g. failed assertions caused by bugs), or4190# an unknown error occurred (e.g. the git binary died unexpectedly).4191# 503: The server is currently unavailable (because it is overloaded,4192# or down for maintenance). Generally, this is a temporary state.4193sub die_error {4194my$status=shift||500;4195my$error= esc_html(shift) ||"Internal Server Error";4196my$extra=shift;4197my%opts=@_;41984199my%http_responses= (4200400=>'400 Bad Request',4201403=>'403 Forbidden',4202404=>'404 Not Found',4203500=>'500 Internal Server Error',4204503=>'503 Service Unavailable',4205);4206 git_header_html($http_responses{$status},undef,%opts);4207print<<EOF;4208<div class="page_body">4209<br /><br />4210$status-$error4211<br />4212EOF4213if(defined$extra) {4214print"<hr />\n".4215"$extra\n";4216}4217print"</div>\n";42184219 git_footer_html();4220goto DONE_GITWEB4221unless($opts{'-error_handler'});4222}42234224## ----------------------------------------------------------------------4225## functions printing or outputting HTML: navigation42264227sub git_print_page_nav {4228my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;4229$extra=''if!defined$extra;# pager or formats42304231my@navs=qw(summary shortlog log commit commitdiff tree);4232if($suppress) {4233@navs=grep{$_ne$suppress}@navs;4234}42354236my%arg=map{$_=> {action=>$_} }@navs;4237if(defined$head) {4238for(qw(commit commitdiff)) {4239$arg{$_}{'hash'} =$head;4240}4241if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {4242for(qw(shortlog log)) {4243$arg{$_}{'hash'} =$head;4244}4245}4246}42474248$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;4249$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;42504251my@actions= gitweb_get_feature('actions');4252my%repl= (4253'%'=>'%',4254'n'=>$project,# project name4255'f'=>$git_dir,# project path within filesystem4256'h'=>$treehead||'',# current hash ('h' parameter)4257'b'=>$treebase||'',# hash base ('hb' parameter)4258);4259while(@actions) {4260my($label,$link,$pos) =splice(@actions,0,3);4261# insert4262@navs=map{$_eq$pos? ($_,$label) :$_}@navs;4263# munch munch4264$link=~s/%([%nfhb])/$repl{$1}/g;4265$arg{$label}{'_href'} =$link;4266}42674268print"<div class=\"page_nav\">\n".4269(join" | ",4270map{$_eq$current?4271$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")4272}@navs);4273print"<br/>\n$extra<br/>\n".4274"</div>\n";4275}42764277# returns a submenu for the nagivation of the refs views (tags, heads,4278# remotes) with the current view disabled and the remotes view only4279# available if the feature is enabled4280sub format_ref_views {4281my($current) =@_;4282my@ref_views=qw{tags heads};4283push@ref_views,'remotes'if gitweb_check_feature('remote_heads');4284returnjoin" | ",map{4285$_eq$current?$_:4286$cgi->a({-href => href(action=>$_)},$_)4287}@ref_views4288}42894290sub format_paging_nav {4291my($action,$page,$has_next_link) =@_;4292my$paging_nav;429342944295if($page>0) {4296$paging_nav.=4297$cgi->a({-href => href(-replay=>1, page=>undef)},"first") .4298" ⋅ ".4299$cgi->a({-href => href(-replay=>1, page=>$page-1),4300-accesskey =>"p", -title =>"Alt-p"},"prev");4301}else{4302$paging_nav.="first ⋅ prev";4303}43044305if($has_next_link) {4306$paging_nav.=" ⋅ ".4307$cgi->a({-href => href(-replay=>1, page=>$page+1),4308-accesskey =>"n", -title =>"Alt-n"},"next");4309}else{4310$paging_nav.=" ⋅ next";4311}43124313return$paging_nav;4314}43154316## ......................................................................4317## functions printing or outputting HTML: div43184319sub git_print_header_div {4320my($action,$title,$hash,$hash_base) =@_;4321my%args= ();43224323$args{'action'} =$action;4324$args{'hash'} =$hashif$hash;4325$args{'hash_base'} =$hash_baseif$hash_base;43264327print"<div class=\"header\">\n".4328$cgi->a({-href => href(%args), -class=>"title"},4329$title?$title:$action) .4330"\n</div>\n";4331}43324333sub format_repo_url {4334my($name,$url) =@_;4335return"<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";4336}43374338# Group output by placing it in a DIV element and adding a header.4339# Options for start_div() can be provided by passing a hash reference as the4340# first parameter to the function.4341# Options to git_print_header_div() can be provided by passing an array4342# reference. This must follow the options to start_div if they are present.4343# The content can be a scalar, which is output as-is, a scalar reference, which4344# is output after html escaping, an IO handle passed either as *handle or4345# *handle{IO}, or a function reference. In the latter case all following4346# parameters will be taken as argument to the content function call.4347sub git_print_section {4348my($div_args,$header_args,$content);4349my$arg=shift;4350if(ref($arg)eq'HASH') {4351$div_args=$arg;4352$arg=shift;4353}4354if(ref($arg)eq'ARRAY') {4355$header_args=$arg;4356$arg=shift;4357}4358$content=$arg;43594360print$cgi->start_div($div_args);4361 git_print_header_div(@$header_args);43624363if(ref($content)eq'CODE') {4364$content->(@_);4365}elsif(ref($content)eq'SCALAR') {4366print esc_html($$content);4367}elsif(ref($content)eq'GLOB'or ref($content)eq'IO::Handle') {4368print<$content>;4369}elsif(!ref($content) &&defined($content)) {4370print$content;4371}43724373print$cgi->end_div;4374}43754376sub format_timestamp_html {4377my$date=shift;4378my$strtime=$date->{'rfc2822'};43794380my(undef,undef,$datetime_class) =4381 gitweb_get_feature('javascript-timezone');4382if($datetime_class) {4383$strtime= qq!<span class="$datetime_class">$strtime</span>!;4384}43854386my$localtime_format='(%02d:%02d%s)';4387if($date->{'hour_local'} <6) {4388$localtime_format='(<span class="atnight">%02d:%02d</span>%s)';4389}4390$strtime.=' '.4391sprintf($localtime_format,4392$date->{'hour_local'},$date->{'minute_local'},$date->{'tz_local'});43934394return$strtime;4395}43964397# Outputs the author name and date in long form4398sub git_print_authorship {4399my$co=shift;4400my%opts=@_;4401my$tag=$opts{-tag} ||'div';4402my$author=$co->{'author_name'};44034404my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});4405print"<$tagclass=\"author_date\">".4406 format_search_author($author,"author", esc_html($author)) .4407" [".format_timestamp_html(\%ad)."]".4408 git_get_avatar($co->{'author_email'}, -pad_before =>1) .4409"</$tag>\n";4410}44114412# Outputs table rows containing the full author or committer information,4413# in the format expected for 'commit' view (& similar).4414# Parameters are a commit hash reference, followed by the list of people4415# to output information for. If the list is empty it defaults to both4416# author and committer.4417sub git_print_authorship_rows {4418my$co=shift;4419# too bad we can't use @people = @_ || ('author', 'committer')4420my@people=@_;4421@people= ('author','committer')unless@people;4422foreachmy$who(@people) {4423my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});4424print"<tr><td>$who</td><td>".4425 format_search_author($co->{"${who}_name"},$who,4426 esc_html($co->{"${who}_name"})) ." ".4427 format_search_author($co->{"${who}_email"},$who,4428 esc_html("<".$co->{"${who}_email"} .">")) .4429"</td><td rowspan=\"2\">".4430 git_get_avatar($co->{"${who}_email"}, -size =>'double') .4431"</td></tr>\n".4432"<tr>".4433"<td></td><td>".4434 format_timestamp_html(\%wd) .4435"</td>".4436"</tr>\n";4437}4438}44394440sub git_print_page_path {4441my$name=shift;4442my$type=shift;4443my$hb=shift;444444454446print"<div class=\"page_path\">";4447print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),4448-title =>'tree root'}, to_utf8("[$project]"));4449print" / ";4450if(defined$name) {4451my@dirname=split'/',$name;4452my$basename=pop@dirname;4453my$fullname='';44544455foreachmy$dir(@dirname) {4456$fullname.= ($fullname?'/':'') .$dir;4457print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,4458 hash_base=>$hb),4459-title =>$fullname}, esc_path($dir));4460print" / ";4461}4462if(defined$type&&$typeeq'blob') {4463print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,4464 hash_base=>$hb),4465-title =>$name}, esc_path($basename));4466}elsif(defined$type&&$typeeq'tree') {4467print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,4468 hash_base=>$hb),4469-title =>$name}, esc_path($basename));4470print" / ";4471}else{4472print esc_path($basename);4473}4474}4475print"<br/></div>\n";4476}44774478sub git_print_log {4479my$log=shift;4480my%opts=@_;44814482if($opts{'-remove_title'}) {4483# remove title, i.e. first line of log4484shift@$log;4485}4486# remove leading empty lines4487while(defined$log->[0] &&$log->[0]eq"") {4488shift@$log;4489}44904491# print log4492my$skip_blank_line=0;4493foreachmy$line(@$log) {4494if($line=~m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {4495if(!$opts{'-remove_signoff'}) {4496print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";4497$skip_blank_line=1;4498}4499next;4500}45014502if($line=~ m,\s*([a-z]*link): (https?://\S+),i) {4503if(!$opts{'-remove_signoff'}) {4504print"<span class=\"signoff\">". esc_html($1) .": ".4505"<a href=\"". esc_html($2) ."\">". esc_html($2) ."</a>".4506"</span><br/>\n";4507$skip_blank_line=1;4508}4509next;4510}45114512# print only one empty line4513# do not print empty line after signoff4514if($lineeq"") {4515next if($skip_blank_line);4516$skip_blank_line=1;4517}else{4518$skip_blank_line=0;4519}45204521print format_log_line_html($line) ."<br/>\n";4522}45234524if($opts{'-final_empty_line'}) {4525# end with single empty line4526print"<br/>\n"unless$skip_blank_line;4527}4528}45294530# return link target (what link points to)4531sub git_get_link_target {4532my$hash=shift;4533my$link_target;45344535# read link4536open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4537orreturn;4538{4539local$/=undef;4540$link_target= <$fd>;4541}4542close$fd4543orreturn;45444545return$link_target;4546}45474548# given link target, and the directory (basedir) the link is in,4549# return target of link relative to top directory (top tree);4550# return undef if it is not possible (including absolute links).4551sub normalize_link_target {4552my($link_target,$basedir) =@_;45534554# absolute symlinks (beginning with '/') cannot be normalized4555return if(substr($link_target,0,1)eq'/');45564557# normalize link target to path from top (root) tree (dir)4558my$path;4559if($basedir) {4560$path=$basedir.'/'.$link_target;4561}else{4562# we are in top (root) tree (dir)4563$path=$link_target;4564}45654566# remove //, /./, and /../4567my@path_parts;4568foreachmy$part(split('/',$path)) {4569# discard '.' and ''4570next if(!$part||$parteq'.');4571# handle '..'4572if($parteq'..') {4573if(@path_parts) {4574pop@path_parts;4575}else{4576# link leads outside repository (outside top dir)4577return;4578}4579}else{4580push@path_parts,$part;4581}4582}4583$path=join('/',@path_parts);45844585return$path;4586}45874588# print tree entry (row of git_tree), but without encompassing <tr> element4589sub git_print_tree_entry {4590my($t,$basedir,$hash_base,$have_blame) =@_;45914592my%base_key= ();4593$base_key{'hash_base'} =$hash_baseifdefined$hash_base;45944595# The format of a table row is: mode list link. Where mode is4596# the mode of the entry, list is the name of the entry, an href,4597# and link is the action links of the entry.45984599print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";4600if(exists$t->{'size'}) {4601print"<td class=\"size\">$t->{'size'}</td>\n";4602}4603if($t->{'type'}eq"blob") {4604print"<td class=\"list\">".4605$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4606 file_name=>"$basedir$t->{'name'}",%base_key),4607-class=>"list"}, esc_path($t->{'name'}));4608if(S_ISLNK(oct$t->{'mode'})) {4609my$link_target= git_get_link_target($t->{'hash'});4610if($link_target) {4611my$norm_target= normalize_link_target($link_target,$basedir);4612if(defined$norm_target) {4613print" -> ".4614$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,4615 file_name=>$norm_target),4616-title =>$norm_target}, esc_path($link_target));4617}else{4618print" -> ". esc_path($link_target);4619}4620}4621}4622print"</td>\n";4623print"<td class=\"link\">";4624print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},4625 file_name=>"$basedir$t->{'name'}",%base_key)},4626"blob");4627if($have_blame) {4628print" | ".4629$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},4630 file_name=>"$basedir$t->{'name'}",%base_key)},4631"blame");4632}4633if(defined$hash_base) {4634print" | ".4635$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4636 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},4637"history");4638}4639print" | ".4640$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,4641 file_name=>"$basedir$t->{'name'}")},4642"raw");4643print"</td>\n";46444645}elsif($t->{'type'}eq"tree") {4646print"<td class=\"list\">";4647print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4648 file_name=>"$basedir$t->{'name'}",4649%base_key)},4650 esc_path($t->{'name'}));4651print"</td>\n";4652print"<td class=\"link\">";4653print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},4654 file_name=>"$basedir$t->{'name'}",4655%base_key)},4656"tree");4657if(defined$hash_base) {4658print" | ".4659$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,4660 file_name=>"$basedir$t->{'name'}")},4661"history");4662}4663print"</td>\n";4664}else{4665# unknown object: we can only present history for it4666# (this includes 'commit' object, i.e. submodule support)4667print"<td class=\"list\">".4668 esc_path($t->{'name'}) .4669"</td>\n";4670print"<td class=\"link\">";4671if(defined$hash_base) {4672print$cgi->a({-href => href(action=>"history",4673 hash_base=>$hash_base,4674 file_name=>"$basedir$t->{'name'}")},4675"history");4676}4677print"</td>\n";4678}4679}46804681## ......................................................................4682## functions printing large fragments of HTML46834684# get pre-image filenames for merge (combined) diff4685sub fill_from_file_info {4686my($diff,@parents) =@_;46874688$diff->{'from_file'} = [ ];4689$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;4690for(my$i=0;$i<$diff->{'nparents'};$i++) {4691if($diff->{'status'}[$i]eq'R'||4692$diff->{'status'}[$i]eq'C') {4693$diff->{'from_file'}[$i] =4694 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);4695}4696}46974698return$diff;4699}47004701# is current raw difftree line of file deletion4702sub is_deleted {4703my$diffinfo=shift;47044705return$diffinfo->{'to_id'}eq('0' x 40);4706}47074708# does patch correspond to [previous] difftree raw line4709# $diffinfo - hashref of parsed raw diff format4710# $patchinfo - hashref of parsed patch diff format4711# (the same keys as in $diffinfo)4712sub is_patch_split {4713my($diffinfo,$patchinfo) =@_;47144715returndefined$diffinfo&&defined$patchinfo4716&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};4717}471847194720sub git_difftree_body {4721my($difftree,$hash,@parents) =@_;4722my($parent) =$parents[0];4723my$have_blame= gitweb_check_feature('blame');4724print"<div class=\"list_head\">\n";4725if($#{$difftree} >10) {4726print(($#{$difftree} +1) ." files changed:\n");4727}4728print"</div>\n";47294730print"<table class=\"".4731(@parents>1?"combined ":"") .4732"diff_tree\">\n";47334734# header only for combined diff in 'commitdiff' view4735my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';4736if($has_header) {4737# table header4738print"<thead><tr>\n".4739"<th></th><th></th>\n";# filename, patchN link4740for(my$i=0;$i<@parents;$i++) {4741my$par=$parents[$i];4742print"<th>".4743$cgi->a({-href => href(action=>"commitdiff",4744 hash=>$hash, hash_parent=>$par),4745-title =>'commitdiff to parent number '.4746($i+1) .': '.substr($par,0,7)},4747$i+1) .4748" </th>\n";4749}4750print"</tr></thead>\n<tbody>\n";4751}47524753my$alternate=1;4754my$patchno=0;4755foreachmy$line(@{$difftree}) {4756my$diff= parsed_difftree_line($line);47574758if($alternate) {4759print"<tr class=\"dark\">\n";4760}else{4761print"<tr class=\"light\">\n";4762}4763$alternate^=1;47644765if(exists$diff->{'nparents'}) {# combined diff47664767 fill_from_file_info($diff,@parents)4768unlessexists$diff->{'from_file'};47694770if(!is_deleted($diff)) {4771# file exists in the result (child) commit4772print"<td>".4773$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4774 file_name=>$diff->{'to_file'},4775 hash_base=>$hash),4776-class=>"list"}, esc_path($diff->{'to_file'})) .4777"</td>\n";4778}else{4779print"<td>".4780 esc_path($diff->{'to_file'}) .4781"</td>\n";4782}47834784if($actioneq'commitdiff') {4785# link to patch4786$patchno++;4787print"<td class=\"link\">".4788$cgi->a({-href => href(-anchor=>"patch$patchno")},4789"patch") .4790" | ".4791"</td>\n";4792}47934794my$has_history=0;4795my$not_deleted=0;4796for(my$i=0;$i<$diff->{'nparents'};$i++) {4797my$hash_parent=$parents[$i];4798my$from_hash=$diff->{'from_id'}[$i];4799my$from_path=$diff->{'from_file'}[$i];4800my$status=$diff->{'status'}[$i];48014802$has_history||= ($statusne'A');4803$not_deleted||= ($statusne'D');48044805if($statuseq'A') {4806print"<td class=\"link\"align=\"right\"> | </td>\n";4807}elsif($statuseq'D') {4808print"<td class=\"link\">".4809$cgi->a({-href => href(action=>"blob",4810 hash_base=>$hash,4811 hash=>$from_hash,4812 file_name=>$from_path)},4813"blob". ($i+1)) .4814" | </td>\n";4815}else{4816if($diff->{'to_id'}eq$from_hash) {4817print"<td class=\"link nochange\">";4818}else{4819print"<td class=\"link\">";4820}4821print$cgi->a({-href => href(action=>"blobdiff",4822 hash=>$diff->{'to_id'},4823 hash_parent=>$from_hash,4824 hash_base=>$hash,4825 hash_parent_base=>$hash_parent,4826 file_name=>$diff->{'to_file'},4827 file_parent=>$from_path)},4828"diff". ($i+1)) .4829" | </td>\n";4830}4831}48324833print"<td class=\"link\">";4834if($not_deleted) {4835print$cgi->a({-href => href(action=>"blob",4836 hash=>$diff->{'to_id'},4837 file_name=>$diff->{'to_file'},4838 hash_base=>$hash)},4839"blob");4840print" | "if($has_history);4841}4842if($has_history) {4843print$cgi->a({-href => href(action=>"history",4844 file_name=>$diff->{'to_file'},4845 hash_base=>$hash)},4846"history");4847}4848print"</td>\n";48494850print"</tr>\n";4851next;# instead of 'else' clause, to avoid extra indent4852}4853# else ordinary diff48544855my($to_mode_oct,$to_mode_str,$to_file_type);4856my($from_mode_oct,$from_mode_str,$from_file_type);4857if($diff->{'to_mode'}ne('0' x 6)) {4858$to_mode_oct=oct$diff->{'to_mode'};4859if(S_ISREG($to_mode_oct)) {# only for regular file4860$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits4861}4862$to_file_type= file_type($diff->{'to_mode'});4863}4864if($diff->{'from_mode'}ne('0' x 6)) {4865$from_mode_oct=oct$diff->{'from_mode'};4866if(S_ISREG($from_mode_oct)) {# only for regular file4867$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits4868}4869$from_file_type= file_type($diff->{'from_mode'});4870}48714872if($diff->{'status'}eq"A") {# created4873my$mode_chng="<span class=\"file_status new\">[new$to_file_type";4874$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;4875$mode_chng.="]</span>";4876print"<td>";4877print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4878 hash_base=>$hash, file_name=>$diff->{'file'}),4879-class=>"list"}, esc_path($diff->{'file'}));4880print"</td>\n";4881print"<td>$mode_chng</td>\n";4882print"<td class=\"link\">";4883if($actioneq'commitdiff') {4884# link to patch4885$patchno++;4886print$cgi->a({-href => href(-anchor=>"patch$patchno")},4887"patch") .4888" | ";4889}4890print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4891 hash_base=>$hash, file_name=>$diff->{'file'})},4892"blob");4893print"</td>\n";48944895}elsif($diff->{'status'}eq"D") {# deleted4896my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";4897print"<td>";4898print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4899 hash_base=>$parent, file_name=>$diff->{'file'}),4900-class=>"list"}, esc_path($diff->{'file'}));4901print"</td>\n";4902print"<td>$mode_chng</td>\n";4903print"<td class=\"link\">";4904if($actioneq'commitdiff') {4905# link to patch4906$patchno++;4907print$cgi->a({-href => href(-anchor=>"patch$patchno")},4908"patch") .4909" | ";4910}4911print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},4912 hash_base=>$parent, file_name=>$diff->{'file'})},4913"blob") ." | ";4914if($have_blame) {4915print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,4916 file_name=>$diff->{'file'})},4917"blame") ." | ";4918}4919print$cgi->a({-href => href(action=>"history", hash_base=>$parent,4920 file_name=>$diff->{'file'})},4921"history");4922print"</td>\n";49234924}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed4925my$mode_chnge="";4926if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4927$mode_chnge="<span class=\"file_status mode_chnge\">[changed";4928if($from_file_typene$to_file_type) {4929$mode_chnge.=" from$from_file_typeto$to_file_type";4930}4931if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {4932if($from_mode_str&&$to_mode_str) {4933$mode_chnge.=" mode:$from_mode_str->$to_mode_str";4934}elsif($to_mode_str) {4935$mode_chnge.=" mode:$to_mode_str";4936}4937}4938$mode_chnge.="]</span>\n";4939}4940print"<td>";4941print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4942 hash_base=>$hash, file_name=>$diff->{'file'}),4943-class=>"list"}, esc_path($diff->{'file'}));4944print"</td>\n";4945print"<td>$mode_chnge</td>\n";4946print"<td class=\"link\">";4947if($actioneq'commitdiff') {4948# link to patch4949$patchno++;4950print$cgi->a({-href => href(-anchor=>"patch$patchno")},4951"patch") .4952" | ";4953}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {4954# "commit" view and modified file (not onlu mode changed)4955print$cgi->a({-href => href(action=>"blobdiff",4956 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},4957 hash_base=>$hash, hash_parent_base=>$parent,4958 file_name=>$diff->{'file'})},4959"diff") .4960" | ";4961}4962print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},4963 hash_base=>$hash, file_name=>$diff->{'file'})},4964"blob") ." | ";4965if($have_blame) {4966print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,4967 file_name=>$diff->{'file'})},4968"blame") ." | ";4969}4970print$cgi->a({-href => href(action=>"history", hash_base=>$hash,4971 file_name=>$diff->{'file'})},4972"history");4973print"</td>\n";49744975}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied4976my%status_name= ('R'=>'moved','C'=>'copied');4977my$nstatus=$status_name{$diff->{'status'}};4978my$mode_chng="";4979if($diff->{'from_mode'} !=$diff->{'to_mode'}) {4980# mode also for directories, so we cannot use $to_mode_str4981$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);4982}4983print"<td>".4984$cgi->a({-href => href(action=>"blob", hash_base=>$hash,4985 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),4986-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".4987"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".4988$cgi->a({-href => href(action=>"blob", hash_base=>$parent,4989 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),4990-class=>"list"}, esc_path($diff->{'from_file'})) .4991" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".4992"<td class=\"link\">";4993if($actioneq'commitdiff') {4994# link to patch4995$patchno++;4996print$cgi->a({-href => href(-anchor=>"patch$patchno")},4997"patch") .4998" | ";4999}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {5000# "commit" view and modified file (not only pure rename or copy)5001print$cgi->a({-href => href(action=>"blobdiff",5002 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},5003 hash_base=>$hash, hash_parent_base=>$parent,5004 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},5005"diff") .5006" | ";5007}5008print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},5009 hash_base=>$parent, file_name=>$diff->{'to_file'})},5010"blob") ." | ";5011if($have_blame) {5012print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,5013 file_name=>$diff->{'to_file'})},5014"blame") ." | ";5015}5016print$cgi->a({-href => href(action=>"history", hash_base=>$hash,5017 file_name=>$diff->{'to_file'})},5018"history");5019print"</td>\n";50205021}# we should not encounter Unmerged (U) or Unknown (X) status5022print"</tr>\n";5023}5024print"</tbody>"if$has_header;5025print"</table>\n";5026}50275028# Print context lines and then rem/add lines in a side-by-side manner.5029sub print_sidebyside_diff_lines {5030my($ctx,$rem,$add) =@_;50315032# print context block before add/rem block5033if(@$ctx) {5034print join'',5035'<div class="chunk_block ctx">',5036'<div class="old">',5037@$ctx,5038'</div>',5039'<div class="new">',5040@$ctx,5041'</div>',5042'</div>';5043}50445045if(!@$add) {5046# pure removal5047print join'',5048'<div class="chunk_block rem">',5049'<div class="old">',5050@$rem,5051'</div>',5052'</div>';5053}elsif(!@$rem) {5054# pure addition5055print join'',5056'<div class="chunk_block add">',5057'<div class="new">',5058@$add,5059'</div>',5060'</div>';5061}else{5062print join'',5063'<div class="chunk_block chg">',5064'<div class="old">',5065@$rem,5066'</div>',5067'<div class="new">',5068@$add,5069'</div>',5070'</div>';5071}5072}50735074# Print context lines and then rem/add lines in inline manner.5075sub print_inline_diff_lines {5076my($ctx,$rem,$add) =@_;50775078print@$ctx,@$rem,@$add;5079}50805081# Format removed and added line, mark changed part and HTML-format them.5082# Implementation is based on contrib/diff-highlight5083sub format_rem_add_lines_pair {5084my($rem,$add,$num_parents) =@_;50855086# We need to untabify lines before split()'ing them;5087# otherwise offsets would be invalid.5088chomp$rem;5089chomp$add;5090$rem= untabify($rem);5091$add= untabify($add);50925093my@rem=split(//,$rem);5094my@add=split(//,$add);5095my($esc_rem,$esc_add);5096# Ignore leading +/- characters for each parent.5097my($prefix_len,$suffix_len) = ($num_parents,0);5098my($prefix_has_nonspace,$suffix_has_nonspace);50995100my$shorter= (@rem<@add) ?@rem:@add;5101while($prefix_len<$shorter) {5102last if($rem[$prefix_len]ne$add[$prefix_len]);51035104$prefix_has_nonspace=1if($rem[$prefix_len] !~/\s/);5105$prefix_len++;5106}51075108while($prefix_len+$suffix_len<$shorter) {5109last if($rem[-1-$suffix_len]ne$add[-1-$suffix_len]);51105111$suffix_has_nonspace=1if($rem[-1-$suffix_len] !~/\s/);5112$suffix_len++;5113}51145115# Mark lines that are different from each other, but have some common5116# part that isn't whitespace. If lines are completely different, don't5117# mark them because that would make output unreadable, especially if5118# diff consists of multiple lines.5119if($prefix_has_nonspace||$suffix_has_nonspace) {5120$esc_rem= esc_html_hl_regions($rem,'marked',5121[$prefix_len,@rem-$suffix_len], -nbsp=>1);5122$esc_add= esc_html_hl_regions($add,'marked',5123[$prefix_len,@add-$suffix_len], -nbsp=>1);5124}else{5125$esc_rem= esc_html($rem, -nbsp=>1);5126$esc_add= esc_html($add, -nbsp=>1);5127}51285129return format_diff_line(\$esc_rem,'rem'),5130 format_diff_line(\$esc_add,'add');5131}51325133# HTML-format diff context, removed and added lines.5134sub format_ctx_rem_add_lines {5135my($ctx,$rem,$add,$num_parents) =@_;5136my(@new_ctx,@new_rem,@new_add);5137my$can_highlight=0;5138my$is_combined= ($num_parents>1);51395140# Highlight if every removed line has a corresponding added line.5141if(@$add>0&&@$add==@$rem) {5142$can_highlight=1;51435144# Highlight lines in combined diff only if the chunk contains5145# diff between the same version, e.g.5146#5147# - a5148# - b5149# + c5150# + d5151#5152# Otherwise the highlightling would be confusing.5153if($is_combined) {5154for(my$i=0;$i<@$add;$i++) {5155my$prefix_rem=substr($rem->[$i],0,$num_parents);5156my$prefix_add=substr($add->[$i],0,$num_parents);51575158$prefix_rem=~s/-/+/g;51595160if($prefix_remne$prefix_add) {5161$can_highlight=0;5162last;5163}5164}5165}5166}51675168if($can_highlight) {5169for(my$i=0;$i<@$add;$i++) {5170my($line_rem,$line_add) = format_rem_add_lines_pair(5171$rem->[$i],$add->[$i],$num_parents);5172push@new_rem,$line_rem;5173push@new_add,$line_add;5174}5175}else{5176@new_rem=map{ format_diff_line($_,'rem') }@$rem;5177@new_add=map{ format_diff_line($_,'add') }@$add;5178}51795180@new_ctx=map{ format_diff_line($_,'ctx') }@$ctx;51815182return(\@new_ctx, \@new_rem, \@new_add);5183}51845185# Print context lines and then rem/add lines.5186sub print_diff_lines {5187my($ctx,$rem,$add,$diff_style,$num_parents) =@_;5188my$is_combined=$num_parents>1;51895190($ctx,$rem,$add) = format_ctx_rem_add_lines($ctx,$rem,$add,5191$num_parents);51925193if($diff_styleeq'sidebyside'&& !$is_combined) {5194 print_sidebyside_diff_lines($ctx,$rem,$add);5195}else{5196# default 'inline' style and unknown styles5197 print_inline_diff_lines($ctx,$rem,$add);5198}5199}52005201sub print_diff_chunk {5202my($diff_style,$num_parents,$from,$to,@chunk) =@_;5203my(@ctx,@rem,@add);52045205# The class of the previous line.5206my$prev_class='';52075208return unless@chunk;52095210# incomplete last line might be among removed or added lines,5211# or both, or among context lines: find which5212for(my$i=1;$i<@chunk;$i++) {5213if($chunk[$i][0]eq'incomplete') {5214$chunk[$i][0] =$chunk[$i-1][0];5215}5216}52175218# guardian5219push@chunk, ["",""];52205221foreachmy$line_info(@chunk) {5222my($class,$line) =@$line_info;52235224# print chunk headers5225if($class&&$classeq'chunk_header') {5226print format_diff_line($line,$class,$from,$to);5227next;5228}52295230## print from accumulator when have some add/rem lines or end5231# of chunk (flush context lines), or when have add and rem5232# lines and new block is reached (otherwise add/rem lines could5233# be reordered)5234if(!$class|| ((@rem||@add) &&$classeq'ctx') ||5235(@rem&&@add&&$classne$prev_class)) {5236 print_diff_lines(\@ctx, \@rem, \@add,5237$diff_style,$num_parents);5238@ctx=@rem=@add= ();5239}52405241## adding lines to accumulator5242# guardian value5243last unless$line;5244# rem, add or change5245if($classeq'rem') {5246push@rem,$line;5247}elsif($classeq'add') {5248push@add,$line;5249}5250# context line5251if($classeq'ctx') {5252push@ctx,$line;5253}52545255$prev_class=$class;5256}5257}52585259sub git_patchset_body {5260my($fd,$diff_style,$difftree,$hash,@hash_parents) =@_;5261my($hash_parent) =$hash_parents[0];52625263my$is_combined= (@hash_parents>1);5264my$patch_idx=0;5265my$patch_number=0;5266my$patch_line;5267my$diffinfo;5268my$to_name;5269my(%from,%to);5270my@chunk;# for side-by-side diff52715272print"<div class=\"patchset\">\n";52735274# skip to first patch5275while($patch_line= <$fd>) {5276chomp$patch_line;52775278last if($patch_line=~m/^diff /);5279}52805281 PATCH:5282while($patch_line) {52835284# parse "git diff" header line5285if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {5286# $1 is from_name, which we do not use5287$to_name= unquote($2);5288$to_name=~s!^b/!!;5289}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {5290# $1 is 'cc' or 'combined', which we do not use5291$to_name= unquote($2);5292}else{5293$to_name=undef;5294}52955296# check if current patch belong to current raw line5297# and parse raw git-diff line if needed5298if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {5299# this is continuation of a split patch5300print"<div class=\"patch cont\">\n";5301}else{5302# advance raw git-diff output if needed5303$patch_idx++ifdefined$diffinfo;53045305# read and prepare patch information5306$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);53075308# compact combined diff output can have some patches skipped5309# find which patch (using pathname of result) we are at now;5310if($is_combined) {5311while($to_namene$diffinfo->{'to_file'}) {5312print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5313 format_diff_cc_simplified($diffinfo,@hash_parents) .5314"</div>\n";# class="patch"53155316$patch_idx++;5317$patch_number++;53185319last if$patch_idx>$#$difftree;5320$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);5321}5322}53235324# modifies %from, %to hashes5325 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);53265327# this is first patch for raw difftree line with $patch_idx index5328# we index @$difftree array from 0, but number patches from 15329print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";5330}53315332# git diff header5333#assert($patch_line =~ m/^diff /) if DEBUG;5334#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed5335$patch_number++;5336# print "git diff" header5337print format_git_diff_header_line($patch_line,$diffinfo,5338 \%from, \%to);53395340# print extended diff header5341print"<div class=\"diff extended_header\">\n";5342 EXTENDED_HEADER:5343while($patch_line= <$fd>) {5344chomp$patch_line;53455346last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);53475348print format_extended_diff_header_line($patch_line,$diffinfo,5349 \%from, \%to);5350}5351print"</div>\n";# class="diff extended_header"53525353# from-file/to-file diff header5354if(!$patch_line) {5355print"</div>\n";# class="patch"5356last PATCH;5357}5358next PATCH if($patch_line=~m/^diff /);5359#assert($patch_line =~ m/^---/) if DEBUG;53605361my$last_patch_line=$patch_line;5362$patch_line= <$fd>;5363chomp$patch_line;5364#assert($patch_line =~ m/^\+\+\+/) if DEBUG;53655366print format_diff_from_to_header($last_patch_line,$patch_line,5367$diffinfo, \%from, \%to,5368@hash_parents);53695370# the patch itself5371 LINE:5372while($patch_line= <$fd>) {5373chomp$patch_line;53745375next PATCH if($patch_line=~m/^diff /);53765377my$class= diff_line_class($patch_line, \%from, \%to);53785379if($classeq'chunk_header') {5380 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5381@chunk= ();5382}53835384push@chunk, [$class,$patch_line];5385}53865387}continue{5388if(@chunk) {5389 print_diff_chunk($diff_style,scalar@hash_parents, \%from, \%to,@chunk);5390@chunk= ();5391}5392print"</div>\n";# class="patch"5393}53945395# for compact combined (--cc) format, with chunk and patch simplification5396# the patchset might be empty, but there might be unprocessed raw lines5397for(++$patch_idxif$patch_number>0;5398$patch_idx<@$difftree;5399++$patch_idx) {5400# read and prepare patch information5401$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);54025403# generate anchor for "patch" links in difftree / whatchanged part5404print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".5405 format_diff_cc_simplified($diffinfo,@hash_parents) .5406"</div>\n";# class="patch"54075408$patch_number++;5409}54105411if($patch_number==0) {5412if(@hash_parents>1) {5413print"<div class=\"diff nodifferences\">Trivial merge</div>\n";5414}else{5415print"<div class=\"diff nodifferences\">No differences found</div>\n";5416}5417}54185419print"</div>\n";# class="patchset"5420}54215422# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54235424sub git_project_search_form {5425my($searchtext,$search_use_regexp) =@_;54265427my$limit='';5428if($project_filter) {5429$limit=" in '$project_filter/'";5430}54315432print"<div class=\"projsearch\">\n";5433print$cgi->startform(-method=>'get', -action =>$my_uri) .5434$cgi->hidden(-name =>'a', -value =>'project_list') ."\n";5435print$cgi->hidden(-name =>'pf', -value =>$project_filter)."\n"5436if(defined$project_filter);5437print$cgi->textfield(-name =>'s', -value =>$searchtext,5438-title =>"Search project by name and description$limit",5439-size =>60) ."\n".5440"<span title=\"Extended regular expression\">".5441$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',5442-checked =>$search_use_regexp) .5443"</span>\n".5444$cgi->submit(-name =>'btnS', -value =>'Search') .5445$cgi->end_form() ."\n".5446$cgi->a({-href => href(project =>undef, searchtext =>undef,5447 project_filter =>$project_filter)},5448 esc_html("List all projects$limit")) ."<br />\n";5449print"</div>\n";5450}54515452# entry for given @keys needs filling if at least one of keys in list5453# is not present in %$project_info5454sub project_info_needs_filling {5455my($project_info,@keys) =@_;54565457# return List::MoreUtils::any { !exists $project_info->{$_} } @keys;5458foreachmy$key(@keys) {5459if(!exists$project_info->{$key}) {5460return1;5461}5462}5463return;5464}54655466# fills project list info (age, description, owner, category, forks, etc.)5467# for each project in the list, removing invalid projects from5468# returned list, or fill only specified info.5469#5470# Invalid projects are removed from the returned list if and only if you5471# ask 'age' or 'age_string' to be filled, because they are the only fields5472# that run unconditionally git command that requires repository, and5473# therefore do always check if project repository is invalid.5474#5475# USAGE:5476# * fill_project_list_info(\@project_list, 'descr_long', 'ctags')5477# ensures that 'descr_long' and 'ctags' fields are filled5478# * @project_list = fill_project_list_info(\@project_list)5479# ensures that all fields are filled (and invalid projects removed)5480#5481# NOTE: modifies $projlist, but does not remove entries from it5482sub fill_project_list_info {5483my($projlist,@wanted_keys) =@_;5484my@projects;5485my$filter_set=sub{return@_; };5486if(@wanted_keys) {5487my%wanted_keys=map{$_=>1}@wanted_keys;5488$filter_set=sub{returngrep{$wanted_keys{$_} }@_; };5489}54905491my$show_ctags= gitweb_check_feature('ctags');5492 PROJECT:5493foreachmy$pr(@$projlist) {5494if(project_info_needs_filling($pr,$filter_set->('age','age_string'))) {5495my(@activity) = git_get_last_activity($pr->{'path'});5496unless(@activity) {5497next PROJECT;5498}5499($pr->{'age'},$pr->{'age_string'}) =@activity;5500}5501if(project_info_needs_filling($pr,$filter_set->('descr','descr_long'))) {5502my$descr= git_get_project_description($pr->{'path'}) ||"";5503$descr= to_utf8($descr);5504$pr->{'descr_long'} =$descr;5505$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);5506}5507if(project_info_needs_filling($pr,$filter_set->('owner'))) {5508$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";5509}5510if($show_ctags&&5511 project_info_needs_filling($pr,$filter_set->('ctags'))) {5512$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});5513}5514if($projects_list_group_categories&&5515 project_info_needs_filling($pr,$filter_set->('category'))) {5516my$cat= git_get_project_category($pr->{'path'}) ||5517$project_list_default_category;5518$pr->{'category'} = to_utf8($cat);5519}55205521push@projects,$pr;5522}55235524return@projects;5525}55265527sub sort_projects_list {5528my($projlist,$order) =@_;5529my@projects;55305531my%order_info= (5532 project => { key =>'path', type =>'str'},5533 descr => { key =>'descr_long', type =>'str'},5534 owner => { key =>'owner', type =>'str'},5535 age => { key =>'age', type =>'num'}5536);5537my$oi=$order_info{$order};5538return@$projlistunlessdefined$oi;5539if($oi->{'type'}eq'str') {5540@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@$projlist;5541}else{5542@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@$projlist;5543}55445545return@projects;5546}55475548# returns a hash of categories, containing the list of project5549# belonging to each category5550sub build_projlist_by_category {5551my($projlist,$from,$to) =@_;5552my%categories;55535554$from=0unlessdefined$from;5555$to=$#$projlistif(!defined$to||$#$projlist<$to);55565557for(my$i=$from;$i<=$to;$i++) {5558my$pr=$projlist->[$i];5559push@{$categories{$pr->{'category'} }},$pr;5560}55615562returnwantarray?%categories: \%categories;5563}55645565# print 'sort by' <th> element, generating 'sort by $name' replay link5566# if that order is not selected5567sub print_sort_th {5568print format_sort_th(@_);5569}55705571sub format_sort_th {5572my($name,$order,$header) =@_;5573my$sort_th="";5574$header||=ucfirst($name);55755576if($ordereq$name) {5577$sort_th.="<th>$header</th>\n";5578}else{5579$sort_th.="<th>".5580$cgi->a({-href => href(-replay=>1, order=>$name),5581-class=>"header"},$header) .5582"</th>\n";5583}55845585return$sort_th;5586}55875588sub git_project_list_rows {5589my($projlist,$from,$to,$check_forks) =@_;55905591$from=0unlessdefined$from;5592$to=$#$projlistif(!defined$to||$#$projlist<$to);55935594my$alternate=1;5595for(my$i=$from;$i<=$to;$i++) {5596my$pr=$projlist->[$i];55975598if($alternate) {5599print"<tr class=\"dark\">\n";5600}else{5601print"<tr class=\"light\">\n";5602}5603$alternate^=1;56045605if($check_forks) {5606print"<td>";5607if($pr->{'forks'}) {5608my$nforks=scalar@{$pr->{'forks'}};5609if($nforks>0) {5610print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),5611-title =>"$nforksforks"},"+");5612}else{5613print$cgi->span({-title =>"$nforksforks"},"+");5614}5615}5616print"</td>\n";5617}5618print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5619-class=>"list"},5620 esc_html_match_hl($pr->{'path'},$search_regexp)) .5621"</td>\n".5622"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),5623-class=>"list",5624-title =>$pr->{'descr_long'}},5625$search_regexp5626? esc_html_match_hl_chopped($pr->{'descr_long'},5627$pr->{'descr'},$search_regexp)5628: esc_html($pr->{'descr'})) .5629"</td>\n";5630unless($omit_owner) {5631print"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";5632}5633unless($omit_age_column) {5634print"<td class=\"". age_class($pr->{'age'}) ."\">".5635(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n";5636}5637print"<td class=\"link\">".5638$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".5639$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".5640$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".5641$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .5642($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .5643"</td>\n".5644"</tr>\n";5645}5646}56475648sub git_project_list_body {5649# actually uses global variable $project5650my($projlist,$order,$from,$to,$extra,$no_header) =@_;5651my@projects=@$projlist;56525653my$check_forks= gitweb_check_feature('forks');5654my$show_ctags= gitweb_check_feature('ctags');5655my$tagfilter=$show_ctags?$input_params{'ctag'} :undef;5656$check_forks=undef5657if($tagfilter||$search_regexp);56585659# filtering out forks before filling info allows to do less work5660@projects= filter_forks_from_projects_list(\@projects)5661if($check_forks);5662# search_projects_list pre-fills required info5663@projects= search_projects_list(\@projects,5664'search_regexp'=>$search_regexp,5665'tagfilter'=>$tagfilter)5666if($tagfilter||$search_regexp);5667# fill the rest5668my@all_fields= ('descr','descr_long','ctags','category');5669push@all_fields, ('age','age_string')unless($omit_age_column);5670push@all_fields,'owner'unless($omit_owner);5671@projects= fill_project_list_info(\@projects,@all_fields);56725673$order||=$default_projects_order;5674$from=0unlessdefined$from;5675$to=$#projectsif(!defined$to||$#projects<$to);56765677# short circuit5678if($from>$to) {5679print"<center>\n".5680"<b>No such projects found</b><br />\n".5681"Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".5682"</center>\n<br />\n";5683return;5684}56855686@projects= sort_projects_list(\@projects,$order);56875688if($show_ctags) {5689my$ctags= git_gather_all_ctags(\@projects);5690my$cloud= git_populate_project_tagcloud($ctags);5691print git_show_project_tagcloud($cloud,64);5692}56935694print"<table class=\"project_list\">\n";5695unless($no_header) {5696print"<tr>\n";5697if($check_forks) {5698print"<th></th>\n";5699}5700 print_sort_th('project',$order,'Project');5701 print_sort_th('descr',$order,'Description');5702 print_sort_th('owner',$order,'Owner')unless$omit_owner;5703 print_sort_th('age',$order,'Last Change')unless$omit_age_column;5704print"<th></th>\n".# for links5705"</tr>\n";5706}57075708if($projects_list_group_categories) {5709# only display categories with projects in the $from-$to window5710@projects=sort{$a->{'category'}cmp$b->{'category'}}@projects[$from..$to];5711my%categories= build_projlist_by_category(\@projects,$from,$to);5712foreachmy$cat(sort keys%categories) {5713unless($cateq"") {5714print"<tr>\n";5715if($check_forks) {5716print"<td></td>\n";5717}5718print"<td class=\"category\"colspan=\"5\">".esc_html($cat)."</td>\n";5719print"</tr>\n";5720}57215722 git_project_list_rows($categories{$cat},undef,undef,$check_forks);5723}5724}else{5725 git_project_list_rows(\@projects,$from,$to,$check_forks);5726}57275728if(defined$extra) {5729print"<tr>\n";5730if($check_forks) {5731print"<td></td>\n";5732}5733print"<td colspan=\"5\">$extra</td>\n".5734"</tr>\n";5735}5736print"</table>\n";5737}57385739sub git_log_body {5740# uses global variable $project5741my($commitlist,$from,$to,$refs,$extra) =@_;57425743$from=0unlessdefined$from;5744$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57455746for(my$i=0;$i<=$to;$i++) {5747my%co= %{$commitlist->[$i]};5748next if!%co;5749my$commit=$co{'id'};5750my$ref= format_ref_marker($refs,$commit);5751 git_print_header_div('commit',5752"<span class=\"age\">$co{'age_string'}</span>".5753 esc_html($co{'title'}) .$ref,5754$commit);5755print"<div class=\"title_text\">\n".5756"<div class=\"log_link\">\n".5757$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5758" | ".5759$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5760" | ".5761$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5762"<br/>\n".5763"</div>\n";5764 git_print_authorship(\%co, -tag =>'span');5765print"<br/>\n</div>\n";57665767print"<div class=\"log_body\">\n";5768 git_print_log($co{'comment'}, -final_empty_line=>1);5769print"</div>\n";5770}5771if($extra) {5772print"<div class=\"page_nav\">\n";5773print"$extra\n";5774print"</div>\n";5775}5776}57775778sub git_shortlog_body {5779# uses global variable $project5780my($commitlist,$from,$to,$refs,$extra) =@_;57815782$from=0unlessdefined$from;5783$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);57845785print"<table class=\"shortlog\">\n";5786my$alternate=1;5787for(my$i=$from;$i<=$to;$i++) {5788my%co= %{$commitlist->[$i]};5789my$commit=$co{'id'};5790my$ref= format_ref_marker($refs,$commit);5791if($alternate) {5792print"<tr class=\"dark\">\n";5793}else{5794print"<tr class=\"light\">\n";5795}5796$alternate^=1;5797# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .5798print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5799 format_author_html('td', \%co,10) ."<td>";5800print format_subject_html($co{'title'},$co{'title_short'},5801 href(action=>"commit", hash=>$commit),$ref);5802print"</td>\n".5803"<td class=\"link\">".5804$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".5805$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".5806$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");5807my$snapshot_links= format_snapshot_links($commit);5808if(defined$snapshot_links) {5809print" | ".$snapshot_links;5810}5811print"</td>\n".5812"</tr>\n";5813}5814if(defined$extra) {5815print"<tr>\n".5816"<td colspan=\"4\">$extra</td>\n".5817"</tr>\n";5818}5819print"</table>\n";5820}58215822sub git_history_body {5823# Warning: assumes constant type (blob or tree) during history5824my($commitlist,$from,$to,$refs,$extra,5825$file_name,$file_hash,$ftype) =@_;58265827$from=0unlessdefined$from;5828$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});58295830print"<table class=\"history\">\n";5831my$alternate=1;5832for(my$i=$from;$i<=$to;$i++) {5833my%co= %{$commitlist->[$i]};5834if(!%co) {5835next;5836}5837my$commit=$co{'id'};58385839my$ref= format_ref_marker($refs,$commit);58405841if($alternate) {5842print"<tr class=\"dark\">\n";5843}else{5844print"<tr class=\"light\">\n";5845}5846$alternate^=1;5847print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5848# shortlog: format_author_html('td', \%co, 10)5849 format_author_html('td', \%co,15,3) ."<td>";5850# originally git_history used chop_str($co{'title'}, 50)5851print format_subject_html($co{'title'},$co{'title_short'},5852 href(action=>"commit", hash=>$commit),$ref);5853print"</td>\n".5854"<td class=\"link\">".5855$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".5856$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");58575858if($ftypeeq'blob') {5859my$blob_current=$file_hash;5860my$blob_parent= git_get_hash_by_path($commit,$file_name);5861if(defined$blob_current&&defined$blob_parent&&5862$blob_currentne$blob_parent) {5863print" | ".5864$cgi->a({-href => href(action=>"blobdiff",5865 hash=>$blob_current, hash_parent=>$blob_parent,5866 hash_base=>$hash_base, hash_parent_base=>$commit,5867 file_name=>$file_name)},5868"diff to current");5869}5870}5871print"</td>\n".5872"</tr>\n";5873}5874if(defined$extra) {5875print"<tr>\n".5876"<td colspan=\"4\">$extra</td>\n".5877"</tr>\n";5878}5879print"</table>\n";5880}58815882sub git_tags_body {5883# uses global variable $project5884my($taglist,$from,$to,$extra) =@_;5885$from=0unlessdefined$from;5886$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);58875888print"<table class=\"tags\">\n";5889my$alternate=1;5890for(my$i=$from;$i<=$to;$i++) {5891my$entry=$taglist->[$i];5892my%tag=%$entry;5893my$comment=$tag{'subject'};5894my$comment_short;5895if(defined$comment) {5896$comment_short= chop_str($comment,30,5);5897}5898if($alternate) {5899print"<tr class=\"dark\">\n";5900}else{5901print"<tr class=\"light\">\n";5902}5903$alternate^=1;5904if(defined$tag{'age'}) {5905print"<td><i>$tag{'age'}</i></td>\n";5906}else{5907print"<td></td>\n";5908}5909print"<td>".5910$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),5911-class=>"list name"}, esc_html($tag{'name'})) .5912"</td>\n".5913"<td>";5914if(defined$comment) {5915print format_subject_html($comment,$comment_short,5916 href(action=>"tag", hash=>$tag{'id'}));5917}5918print"</td>\n".5919"<td class=\"selflink\">";5920if($tag{'type'}eq"tag") {5921print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");5922}else{5923print" ";5924}5925print"</td>\n".5926"<td class=\"link\">"." | ".5927$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});5928if($tag{'reftype'}eq"commit") {5929print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .5930" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");5931}elsif($tag{'reftype'}eq"blob") {5932print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");5933}5934print"</td>\n".5935"</tr>";5936}5937if(defined$extra) {5938print"<tr>\n".5939"<td colspan=\"5\">$extra</td>\n".5940"</tr>\n";5941}5942print"</table>\n";5943}59445945sub git_heads_body {5946# uses global variable $project5947my($headlist,$head_at,$from,$to,$extra) =@_;5948$from=0unlessdefined$from;5949$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);59505951print"<table class=\"heads\">\n";5952my$alternate=1;5953for(my$i=$from;$i<=$to;$i++) {5954my$entry=$headlist->[$i];5955my%ref=%$entry;5956my$curr=defined$head_at&&$ref{'id'}eq$head_at;5957if($alternate) {5958print"<tr class=\"dark\">\n";5959}else{5960print"<tr class=\"light\">\n";5961}5962$alternate^=1;5963print"<td><i>$ref{'age'}</i></td>\n".5964($curr?"<td class=\"current_head\">":"<td>") .5965$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),5966-class=>"list name"},esc_html($ref{'name'})) .5967"</td>\n".5968"<td class=\"link\">".5969$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".5970$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".5971$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})},"tree") .5972"</td>\n".5973"</tr>";5974}5975if(defined$extra) {5976print"<tr>\n".5977"<td colspan=\"3\">$extra</td>\n".5978"</tr>\n";5979}5980print"</table>\n";5981}59825983# Display a single remote block5984sub git_remote_block {5985my($remote,$rdata,$limit,$head) =@_;59865987my$heads=$rdata->{'heads'};5988my$fetch=$rdata->{'fetch'};5989my$push=$rdata->{'push'};59905991my$urls_table="<table class=\"projects_list\">\n";59925993if(defined$fetch) {5994if($fetcheq$push) {5995$urls_table.= format_repo_url("URL",$fetch);5996}else{5997$urls_table.= format_repo_url("Fetch URL",$fetch);5998$urls_table.= format_repo_url("Push URL",$push)ifdefined$push;5999}6000}elsif(defined$push) {6001$urls_table.= format_repo_url("Push URL",$push);6002}else{6003$urls_table.= format_repo_url("","No remote URL");6004}60056006$urls_table.="</table>\n";60076008my$dots;6009if(defined$limit&&$limit<@$heads) {6010$dots=$cgi->a({-href => href(action=>"remotes", hash=>$remote)},"...");6011}60126013print$urls_table;6014 git_heads_body($heads,$head,0,$limit,$dots);6015}60166017# Display a list of remote names with the respective fetch and push URLs6018sub git_remotes_list {6019my($remotedata,$limit) =@_;6020print"<table class=\"heads\">\n";6021my$alternate=1;6022my@remotes=sort keys%$remotedata;60236024my$limited=$limit&&$limit<@remotes;60256026$#remotes=$limit-1if$limited;60276028while(my$remote=shift@remotes) {6029my$rdata=$remotedata->{$remote};6030my$fetch=$rdata->{'fetch'};6031my$push=$rdata->{'push'};6032if($alternate) {6033print"<tr class=\"dark\">\n";6034}else{6035print"<tr class=\"light\">\n";6036}6037$alternate^=1;6038print"<td>".6039$cgi->a({-href=> href(action=>'remotes', hash=>$remote),6040-class=>"list name"},esc_html($remote)) .6041"</td>";6042print"<td class=\"link\">".6043(defined$fetch?$cgi->a({-href=>$fetch},"fetch") :"fetch") .6044" | ".6045(defined$push?$cgi->a({-href=>$push},"push") :"push") .6046"</td>";60476048print"</tr>\n";6049}60506051if($limited) {6052print"<tr>\n".6053"<td colspan=\"3\">".6054$cgi->a({-href => href(action=>"remotes")},"...") .6055"</td>\n"."</tr>\n";6056}60576058print"</table>";6059}60606061# Display remote heads grouped by remote, unless there are too many6062# remotes, in which case we only display the remote names6063sub git_remotes_body {6064my($remotedata,$limit,$head) =@_;6065if($limitand$limit<keys%$remotedata) {6066 git_remotes_list($remotedata,$limit);6067}else{6068 fill_remote_heads($remotedata);6069while(my($remote,$rdata) =each%$remotedata) {6070 git_print_section({-class=>"remote", -id=>$remote},6071["remotes",$remote,$remote],sub{6072 git_remote_block($remote,$rdata,$limit,$head);6073});6074}6075}6076}60776078sub git_search_message {6079my%co=@_;60806081my$greptype;6082if($searchtypeeq'commit') {6083$greptype="--grep=";6084}elsif($searchtypeeq'author') {6085$greptype="--author=";6086}elsif($searchtypeeq'committer') {6087$greptype="--committer=";6088}6089$greptype.=$searchtext;6090my@commitlist= parse_commits($hash,101, (100*$page),undef,6091$greptype,'--regexp-ignore-case',6092$search_use_regexp?'--extended-regexp':'--fixed-strings');60936094my$paging_nav='';6095if($page>0) {6096$paging_nav.=6097$cgi->a({-href => href(-replay=>1, page=>undef)},6098"first") .6099" ⋅ ".6100$cgi->a({-href => href(-replay=>1, page=>$page-1),6101-accesskey =>"p", -title =>"Alt-p"},"prev");6102}else{6103$paging_nav.="first ⋅ prev";6104}6105my$next_link='';6106if($#commitlist>=100) {6107$next_link=6108$cgi->a({-href => href(-replay=>1, page=>$page+1),6109-accesskey =>"n", -title =>"Alt-n"},"next");6110$paging_nav.=" ⋅$next_link";6111}else{6112$paging_nav.=" ⋅ next";6113}61146115 git_header_html();61166117 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);6118 git_print_header_div('commit', esc_html($co{'title'}),$hash);6119if($page==0&& !@commitlist) {6120print"<p>No match.</p>\n";6121}else{6122 git_search_grep_body(\@commitlist,0,99,$next_link);6123}61246125 git_footer_html();6126}61276128sub git_search_changes {6129my%co=@_;61306131local$/="\n";6132open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,6133'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",6134($search_use_regexp?'--pickaxe-regex': ())6135or die_error(500,"Open git-log failed");61366137 git_header_html();61386139 git_print_page_nav('','',$hash,$co{'tree'},$hash);6140 git_print_header_div('commit', esc_html($co{'title'}),$hash);61416142print"<table class=\"pickaxe search\">\n";6143my$alternate=1;6144undef%co;6145my@files;6146while(my$line= <$fd>) {6147chomp$line;6148next unless$line;61496150my%set= parse_difftree_raw_line($line);6151if(defined$set{'commit'}) {6152# finish previous commit6153if(%co) {6154print"</td>\n".6155"<td class=\"link\">".6156$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6157"commit") .6158" | ".6159$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6160 hash_base=>$co{'id'})},6161"tree") .6162"</td>\n".6163"</tr>\n";6164}61656166if($alternate) {6167print"<tr class=\"dark\">\n";6168}else{6169print"<tr class=\"light\">\n";6170}6171$alternate^=1;6172%co= parse_commit($set{'commit'});6173my$author= chop_and_escape_str($co{'author_name'},15,5);6174print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6175"<td><i>$author</i></td>\n".6176"<td>".6177$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6178-class=>"list subject"},6179 chop_and_escape_str($co{'title'},50) ."<br/>");6180}elsif(defined$set{'to_id'}) {6181next if($set{'to_id'} =~m/^0{40}$/);61826183print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6184 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6185-class=>"list"},6186"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6187"<br/>\n";6188}6189}6190close$fd;61916192# finish last commit (warning: repetition!)6193if(%co) {6194print"</td>\n".6195"<td class=\"link\">".6196$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},6197"commit") .6198" | ".6199$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},6200 hash_base=>$co{'id'})},6201"tree") .6202"</td>\n".6203"</tr>\n";6204}62056206print"</table>\n";62076208 git_footer_html();6209}62106211sub git_search_files {6212my%co=@_;62136214local$/="\n";6215open my$fd,"-|", git_cmd(),'grep','-n','-z',6216$search_use_regexp? ('-E','-i') :'-F',6217$searchtext,$co{'tree'}6218or die_error(500,"Open git-grep failed");62196220 git_header_html();62216222 git_print_page_nav('','',$hash,$co{'tree'},$hash);6223 git_print_header_div('commit', esc_html($co{'title'}),$hash);62246225print"<table class=\"grep_search\">\n";6226my$alternate=1;6227my$matches=0;6228my$lastfile='';6229my$file_href;6230while(my$line= <$fd>) {6231chomp$line;6232my($file,$lno,$ltext,$binary);6233last if($matches++>1000);6234if($line=~/^Binary file (.+) matches$/) {6235$file=$1;6236$binary=1;6237}else{6238($file,$lno,$ltext) =split(/\0/,$line,3);6239$file=~s/^$co{'tree'}://;6240}6241if($filene$lastfile) {6242$lastfileand print"</td></tr>\n";6243if($alternate++) {6244print"<tr class=\"dark\">\n";6245}else{6246print"<tr class=\"light\">\n";6247}6248$file_href= href(action=>"blob", hash_base=>$co{'id'},6249 file_name=>$file);6250print"<td class=\"list\">".6251$cgi->a({-href =>$file_href, -class=>"list"}, esc_path($file));6252print"</td><td>\n";6253$lastfile=$file;6254}6255if($binary) {6256print"<div class=\"binary\">Binary file</div>\n";6257}else{6258$ltext= untabify($ltext);6259if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6260$ltext= esc_html($1, -nbsp=>1);6261$ltext.='<span class="match">';6262$ltext.= esc_html($2, -nbsp=>1);6263$ltext.='</span>';6264$ltext.= esc_html($3, -nbsp=>1);6265}else{6266$ltext= esc_html($ltext, -nbsp=>1);6267}6268print"<div class=\"pre\">".6269$cgi->a({-href =>$file_href.'#l'.$lno,6270-class=>"linenr"},sprintf('%4i',$lno)) .6271' '.$ltext."</div>\n";6272}6273}6274if($lastfile) {6275print"</td></tr>\n";6276if($matches>1000) {6277print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6278}6279}else{6280print"<div class=\"diff nodifferences\">No matches found</div>\n";6281}6282close$fd;62836284print"</table>\n";62856286 git_footer_html();6287}62886289sub git_search_grep_body {6290my($commitlist,$from,$to,$extra) =@_;6291$from=0unlessdefined$from;6292$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);62936294print"<table class=\"commit_search\">\n";6295my$alternate=1;6296for(my$i=$from;$i<=$to;$i++) {6297my%co= %{$commitlist->[$i]};6298if(!%co) {6299next;6300}6301my$commit=$co{'id'};6302if($alternate) {6303print"<tr class=\"dark\">\n";6304}else{6305print"<tr class=\"light\">\n";6306}6307$alternate^=1;6308print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6309 format_author_html('td', \%co,15,5) .6310"<td>".6311$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6312-class=>"list subject"},6313 chop_and_escape_str($co{'title'},50) ."<br/>");6314my$comment=$co{'comment'};6315foreachmy$line(@$comment) {6316if($line=~m/^(.*?)($search_regexp)(.*)$/i) {6317my($lead,$match,$trail) = ($1,$2,$3);6318$match= chop_str($match,70,5,'center');6319my$contextlen=int((80-length($match))/2);6320$contextlen=30if($contextlen>30);6321$lead= chop_str($lead,$contextlen,10,'left');6322$trail= chop_str($trail,$contextlen,10,'right');63236324$lead= esc_html($lead);6325$match= esc_html($match);6326$trail= esc_html($trail);63276328print"$lead<span class=\"match\">$match</span>$trail<br />";6329}6330}6331print"</td>\n".6332"<td class=\"link\">".6333$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6334" | ".6335$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .6336" | ".6337$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6338print"</td>\n".6339"</tr>\n";6340}6341if(defined$extra) {6342print"<tr>\n".6343"<td colspan=\"3\">$extra</td>\n".6344"</tr>\n";6345}6346print"</table>\n";6347}63486349## ======================================================================6350## ======================================================================6351## actions63526353sub git_project_list {6354my$order=$input_params{'order'};6355if(defined$order&&$order!~m/none|project|descr|owner|age/) {6356 die_error(400,"Unknown order parameter");6357}63586359my@list= git_get_projects_list($project_filter,$strict_export);6360if(!@list) {6361 die_error(404,"No projects found");6362}63636364 git_header_html();6365if(defined$home_text&& -f $home_text) {6366print"<div class=\"index_include\">\n";6367 insert_file($home_text);6368print"</div>\n";6369}63706371 git_project_search_form($searchtext,$search_use_regexp);6372 git_project_list_body(\@list,$order);6373 git_footer_html();6374}63756376sub git_forks {6377my$order=$input_params{'order'};6378if(defined$order&&$order!~m/none|project|descr|owner|age/) {6379 die_error(400,"Unknown order parameter");6380}63816382my$filter=$project;6383$filter=~s/\.git$//;6384my@list= git_get_projects_list($filter);6385if(!@list) {6386 die_error(404,"No forks found");6387}63886389 git_header_html();6390 git_print_page_nav('','');6391 git_print_header_div('summary',"$projectforks");6392 git_project_list_body(\@list,$order);6393 git_footer_html();6394}63956396sub git_project_index {6397my@projects= git_get_projects_list($project_filter,$strict_export);6398if(!@projects) {6399 die_error(404,"No projects found");6400}64016402print$cgi->header(6403-type =>'text/plain',6404-charset =>'utf-8',6405-content_disposition =>'inline; filename="index.aux"');64066407foreachmy$pr(@projects) {6408if(!exists$pr->{'owner'}) {6409$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");6410}64116412my($path,$owner) = ($pr->{'path'},$pr->{'owner'});6413# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '6414$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6415$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;6416$path=~s/ /\+/g;6417$owner=~s/ /\+/g;64186419print"$path$owner\n";6420}6421}64226423sub git_summary {6424my$descr= git_get_project_description($project) ||"none";6425my%co= parse_commit("HEAD");6426my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();6427my$head=$co{'id'};6428my$remote_heads= gitweb_check_feature('remote_heads');64296430my$owner= git_get_project_owner($project);64316432my$refs= git_get_references();6433# These get_*_list functions return one more to allow us to see if6434# there are more ...6435my@taglist= git_get_tags_list(16);6436my@headlist= git_get_heads_list(16);6437my%remotedata=$remote_heads? git_get_remotes_list() : ();6438my@forklist;6439my$check_forks= gitweb_check_feature('forks');64406441if($check_forks) {6442# find forks of a project6443my$filter=$project;6444$filter=~s/\.git$//;6445@forklist= git_get_projects_list($filter);6446# filter out forks of forks6447@forklist= filter_forks_from_projects_list(\@forklist)6448if(@forklist);6449}64506451 git_header_html();6452 git_print_page_nav('summary','',$head);64536454print"<div class=\"title\"> </div>\n";6455print"<table class=\"projects_list\">\n".6456"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n";6457unless($omit_owner) {6458print"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";6459}6460if(defined$cd{'rfc2822'}) {6461print"<tr id=\"metadata_lchange\"><td>last change</td>".6462"<td>".format_timestamp_html(\%cd)."</td></tr>\n";6463}64646465# use per project git URL list in $projectroot/$project/cloneurl6466# or make project git URL from git base URL and project name6467my$url_tag="URL";6468my@url_list= git_get_project_url_list($project);6469@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;6470foreachmy$git_url(@url_list) {6471next unless$git_url;6472print format_repo_url($url_tag,$git_url);6473$url_tag="";6474}64756476# Tag cloud6477my$show_ctags= gitweb_check_feature('ctags');6478if($show_ctags) {6479my$ctags= git_get_project_ctags($project);6480if(%$ctags) {6481# without ability to add tags, don't show if there are none6482my$cloud= git_populate_project_tagcloud($ctags);6483print"<tr id=\"metadata_ctags\">".6484"<td>content tags</td>".6485"<td>".git_show_project_tagcloud($cloud,48)."</td>".6486"</tr>\n";6487}6488}64896490print"</table>\n";64916492# If XSS prevention is on, we don't include README.html.6493# TODO: Allow a readme in some safe format.6494if(!$prevent_xss&& -s "$projectroot/$project/README.html") {6495print"<div class=\"title\">readme</div>\n".6496"<div class=\"readme\">\n";6497 insert_file("$projectroot/$project/README.html");6498print"\n</div>\n";# class="readme"6499}65006501# we need to request one more than 16 (0..15) to check if6502# those 16 are all6503my@commitlist=$head? parse_commits($head,17) : ();6504if(@commitlist) {6505 git_print_header_div('shortlog');6506 git_shortlog_body(\@commitlist,0,15,$refs,6507$#commitlist<=15?undef:6508$cgi->a({-href => href(action=>"shortlog")},"..."));6509}65106511if(@taglist) {6512 git_print_header_div('tags');6513 git_tags_body(\@taglist,0,15,6514$#taglist<=15?undef:6515$cgi->a({-href => href(action=>"tags")},"..."));6516}65176518if(@headlist) {6519 git_print_header_div('heads');6520 git_heads_body(\@headlist,$head,0,15,6521$#headlist<=15?undef:6522$cgi->a({-href => href(action=>"heads")},"..."));6523}65246525if(%remotedata) {6526 git_print_header_div('remotes');6527 git_remotes_body(\%remotedata,15,$head);6528}65296530if(@forklist) {6531 git_print_header_div('forks');6532 git_project_list_body(\@forklist,'age',0,15,6533$#forklist<=15?undef:6534$cgi->a({-href => href(action=>"forks")},"..."),6535'no_header');6536}65376538 git_footer_html();6539}65406541sub git_tag {6542my%tag= parse_tag($hash);65436544if(!%tag) {6545 die_error(404,"Unknown tag object");6546}65476548my$head= git_get_head_hash($project);6549 git_header_html();6550 git_print_page_nav('','',$head,undef,$head);6551 git_print_header_div('commit', esc_html($tag{'name'}),$hash);6552print"<div class=\"title_text\">\n".6553"<table class=\"object_header\">\n".6554"<tr>\n".6555"<td>object</td>\n".6556"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6557$tag{'object'}) ."</td>\n".6558"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},6559$tag{'type'}) ."</td>\n".6560"</tr>\n";6561if(defined($tag{'author'})) {6562 git_print_authorship_rows(\%tag,'author');6563}6564print"</table>\n\n".6565"</div>\n";6566print"<div class=\"page_body\">";6567my$comment=$tag{'comment'};6568foreachmy$line(@$comment) {6569chomp$line;6570print esc_html($line, -nbsp=>1) ."<br/>\n";6571}6572print"</div>\n";6573 git_footer_html();6574}65756576sub git_blame_common {6577my$format=shift||'porcelain';6578if($formateq'porcelain'&&$input_params{'javascript'}) {6579$format='incremental';6580$action='blame_incremental';# for page title etc6581}65826583# permissions6584 gitweb_check_feature('blame')6585or die_error(403,"Blame view not allowed");65866587# error checking6588 die_error(400,"No file name given")unless$file_name;6589$hash_base||= git_get_head_hash($project);6590 die_error(404,"Couldn't find base commit")unless$hash_base;6591my%co= parse_commit($hash_base)6592or die_error(404,"Commit not found");6593my$ftype="blob";6594if(!defined$hash) {6595$hash= git_get_hash_by_path($hash_base,$file_name,"blob")6596or die_error(404,"Error looking up file");6597}else{6598$ftype= git_get_type($hash);6599if($ftype!~"blob") {6600 die_error(400,"Object is not a blob");6601}6602}66036604my$fd;6605if($formateq'incremental') {6606# get file contents (as base)6607open$fd,"-|", git_cmd(),'cat-file','blob',$hash6608or die_error(500,"Open git-cat-file failed");6609}elsif($formateq'data') {6610# run git-blame --incremental6611open$fd,"-|", git_cmd(),"blame","--incremental",6612$hash_base,"--",$file_name6613or die_error(500,"Open git-blame --incremental failed");6614}else{6615# run git-blame --porcelain6616open$fd,"-|", git_cmd(),"blame",'-p',6617$hash_base,'--',$file_name6618or die_error(500,"Open git-blame --porcelain failed");6619}66206621# incremental blame data returns early6622if($formateq'data') {6623print$cgi->header(6624-type=>"text/plain", -charset =>"utf-8",6625-status=>"200 OK");6626local$| =1;# output autoflush6627while(my$line= <$fd>) {6628print to_utf8($line);6629}6630close$fd6631or print"ERROR$!\n";66326633print'END';6634if(defined$t0&& gitweb_check_feature('timed')) {6635print' '.6636 tv_interval($t0, [ gettimeofday() ]).6637' '.$number_of_git_cmds;6638}6639print"\n";66406641return;6642}66436644# page header6645 git_header_html();6646my$formats_nav=6647$cgi->a({-href => href(action=>"blob", -replay=>1)},6648"blob") .6649" | ";6650if($formateq'incremental') {6651$formats_nav.=6652$cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},6653"blame") ." (non-incremental)";6654}else{6655$formats_nav.=6656$cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},6657"blame") ." (incremental)";6658}6659$formats_nav.=6660" | ".6661$cgi->a({-href => href(action=>"history", -replay=>1)},6662"history") .6663" | ".6664$cgi->a({-href => href(action=>$action, file_name=>$file_name)},6665"HEAD");6666 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);6667 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);6668 git_print_page_path($file_name,$ftype,$hash_base);66696670# page body6671if($formateq'incremental') {6672print"<noscript>\n<div class=\"error\"><center><b>\n".6673"This page requires JavaScript to run.\nUse ".6674$cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},6675'this page').6676" instead.\n".6677"</b></center></div>\n</noscript>\n";66786679print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;6680}66816682print qq!<div class="page_body">\n!;6683print qq!<div id="progress_info">.../ ...</div>\n!6684if($formateq'incremental');6685print qq!<table id="blame_table"class="blame" width="100%">\n!.6686#qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.6687 qq!<thead>\n!.6688 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.6689 qq!</thead>\n!.6690 qq!<tbody>\n!;66916692my@rev_color=qw(light dark);6693my$num_colors=scalar(@rev_color);6694my$current_color=0;66956696if($formateq'incremental') {6697my$color_class=$rev_color[$current_color];66986699#contents of a file6700my$linenr=0;6701 LINE:6702while(my$line= <$fd>) {6703chomp$line;6704$linenr++;67056706print qq!<tr id="l$linenr"class="$color_class">!.6707 qq!<td class="sha1"><a href=""> </a></td>!.6708 qq!<td class="linenr">!.6709 qq!<a class="linenr" href="">$linenr</a></td>!;6710print qq!<td class="pre">! . esc_html($line) ."</td>\n";6711print qq!</tr>\n!;6712}67136714}else{# porcelain, i.e. ordinary blame6715my%metainfo= ();# saves information about commits67166717# blame data6718 LINE:6719while(my$line= <$fd>) {6720chomp$line;6721# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]6722# no <lines in group> for subsequent lines in group of lines6723my($full_rev,$orig_lineno,$lineno,$group_size) =6724($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);6725if(!exists$metainfo{$full_rev}) {6726$metainfo{$full_rev} = {'nprevious'=>0};6727}6728my$meta=$metainfo{$full_rev};6729my$data;6730while($data= <$fd>) {6731chomp$data;6732last if($data=~s/^\t//);# contents of line6733if($data=~/^(\S+)(?: (.*))?$/) {6734$meta->{$1} =$2unlessexists$meta->{$1};6735}6736if($data=~/^previous /) {6737$meta->{'nprevious'}++;6738}6739}6740my$short_rev=substr($full_rev,0,8);6741my$author=$meta->{'author'};6742my%date=6743 parse_date($meta->{'author-time'},$meta->{'author-tz'});6744my$date=$date{'iso-tz'};6745if($group_size) {6746$current_color= ($current_color+1) %$num_colors;6747}6748my$tr_class=$rev_color[$current_color];6749$tr_class.=' boundary'if(exists$meta->{'boundary'});6750$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);6751$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);6752print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";6753if($group_size) {6754print"<td class=\"sha1\"";6755print" title=\"". esc_html($author) .",$date\"";6756print" rowspan=\"$group_size\""if($group_size>1);6757print">";6758print$cgi->a({-href => href(action=>"commit",6759 hash=>$full_rev,6760 file_name=>$file_name)},6761 esc_html($short_rev));6762if($group_size>=2) {6763my@author_initials= ($author=~/\b([[:upper:]])\B/g);6764if(@author_initials) {6765print"<br />".6766 esc_html(join('',@author_initials));6767# or join('.', ...)6768}6769}6770print"</td>\n";6771}6772# 'previous' <sha1 of parent commit> <filename at commit>6773if(exists$meta->{'previous'} &&6774$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {6775$meta->{'parent'} =$1;6776$meta->{'file_parent'} = unquote($2);6777}6778my$linenr_commit=6779exists($meta->{'parent'}) ?6780$meta->{'parent'} :$full_rev;6781my$linenr_filename=6782exists($meta->{'file_parent'}) ?6783$meta->{'file_parent'} : unquote($meta->{'filename'});6784my$blamed= href(action =>'blame',6785 file_name =>$linenr_filename,6786 hash_base =>$linenr_commit);6787print"<td class=\"linenr\">";6788print$cgi->a({ -href =>"$blamed#l$orig_lineno",6789-class=>"linenr"},6790 esc_html($lineno));6791print"</td>";6792print"<td class=\"pre\">". esc_html($data) ."</td>\n";6793print"</tr>\n";6794}# end while67956796}67976798# footer6799print"</tbody>\n".6800"</table>\n";# class="blame"6801print"</div>\n";# class="blame_body"6802close$fd6803or print"Reading blob failed\n";68046805 git_footer_html();6806}68076808sub git_blame {6809 git_blame_common();6810}68116812sub git_blame_incremental {6813 git_blame_common('incremental');6814}68156816sub git_blame_data {6817 git_blame_common('data');6818}68196820sub git_tags {6821my$head= git_get_head_hash($project);6822 git_header_html();6823 git_print_page_nav('','',$head,undef,$head,format_ref_views('tags'));6824 git_print_header_div('summary',$project);68256826my@tagslist= git_get_tags_list();6827if(@tagslist) {6828 git_tags_body(\@tagslist);6829}6830 git_footer_html();6831}68326833sub git_heads {6834my$head= git_get_head_hash($project);6835 git_header_html();6836 git_print_page_nav('','',$head,undef,$head,format_ref_views('heads'));6837 git_print_header_div('summary',$project);68386839my@headslist= git_get_heads_list();6840if(@headslist) {6841 git_heads_body(\@headslist,$head);6842}6843 git_footer_html();6844}68456846# used both for single remote view and for list of all the remotes6847sub git_remotes {6848 gitweb_check_feature('remote_heads')6849or die_error(403,"Remote heads view is disabled");68506851my$head= git_get_head_hash($project);6852my$remote=$input_params{'hash'};68536854my$remotedata= git_get_remotes_list($remote);6855 die_error(500,"Unable to get remote information")unlessdefined$remotedata;68566857unless(%$remotedata) {6858 die_error(404,defined$remote?6859"Remote$remotenot found":6860"No remotes found");6861}68626863 git_header_html(undef,undef, -action_extra =>$remote);6864 git_print_page_nav('','',$head,undef,$head,6865 format_ref_views($remote?'':'remotes'));68666867 fill_remote_heads($remotedata);6868if(defined$remote) {6869 git_print_header_div('remotes',"$remoteremote for$project");6870 git_remote_block($remote,$remotedata->{$remote},undef,$head);6871}else{6872 git_print_header_div('summary',"$projectremotes");6873 git_remotes_body($remotedata,undef,$head);6874}68756876 git_footer_html();6877}68786879sub git_blob_plain {6880my$type=shift;6881my$expires;68826883if(!defined$hash) {6884if(defined$file_name) {6885my$base=$hash_base|| git_get_head_hash($project);6886$hash= git_get_hash_by_path($base,$file_name,"blob")6887or die_error(404,"Cannot find file");6888}else{6889 die_error(400,"No file name defined");6890}6891}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6892# blobs defined by non-textual hash id's can be cached6893$expires="+1d";6894}68956896open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6897or die_error(500,"Open git-cat-file blob '$hash' failed");68986899# content-type (can include charset)6900$type= blob_contenttype($fd,$file_name,$type);69016902# "save as" filename, even when no $file_name is given6903my$save_as="$hash";6904if(defined$file_name) {6905$save_as=$file_name;6906}elsif($type=~m/^text\//) {6907$save_as.='.txt';6908}69096910# With XSS prevention on, blobs of all types except a few known safe6911# ones are served with "Content-Disposition: attachment" to make sure6912# they don't run in our security domain. For certain image types,6913# blob view writes an <img> tag referring to blob_plain view, and we6914# want to be sure not to break that by serving the image as an6915# attachment (though Firefox 3 doesn't seem to care).6916my$sandbox=$prevent_xss&&6917$type!~m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;69186919# serve text/* as text/plain6920if($prevent_xss&&6921($type=~m!^text/[a-z]+\b(.*)$!||6922($type=~m!^[a-z]+/[a-z]\+xml\b(.*)$!&& -T $fd))) {6923my$rest=$1;6924$rest=defined$rest?$rest:'';6925$type="text/plain$rest";6926}69276928print$cgi->header(6929-type =>$type,6930-expires =>$expires,6931-content_disposition =>6932($sandbox?'attachment':'inline')6933.'; filename="'.$save_as.'"');6934local$/=undef;6935binmode STDOUT,':raw';6936print<$fd>;6937binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi6938close$fd;6939}69406941sub git_blob {6942my$expires;69436944if(!defined$hash) {6945if(defined$file_name) {6946my$base=$hash_base|| git_get_head_hash($project);6947$hash= git_get_hash_by_path($base,$file_name,"blob")6948or die_error(404,"Cannot find file");6949}else{6950 die_error(400,"No file name defined");6951}6952}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {6953# blobs defined by non-textual hash id's can be cached6954$expires="+1d";6955}69566957my$have_blame= gitweb_check_feature('blame');6958open my$fd,"-|", git_cmd(),"cat-file","blob",$hash6959or die_error(500,"Couldn't cat$file_name,$hash");6960my$mimetype= blob_mimetype($fd,$file_name);6961# use 'blob_plain' (aka 'raw') view for files that cannot be displayed6962if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {6963close$fd;6964return git_blob_plain($mimetype);6965}6966# we can have blame only for text/* mimetype6967$have_blame&&= ($mimetype=~m!^text/!);69686969my$highlight= gitweb_check_feature('highlight');6970my$syntax= guess_file_syntax($highlight,$mimetype,$file_name);6971$fd= run_highlighter($fd,$highlight,$syntax)6972if$syntax;69736974 git_header_html(undef,$expires);6975my$formats_nav='';6976if(defined$hash_base&& (my%co= parse_commit($hash_base))) {6977if(defined$file_name) {6978if($have_blame) {6979$formats_nav.=6980$cgi->a({-href => href(action=>"blame", -replay=>1)},6981"blame") .6982" | ";6983}6984$formats_nav.=6985$cgi->a({-href => href(action=>"history", -replay=>1)},6986"history") .6987" | ".6988$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6989"raw") .6990" | ".6991$cgi->a({-href => href(action=>"blob",6992 hash_base=>"HEAD", file_name=>$file_name)},6993"HEAD");6994}else{6995$formats_nav.=6996$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},6997"raw");6998}6999 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7000 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7001}else{7002print"<div class=\"page_nav\">\n".7003"<br/><br/></div>\n".7004"<div class=\"title\">".esc_html($hash)."</div>\n";7005}7006 git_print_page_path($file_name,"blob",$hash_base);7007print"<div class=\"page_body\">\n";7008if($mimetype=~m!^image/!) {7009print qq!<img type="!.esc_attr($mimetype).qq!"!;7010if($file_name) {7011print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;7012}7013print qq! src="! .7014 href(action=>"blob_plain", hash=>$hash,7015 hash_base=>$hash_base, file_name=>$file_name) .7016 qq!"/>\n!;7017}else{7018my$nr;7019while(my$line= <$fd>) {7020chomp$line;7021$nr++;7022$line= untabify($line);7023printf qq!<div class="pre"><a id="l%i" href="%s#l%i"class="linenr">%4i</a> %s</div>\n!,7024$nr, esc_attr(href(-replay =>1)),$nr,$nr,7025$syntax? sanitize($line) : esc_html($line, -nbsp=>1);7026}7027}7028close$fd7029or print"Reading blob failed.\n";7030print"</div>";7031 git_footer_html();7032}70337034sub git_tree {7035if(!defined$hash_base) {7036$hash_base="HEAD";7037}7038if(!defined$hash) {7039if(defined$file_name) {7040$hash= git_get_hash_by_path($hash_base,$file_name,"tree");7041}else{7042$hash=$hash_base;7043}7044}7045 die_error(404,"No such tree")unlessdefined($hash);70467047my$show_sizes= gitweb_check_feature('show-sizes');7048my$have_blame= gitweb_check_feature('blame');70497050my@entries= ();7051{7052local$/="\0";7053open my$fd,"-|", git_cmd(),"ls-tree",'-z',7054($show_sizes?'-l': ()),@extra_options,$hash7055or die_error(500,"Open git-ls-tree failed");7056@entries=map{chomp;$_} <$fd>;7057close$fd7058or die_error(404,"Reading tree failed");7059}70607061my$refs= git_get_references();7062my$ref= format_ref_marker($refs,$hash_base);7063 git_header_html();7064my$basedir='';7065if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7066my@views_nav= ();7067if(defined$file_name) {7068push@views_nav,7069$cgi->a({-href => href(action=>"history", -replay=>1)},7070"history"),7071$cgi->a({-href => href(action=>"tree",7072 hash_base=>"HEAD", file_name=>$file_name)},7073"HEAD"),7074}7075my$snapshot_links= format_snapshot_links($hash);7076if(defined$snapshot_links) {7077# FIXME: Should be available when we have no hash base as well.7078push@views_nav,$snapshot_links;7079}7080 git_print_page_nav('tree','',$hash_base,undef,undef,7081join(' | ',@views_nav));7082 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);7083}else{7084undef$hash_base;7085print"<div class=\"page_nav\">\n";7086print"<br/><br/></div>\n";7087print"<div class=\"title\">".esc_html($hash)."</div>\n";7088}7089if(defined$file_name) {7090$basedir=$file_name;7091if($basedirne''&&substr($basedir, -1)ne'/') {7092$basedir.='/';7093}7094 git_print_page_path($file_name,'tree',$hash_base);7095}7096print"<div class=\"page_body\">\n";7097print"<table class=\"tree\">\n";7098my$alternate=1;7099# '..' (top directory) link if possible7100if(defined$hash_base&&7101defined$file_name&&$file_name=~m![^/]+$!) {7102if($alternate) {7103print"<tr class=\"dark\">\n";7104}else{7105print"<tr class=\"light\">\n";7106}7107$alternate^=1;71087109my$up=$file_name;7110$up=~s!/?[^/]+$!!;7111undef$upunless$up;7112# based on git_print_tree_entry7113print'<td class="mode">'. mode_str('040000') ."</td>\n";7114print'<td class="size"> </td>'."\n"if$show_sizes;7115print'<td class="list">';7116print$cgi->a({-href => href(action=>"tree",7117 hash_base=>$hash_base,7118 file_name=>$up)},7119"..");7120print"</td>\n";7121print"<td class=\"link\"></td>\n";71227123print"</tr>\n";7124}7125foreachmy$line(@entries) {7126my%t= parse_ls_tree_line($line, -z =>1, -l =>$show_sizes);71277128if($alternate) {7129print"<tr class=\"dark\">\n";7130}else{7131print"<tr class=\"light\">\n";7132}7133$alternate^=1;71347135 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);71367137print"</tr>\n";7138}7139print"</table>\n".7140"</div>";7141 git_footer_html();7142}71437144sub snapshot_name {7145my($project,$hash) =@_;71467147# path/to/project.git -> project7148# path/to/project/.git -> project7149my$name= to_utf8($project);7150$name=~ s,([^/])/*\.git$,$1,;7151$name= basename($name);7152# sanitize name7153$name=~s/[[:cntrl:]]/?/g;71547155my$ver=$hash;7156if($hash=~/^[0-9a-fA-F]+$/) {7157# shorten SHA-1 hash7158my$full_hash= git_get_full_hash($project,$hash);7159if($full_hash=~/^$hash/&&length($hash) >7) {7160$ver= git_get_short_hash($project,$hash);7161}7162}elsif($hash=~m!^refs/tags/(.*)$!) {7163# tags don't need shortened SHA-1 hash7164$ver=$1;7165}else{7166# branches and other need shortened SHA-1 hash7167if($hash=~m!^refs/(?:heads|remotes)/(.*)$!) {7168$ver=$1;7169}7170$ver.='-'. git_get_short_hash($project,$hash);7171}7172# in case of hierarchical branch names7173$ver=~s!/!.!g;71747175# name = project-version_string7176$name="$name-$ver";71777178returnwantarray? ($name,$name) :$name;7179}71807181sub exit_if_unmodified_since {7182my($latest_epoch) =@_;7183our$cgi;71847185my$if_modified=$cgi->http('IF_MODIFIED_SINCE');7186if(defined$if_modified) {7187my$since;7188if(eval{require HTTP::Date;1; }) {7189$since= HTTP::Date::str2time($if_modified);7190}elsif(eval{require Time::ParseDate;1; }) {7191$since= Time::ParseDate::parsedate($if_modified, GMT =>1);7192}7193if(defined$since&&$latest_epoch<=$since) {7194my%latest_date= parse_date($latest_epoch);7195print$cgi->header(7196-last_modified =>$latest_date{'rfc2822'},7197-status =>'304 Not Modified');7198goto DONE_GITWEB;7199}7200}7201}72027203sub git_snapshot {7204my$format=$input_params{'snapshot_format'};7205if(!@snapshot_fmts) {7206 die_error(403,"Snapshots not allowed");7207}7208# default to first supported snapshot format7209$format||=$snapshot_fmts[0];7210if($format!~m/^[a-z0-9]+$/) {7211 die_error(400,"Invalid snapshot format parameter");7212}elsif(!exists($known_snapshot_formats{$format})) {7213 die_error(400,"Unknown snapshot format");7214}elsif($known_snapshot_formats{$format}{'disabled'}) {7215 die_error(403,"Snapshot format not allowed");7216}elsif(!grep($_eq$format,@snapshot_fmts)) {7217 die_error(403,"Unsupported snapshot format");7218}72197220my$type= git_get_type("$hash^{}");7221if(!$type) {7222 die_error(404,'Object does not exist');7223}elsif($typeeq'blob') {7224 die_error(400,'Object is not a tree-ish');7225}72267227my($name,$prefix) = snapshot_name($project,$hash);7228my$filename="$name$known_snapshot_formats{$format}{'suffix'}";72297230my%co= parse_commit($hash);7231 exit_if_unmodified_since($co{'committer_epoch'})if%co;72327233my$cmd= quote_command(7234 git_cmd(),'archive',7235"--format=$known_snapshot_formats{$format}{'format'}",7236"--prefix=$prefix/",$hash);7237if(exists$known_snapshot_formats{$format}{'compressor'}) {7238$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});7239}72407241$filename=~s/(["\\])/\\$1/g;7242my%latest_date;7243if(%co) {7244%latest_date= parse_date($co{'committer_epoch'},$co{'committer_tz'});7245}72467247print$cgi->header(7248-type =>$known_snapshot_formats{$format}{'type'},7249-content_disposition =>'inline; filename="'.$filename.'"',7250%co? (-last_modified =>$latest_date{'rfc2822'}) : (),7251-status =>'200 OK');72527253open my$fd,"-|",$cmd7254or die_error(500,"Execute git-archive failed");7255binmode STDOUT,':raw';7256print<$fd>;7257binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi7258close$fd;7259}72607261sub git_log_generic {7262my($fmt_name,$body_subr,$base,$parent,$file_name,$file_hash) =@_;72637264my$head= git_get_head_hash($project);7265if(!defined$base) {7266$base=$head;7267}7268if(!defined$page) {7269$page=0;7270}7271my$refs= git_get_references();72727273my$commit_hash=$base;7274if(defined$parent) {7275$commit_hash="$parent..$base";7276}7277my@commitlist=7278 parse_commits($commit_hash,101, (100*$page),7279defined$file_name? ($file_name,"--full-history") : ());72807281my$ftype;7282if(!defined$file_hash&&defined$file_name) {7283# some commits could have deleted file in question,7284# and not have it in tree, but one of them has to have it7285for(my$i=0;$i<@commitlist;$i++) {7286$file_hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);7287last ifdefined$file_hash;7288}7289}7290if(defined$file_hash) {7291$ftype= git_get_type($file_hash);7292}7293if(defined$file_name&& !defined$ftype) {7294 die_error(500,"Unknown type of object");7295}7296my%co;7297if(defined$file_name) {7298%co= parse_commit($base)7299or die_error(404,"Unknown commit object");7300}730173027303my$paging_nav= format_paging_nav($fmt_name,$page,$#commitlist>=100);7304my$next_link='';7305if($#commitlist>=100) {7306$next_link=7307$cgi->a({-href => href(-replay=>1, page=>$page+1),7308-accesskey =>"n", -title =>"Alt-n"},"next");7309}7310my$patch_max= gitweb_get_feature('patches');7311if($patch_max&& !defined$file_name) {7312if($patch_max<0||@commitlist<=$patch_max) {7313$paging_nav.=" ⋅ ".7314$cgi->a({-href => href(action=>"patches", -replay=>1)},7315"patches");7316}7317}73187319 git_header_html();7320 git_print_page_nav($fmt_name,'',$hash,$hash,$hash,$paging_nav);7321if(defined$file_name) {7322 git_print_header_div('commit', esc_html($co{'title'}),$base);7323}else{7324 git_print_header_div('summary',$project)7325}7326 git_print_page_path($file_name,$ftype,$hash_base)7327if(defined$file_name);73287329$body_subr->(\@commitlist,0,99,$refs,$next_link,7330$file_name,$file_hash,$ftype);73317332 git_footer_html();7333}73347335sub git_log {7336 git_log_generic('log', \&git_log_body,7337$hash,$hash_parent);7338}73397340sub git_commit {7341$hash||=$hash_base||"HEAD";7342my%co= parse_commit($hash)7343or die_error(404,"Unknown commit object");73447345my$parent=$co{'parent'};7346my$parents=$co{'parents'};# listref73477348# we need to prepare $formats_nav before any parameter munging7349my$formats_nav;7350if(!defined$parent) {7351# --root commitdiff7352$formats_nav.='(initial)';7353}elsif(@$parents==1) {7354# single parent commit7355$formats_nav.=7356'(parent: '.7357$cgi->a({-href => href(action=>"commit",7358 hash=>$parent)},7359 esc_html(substr($parent,0,7))) .7360')';7361}else{7362# merge commit7363$formats_nav.=7364'(merge: '.7365join(' ',map{7366$cgi->a({-href => href(action=>"commit",7367 hash=>$_)},7368 esc_html(substr($_,0,7)));7369}@$parents) .7370')';7371}7372if(gitweb_check_feature('patches') &&@$parents<=1) {7373$formats_nav.=" | ".7374$cgi->a({-href => href(action=>"patch", -replay=>1)},7375"patch");7376}73777378if(!defined$parent) {7379$parent="--root";7380}7381my@difftree;7382open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",7383@diff_opts,7384(@$parents<=1?$parent:'-c'),7385$hash,"--"7386or die_error(500,"Open git-diff-tree failed");7387@difftree=map{chomp;$_} <$fd>;7388close$fdor die_error(404,"Reading git-diff-tree failed");73897390# non-textual hash id's can be cached7391my$expires;7392if($hash=~m/^[0-9a-fA-F]{40}$/) {7393$expires="+1d";7394}7395my$refs= git_get_references();7396my$ref= format_ref_marker($refs,$co{'id'});73977398 git_header_html(undef,$expires);7399 git_print_page_nav('commit','',7400$hash,$co{'tree'},$hash,7401$formats_nav);74027403if(defined$co{'parent'}) {7404 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);7405}else{7406 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);7407}7408print"<div class=\"title_text\">\n".7409"<table class=\"object_header\">\n";7410 git_print_authorship_rows(\%co);7411print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";7412print"<tr>".7413"<td>tree</td>".7414"<td class=\"sha1\">".7415$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),7416class=>"list"},$co{'tree'}) .7417"</td>".7418"<td class=\"link\">".7419$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},7420"tree");7421my$snapshot_links= format_snapshot_links($hash);7422if(defined$snapshot_links) {7423print" | ".$snapshot_links;7424}7425print"</td>".7426"</tr>\n";74277428foreachmy$par(@$parents) {7429print"<tr>".7430"<td>parent</td>".7431"<td class=\"sha1\">".7432$cgi->a({-href => href(action=>"commit", hash=>$par),7433class=>"list"},$par) .7434"</td>".7435"<td class=\"link\">".7436$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .7437" | ".7438$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .7439"</td>".7440"</tr>\n";7441}7442print"</table>".7443"</div>\n";74447445print"<div class=\"page_body\">\n";7446 git_print_log($co{'comment'});7447print"</div>\n";74487449 git_difftree_body(\@difftree,$hash,@$parents);74507451 git_footer_html();7452}74537454sub git_object {7455# object is defined by:7456# - hash or hash_base alone7457# - hash_base and file_name7458my$type;74597460# - hash or hash_base alone7461if($hash|| ($hash_base&& !defined$file_name)) {7462my$object_id=$hash||$hash_base;74637464open my$fd,"-|", quote_command(7465 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'7466or die_error(404,"Object does not exist");7467$type= <$fd>;7468chomp$type;7469close$fd7470or die_error(404,"Object does not exist");74717472# - hash_base and file_name7473}elsif($hash_base&&defined$file_name) {7474$file_name=~ s,/+$,,;74757476system(git_cmd(),"cat-file",'-e',$hash_base) ==07477or die_error(404,"Base object does not exist");74787479# here errors should not hapen7480open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name7481or die_error(500,"Open git-ls-tree failed");7482my$line= <$fd>;7483close$fd;74847485#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'7486unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {7487 die_error(404,"File or directory for given base does not exist");7488}7489$type=$2;7490$hash=$3;7491}else{7492 die_error(400,"Not enough information to find object");7493}74947495print$cgi->redirect(-uri => href(action=>$type, -full=>1,7496 hash=>$hash, hash_base=>$hash_base,7497 file_name=>$file_name),7498-status =>'302 Found');7499}75007501sub git_blobdiff {7502my$format=shift||'html';7503my$diff_style=$input_params{'diff_style'} ||'inline';75047505my$fd;7506my@difftree;7507my%diffinfo;7508my$expires;75097510# preparing $fd and %diffinfo for git_patchset_body7511# new style URI7512if(defined$hash_base&&defined$hash_parent_base) {7513if(defined$file_name) {7514# read raw output7515open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7516$hash_parent_base,$hash_base,7517"--", (defined$file_parent?$file_parent: ()),$file_name7518or die_error(500,"Open git-diff-tree failed");7519@difftree=map{chomp;$_} <$fd>;7520close$fd7521or die_error(404,"Reading git-diff-tree failed");7522@difftree7523or die_error(404,"Blob diff not found");75247525}elsif(defined$hash&&7526$hash=~/[0-9a-fA-F]{40}/) {7527# try to find filename from $hash75287529# read filtered raw output7530open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7531$hash_parent_base,$hash_base,"--"7532or die_error(500,"Open git-diff-tree failed");7533@difftree=7534# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'7535# $hash == to_id7536grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}7537map{chomp;$_} <$fd>;7538close$fd7539or die_error(404,"Reading git-diff-tree failed");7540@difftree7541or die_error(404,"Blob diff not found");75427543}else{7544 die_error(400,"Missing one of the blob diff parameters");7545}75467547if(@difftree>1) {7548 die_error(400,"Ambiguous blob diff specification");7549}75507551%diffinfo= parse_difftree_raw_line($difftree[0]);7552$file_parent||=$diffinfo{'from_file'} ||$file_name;7553$file_name||=$diffinfo{'to_file'};75547555$hash_parent||=$diffinfo{'from_id'};7556$hash||=$diffinfo{'to_id'};75577558# non-textual hash id's can be cached7559if($hash_base=~m/^[0-9a-fA-F]{40}$/&&7560$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {7561$expires='+1d';7562}75637564# open patch output7565open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7566'-p', ($formateq'html'?"--full-index": ()),7567$hash_parent_base,$hash_base,7568"--", (defined$file_parent?$file_parent: ()),$file_name7569or die_error(500,"Open git-diff-tree failed");7570}75717572# old/legacy style URI -- not generated anymore since 1.4.3.7573if(!%diffinfo) {7574 die_error('404 Not Found',"Missing one of the blob diff parameters")7575}75767577# header7578if($formateq'html') {7579my$formats_nav=7580$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},7581"raw");7582$formats_nav.= diff_style_nav($diff_style);7583 git_header_html(undef,$expires);7584if(defined$hash_base&& (my%co= parse_commit($hash_base))) {7585 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);7586 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);7587}else{7588print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";7589print"<div class=\"title\">".esc_html("$hashvs$hash_parent")."</div>\n";7590}7591if(defined$file_name) {7592 git_print_page_path($file_name,"blob",$hash_base);7593}else{7594print"<div class=\"page_path\"></div>\n";7595}75967597}elsif($formateq'plain') {7598print$cgi->header(7599-type =>'text/plain',7600-charset =>'utf-8',7601-expires =>$expires,7602-content_disposition =>'inline; filename="'."$file_name".'.patch"');76037604print"X-Git-Url: ".$cgi->self_url() ."\n\n";76057606}else{7607 die_error(400,"Unknown blobdiff format");7608}76097610# patch7611if($formateq'html') {7612print"<div class=\"page_body\">\n";76137614 git_patchset_body($fd,$diff_style,7615[ \%diffinfo],$hash_base,$hash_parent_base);7616close$fd;76177618print"</div>\n";# class="page_body"7619 git_footer_html();76207621}else{7622while(my$line= <$fd>) {7623$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;7624$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;76257626print$line;76277628last if$line=~m!^\+\+\+!;7629}7630local$/=undef;7631print<$fd>;7632close$fd;7633}7634}76357636sub git_blobdiff_plain {7637 git_blobdiff('plain');7638}76397640# assumes that it is added as later part of already existing navigation,7641# so it returns "| foo | bar" rather than just "foo | bar"7642sub diff_style_nav {7643my($diff_style,$is_combined) =@_;7644$diff_style||='inline';76457646return""if($is_combined);76477648my@styles= (inline =>'inline','sidebyside'=>'side by side');7649my%styles=@styles;7650@styles=7651@styles[map{$_*2}0..$#styles/2];76527653returnjoin'',7654map{" | ".$_}7655map{7656$_eq$diff_style?$styles{$_} :7657$cgi->a({-href => href(-replay=>1, diff_style =>$_)},$styles{$_})7658}@styles;7659}76607661sub git_commitdiff {7662my%params=@_;7663my$format=$params{-format} ||'html';7664my$diff_style=$input_params{'diff_style'} ||'inline';76657666my($patch_max) = gitweb_get_feature('patches');7667if($formateq'patch') {7668 die_error(403,"Patch view not allowed")unless$patch_max;7669}76707671$hash||=$hash_base||"HEAD";7672my%co= parse_commit($hash)7673or die_error(404,"Unknown commit object");76747675# choose format for commitdiff for merge7676if(!defined$hash_parent&& @{$co{'parents'}} >1) {7677$hash_parent='--cc';7678}7679# we need to prepare $formats_nav before almost any parameter munging7680my$formats_nav;7681if($formateq'html') {7682$formats_nav=7683$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},7684"raw");7685if($patch_max&& @{$co{'parents'}} <=1) {7686$formats_nav.=" | ".7687$cgi->a({-href => href(action=>"patch", -replay=>1)},7688"patch");7689}7690$formats_nav.= diff_style_nav($diff_style, @{$co{'parents'}} >1);76917692if(defined$hash_parent&&7693$hash_parentne'-c'&&$hash_parentne'--cc') {7694# commitdiff with two commits given7695my$hash_parent_short=$hash_parent;7696if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {7697$hash_parent_short=substr($hash_parent,0,7);7698}7699$formats_nav.=7700' (from';7701for(my$i=0;$i< @{$co{'parents'}};$i++) {7702if($co{'parents'}[$i]eq$hash_parent) {7703$formats_nav.=' parent '. ($i+1);7704last;7705}7706}7707$formats_nav.=': '.7708$cgi->a({-href => href(-replay=>1,7709 hash=>$hash_parent, hash_base=>undef)},7710 esc_html($hash_parent_short)) .7711')';7712}elsif(!$co{'parent'}) {7713# --root commitdiff7714$formats_nav.=' (initial)';7715}elsif(scalar@{$co{'parents'}} ==1) {7716# single parent commit7717$formats_nav.=7718' (parent: '.7719$cgi->a({-href => href(-replay=>1,7720 hash=>$co{'parent'}, hash_base=>undef)},7721 esc_html(substr($co{'parent'},0,7))) .7722')';7723}else{7724# merge commit7725if($hash_parenteq'--cc') {7726$formats_nav.=' | '.7727$cgi->a({-href => href(-replay=>1,7728 hash=>$hash, hash_parent=>'-c')},7729'combined');7730}else{# $hash_parent eq '-c'7731$formats_nav.=' | '.7732$cgi->a({-href => href(-replay=>1,7733 hash=>$hash, hash_parent=>'--cc')},7734'compact');7735}7736$formats_nav.=7737' (merge: '.7738join(' ',map{7739$cgi->a({-href => href(-replay=>1,7740 hash=>$_, hash_base=>undef)},7741 esc_html(substr($_,0,7)));7742} @{$co{'parents'}} ) .7743')';7744}7745}77467747my$hash_parent_param=$hash_parent;7748if(!defined$hash_parent_param) {7749# --cc for multiple parents, --root for parentless7750$hash_parent_param=7751@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';7752}77537754# read commitdiff7755my$fd;7756my@difftree;7757if($formateq'html') {7758open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7759"--no-commit-id","--patch-with-raw","--full-index",7760$hash_parent_param,$hash,"--"7761or die_error(500,"Open git-diff-tree failed");77627763while(my$line= <$fd>) {7764chomp$line;7765# empty line ends raw part of diff-tree output7766last unless$line;7767push@difftree,scalar parse_difftree_raw_line($line);7768}77697770}elsif($formateq'plain') {7771open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,7772'-p',$hash_parent_param,$hash,"--"7773or die_error(500,"Open git-diff-tree failed");7774}elsif($formateq'patch') {7775# For commit ranges, we limit the output to the number of7776# patches specified in the 'patches' feature.7777# For single commits, we limit the output to a single patch,7778# diverging from the git-format-patch default.7779my@commit_spec= ();7780if($hash_parent) {7781if($patch_max>0) {7782push@commit_spec,"-$patch_max";7783}7784push@commit_spec,'-n',"$hash_parent..$hash";7785}else{7786if($params{-single}) {7787push@commit_spec,'-1';7788}else{7789if($patch_max>0) {7790push@commit_spec,"-$patch_max";7791}7792push@commit_spec,"-n";7793}7794push@commit_spec,'--root',$hash;7795}7796open$fd,"-|", git_cmd(),"format-patch",@diff_opts,7797'--encoding=utf8','--stdout',@commit_spec7798or die_error(500,"Open git-format-patch failed");7799}else{7800 die_error(400,"Unknown commitdiff format");7801}78027803# non-textual hash id's can be cached7804my$expires;7805if($hash=~m/^[0-9a-fA-F]{40}$/) {7806$expires="+1d";7807}78087809# write commit message7810if($formateq'html') {7811my$refs= git_get_references();7812my$ref= format_ref_marker($refs,$co{'id'});78137814 git_header_html(undef,$expires);7815 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);7816 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);7817print"<div class=\"title_text\">\n".7818"<table class=\"object_header\">\n";7819 git_print_authorship_rows(\%co);7820print"</table>".7821"</div>\n";7822print"<div class=\"page_body\">\n";7823if(@{$co{'comment'}} >1) {7824print"<div class=\"log\">\n";7825 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);7826print"</div>\n";# class="log"7827}78287829}elsif($formateq'plain') {7830my$refs= git_get_references("tags");7831my$tagname= git_get_rev_name_tags($hash);7832my$filename= basename($project) ."-$hash.patch";78337834print$cgi->header(7835-type =>'text/plain',7836-charset =>'utf-8',7837-expires =>$expires,7838-content_disposition =>'inline; filename="'."$filename".'"');7839my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});7840print"From: ". to_utf8($co{'author'}) ."\n";7841print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";7842print"Subject: ". to_utf8($co{'title'}) ."\n";78437844print"X-Git-Tag:$tagname\n"if$tagname;7845print"X-Git-Url: ".$cgi->self_url() ."\n\n";78467847foreachmy$line(@{$co{'comment'}}) {7848print to_utf8($line) ."\n";7849}7850print"---\n\n";7851}elsif($formateq'patch') {7852my$filename= basename($project) ."-$hash.patch";78537854print$cgi->header(7855-type =>'text/plain',7856-charset =>'utf-8',7857-expires =>$expires,7858-content_disposition =>'inline; filename="'."$filename".'"');7859}78607861# write patch7862if($formateq'html') {7863my$use_parents= !defined$hash_parent||7864$hash_parenteq'-c'||$hash_parenteq'--cc';7865 git_difftree_body(\@difftree,$hash,7866$use_parents? @{$co{'parents'}} :$hash_parent);7867print"<br/>\n";78687869 git_patchset_body($fd,$diff_style,7870 \@difftree,$hash,7871$use_parents? @{$co{'parents'}} :$hash_parent);7872close$fd;7873print"</div>\n";# class="page_body"7874 git_footer_html();78757876}elsif($formateq'plain') {7877local$/=undef;7878print<$fd>;7879close$fd7880or print"Reading git-diff-tree failed\n";7881}elsif($formateq'patch') {7882local$/=undef;7883print<$fd>;7884close$fd7885or print"Reading git-format-patch failed\n";7886}7887}78887889sub git_commitdiff_plain {7890 git_commitdiff(-format =>'plain');7891}78927893# format-patch-style patches7894sub git_patch {7895 git_commitdiff(-format =>'patch', -single =>1);7896}78977898sub git_patches {7899 git_commitdiff(-format =>'patch');7900}79017902sub git_history {7903 git_log_generic('history', \&git_history_body,7904$hash_base,$hash_parent_base,7905$file_name,$hash);7906}79077908sub git_search {7909$searchtype||='commit';79107911# check if appropriate features are enabled7912 gitweb_check_feature('search')7913or die_error(403,"Search is disabled");7914if($searchtypeeq'pickaxe') {7915# pickaxe may take all resources of your box and run for several minutes7916# with every query - so decide by yourself how public you make this feature7917 gitweb_check_feature('pickaxe')7918or die_error(403,"Pickaxe search is disabled");7919}7920if($searchtypeeq'grep') {7921# grep search might be potentially CPU-intensive, too7922 gitweb_check_feature('grep')7923or die_error(403,"Grep search is disabled");7924}79257926if(!defined$searchtext) {7927 die_error(400,"Text field is empty");7928}7929if(!defined$hash) {7930$hash= git_get_head_hash($project);7931}7932my%co= parse_commit($hash);7933if(!%co) {7934 die_error(404,"Unknown commit object");7935}7936if(!defined$page) {7937$page=0;7938}79397940if($searchtypeeq'commit'||7941$searchtypeeq'author'||7942$searchtypeeq'committer') {7943 git_search_message(%co);7944}elsif($searchtypeeq'pickaxe') {7945 git_search_changes(%co);7946}elsif($searchtypeeq'grep') {7947 git_search_files(%co);7948}else{7949 die_error(400,"Unknown search type");7950}7951}79527953sub git_search_help {7954 git_header_html();7955 git_print_page_nav('','',$hash,$hash,$hash);7956print<<EOT;7957<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without7958regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,7959the pattern entered is recognized as the POSIX extended7960<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case7961insensitive).</p>7962<dl>7963<dt><b>commit</b></dt>7964<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>7965EOT7966my$have_grep= gitweb_check_feature('grep');7967if($have_grep) {7968print<<EOT;7969<dt><b>grep</b></dt>7970<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing7971 a different one) are searched for the given pattern. On large trees, this search can take7972a while and put some strain on the server, so please use it with some consideration. Note that7973due to git-grep peculiarity, currently if regexp mode is turned off, the matches are7974case-sensitive.</dd>7975EOT7976}7977print<<EOT;7978<dt><b>author</b></dt>7979<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>7980<dt><b>committer</b></dt>7981<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>7982EOT7983my$have_pickaxe= gitweb_check_feature('pickaxe');7984if($have_pickaxe) {7985print<<EOT;7986<dt><b>pickaxe</b></dt>7987<dd>All commits that caused the string to appear or disappear from any file (changes that7988added, removed or "modified" the string) will be listed. This search can take a while and7989takes a lot of strain on the server, so please use it wisely. Note that since you may be7990interested even in changes just changing the case as well, this search is case sensitive.</dd>7991EOT7992}7993print"</dl>\n";7994 git_footer_html();7995}79967997sub git_shortlog {7998 git_log_generic('shortlog', \&git_shortlog_body,7999$hash,$hash_parent);8000}80018002## ......................................................................8003## feeds (RSS, Atom; OPML)80048005sub git_feed {8006my$format=shift||'atom';8007my$have_blame= gitweb_check_feature('blame');80088009# Atom: http://www.atomenabled.org/developers/syndication/8010# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ8011if($formatne'rss'&&$formatne'atom') {8012 die_error(400,"Unknown web feed format");8013}80148015# log/feed of current (HEAD) branch, log of given branch, history of file/directory8016my$head=$hash||'HEAD';8017my@commitlist= parse_commits($head,150,0,$file_name);80188019my%latest_commit;8020my%latest_date;8021my$content_type="application/$format+xml";8022if(defined$cgi->http('HTTP_ACCEPT') &&8023$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {8024# browser (feed reader) prefers text/xml8025$content_type='text/xml';8026}8027if(defined($commitlist[0])) {8028%latest_commit= %{$commitlist[0]};8029my$latest_epoch=$latest_commit{'committer_epoch'};8030 exit_if_unmodified_since($latest_epoch);8031%latest_date= parse_date($latest_epoch,$latest_commit{'committer_tz'});8032}8033print$cgi->header(8034-type =>$content_type,8035-charset =>'utf-8',8036%latest_date? (-last_modified =>$latest_date{'rfc2822'}) : (),8037-status =>'200 OK');80388039# Optimization: skip generating the body if client asks only8040# for Last-Modified date.8041return if($cgi->request_method()eq'HEAD');80428043# header variables8044my$title="$site_name-$project/$action";8045my$feed_type='log';8046if(defined$hash) {8047$title.=" - '$hash'";8048$feed_type='branch log';8049if(defined$file_name) {8050$title.=" ::$file_name";8051$feed_type='history';8052}8053}elsif(defined$file_name) {8054$title.=" -$file_name";8055$feed_type='history';8056}8057$title.="$feed_type";8058my$descr= git_get_project_description($project);8059if(defined$descr) {8060$descr= esc_html($descr);8061}else{8062$descr="$project".8063($formateq'rss'?'RSS':'Atom') .8064" feed";8065}8066my$owner= git_get_project_owner($project);8067$owner= esc_html($owner);80688069#header8070my$alt_url;8071if(defined$file_name) {8072$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);8073}elsif(defined$hash) {8074$alt_url= href(-full=>1, action=>"log", hash=>$hash);8075}else{8076$alt_url= href(-full=>1, action=>"summary");8077}8078print qq!<?xml version="1.0" encoding="utf-8"?>\n!;8079if($formateq'rss') {8080print<<XML;8081<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">8082<channel>8083XML8084print"<title>$title</title>\n".8085"<link>$alt_url</link>\n".8086"<description>$descr</description>\n".8087"<language>en</language>\n".8088# project owner is responsible for 'editorial' content8089"<managingEditor>$owner</managingEditor>\n";8090if(defined$logo||defined$favicon) {8091# prefer the logo to the favicon, since RSS8092# doesn't allow both8093my$img= esc_url($logo||$favicon);8094print"<image>\n".8095"<url>$img</url>\n".8096"<title>$title</title>\n".8097"<link>$alt_url</link>\n".8098"</image>\n";8099}8100if(%latest_date) {8101print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";8102print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";8103}8104print"<generator>gitweb v.$version/$git_version</generator>\n";8105}elsif($formateq'atom') {8106print<<XML;8107<feed xmlns="http://www.w3.org/2005/Atom">8108XML8109print"<title>$title</title>\n".8110"<subtitle>$descr</subtitle>\n".8111'<link rel="alternate" type="text/html" href="'.8112$alt_url.'" />'."\n".8113'<link rel="self" type="'.$content_type.'" href="'.8114$cgi->self_url() .'" />'."\n".8115"<id>". href(-full=>1) ."</id>\n".8116# use project owner for feed author8117"<author><name>$owner</name></author>\n";8118if(defined$favicon) {8119print"<icon>". esc_url($favicon) ."</icon>\n";8120}8121if(defined$logo) {8122# not twice as wide as tall: 72 x 27 pixels8123print"<logo>". esc_url($logo) ."</logo>\n";8124}8125if(!%latest_date) {8126# dummy date to keep the feed valid until commits trickle in:8127print"<updated>1970-01-01T00:00:00Z</updated>\n";8128}else{8129print"<updated>$latest_date{'iso-8601'}</updated>\n";8130}8131print"<generator version='$version/$git_version'>gitweb</generator>\n";8132}81338134# contents8135for(my$i=0;$i<=$#commitlist;$i++) {8136my%co= %{$commitlist[$i]};8137my$commit=$co{'id'};8138# we read 150, we always show 30 and the ones more recent than 48 hours8139if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {8140last;8141}8142my%cd= parse_date($co{'author_epoch'},$co{'author_tz'});81438144# get list of changed files8145open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,8146$co{'parent'} ||"--root",8147$co{'id'},"--", (defined$file_name?$file_name: ())8148ornext;8149my@difftree=map{chomp;$_} <$fd>;8150close$fd8151ornext;81528153# print element (entry, item)8154my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);8155if($formateq'rss') {8156print"<item>\n".8157"<title>". esc_html($co{'title'}) ."</title>\n".8158"<author>". esc_html($co{'author'}) ."</author>\n".8159"<pubDate>$cd{'rfc2822'}</pubDate>\n".8160"<guid isPermaLink=\"true\">$co_url</guid>\n".8161"<link>$co_url</link>\n".8162"<description>". esc_html($co{'title'}) ."</description>\n".8163"<content:encoded>".8164"<![CDATA[\n";8165}elsif($formateq'atom') {8166print"<entry>\n".8167"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".8168"<updated>$cd{'iso-8601'}</updated>\n".8169"<author>\n".8170" <name>". esc_html($co{'author_name'}) ."</name>\n";8171if($co{'author_email'}) {8172print" <email>". esc_html($co{'author_email'}) ."</email>\n";8173}8174print"</author>\n".8175# use committer for contributor8176"<contributor>\n".8177" <name>". esc_html($co{'committer_name'}) ."</name>\n";8178if($co{'committer_email'}) {8179print" <email>". esc_html($co{'committer_email'}) ."</email>\n";8180}8181print"</contributor>\n".8182"<published>$cd{'iso-8601'}</published>\n".8183"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".8184"<id>$co_url</id>\n".8185"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".8186"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";8187}8188my$comment=$co{'comment'};8189print"<pre>\n";8190foreachmy$line(@$comment) {8191$line= esc_html($line);8192print"$line\n";8193}8194print"</pre><ul>\n";8195foreachmy$difftree_line(@difftree) {8196my%difftree= parse_difftree_raw_line($difftree_line);8197next if!$difftree{'from_id'};81988199my$file=$difftree{'file'} ||$difftree{'to_file'};82008201print"<li>".8202"[".8203$cgi->a({-href => href(-full=>1, action=>"blobdiff",8204 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},8205 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},8206 file_name=>$file, file_parent=>$difftree{'from_file'}),8207-title =>"diff"},'D');8208if($have_blame) {8209print$cgi->a({-href => href(-full=>1, action=>"blame",8210 file_name=>$file, hash_base=>$commit),8211-title =>"blame"},'B');8212}8213# if this is not a feed of a file history8214if(!defined$file_name||$file_namene$file) {8215print$cgi->a({-href => href(-full=>1, action=>"history",8216 file_name=>$file, hash=>$commit),8217-title =>"history"},'H');8218}8219$file= esc_path($file);8220print"] ".8221"$file</li>\n";8222}8223if($formateq'rss') {8224print"</ul>]]>\n".8225"</content:encoded>\n".8226"</item>\n";8227}elsif($formateq'atom') {8228print"</ul>\n</div>\n".8229"</content>\n".8230"</entry>\n";8231}8232}82338234# end of feed8235if($formateq'rss') {8236print"</channel>\n</rss>\n";8237}elsif($formateq'atom') {8238print"</feed>\n";8239}8240}82418242sub git_rss {8243 git_feed('rss');8244}82458246sub git_atom {8247 git_feed('atom');8248}82498250sub git_opml {8251my@list= git_get_projects_list($project_filter,$strict_export);8252if(!@list) {8253 die_error(404,"No projects found");8254}82558256print$cgi->header(8257-type =>'text/xml',8258-charset =>'utf-8',8259-content_disposition =>'inline; filename="opml.xml"');82608261my$title= esc_html($site_name);8262my$filter=" within subdirectory ";8263if(defined$project_filter) {8264$filter.= esc_html($project_filter);8265}else{8266$filter="";8267}8268print<<XML;8269<?xml version="1.0" encoding="utf-8"?>8270<opml version="1.0">8271<head>8272 <title>$titleOPML Export$filter</title>8273</head>8274<body>8275<outline text="git RSS feeds">8276XML82778278foreachmy$pr(@list) {8279my%proj=%$pr;8280my$head= git_get_head_hash($proj{'path'});8281if(!defined$head) {8282next;8283}8284$git_dir="$projectroot/$proj{'path'}";8285my%co= parse_commit($head);8286if(!%co) {8287next;8288}82898290my$path= esc_html(chop_str($proj{'path'},25,5));8291my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);8292my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);8293print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";8294}8295print<<XML;8296</outline>8297</body>8298</opml>8299XML8300}