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 10use strict; 11use warnings; 12use CGI qw(:standard :escapeHTML -nosticky); 13use CGI::Util qw(unescape); 14use CGI::Carp qw(fatalsToBrowser); 15use Encode; 16use Fcntl ':mode'; 17use File::Find qw(); 18use File::Basename qw(basename); 19binmode STDOUT,':utf8'; 20 21BEGIN{ 22 CGI->compile()if$ENV{'MOD_PERL'}; 23} 24 25our$cgi= new CGI; 26our$version="++GIT_VERSION++"; 27our$my_url=$cgi->url(); 28our$my_uri=$cgi->url(-absolute =>1); 29 30# Base URL for relative URLs in gitweb ($logo, $favicon, ...), 31# needed and used only for URLs with nonempty PATH_INFO 32our$base_url=$my_url; 33 34# When the script is used as DirectoryIndex, the URL does not contain the name 35# of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we 36# have to do it ourselves. We make $path_info global because it's also used 37# later on. 38# 39# Another issue with the script being the DirectoryIndex is that the resulting 40# $my_url data is not the full script URL: this is good, because we want 41# generated links to keep implying the script name if it wasn't explicitly 42# indicated in the URL we're handling, but it means that $my_url cannot be used 43# as base URL. 44# Therefore, if we needed to strip PATH_INFO, then we know that we have 45# to build the base URL ourselves: 46our$path_info=$ENV{"PATH_INFO"}; 47if($path_info) { 48if($my_url=~ s,\Q$path_info\E$,, && 49$my_uri=~ s,\Q$path_info\E$,, && 50defined$ENV{'SCRIPT_NAME'}) { 51$base_url=$cgi->url(-base =>1) .$ENV{'SCRIPT_NAME'}; 52} 53} 54 55# core git executable to use 56# this can just be "git" if your webserver has a sensible PATH 57our$GIT="++GIT_BINDIR++/git"; 58 59# absolute fs-path which will be prepended to the project path 60#our $projectroot = "/pub/scm"; 61our$projectroot="++GITWEB_PROJECTROOT++"; 62 63# fs traversing limit for getting project list 64# the number is relative to the projectroot 65our$project_maxdepth="++GITWEB_PROJECT_MAXDEPTH++"; 66 67# target of the home link on top of all pages 68our$home_link=$my_uri||"/"; 69 70# string of the home link on top of all pages 71our$home_link_str="++GITWEB_HOME_LINK_STR++"; 72 73# name of your site or organization to appear in page titles 74# replace this with something more descriptive for clearer bookmarks 75our$site_name="++GITWEB_SITENAME++" 76|| ($ENV{'SERVER_NAME'} ||"Untitled") ." Git"; 77 78# filename of html text to include at top of each page 79our$site_header="++GITWEB_SITE_HEADER++"; 80# html text to include at home page 81our$home_text="++GITWEB_HOMETEXT++"; 82# filename of html text to include at bottom of each page 83our$site_footer="++GITWEB_SITE_FOOTER++"; 84 85# URI of stylesheets 86our@stylesheets= ("++GITWEB_CSS++"); 87# URI of a single stylesheet, which can be overridden in GITWEB_CONFIG. 88our$stylesheet=undef; 89# URI of GIT logo (72x27 size) 90our$logo="++GITWEB_LOGO++"; 91# URI of GIT favicon, assumed to be image/png type 92our$favicon="++GITWEB_FAVICON++"; 93 94# URI and label (title) of GIT logo link 95#our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/"; 96#our $logo_label = "git documentation"; 97our$logo_url="http://git-scm.com/"; 98our$logo_label="git homepage"; 99 100# source of projects list 101our$projects_list="++GITWEB_LIST++"; 102 103# the width (in characters) of the projects list "Description" column 104our$projects_list_description_width=25; 105 106# default order of projects list 107# valid values are none, project, descr, owner, and age 108our$default_projects_order="project"; 109 110# show repository only if this file exists 111# (only effective if this variable evaluates to true) 112our$export_ok="++GITWEB_EXPORT_OK++"; 113 114# show repository only if this subroutine returns true 115# when given the path to the project, for example: 116# sub { return -e "$_[0]/git-daemon-export-ok"; } 117our$export_auth_hook=undef; 118 119# only allow viewing of repositories also shown on the overview page 120our$strict_export="++GITWEB_STRICT_EXPORT++"; 121 122# list of git base URLs used for URL to where fetch project from, 123# i.e. full URL is "$git_base_url/$project" 124our@git_base_url_list=grep{$_ne''} ("++GITWEB_BASE_URL++"); 125 126# default blob_plain mimetype and default charset for text/plain blob 127our$default_blob_plain_mimetype='text/plain'; 128our$default_text_plain_charset=undef; 129 130# file to use for guessing MIME types before trying /etc/mime.types 131# (relative to the current git repository) 132our$mimetypes_file=undef; 133 134# assume this charset if line contains non-UTF-8 characters; 135# it should be valid encoding (see Encoding::Supported(3pm) for list), 136# for which encoding all byte sequences are valid, for example 137# 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it 138# could be even 'utf-8' for the old behavior) 139our$fallback_encoding='latin1'; 140 141# rename detection options for git-diff and git-diff-tree 142# - default is '-M', with the cost proportional to 143# (number of removed files) * (number of new files). 144# - more costly is '-C' (which implies '-M'), with the cost proportional to 145# (number of changed files + number of removed files) * (number of new files) 146# - even more costly is '-C', '--find-copies-harder' with cost 147# (number of files in the original tree) * (number of new files) 148# - one might want to include '-B' option, e.g. '-B', '-M' 149our@diff_opts= ('-M');# taken from git_commit 150 151# Disables features that would allow repository owners to inject script into 152# the gitweb domain. 153our$prevent_xss=0; 154 155# information about snapshot formats that gitweb is capable of serving 156our%known_snapshot_formats= ( 157# name => { 158# 'display' => display name, 159# 'type' => mime type, 160# 'suffix' => filename suffix, 161# 'format' => --format for git-archive, 162# 'compressor' => [compressor command and arguments] 163# (array reference, optional)} 164# 165'tgz'=> { 166'display'=>'tar.gz', 167'type'=>'application/x-gzip', 168'suffix'=>'.tar.gz', 169'format'=>'tar', 170'compressor'=> ['gzip']}, 171 172'tbz2'=> { 173'display'=>'tar.bz2', 174'type'=>'application/x-bzip2', 175'suffix'=>'.tar.bz2', 176'format'=>'tar', 177'compressor'=> ['bzip2']}, 178 179'zip'=> { 180'display'=>'zip', 181'type'=>'application/x-zip', 182'suffix'=>'.zip', 183'format'=>'zip'}, 184); 185 186# Aliases so we understand old gitweb.snapshot values in repository 187# configuration. 188our%known_snapshot_format_aliases= ( 189'gzip'=>'tgz', 190'bzip2'=>'tbz2', 191 192# backward compatibility: legacy gitweb config support 193'x-gzip'=>undef,'gz'=>undef, 194'x-bzip2'=>undef,'bz2'=>undef, 195'x-zip'=>undef,''=>undef, 196); 197 198# Pixel sizes for icons and avatars. If the default font sizes or lineheights 199# are changed, it may be appropriate to change these values too via 200# $GITWEB_CONFIG. 201our%avatar_size= ( 202'default'=>16, 203'double'=>32 204); 205 206# You define site-wide feature defaults here; override them with 207# $GITWEB_CONFIG as necessary. 208our%feature= ( 209# feature => { 210# 'sub' => feature-sub (subroutine), 211# 'override' => allow-override (boolean), 212# 'default' => [ default options...] (array reference)} 213# 214# if feature is overridable (it means that allow-override has true value), 215# then feature-sub will be called with default options as parameters; 216# return value of feature-sub indicates if to enable specified feature 217# 218# if there is no 'sub' key (no feature-sub), then feature cannot be 219# overriden 220# 221# use gitweb_get_feature(<feature>) to retrieve the <feature> value 222# (an array) or gitweb_check_feature(<feature>) to check if <feature> 223# is enabled 224 225# Enable the 'blame' blob view, showing the last commit that modified 226# each line in the file. This can be very CPU-intensive. 227 228# To enable system wide have in $GITWEB_CONFIG 229# $feature{'blame'}{'default'} = [1]; 230# To have project specific config enable override in $GITWEB_CONFIG 231# $feature{'blame'}{'override'} = 1; 232# and in project config gitweb.blame = 0|1; 233'blame'=> { 234'sub'=>sub{ feature_bool('blame',@_) }, 235'override'=>0, 236'default'=> [0]}, 237 238# Enable the 'snapshot' link, providing a compressed archive of any 239# tree. This can potentially generate high traffic if you have large 240# project. 241 242# Value is a list of formats defined in %known_snapshot_formats that 243# you wish to offer. 244# To disable system wide have in $GITWEB_CONFIG 245# $feature{'snapshot'}{'default'} = []; 246# To have project specific config enable override in $GITWEB_CONFIG 247# $feature{'snapshot'}{'override'} = 1; 248# and in project config, a comma-separated list of formats or "none" 249# to disable. Example: gitweb.snapshot = tbz2,zip; 250'snapshot'=> { 251'sub'=> \&feature_snapshot, 252'override'=>0, 253'default'=> ['tgz']}, 254 255# Enable text search, which will list the commits which match author, 256# committer or commit text to a given string. Enabled by default. 257# Project specific override is not supported. 258'search'=> { 259'override'=>0, 260'default'=> [1]}, 261 262# Enable grep search, which will list the files in currently selected 263# tree containing the given string. Enabled by default. This can be 264# potentially CPU-intensive, of course. 265 266# To enable system wide have in $GITWEB_CONFIG 267# $feature{'grep'}{'default'} = [1]; 268# To have project specific config enable override in $GITWEB_CONFIG 269# $feature{'grep'}{'override'} = 1; 270# and in project config gitweb.grep = 0|1; 271'grep'=> { 272'sub'=>sub{ feature_bool('grep',@_) }, 273'override'=>0, 274'default'=> [1]}, 275 276# Enable the pickaxe search, which will list the commits that modified 277# a given string in a file. This can be practical and quite faster 278# alternative to 'blame', but still potentially CPU-intensive. 279 280# To enable system wide have in $GITWEB_CONFIG 281# $feature{'pickaxe'}{'default'} = [1]; 282# To have project specific config enable override in $GITWEB_CONFIG 283# $feature{'pickaxe'}{'override'} = 1; 284# and in project config gitweb.pickaxe = 0|1; 285'pickaxe'=> { 286'sub'=>sub{ feature_bool('pickaxe',@_) }, 287'override'=>0, 288'default'=> [1]}, 289 290# Make gitweb use an alternative format of the URLs which can be 291# more readable and natural-looking: project name is embedded 292# directly in the path and the query string contains other 293# auxiliary information. All gitweb installations recognize 294# URL in either format; this configures in which formats gitweb 295# generates links. 296 297# To enable system wide have in $GITWEB_CONFIG 298# $feature{'pathinfo'}{'default'} = [1]; 299# Project specific override is not supported. 300 301# Note that you will need to change the default location of CSS, 302# favicon, logo and possibly other files to an absolute URL. Also, 303# if gitweb.cgi serves as your indexfile, you will need to force 304# $my_uri to contain the script name in your $GITWEB_CONFIG. 305'pathinfo'=> { 306'override'=>0, 307'default'=> [0]}, 308 309# Make gitweb consider projects in project root subdirectories 310# to be forks of existing projects. Given project $projname.git, 311# projects matching $projname/*.git will not be shown in the main 312# projects list, instead a '+' mark will be added to $projname 313# there and a 'forks' view will be enabled for the project, listing 314# all the forks. If project list is taken from a file, forks have 315# to be listed after the main project. 316 317# To enable system wide have in $GITWEB_CONFIG 318# $feature{'forks'}{'default'} = [1]; 319# Project specific override is not supported. 320'forks'=> { 321'override'=>0, 322'default'=> [0]}, 323 324# Insert custom links to the action bar of all project pages. 325# This enables you mainly to link to third-party scripts integrating 326# into gitweb; e.g. git-browser for graphical history representation 327# or custom web-based repository administration interface. 328 329# The 'default' value consists of a list of triplets in the form 330# (label, link, position) where position is the label after which 331# to insert the link and link is a format string where %n expands 332# to the project name, %f to the project path within the filesystem, 333# %h to the current hash (h gitweb parameter) and %b to the current 334# hash base (hb gitweb parameter); %% expands to %. 335 336# To enable system wide have in $GITWEB_CONFIG e.g. 337# $feature{'actions'}{'default'} = [('graphiclog', 338# '/git-browser/by-commit.html?r=%n', 'summary')]; 339# Project specific override is not supported. 340'actions'=> { 341'override'=>0, 342'default'=> []}, 343 344# Allow gitweb scan project content tags described in ctags/ 345# of project repository, and display the popular Web 2.0-ish 346# "tag cloud" near the project list. Note that this is something 347# COMPLETELY different from the normal Git tags. 348 349# gitweb by itself can show existing tags, but it does not handle 350# tagging itself; you need an external application for that. 351# For an example script, check Girocco's cgi/tagproj.cgi. 352# You may want to install the HTML::TagCloud Perl module to get 353# a pretty tag cloud instead of just a list of tags. 354 355# To enable system wide have in $GITWEB_CONFIG 356# $feature{'ctags'}{'default'} = ['path_to_tag_script']; 357# Project specific override is not supported. 358'ctags'=> { 359'override'=>0, 360'default'=> [0]}, 361 362# The maximum number of patches in a patchset generated in patch 363# view. Set this to 0 or undef to disable patch view, or to a 364# negative number to remove any limit. 365 366# To disable system wide have in $GITWEB_CONFIG 367# $feature{'patches'}{'default'} = [0]; 368# To have project specific config enable override in $GITWEB_CONFIG 369# $feature{'patches'}{'override'} = 1; 370# and in project config gitweb.patches = 0|n; 371# where n is the maximum number of patches allowed in a patchset. 372'patches'=> { 373'sub'=> \&feature_patches, 374'override'=>0, 375'default'=> [16]}, 376 377# Avatar support. When this feature is enabled, views such as 378# shortlog or commit will display an avatar associated with 379# the email of the committer(s) and/or author(s). 380 381# Currently available providers are gravatar and picon. 382# If an unknown provider is specified, the feature is disabled. 383 384# Gravatar depends on Digest::MD5. 385# Picon currently relies on the indiana.edu database. 386 387# To enable system wide have in $GITWEB_CONFIG 388# $feature{'avatar'}{'default'} = ['<provider>']; 389# where <provider> is either gravatar or picon. 390# To have project specific config enable override in $GITWEB_CONFIG 391# $feature{'avatar'}{'override'} = 1; 392# and in project config gitweb.avatar = <provider>; 393'avatar'=> { 394'sub'=> \&feature_avatar, 395'override'=>0, 396'default'=> ['']}, 397); 398 399sub gitweb_get_feature { 400my($name) =@_; 401return unlessexists$feature{$name}; 402my($sub,$override,@defaults) = ( 403$feature{$name}{'sub'}, 404$feature{$name}{'override'}, 405@{$feature{$name}{'default'}}); 406if(!$override) {return@defaults; } 407if(!defined$sub) { 408warn"feature$nameis not overridable"; 409return@defaults; 410} 411return$sub->(@defaults); 412} 413 414# A wrapper to check if a given feature is enabled. 415# With this, you can say 416# 417# my $bool_feat = gitweb_check_feature('bool_feat'); 418# gitweb_check_feature('bool_feat') or somecode; 419# 420# instead of 421# 422# my ($bool_feat) = gitweb_get_feature('bool_feat'); 423# (gitweb_get_feature('bool_feat'))[0] or somecode; 424# 425sub gitweb_check_feature { 426return(gitweb_get_feature(@_))[0]; 427} 428 429 430sub feature_bool { 431my$key=shift; 432my($val) = git_get_project_config($key,'--bool'); 433 434if(!defined$val) { 435return($_[0]); 436}elsif($valeq'true') { 437return(1); 438}elsif($valeq'false') { 439return(0); 440} 441} 442 443sub feature_snapshot { 444my(@fmts) =@_; 445 446my($val) = git_get_project_config('snapshot'); 447 448if($val) { 449@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 450} 451 452return@fmts; 453} 454 455sub feature_patches { 456my@val= (git_get_project_config('patches','--int')); 457 458if(@val) { 459return@val; 460} 461 462return($_[0]); 463} 464 465sub feature_avatar { 466my@val= (git_get_project_config('avatar')); 467 468return@val?@val:@_; 469} 470 471# checking HEAD file with -e is fragile if the repository was 472# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 473# and then pruned. 474sub check_head_link { 475my($dir) =@_; 476my$headfile="$dir/HEAD"; 477return((-e $headfile) || 478(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 479} 480 481sub check_export_ok { 482my($dir) =@_; 483return(check_head_link($dir) && 484(!$export_ok|| -e "$dir/$export_ok") && 485(!$export_auth_hook||$export_auth_hook->($dir))); 486} 487 488# process alternate names for backward compatibility 489# filter out unsupported (unknown) snapshot formats 490sub filter_snapshot_fmts { 491my@fmts=@_; 492 493@fmts=map{ 494exists$known_snapshot_format_aliases{$_} ? 495$known_snapshot_format_aliases{$_} :$_}@fmts; 496@fmts=grep{ 497exists$known_snapshot_formats{$_} }@fmts; 498} 499 500our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 501if(-e $GITWEB_CONFIG) { 502do$GITWEB_CONFIG; 503}else{ 504our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 505do$GITWEB_CONFIG_SYSTEMif-e $GITWEB_CONFIG_SYSTEM; 506} 507 508# version of the core git binary 509our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 510 511$projects_list||=$projectroot; 512 513# ====================================================================== 514# input validation and dispatch 515 516# input parameters can be collected from a variety of sources (presently, CGI 517# and PATH_INFO), so we define an %input_params hash that collects them all 518# together during validation: this allows subsequent uses (e.g. href()) to be 519# agnostic of the parameter origin 520 521our%input_params= (); 522 523# input parameters are stored with the long parameter name as key. This will 524# also be used in the href subroutine to convert parameters to their CGI 525# equivalent, and since the href() usage is the most frequent one, we store 526# the name -> CGI key mapping here, instead of the reverse. 527# 528# XXX: Warning: If you touch this, check the search form for updating, 529# too. 530 531our@cgi_param_mapping= ( 532 project =>"p", 533 action =>"a", 534 file_name =>"f", 535 file_parent =>"fp", 536 hash =>"h", 537 hash_parent =>"hp", 538 hash_base =>"hb", 539 hash_parent_base =>"hpb", 540 page =>"pg", 541 order =>"o", 542 searchtext =>"s", 543 searchtype =>"st", 544 snapshot_format =>"sf", 545 extra_options =>"opt", 546 search_use_regexp =>"sr", 547); 548our%cgi_param_mapping=@cgi_param_mapping; 549 550# we will also need to know the possible actions, for validation 551our%actions= ( 552"blame"=> \&git_blame, 553"blobdiff"=> \&git_blobdiff, 554"blobdiff_plain"=> \&git_blobdiff_plain, 555"blob"=> \&git_blob, 556"blob_plain"=> \&git_blob_plain, 557"commitdiff"=> \&git_commitdiff, 558"commitdiff_plain"=> \&git_commitdiff_plain, 559"commit"=> \&git_commit, 560"forks"=> \&git_forks, 561"heads"=> \&git_heads, 562"history"=> \&git_history, 563"log"=> \&git_log, 564"patch"=> \&git_patch, 565"patches"=> \&git_patches, 566"rss"=> \&git_rss, 567"atom"=> \&git_atom, 568"search"=> \&git_search, 569"search_help"=> \&git_search_help, 570"shortlog"=> \&git_shortlog, 571"summary"=> \&git_summary, 572"tag"=> \&git_tag, 573"tags"=> \&git_tags, 574"tree"=> \&git_tree, 575"snapshot"=> \&git_snapshot, 576"object"=> \&git_object, 577# those below don't need $project 578"opml"=> \&git_opml, 579"project_list"=> \&git_project_list, 580"project_index"=> \&git_project_index, 581); 582 583# finally, we have the hash of allowed extra_options for the commands that 584# allow them 585our%allowed_options= ( 586"--no-merges"=> [qw(rss atom log shortlog history)], 587); 588 589# fill %input_params with the CGI parameters. All values except for 'opt' 590# should be single values, but opt can be an array. We should probably 591# build an array of parameters that can be multi-valued, but since for the time 592# being it's only this one, we just single it out 593while(my($name,$symbol) =each%cgi_param_mapping) { 594if($symboleq'opt') { 595$input_params{$name} = [$cgi->param($symbol) ]; 596}else{ 597$input_params{$name} =$cgi->param($symbol); 598} 599} 600 601# now read PATH_INFO and update the parameter list for missing parameters 602sub evaluate_path_info { 603return ifdefined$input_params{'project'}; 604return if!$path_info; 605$path_info=~ s,^/+,,; 606return if!$path_info; 607 608# find which part of PATH_INFO is project 609my$project=$path_info; 610$project=~ s,/+$,,; 611while($project&& !check_head_link("$projectroot/$project")) { 612$project=~ s,/*[^/]*$,,; 613} 614return unless$project; 615$input_params{'project'} =$project; 616 617# do not change any parameters if an action is given using the query string 618return if$input_params{'action'}; 619$path_info=~ s,^\Q$project\E/*,,; 620 621# next, check if we have an action 622my$action=$path_info; 623$action=~ s,/.*$,,; 624if(exists$actions{$action}) { 625$path_info=~ s,^$action/*,,; 626$input_params{'action'} =$action; 627} 628 629# list of actions that want hash_base instead of hash, but can have no 630# pathname (f) parameter 631my@wants_base= ( 632'tree', 633'history', 634); 635 636# we want to catch 637# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 638my($parentrefname,$parentpathname,$refname,$pathname) = 639($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/); 640 641# first, analyze the 'current' part 642if(defined$pathname) { 643# we got "branch:filename" or "branch:dir/" 644# we could use git_get_type(branch:pathname), but: 645# - it needs $git_dir 646# - it does a git() call 647# - the convention of terminating directories with a slash 648# makes it superfluous 649# - embedding the action in the PATH_INFO would make it even 650# more superfluous 651$pathname=~ s,^/+,,; 652if(!$pathname||substr($pathname, -1)eq"/") { 653$input_params{'action'} ||="tree"; 654$pathname=~ s,/$,,; 655}else{ 656# the default action depends on whether we had parent info 657# or not 658if($parentrefname) { 659$input_params{'action'} ||="blobdiff_plain"; 660}else{ 661$input_params{'action'} ||="blob_plain"; 662} 663} 664$input_params{'hash_base'} ||=$refname; 665$input_params{'file_name'} ||=$pathname; 666}elsif(defined$refname) { 667# we got "branch". In this case we have to choose if we have to 668# set hash or hash_base. 669# 670# Most of the actions without a pathname only want hash to be 671# set, except for the ones specified in @wants_base that want 672# hash_base instead. It should also be noted that hand-crafted 673# links having 'history' as an action and no pathname or hash 674# set will fail, but that happens regardless of PATH_INFO. 675$input_params{'action'} ||="shortlog"; 676if(grep{$_eq$input_params{'action'} }@wants_base) { 677$input_params{'hash_base'} ||=$refname; 678}else{ 679$input_params{'hash'} ||=$refname; 680} 681} 682 683# next, handle the 'parent' part, if present 684if(defined$parentrefname) { 685# a missing pathspec defaults to the 'current' filename, allowing e.g. 686# someproject/blobdiff/oldrev..newrev:/filename 687if($parentpathname) { 688$parentpathname=~ s,^/+,,; 689$parentpathname=~ s,/$,,; 690$input_params{'file_parent'} ||=$parentpathname; 691}else{ 692$input_params{'file_parent'} ||=$input_params{'file_name'}; 693} 694# we assume that hash_parent_base is wanted if a path was specified, 695# or if the action wants hash_base instead of hash 696if(defined$input_params{'file_parent'} || 697grep{$_eq$input_params{'action'} }@wants_base) { 698$input_params{'hash_parent_base'} ||=$parentrefname; 699}else{ 700$input_params{'hash_parent'} ||=$parentrefname; 701} 702} 703 704# for the snapshot action, we allow URLs in the form 705# $project/snapshot/$hash.ext 706# where .ext determines the snapshot and gets removed from the 707# passed $refname to provide the $hash. 708# 709# To be able to tell that $refname includes the format extension, we 710# require the following two conditions to be satisfied: 711# - the hash input parameter MUST have been set from the $refname part 712# of the URL (i.e. they must be equal) 713# - the snapshot format MUST NOT have been defined already (e.g. from 714# CGI parameter sf) 715# It's also useless to try any matching unless $refname has a dot, 716# so we check for that too 717if(defined$input_params{'action'} && 718$input_params{'action'}eq'snapshot'&& 719defined$refname&&index($refname,'.') != -1&& 720$refnameeq$input_params{'hash'} && 721!defined$input_params{'snapshot_format'}) { 722# We loop over the known snapshot formats, checking for 723# extensions. Allowed extensions are both the defined suffix 724# (which includes the initial dot already) and the snapshot 725# format key itself, with a prepended dot 726while(my($fmt,$opt) =each%known_snapshot_formats) { 727my$hash=$refname; 728unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 729next; 730} 731my$sfx=$1; 732# a valid suffix was found, so set the snapshot format 733# and reset the hash parameter 734$input_params{'snapshot_format'} =$fmt; 735$input_params{'hash'} =$hash; 736# we also set the format suffix to the one requested 737# in the URL: this way a request for e.g. .tgz returns 738# a .tgz instead of a .tar.gz 739$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 740last; 741} 742} 743} 744evaluate_path_info(); 745 746our$action=$input_params{'action'}; 747if(defined$action) { 748if(!validate_action($action)) { 749 die_error(400,"Invalid action parameter"); 750} 751} 752 753# parameters which are pathnames 754our$project=$input_params{'project'}; 755if(defined$project) { 756if(!validate_project($project)) { 757undef$project; 758 die_error(404,"No such project"); 759} 760} 761 762our$file_name=$input_params{'file_name'}; 763if(defined$file_name) { 764if(!validate_pathname($file_name)) { 765 die_error(400,"Invalid file parameter"); 766} 767} 768 769our$file_parent=$input_params{'file_parent'}; 770if(defined$file_parent) { 771if(!validate_pathname($file_parent)) { 772 die_error(400,"Invalid file parent parameter"); 773} 774} 775 776# parameters which are refnames 777our$hash=$input_params{'hash'}; 778if(defined$hash) { 779if(!validate_refname($hash)) { 780 die_error(400,"Invalid hash parameter"); 781} 782} 783 784our$hash_parent=$input_params{'hash_parent'}; 785if(defined$hash_parent) { 786if(!validate_refname($hash_parent)) { 787 die_error(400,"Invalid hash parent parameter"); 788} 789} 790 791our$hash_base=$input_params{'hash_base'}; 792if(defined$hash_base) { 793if(!validate_refname($hash_base)) { 794 die_error(400,"Invalid hash base parameter"); 795} 796} 797 798our@extra_options= @{$input_params{'extra_options'}}; 799# @extra_options is always defined, since it can only be (currently) set from 800# CGI, and $cgi->param() returns the empty array in array context if the param 801# is not set 802foreachmy$opt(@extra_options) { 803if(not exists$allowed_options{$opt}) { 804 die_error(400,"Invalid option parameter"); 805} 806if(not grep(/^$action$/, @{$allowed_options{$opt}})) { 807 die_error(400,"Invalid option parameter for this action"); 808} 809} 810 811our$hash_parent_base=$input_params{'hash_parent_base'}; 812if(defined$hash_parent_base) { 813if(!validate_refname($hash_parent_base)) { 814 die_error(400,"Invalid hash parent base parameter"); 815} 816} 817 818# other parameters 819our$page=$input_params{'page'}; 820if(defined$page) { 821if($page=~m/[^0-9]/) { 822 die_error(400,"Invalid page parameter"); 823} 824} 825 826our$searchtype=$input_params{'searchtype'}; 827if(defined$searchtype) { 828if($searchtype=~m/[^a-z]/) { 829 die_error(400,"Invalid searchtype parameter"); 830} 831} 832 833our$search_use_regexp=$input_params{'search_use_regexp'}; 834 835our$searchtext=$input_params{'searchtext'}; 836our$search_regexp; 837if(defined$searchtext) { 838if(length($searchtext) <2) { 839 die_error(403,"At least two characters are required for search parameter"); 840} 841$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext; 842} 843 844# path to the current git repository 845our$git_dir; 846$git_dir="$projectroot/$project"if$project; 847 848# list of supported snapshot formats 849our@snapshot_fmts= gitweb_get_feature('snapshot'); 850@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts); 851 852# check that the avatar feature is set to a known provider name, 853# and for each provider check if the dependencies are satisfied. 854# if the provider name is invalid or the dependencies are not met, 855# reset $git_avatar to the empty string. 856our($git_avatar) = gitweb_get_feature('avatar'); 857if($git_avatareq'gravatar') { 858$git_avatar=''unless(eval{require Digest::MD5;1; }); 859}elsif($git_avatareq'picon') { 860# no dependencies 861}else{ 862$git_avatar=''; 863} 864 865# dispatch 866if(!defined$action) { 867if(defined$hash) { 868$action= git_get_type($hash); 869}elsif(defined$hash_base&&defined$file_name) { 870$action= git_get_type("$hash_base:$file_name"); 871}elsif(defined$project) { 872$action='summary'; 873}else{ 874$action='project_list'; 875} 876} 877if(!defined($actions{$action})) { 878 die_error(400,"Unknown action"); 879} 880if($action!~m/^(?:opml|project_list|project_index)$/&& 881!$project) { 882 die_error(400,"Project needed"); 883} 884$actions{$action}->(); 885exit; 886 887## ====================================================================== 888## action links 889 890sub href { 891my%params=@_; 892# default is to use -absolute url() i.e. $my_uri 893my$href=$params{-full} ?$my_url:$my_uri; 894 895$params{'project'} =$projectunlessexists$params{'project'}; 896 897if($params{-replay}) { 898while(my($name,$symbol) =each%cgi_param_mapping) { 899if(!exists$params{$name}) { 900$params{$name} =$input_params{$name}; 901} 902} 903} 904 905my$use_pathinfo= gitweb_check_feature('pathinfo'); 906if($use_pathinfoand defined$params{'project'}) { 907# try to put as many parameters as possible in PATH_INFO: 908# - project name 909# - action 910# - hash_parent or hash_parent_base:/file_parent 911# - hash or hash_base:/filename 912# - the snapshot_format as an appropriate suffix 913 914# When the script is the root DirectoryIndex for the domain, 915# $href here would be something like http://gitweb.example.com/ 916# Thus, we strip any trailing / from $href, to spare us double 917# slashes in the final URL 918$href=~ s,/$,,; 919 920# Then add the project name, if present 921$href.="/".esc_url($params{'project'}); 922delete$params{'project'}; 923 924# since we destructively absorb parameters, we keep this 925# boolean that remembers if we're handling a snapshot 926my$is_snapshot=$params{'action'}eq'snapshot'; 927 928# Summary just uses the project path URL, any other action is 929# added to the URL 930if(defined$params{'action'}) { 931$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary'; 932delete$params{'action'}; 933} 934 935# Next, we put hash_parent_base:/file_parent..hash_base:/file_name, 936# stripping nonexistent or useless pieces 937$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'} 938||$params{'hash_parent'} ||$params{'hash'}); 939if(defined$params{'hash_base'}) { 940if(defined$params{'hash_parent_base'}) { 941$href.= esc_url($params{'hash_parent_base'}); 942# skip the file_parent if it's the same as the file_name 943delete$params{'file_parent'}if$params{'file_parent'}eq$params{'file_name'}; 944if(defined$params{'file_parent'} &&$params{'file_parent'} !~/\.\./) { 945$href.=":/".esc_url($params{'file_parent'}); 946delete$params{'file_parent'}; 947} 948$href.=".."; 949delete$params{'hash_parent'}; 950delete$params{'hash_parent_base'}; 951}elsif(defined$params{'hash_parent'}) { 952$href.= esc_url($params{'hash_parent'}).".."; 953delete$params{'hash_parent'}; 954} 955 956$href.= esc_url($params{'hash_base'}); 957if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) { 958$href.=":/".esc_url($params{'file_name'}); 959delete$params{'file_name'}; 960} 961delete$params{'hash'}; 962delete$params{'hash_base'}; 963}elsif(defined$params{'hash'}) { 964$href.= esc_url($params{'hash'}); 965delete$params{'hash'}; 966} 967 968# If the action was a snapshot, we can absorb the 969# snapshot_format parameter too 970if($is_snapshot) { 971my$fmt=$params{'snapshot_format'}; 972# snapshot_format should always be defined when href() 973# is called, but just in case some code forgets, we 974# fall back to the default 975$fmt||=$snapshot_fmts[0]; 976$href.=$known_snapshot_formats{$fmt}{'suffix'}; 977delete$params{'snapshot_format'}; 978} 979} 980 981# now encode the parameters explicitly 982my@result= (); 983for(my$i=0;$i<@cgi_param_mapping;$i+=2) { 984my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]); 985if(defined$params{$name}) { 986if(ref($params{$name})eq"ARRAY") { 987foreachmy$par(@{$params{$name}}) { 988push@result,$symbol."=". esc_param($par); 989} 990}else{ 991push@result,$symbol."=". esc_param($params{$name}); 992} 993} 994} 995$href.="?".join(';',@result)ifscalar@result; 996 997return$href; 998} 99910001001## ======================================================================1002## validation, quoting/unquoting and escaping10031004sub validate_action {1005my$input=shift||returnundef;1006returnundefunlessexists$actions{$input};1007return$input;1008}10091010sub validate_project {1011my$input=shift||returnundef;1012if(!validate_pathname($input) ||1013!(-d "$projectroot/$input") ||1014!check_export_ok("$projectroot/$input") ||1015($strict_export&& !project_in_list($input))) {1016returnundef;1017}else{1018return$input;1019}1020}10211022sub validate_pathname {1023my$input=shift||returnundef;10241025# no '.' or '..' as elements of path, i.e. no '.' nor '..'1026# at the beginning, at the end, and between slashes.1027# also this catches doubled slashes1028if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1029returnundef;1030}1031# no null characters1032if($input=~m!\0!) {1033returnundef;1034}1035return$input;1036}10371038sub validate_refname {1039my$input=shift||returnundef;10401041# textual hashes are O.K.1042if($input=~m/^[0-9a-fA-F]{40}$/) {1043return$input;1044}1045# it must be correct pathname1046$input= validate_pathname($input)1047orreturnundef;1048# restrictions on ref name according to git-check-ref-format1049if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1050returnundef;1051}1052return$input;1053}10541055# decode sequences of octets in utf8 into Perl's internal form,1056# which is utf-8 with utf8 flag set if needed. gitweb writes out1057# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1058sub to_utf8 {1059my$str=shift;1060if(utf8::valid($str)) {1061 utf8::decode($str);1062return$str;1063}else{1064return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1065}1066}10671068# quote unsafe chars, but keep the slash, even when it's not1069# correct, but quoted slashes look too horrible in bookmarks1070sub esc_param {1071my$str=shift;1072$str=~s/([^A-Za-z0-9\-_.~()\/:@])/sprintf("%%%02X",ord($1))/eg;1073$str=~s/\+/%2B/g;1074$str=~s/ /\+/g;1075return$str;1076}10771078# quote unsafe chars in whole URL, so some charactrs cannot be quoted1079sub esc_url {1080my$str=shift;1081$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X",ord($1))/eg;1082$str=~s/\+/%2B/g;1083$str=~s/ /\+/g;1084return$str;1085}10861087# replace invalid utf8 character with SUBSTITUTION sequence1088sub esc_html {1089my$str=shift;1090my%opts=@_;10911092$str= to_utf8($str);1093$str=$cgi->escapeHTML($str);1094if($opts{'-nbsp'}) {1095$str=~s/ / /g;1096}1097$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1098return$str;1099}11001101# quote control characters and escape filename to HTML1102sub esc_path {1103my$str=shift;1104my%opts=@_;11051106$str= to_utf8($str);1107$str=$cgi->escapeHTML($str);1108if($opts{'-nbsp'}) {1109$str=~s/ / /g;1110}1111$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1112return$str;1113}11141115# Make control characters "printable", using character escape codes (CEC)1116sub quot_cec {1117my$cntrl=shift;1118my%opts=@_;1119my%es= (# character escape codes, aka escape sequences1120"\t"=>'\t',# tab (HT)1121"\n"=>'\n',# line feed (LF)1122"\r"=>'\r',# carrige return (CR)1123"\f"=>'\f',# form feed (FF)1124"\b"=>'\b',# backspace (BS)1125"\a"=>'\a',# alarm (bell) (BEL)1126"\e"=>'\e',# escape (ESC)1127"\013"=>'\v',# vertical tab (VT)1128"\000"=>'\0',# nul character (NUL)1129);1130my$chr= ( (exists$es{$cntrl})1131?$es{$cntrl}1132:sprintf('\%2x',ord($cntrl)) );1133if($opts{-nohtml}) {1134return$chr;1135}else{1136return"<span class=\"cntrl\">$chr</span>";1137}1138}11391140# Alternatively use unicode control pictures codepoints,1141# Unicode "printable representation" (PR)1142sub quot_upr {1143my$cntrl=shift;1144my%opts=@_;11451146my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1147if($opts{-nohtml}) {1148return$chr;1149}else{1150return"<span class=\"cntrl\">$chr</span>";1151}1152}11531154# git may return quoted and escaped filenames1155sub unquote {1156my$str=shift;11571158sub unq {1159my$seq=shift;1160my%es= (# character escape codes, aka escape sequences1161't'=>"\t",# tab (HT, TAB)1162'n'=>"\n",# newline (NL)1163'r'=>"\r",# return (CR)1164'f'=>"\f",# form feed (FF)1165'b'=>"\b",# backspace (BS)1166'a'=>"\a",# alarm (bell) (BEL)1167'e'=>"\e",# escape (ESC)1168'v'=>"\013",# vertical tab (VT)1169);11701171if($seq=~m/^[0-7]{1,3}$/) {1172# octal char sequence1173returnchr(oct($seq));1174}elsif(exists$es{$seq}) {1175# C escape sequence, aka character escape code1176return$es{$seq};1177}1178# quoted ordinary character1179return$seq;1180}11811182if($str=~m/^"(.*)"$/) {1183# needs unquoting1184$str=$1;1185$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1186}1187return$str;1188}11891190# escape tabs (convert tabs to spaces)1191sub untabify {1192my$line=shift;11931194while((my$pos=index($line,"\t")) != -1) {1195if(my$count= (8- ($pos%8))) {1196my$spaces=' ' x $count;1197$line=~s/\t/$spaces/;1198}1199}12001201return$line;1202}12031204sub project_in_list {1205my$project=shift;1206my@list= git_get_projects_list();1207return@list&&scalar(grep{$_->{'path'}eq$project}@list);1208}12091210## ----------------------------------------------------------------------1211## HTML aware string manipulation12121213# Try to chop given string on a word boundary between position1214# $len and $len+$add_len. If there is no word boundary there,1215# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1216# (marking chopped part) would be longer than given string.1217sub chop_str {1218my$str=shift;1219my$len=shift;1220my$add_len=shift||10;1221my$where=shift||'right';# 'left' | 'center' | 'right'12221223# Make sure perl knows it is utf8 encoded so we don't1224# cut in the middle of a utf8 multibyte char.1225$str= to_utf8($str);12261227# allow only $len chars, but don't cut a word if it would fit in $add_len1228# if it doesn't fit, cut it if it's still longer than the dots we would add1229# remove chopped character entities entirely12301231# when chopping in the middle, distribute $len into left and right part1232# return early if chopping wouldn't make string shorter1233if($whereeq'center') {1234return$strif($len+5>=length($str));# filler is length 51235$len=int($len/2);1236}else{1237return$strif($len+4>=length($str));# filler is length 41238}12391240# regexps: ending and beginning with word part up to $add_len1241my$endre=qr/.{$len}\w{0,$add_len}/;1242my$begre=qr/\w{0,$add_len}.{$len}/;12431244if($whereeq'left') {1245$str=~m/^(.*?)($begre)$/;1246my($lead,$body) = ($1,$2);1247if(length($lead) >4) {1248$body=~s/^[^;]*;//if($lead=~m/&[^;]*$/);1249$lead=" ...";1250}1251return"$lead$body";12521253}elsif($whereeq'center') {1254$str=~m/^($endre)(.*)$/;1255my($left,$str) = ($1,$2);1256$str=~m/^(.*?)($begre)$/;1257my($mid,$right) = ($1,$2);1258if(length($mid) >5) {1259$left=~s/&[^;]*$//;1260$right=~s/^[^;]*;//if($mid=~m/&[^;]*$/);1261$mid=" ... ";1262}1263return"$left$mid$right";12641265}else{1266$str=~m/^($endre)(.*)$/;1267my$body=$1;1268my$tail=$2;1269if(length($tail) >4) {1270$body=~s/&[^;]*$//;1271$tail="... ";1272}1273return"$body$tail";1274}1275}12761277# takes the same arguments as chop_str, but also wraps a <span> around the1278# result with a title attribute if it does get chopped. Additionally, the1279# string is HTML-escaped.1280sub chop_and_escape_str {1281my($str) =@_;12821283my$chopped= chop_str(@_);1284if($choppedeq$str) {1285return esc_html($chopped);1286}else{1287$str=~s/[[:cntrl:]]/?/g;1288return$cgi->span({-title=>$str}, esc_html($chopped));1289}1290}12911292## ----------------------------------------------------------------------1293## functions returning short strings12941295# CSS class for given age value (in seconds)1296sub age_class {1297my$age=shift;12981299if(!defined$age) {1300return"noage";1301}elsif($age<60*60*2) {1302return"age0";1303}elsif($age<60*60*24*2) {1304return"age1";1305}else{1306return"age2";1307}1308}13091310# convert age in seconds to "nn units ago" string1311sub age_string {1312my$age=shift;1313my$age_str;13141315if($age>60*60*24*365*2) {1316$age_str= (int$age/60/60/24/365);1317$age_str.=" years ago";1318}elsif($age>60*60*24*(365/12)*2) {1319$age_str=int$age/60/60/24/(365/12);1320$age_str.=" months ago";1321}elsif($age>60*60*24*7*2) {1322$age_str=int$age/60/60/24/7;1323$age_str.=" weeks ago";1324}elsif($age>60*60*24*2) {1325$age_str=int$age/60/60/24;1326$age_str.=" days ago";1327}elsif($age>60*60*2) {1328$age_str=int$age/60/60;1329$age_str.=" hours ago";1330}elsif($age>60*2) {1331$age_str=int$age/60;1332$age_str.=" min ago";1333}elsif($age>2) {1334$age_str=int$age;1335$age_str.=" sec ago";1336}else{1337$age_str.=" right now";1338}1339return$age_str;1340}13411342useconstant{1343 S_IFINVALID =>0030000,1344 S_IFGITLINK =>0160000,1345};13461347# submodule/subproject, a commit object reference1348sub S_ISGITLINK {1349my$mode=shift;13501351return(($mode& S_IFMT) == S_IFGITLINK)1352}13531354# convert file mode in octal to symbolic file mode string1355sub mode_str {1356my$mode=oct shift;13571358if(S_ISGITLINK($mode)) {1359return'm---------';1360}elsif(S_ISDIR($mode& S_IFMT)) {1361return'drwxr-xr-x';1362}elsif(S_ISLNK($mode)) {1363return'lrwxrwxrwx';1364}elsif(S_ISREG($mode)) {1365# git cares only about the executable bit1366if($mode& S_IXUSR) {1367return'-rwxr-xr-x';1368}else{1369return'-rw-r--r--';1370};1371}else{1372return'----------';1373}1374}13751376# convert file mode in octal to file type string1377sub file_type {1378my$mode=shift;13791380if($mode!~m/^[0-7]+$/) {1381return$mode;1382}else{1383$mode=oct$mode;1384}13851386if(S_ISGITLINK($mode)) {1387return"submodule";1388}elsif(S_ISDIR($mode& S_IFMT)) {1389return"directory";1390}elsif(S_ISLNK($mode)) {1391return"symlink";1392}elsif(S_ISREG($mode)) {1393return"file";1394}else{1395return"unknown";1396}1397}13981399# convert file mode in octal to file type description string1400sub file_type_long {1401my$mode=shift;14021403if($mode!~m/^[0-7]+$/) {1404return$mode;1405}else{1406$mode=oct$mode;1407}14081409if(S_ISGITLINK($mode)) {1410return"submodule";1411}elsif(S_ISDIR($mode& S_IFMT)) {1412return"directory";1413}elsif(S_ISLNK($mode)) {1414return"symlink";1415}elsif(S_ISREG($mode)) {1416if($mode& S_IXUSR) {1417return"executable";1418}else{1419return"file";1420};1421}else{1422return"unknown";1423}1424}142514261427## ----------------------------------------------------------------------1428## functions returning short HTML fragments, or transforming HTML fragments1429## which don't belong to other sections14301431# format line of commit message.1432sub format_log_line_html {1433my$line=shift;14341435$line= esc_html($line, -nbsp=>1);1436$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1437$cgi->a({-href => href(action=>"object", hash=>$1),1438-class=>"text"},$1);1439}eg;14401441return$line;1442}14431444# format marker of refs pointing to given object14451446# the destination action is chosen based on object type and current context:1447# - for annotated tags, we choose the tag view unless it's the current view1448# already, in which case we go to shortlog view1449# - for other refs, we keep the current view if we're in history, shortlog or1450# log view, and select shortlog otherwise1451sub format_ref_marker {1452my($refs,$id) =@_;1453my$markers='';14541455if(defined$refs->{$id}) {1456foreachmy$ref(@{$refs->{$id}}) {1457# this code exploits the fact that non-lightweight tags are the1458# only indirect objects, and that they are the only objects for which1459# we want to use tag instead of shortlog as action1460my($type,$name) =qw();1461my$indirect= ($ref=~s/\^\{\}$//);1462# e.g. tags/v2.6.11 or heads/next1463if($ref=~m!^(.*?)s?/(.*)$!) {1464$type=$1;1465$name=$2;1466}else{1467$type="ref";1468$name=$ref;1469}14701471my$class=$type;1472$class.=" indirect"if$indirect;14731474my$dest_action="shortlog";14751476if($indirect) {1477$dest_action="tag"unless$actioneq"tag";1478}elsif($action=~/^(history|(short)?log)$/) {1479$dest_action=$action;1480}14811482my$dest="";1483$dest.="refs/"unless$ref=~ m!^refs/!;1484$dest.=$ref;14851486my$link=$cgi->a({1487-href => href(1488 action=>$dest_action,1489 hash=>$dest1490)},$name);14911492$markers.=" <span class=\"$class\"title=\"$ref\">".1493$link."</span>";1494}1495}14961497if($markers) {1498return' <span class="refs">'.$markers.'</span>';1499}else{1500return"";1501}1502}15031504# format, perhaps shortened and with markers, title line1505sub format_subject_html {1506my($long,$short,$href,$extra) =@_;1507$extra=''unlessdefined($extra);15081509if(length($short) <length($long)) {1510$long=~s/[[:cntrl:]]/?/g;1511return$cgi->a({-href =>$href, -class=>"list subject",1512-title => to_utf8($long)},1513 esc_html($short) .$extra);1514}else{1515return$cgi->a({-href =>$href, -class=>"list subject"},1516 esc_html($long) .$extra);1517}1518}15191520# Rather than recomputing the url for an email multiple times, we cache it1521# after the first hit. This gives a visible benefit in views where the avatar1522# for the same email is used repeatedly (e.g. shortlog).1523# The cache is shared by all avatar engines (currently gravatar only), which1524# are free to use it as preferred. Since only one avatar engine is used for any1525# given page, there's no risk for cache conflicts.1526our%avatar_cache= ();15271528# Compute the picon url for a given email, by using the picon search service over at1529# http://www.cs.indiana.edu/picons/search.html1530sub picon_url {1531my$email=lc shift;1532if(!$avatar_cache{$email}) {1533my($user,$domain) =split('@',$email);1534$avatar_cache{$email} =1535"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1536"$domain/$user/".1537"users+domains+unknown/up/single";1538}1539return$avatar_cache{$email};1540}15411542# Compute the gravatar url for a given email, if it's not in the cache already.1543# Gravatar stores only the part of the URL before the size, since that's the1544# one computationally more expensive. This also allows reuse of the cache for1545# different sizes (for this particular engine).1546sub gravatar_url {1547my$email=lc shift;1548my$size=shift;1549$avatar_cache{$email} ||=1550"http://www.gravatar.com/avatar/".1551 Digest::MD5::md5_hex($email) ."?s=";1552return$avatar_cache{$email} .$size;1553}15541555# Insert an avatar for the given $email at the given $size if the feature1556# is enabled.1557sub git_get_avatar {1558my($email,%opts) =@_;1559my$pre_white= ($opts{-pad_before} ?" ":"");1560my$post_white= ($opts{-pad_after} ?" ":"");1561$opts{-size} ||='default';1562my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1563my$url="";1564if($git_avatareq'gravatar') {1565$url= gravatar_url($email,$size);1566}elsif($git_avatareq'picon') {1567$url= picon_url($email);1568}1569# Other providers can be added by extending the if chain, defining $url1570# as needed. If no variant puts something in $url, we assume avatars1571# are completely disabled/unavailable.1572if($url) {1573return$pre_white.1574"<img width=\"$size\"".1575"class=\"avatar\"".1576"src=\"$url\"".1577"alt=\"\"".1578"/>".$post_white;1579}else{1580return"";1581}1582}15831584# format the author name of the given commit with the given tag1585# the author name is chopped and escaped according to the other1586# optional parameters (see chop_str).1587sub format_author_html {1588my$tag=shift;1589my$co=shift;1590my$author= chop_and_escape_str($co->{'author_name'},@_);1591return"<$tagclass=\"author\">".1592 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1593$author."</$tag>";1594}15951596# format git diff header line, i.e. "diff --(git|combined|cc) ..."1597sub format_git_diff_header_line {1598my$line=shift;1599my$diffinfo=shift;1600my($from,$to) =@_;16011602if($diffinfo->{'nparents'}) {1603# combined diff1604$line=~s!^(diff (.*?) )"?.*$!$1!;1605if($to->{'href'}) {1606$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1607 esc_path($to->{'file'}));1608}else{# file was deleted (no href)1609$line.= esc_path($to->{'file'});1610}1611}else{1612# "ordinary" diff1613$line=~s!^(diff (.*?) )"?a/.*$!$1!;1614if($from->{'href'}) {1615$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1616'a/'. esc_path($from->{'file'}));1617}else{# file was added (no href)1618$line.='a/'. esc_path($from->{'file'});1619}1620$line.=' ';1621if($to->{'href'}) {1622$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1623'b/'. esc_path($to->{'file'}));1624}else{# file was deleted1625$line.='b/'. esc_path($to->{'file'});1626}1627}16281629return"<div class=\"diff header\">$line</div>\n";1630}16311632# format extended diff header line, before patch itself1633sub format_extended_diff_header_line {1634my$line=shift;1635my$diffinfo=shift;1636my($from,$to) =@_;16371638# match <path>1639if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1640$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1641 esc_path($from->{'file'}));1642}1643if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1644$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1645 esc_path($to->{'file'}));1646}1647# match single <mode>1648if($line=~m/\s(\d{6})$/) {1649$line.='<span class="info"> ('.1650 file_type_long($1) .1651')</span>';1652}1653# match <hash>1654if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1655# can match only for combined diff1656$line='index ';1657for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1658if($from->{'href'}[$i]) {1659$line.=$cgi->a({-href=>$from->{'href'}[$i],1660-class=>"hash"},1661substr($diffinfo->{'from_id'}[$i],0,7));1662}else{1663$line.='0' x 7;1664}1665# separator1666$line.=','if($i<$diffinfo->{'nparents'} -1);1667}1668$line.='..';1669if($to->{'href'}) {1670$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1671substr($diffinfo->{'to_id'},0,7));1672}else{1673$line.='0' x 7;1674}16751676}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {1677# can match only for ordinary diff1678my($from_link,$to_link);1679if($from->{'href'}) {1680$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},1681substr($diffinfo->{'from_id'},0,7));1682}else{1683$from_link='0' x 7;1684}1685if($to->{'href'}) {1686$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1687substr($diffinfo->{'to_id'},0,7));1688}else{1689$to_link='0' x 7;1690}1691my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});1692$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;1693}16941695return$line."<br/>\n";1696}16971698# format from-file/to-file diff header1699sub format_diff_from_to_header {1700my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;1701my$line;1702my$result='';17031704$line=$from_line;1705#assert($line =~ m/^---/) if DEBUG;1706# no extra formatting for "^--- /dev/null"1707if(!$diffinfo->{'nparents'}) {1708# ordinary (single parent) diff1709if($line=~m!^--- "?a/!) {1710if($from->{'href'}) {1711$line='--- a/'.1712$cgi->a({-href=>$from->{'href'}, -class=>"path"},1713 esc_path($from->{'file'}));1714}else{1715$line='--- a/'.1716 esc_path($from->{'file'});1717}1718}1719$result.= qq!<div class="diff from_file">$line</div>\n!;17201721}else{1722# combined diff (merge commit)1723for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1724if($from->{'href'}[$i]) {1725$line='--- '.1726$cgi->a({-href=>href(action=>"blobdiff",1727 hash_parent=>$diffinfo->{'from_id'}[$i],1728 hash_parent_base=>$parents[$i],1729 file_parent=>$from->{'file'}[$i],1730 hash=>$diffinfo->{'to_id'},1731 hash_base=>$hash,1732 file_name=>$to->{'file'}),1733-class=>"path",1734-title=>"diff". ($i+1)},1735$i+1) .1736'/'.1737$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},1738 esc_path($from->{'file'}[$i]));1739}else{1740$line='--- /dev/null';1741}1742$result.= qq!<div class="diff from_file">$line</div>\n!;1743}1744}17451746$line=$to_line;1747#assert($line =~ m/^\+\+\+/) if DEBUG;1748# no extra formatting for "^+++ /dev/null"1749if($line=~m!^\+\+\+ "?b/!) {1750if($to->{'href'}) {1751$line='+++ b/'.1752$cgi->a({-href=>$to->{'href'}, -class=>"path"},1753 esc_path($to->{'file'}));1754}else{1755$line='+++ b/'.1756 esc_path($to->{'file'});1757}1758}1759$result.= qq!<div class="diff to_file">$line</div>\n!;17601761return$result;1762}17631764# create note for patch simplified by combined diff1765sub format_diff_cc_simplified {1766my($diffinfo,@parents) =@_;1767my$result='';17681769$result.="<div class=\"diff header\">".1770"diff --cc ";1771if(!is_deleted($diffinfo)) {1772$result.=$cgi->a({-href => href(action=>"blob",1773 hash_base=>$hash,1774 hash=>$diffinfo->{'to_id'},1775 file_name=>$diffinfo->{'to_file'}),1776-class=>"path"},1777 esc_path($diffinfo->{'to_file'}));1778}else{1779$result.= esc_path($diffinfo->{'to_file'});1780}1781$result.="</div>\n".# class="diff header"1782"<div class=\"diff nodifferences\">".1783"Simple merge".1784"</div>\n";# class="diff nodifferences"17851786return$result;1787}17881789# format patch (diff) line (not to be used for diff headers)1790sub format_diff_line {1791my$line=shift;1792my($from,$to) =@_;1793my$diff_class="";17941795chomp$line;17961797if($from&&$to&&ref($from->{'href'})eq"ARRAY") {1798# combined diff1799my$prefix=substr($line,0,scalar@{$from->{'href'}});1800if($line=~m/^\@{3}/) {1801$diff_class=" chunk_header";1802}elsif($line=~m/^\\/) {1803$diff_class=" incomplete";1804}elsif($prefix=~tr/+/+/) {1805$diff_class=" add";1806}elsif($prefix=~tr/-/-/) {1807$diff_class=" rem";1808}1809}else{1810# assume ordinary diff1811my$char=substr($line,0,1);1812if($chareq'+') {1813$diff_class=" add";1814}elsif($chareq'-') {1815$diff_class=" rem";1816}elsif($chareq'@') {1817$diff_class=" chunk_header";1818}elsif($chareq"\\") {1819$diff_class=" incomplete";1820}1821}1822$line= untabify($line);1823if($from&&$to&&$line=~m/^\@{2} /) {1824my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =1825$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;18261827$from_lines=0unlessdefined$from_lines;1828$to_lines=0unlessdefined$to_lines;18291830if($from->{'href'}) {1831$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",1832-class=>"list"},$from_text);1833}1834if($to->{'href'}) {1835$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",1836-class=>"list"},$to_text);1837}1838$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".1839"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";1840return"<div class=\"diff$diff_class\">$line</div>\n";1841}elsif($from&&$to&&$line=~m/^\@{3}/) {1842my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;1843my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);18441845@from_text=split(' ',$ranges);1846for(my$i=0;$i<@from_text; ++$i) {1847($from_start[$i],$from_nlines[$i]) =1848(split(',',substr($from_text[$i],1)),0);1849}18501851$to_text=pop@from_text;1852$to_start=pop@from_start;1853$to_nlines=pop@from_nlines;18541855$line="<span class=\"chunk_info\">$prefix";1856for(my$i=0;$i<@from_text; ++$i) {1857if($from->{'href'}[$i]) {1858$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",1859-class=>"list"},$from_text[$i]);1860}else{1861$line.=$from_text[$i];1862}1863$line.=" ";1864}1865if($to->{'href'}) {1866$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",1867-class=>"list"},$to_text);1868}else{1869$line.=$to_text;1870}1871$line.="$prefix</span>".1872"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";1873return"<div class=\"diff$diff_class\">$line</div>\n";1874}1875return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";1876}18771878# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",1879# linked. Pass the hash of the tree/commit to snapshot.1880sub format_snapshot_links {1881my($hash) =@_;1882my$num_fmts=@snapshot_fmts;1883if($num_fmts>1) {1884# A parenthesized list of links bearing format names.1885# e.g. "snapshot (_tar.gz_ _zip_)"1886return"snapshot (".join(' ',map1887$cgi->a({1888-href => href(1889 action=>"snapshot",1890 hash=>$hash,1891 snapshot_format=>$_1892)1893},$known_snapshot_formats{$_}{'display'})1894,@snapshot_fmts) .")";1895}elsif($num_fmts==1) {1896# A single "snapshot" link whose tooltip bears the format name.1897# i.e. "_snapshot_"1898my($fmt) =@snapshot_fmts;1899return1900$cgi->a({1901-href => href(1902 action=>"snapshot",1903 hash=>$hash,1904 snapshot_format=>$fmt1905),1906-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"1907},"snapshot");1908}else{# $num_fmts == 01909returnundef;1910}1911}19121913## ......................................................................1914## functions returning values to be passed, perhaps after some1915## transformation, to other functions; e.g. returning arguments to href()19161917# returns hash to be passed to href to generate gitweb URL1918# in -title key it returns description of link1919sub get_feed_info {1920my$format=shift||'Atom';1921my%res= (action =>lc($format));19221923# feed links are possible only for project views1924return unless(defined$project);1925# some views should link to OPML, or to generic project feed,1926# or don't have specific feed yet (so they should use generic)1927return if($action=~/^(?:tags|heads|forks|tag|search)$/x);19281929my$branch;1930# branches refs uses 'refs/heads/' prefix (fullname) to differentiate1931# from tag links; this also makes possible to detect branch links1932if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||1933(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {1934$branch=$1;1935}1936# find log type for feed description (title)1937my$type='log';1938if(defined$file_name) {1939$type="history of$file_name";1940$type.="/"if($actioneq'tree');1941$type.=" on '$branch'"if(defined$branch);1942}else{1943$type="log of$branch"if(defined$branch);1944}19451946$res{-title} =$type;1947$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);1948$res{'file_name'} =$file_name;19491950return%res;1951}19521953## ----------------------------------------------------------------------1954## git utility subroutines, invoking git commands19551956# returns path to the core git executable and the --git-dir parameter as list1957sub git_cmd {1958return$GIT,'--git-dir='.$git_dir;1959}19601961# quote the given arguments for passing them to the shell1962# quote_command("command", "arg 1", "arg with ' and ! characters")1963# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"1964# Try to avoid using this function wherever possible.1965sub quote_command {1966returnjoin(' ',1967map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);1968}19691970# get HEAD ref of given project as hash1971sub git_get_head_hash {1972my$project=shift;1973my$o_git_dir=$git_dir;1974my$retval=undef;1975$git_dir="$projectroot/$project";1976if(open my$fd,"-|", git_cmd(),"rev-parse","--verify","HEAD") {1977my$head= <$fd>;1978close$fd;1979if(defined$head&&$head=~/^([0-9a-fA-F]{40})$/) {1980$retval=$1;1981}1982}1983if(defined$o_git_dir) {1984$git_dir=$o_git_dir;1985}1986return$retval;1987}19881989# get type of given object1990sub git_get_type {1991my$hash=shift;19921993open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;1994my$type= <$fd>;1995close$fdorreturn;1996chomp$type;1997return$type;1998}19992000# repository configuration2001our$config_file='';2002our%config;20032004# store multiple values for single key as anonymous array reference2005# single values stored directly in the hash, not as [ <value> ]2006sub hash_set_multi {2007my($hash,$key,$value) =@_;20082009if(!exists$hash->{$key}) {2010$hash->{$key} =$value;2011}elsif(!ref$hash->{$key}) {2012$hash->{$key} = [$hash->{$key},$value];2013}else{2014push@{$hash->{$key}},$value;2015}2016}20172018# return hash of git project configuration2019# optionally limited to some section, e.g. 'gitweb'2020sub git_parse_project_config {2021my$section_regexp=shift;2022my%config;20232024local$/="\0";20252026open my$fh,"-|", git_cmd(),"config",'-z','-l',2027orreturn;20282029while(my$keyval= <$fh>) {2030chomp$keyval;2031my($key,$value) =split(/\n/,$keyval,2);20322033 hash_set_multi(\%config,$key,$value)2034if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2035}2036close$fh;20372038return%config;2039}20402041# convert config value to boolean: 'true' or 'false'2042# no value, number > 0, 'true' and 'yes' values are true2043# rest of values are treated as false (never as error)2044sub config_to_bool {2045my$val=shift;20462047return1if!defined$val;# section.key20482049# strip leading and trailing whitespace2050$val=~s/^\s+//;2051$val=~s/\s+$//;20522053return(($val=~/^\d+$/&&$val) ||# section.key = 12054($val=~/^(?:true|yes)$/i));# section.key = true2055}20562057# convert config value to simple decimal number2058# an optional value suffix of 'k', 'm', or 'g' will cause the value2059# to be multiplied by 1024, 1048576, or 10737418242060sub config_to_int {2061my$val=shift;20622063# strip leading and trailing whitespace2064$val=~s/^\s+//;2065$val=~s/\s+$//;20662067if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2068$unit=lc($unit);2069# unknown unit is treated as 12070return$num* ($uniteq'g'?1073741824:2071$uniteq'm'?1048576:2072$uniteq'k'?1024:1);2073}2074return$val;2075}20762077# convert config value to array reference, if needed2078sub config_to_multi {2079my$val=shift;20802081returnref($val) ?$val: (defined($val) ? [$val] : []);2082}20832084sub git_get_project_config {2085my($key,$type) =@_;20862087# key sanity check2088return unless($key);2089$key=~s/^gitweb\.//;2090return if($key=~m/\W/);20912092# type sanity check2093if(defined$type) {2094$type=~s/^--//;2095$type=undef2096unless($typeeq'bool'||$typeeq'int');2097}20982099# get config2100if(!defined$config_file||2101$config_filene"$git_dir/config") {2102%config= git_parse_project_config('gitweb');2103$config_file="$git_dir/config";2104}21052106# check if config variable (key) exists2107return unlessexists$config{"gitweb.$key"};21082109# ensure given type2110if(!defined$type) {2111return$config{"gitweb.$key"};2112}elsif($typeeq'bool') {2113# backward compatibility: 'git config --bool' returns true/false2114return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2115}elsif($typeeq'int') {2116return config_to_int($config{"gitweb.$key"});2117}2118return$config{"gitweb.$key"};2119}21202121# get hash of given path at given ref2122sub git_get_hash_by_path {2123my$base=shift;2124my$path=shift||returnundef;2125my$type=shift;21262127$path=~ s,/+$,,;21282129open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2130or die_error(500,"Open git-ls-tree failed");2131my$line= <$fd>;2132close$fdorreturnundef;21332134if(!defined$line) {2135# there is no tree or hash given by $path at $base2136returnundef;2137}21382139#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2140$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2141if(defined$type&&$typene$2) {2142# type doesn't match2143returnundef;2144}2145return$3;2146}21472148# get path of entry with given hash at given tree-ish (ref)2149# used to get 'from' filename for combined diff (merge commit) for renames2150sub git_get_path_by_hash {2151my$base=shift||return;2152my$hash=shift||return;21532154local$/="\0";21552156open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2157orreturnundef;2158while(my$line= <$fd>) {2159chomp$line;21602161#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2162#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2163if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2164close$fd;2165return$1;2166}2167}2168close$fd;2169returnundef;2170}21712172## ......................................................................2173## git utility functions, directly accessing git repository21742175sub git_get_project_description {2176my$path=shift;21772178$git_dir="$projectroot/$path";2179open my$fd,'<',"$git_dir/description"2180orreturn git_get_project_config('description');2181my$descr= <$fd>;2182close$fd;2183if(defined$descr) {2184chomp$descr;2185}2186return$descr;2187}21882189sub git_get_project_ctags {2190my$path=shift;2191my$ctags= {};21922193$git_dir="$projectroot/$path";2194opendir my$dh,"$git_dir/ctags"2195orreturn$ctags;2196foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2197open my$ct,'<',$_ornext;2198my$val= <$ct>;2199chomp$val;2200close$ct;2201my$ctag=$_;$ctag=~ s#.*/##;2202$ctags->{$ctag} =$val;2203}2204closedir$dh;2205$ctags;2206}22072208sub git_populate_project_tagcloud {2209my$ctags=shift;22102211# First, merge different-cased tags; tags vote on casing2212my%ctags_lc;2213foreach(keys%$ctags) {2214$ctags_lc{lc$_}->{count} +=$ctags->{$_};2215if(not$ctags_lc{lc$_}->{topcount}2216or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2217$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2218$ctags_lc{lc$_}->{topname} =$_;2219}2220}22212222my$cloud;2223if(eval{require HTML::TagCloud;1; }) {2224$cloud= HTML::TagCloud->new;2225foreach(sort keys%ctags_lc) {2226# Pad the title with spaces so that the cloud looks2227# less crammed.2228my$title=$ctags_lc{$_}->{topname};2229$title=~s/ / /g;2230$title=~s/^/ /g;2231$title=~s/$/ /g;2232$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2233}2234}else{2235$cloud= \%ctags_lc;2236}2237$cloud;2238}22392240sub git_show_project_tagcloud {2241my($cloud,$count) =@_;2242print STDERR ref($cloud)."..\n";2243if(ref$cloudeq'HTML::TagCloud') {2244return$cloud->html_and_css($count);2245}else{2246my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2247return'<p align="center">'.join(', ',map{2248"<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"2249}splice(@tags,0,$count)) .'</p>';2250}2251}22522253sub git_get_project_url_list {2254my$path=shift;22552256$git_dir="$projectroot/$path";2257open my$fd,'<',"$git_dir/cloneurl"2258orreturnwantarray?2259@{ config_to_multi(git_get_project_config('url')) } :2260 config_to_multi(git_get_project_config('url'));2261my@git_project_url_list=map{chomp;$_} <$fd>;2262close$fd;22632264returnwantarray?@git_project_url_list: \@git_project_url_list;2265}22662267sub git_get_projects_list {2268my($filter) =@_;2269my@list;22702271$filter||='';2272$filter=~s/\.git$//;22732274my$check_forks= gitweb_check_feature('forks');22752276if(-d $projects_list) {2277# search in directory2278my$dir=$projects_list. ($filter?"/$filter":'');2279# remove the trailing "/"2280$dir=~s!/+$!!;2281my$pfxlen=length("$dir");2282my$pfxdepth= ($dir=~tr!/!!);22832284 File::Find::find({2285 follow_fast =>1,# follow symbolic links2286 follow_skip =>2,# ignore duplicates2287 dangling_symlinks =>0,# ignore dangling symlinks, silently2288 wanted =>sub{2289# skip project-list toplevel, if we get it.2290return if(m!^[/.]$!);2291# only directories can be git repositories2292return unless(-d $_);2293# don't traverse too deep (Find is super slow on os x)2294if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2295$File::Find::prune =1;2296return;2297}22982299my$subdir=substr($File::Find::name,$pfxlen+1);2300# we check related file in $projectroot2301my$path= ($filter?"$filter/":'') .$subdir;2302if(check_export_ok("$projectroot/$path")) {2303push@list, { path =>$path};2304$File::Find::prune =1;2305}2306},2307},"$dir");23082309}elsif(-f $projects_list) {2310# read from file(url-encoded):2311# 'git%2Fgit.git Linus+Torvalds'2312# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2313# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2314my%paths;2315open my$fd,'<',$projects_listorreturn;2316 PROJECT:2317while(my$line= <$fd>) {2318chomp$line;2319my($path,$owner) =split' ',$line;2320$path= unescape($path);2321$owner= unescape($owner);2322if(!defined$path) {2323next;2324}2325if($filterne'') {2326# looking for forks;2327my$pfx=substr($path,0,length($filter));2328if($pfxne$filter) {2329next PROJECT;2330}2331my$sfx=substr($path,length($filter));2332if($sfx!~/^\/.*\.git$/) {2333next PROJECT;2334}2335}elsif($check_forks) {2336 PATH:2337foreachmy$filter(keys%paths) {2338# looking for forks;2339my$pfx=substr($path,0,length($filter));2340if($pfxne$filter) {2341next PATH;2342}2343my$sfx=substr($path,length($filter));2344if($sfx!~/^\/.*\.git$/) {2345next PATH;2346}2347# is a fork, don't include it in2348# the list2349next PROJECT;2350}2351}2352if(check_export_ok("$projectroot/$path")) {2353my$pr= {2354 path =>$path,2355 owner => to_utf8($owner),2356};2357push@list,$pr;2358(my$forks_path=$path) =~s/\.git$//;2359$paths{$forks_path}++;2360}2361}2362close$fd;2363}2364return@list;2365}23662367our$gitweb_project_owner=undef;2368sub git_get_project_list_from_file {23692370return if(defined$gitweb_project_owner);23712372$gitweb_project_owner= {};2373# read from file (url-encoded):2374# 'git%2Fgit.git Linus+Torvalds'2375# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2376# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2377if(-f $projects_list) {2378open(my$fd,'<',$projects_list);2379while(my$line= <$fd>) {2380chomp$line;2381my($pr,$ow) =split' ',$line;2382$pr= unescape($pr);2383$ow= unescape($ow);2384$gitweb_project_owner->{$pr} = to_utf8($ow);2385}2386close$fd;2387}2388}23892390sub git_get_project_owner {2391my$project=shift;2392my$owner;23932394returnundefunless$project;2395$git_dir="$projectroot/$project";23962397if(!defined$gitweb_project_owner) {2398 git_get_project_list_from_file();2399}24002401if(exists$gitweb_project_owner->{$project}) {2402$owner=$gitweb_project_owner->{$project};2403}2404if(!defined$owner){2405$owner= git_get_project_config('owner');2406}2407if(!defined$owner) {2408$owner= get_file_owner("$git_dir");2409}24102411return$owner;2412}24132414sub git_get_last_activity {2415my($path) =@_;2416my$fd;24172418$git_dir="$projectroot/$path";2419open($fd,"-|", git_cmd(),'for-each-ref',2420'--format=%(committer)',2421'--sort=-committerdate',2422'--count=1',2423'refs/heads')orreturn;2424my$most_recent= <$fd>;2425close$fdorreturn;2426if(defined$most_recent&&2427$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2428my$timestamp=$1;2429my$age=time-$timestamp;2430return($age, age_string($age));2431}2432return(undef,undef);2433}24342435sub git_get_references {2436my$type=shift||"";2437my%refs;2438# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112439# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2440open my$fd,"-|", git_cmd(),"show-ref","--dereference",2441($type? ("--","refs/$type") : ())# use -- <pattern> if $type2442orreturn;24432444while(my$line= <$fd>) {2445chomp$line;2446if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2447if(defined$refs{$1}) {2448push@{$refs{$1}},$2;2449}else{2450$refs{$1} = [$2];2451}2452}2453}2454close$fdorreturn;2455return \%refs;2456}24572458sub git_get_rev_name_tags {2459my$hash=shift||returnundef;24602461open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2462orreturn;2463my$name_rev= <$fd>;2464close$fd;24652466if($name_rev=~ m|^$hash tags/(.*)$|) {2467return$1;2468}else{2469# catches also '$hash undefined' output2470returnundef;2471}2472}24732474## ----------------------------------------------------------------------2475## parse to hash functions24762477sub parse_date {2478my$epoch=shift;2479my$tz=shift||"-0000";24802481my%date;2482my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2483my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2484my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2485$date{'hour'} =$hour;2486$date{'minute'} =$min;2487$date{'mday'} =$mday;2488$date{'day'} =$days[$wday];2489$date{'month'} =$months[$mon];2490$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2491$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2492$date{'mday-time'} =sprintf"%d%s%02d:%02d",2493$mday,$months[$mon],$hour,$min;2494$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",24951900+$year,1+$mon,$mday,$hour,$min,$sec;24962497$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2498my$local=$epoch+ ((int$1+ ($2/60)) *3600);2499($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2500$date{'hour_local'} =$hour;2501$date{'minute_local'} =$min;2502$date{'tz_local'} =$tz;2503$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",25041900+$year,$mon+1,$mday,2505$hour,$min,$sec,$tz);2506return%date;2507}25082509sub parse_tag {2510my$tag_id=shift;2511my%tag;2512my@comment;25132514open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2515$tag{'id'} =$tag_id;2516while(my$line= <$fd>) {2517chomp$line;2518if($line=~m/^object ([0-9a-fA-F]{40})$/) {2519$tag{'object'} =$1;2520}elsif($line=~m/^type (.+)$/) {2521$tag{'type'} =$1;2522}elsif($line=~m/^tag (.+)$/) {2523$tag{'name'} =$1;2524}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2525$tag{'author'} =$1;2526$tag{'author_epoch'} =$2;2527$tag{'author_tz'} =$3;2528if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2529$tag{'author_name'} =$1;2530$tag{'author_email'} =$2;2531}else{2532$tag{'author_name'} =$tag{'author'};2533}2534}elsif($line=~m/--BEGIN/) {2535push@comment,$line;2536last;2537}elsif($lineeq"") {2538last;2539}2540}2541push@comment, <$fd>;2542$tag{'comment'} = \@comment;2543close$fdorreturn;2544if(!defined$tag{'name'}) {2545return2546};2547return%tag2548}25492550sub parse_commit_text {2551my($commit_text,$withparents) =@_;2552my@commit_lines=split'\n',$commit_text;2553my%co;25542555pop@commit_lines;# Remove '\0'25562557if(!@commit_lines) {2558return;2559}25602561my$header=shift@commit_lines;2562if($header!~m/^[0-9a-fA-F]{40}/) {2563return;2564}2565($co{'id'},my@parents) =split' ',$header;2566while(my$line=shift@commit_lines) {2567last if$lineeq"\n";2568if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2569$co{'tree'} =$1;2570}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2571push@parents,$1;2572}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2573$co{'author'} = to_utf8($1);2574$co{'author_epoch'} =$2;2575$co{'author_tz'} =$3;2576if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2577$co{'author_name'} =$1;2578$co{'author_email'} =$2;2579}else{2580$co{'author_name'} =$co{'author'};2581}2582}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2583$co{'committer'} = to_utf8($1);2584$co{'committer_epoch'} =$2;2585$co{'committer_tz'} =$3;2586if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2587$co{'committer_name'} =$1;2588$co{'committer_email'} =$2;2589}else{2590$co{'committer_name'} =$co{'committer'};2591}2592}2593}2594if(!defined$co{'tree'}) {2595return;2596};2597$co{'parents'} = \@parents;2598$co{'parent'} =$parents[0];25992600foreachmy$title(@commit_lines) {2601$title=~s/^ //;2602if($titlene"") {2603$co{'title'} = chop_str($title,80,5);2604# remove leading stuff of merges to make the interesting part visible2605if(length($title) >50) {2606$title=~s/^Automatic //;2607$title=~s/^merge (of|with) /Merge ... /i;2608if(length($title) >50) {2609$title=~s/(http|rsync):\/\///;2610}2611if(length($title) >50) {2612$title=~s/(master|www|rsync)\.//;2613}2614if(length($title) >50) {2615$title=~s/kernel.org:?//;2616}2617if(length($title) >50) {2618$title=~s/\/pub\/scm//;2619}2620}2621$co{'title_short'} = chop_str($title,50,5);2622last;2623}2624}2625if(!defined$co{'title'} ||$co{'title'}eq"") {2626$co{'title'} =$co{'title_short'} ='(no commit message)';2627}2628# remove added spaces2629foreachmy$line(@commit_lines) {2630$line=~s/^ //;2631}2632$co{'comment'} = \@commit_lines;26332634my$age=time-$co{'committer_epoch'};2635$co{'age'} =$age;2636$co{'age_string'} = age_string($age);2637my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2638if($age>60*60*24*7*2) {2639$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2640$co{'age_string_age'} =$co{'age_string'};2641}else{2642$co{'age_string_date'} =$co{'age_string'};2643$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2644}2645return%co;2646}26472648sub parse_commit {2649my($commit_id) =@_;2650my%co;26512652local$/="\0";26532654open my$fd,"-|", git_cmd(),"rev-list",2655"--parents",2656"--header",2657"--max-count=1",2658$commit_id,2659"--",2660or die_error(500,"Open git-rev-list failed");2661%co= parse_commit_text(<$fd>,1);2662close$fd;26632664return%co;2665}26662667sub parse_commits {2668my($commit_id,$maxcount,$skip,$filename,@args) =@_;2669my@cos;26702671$maxcount||=1;2672$skip||=0;26732674local$/="\0";26752676open my$fd,"-|", git_cmd(),"rev-list",2677"--header",2678@args,2679("--max-count=".$maxcount),2680("--skip=".$skip),2681@extra_options,2682$commit_id,2683"--",2684($filename? ($filename) : ())2685or die_error(500,"Open git-rev-list failed");2686while(my$line= <$fd>) {2687my%co= parse_commit_text($line);2688push@cos, \%co;2689}2690close$fd;26912692returnwantarray?@cos: \@cos;2693}26942695# parse line of git-diff-tree "raw" output2696sub parse_difftree_raw_line {2697my$line=shift;2698my%res;26992700# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'2701# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'2702if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {2703$res{'from_mode'} =$1;2704$res{'to_mode'} =$2;2705$res{'from_id'} =$3;2706$res{'to_id'} =$4;2707$res{'status'} =$5;2708$res{'similarity'} =$6;2709if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied2710($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);2711}else{2712$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);2713}2714}2715# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'2716# combined diff (for merge commit)2717elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {2718$res{'nparents'} =length($1);2719$res{'from_mode'} = [split(' ',$2) ];2720$res{'to_mode'} =pop@{$res{'from_mode'}};2721$res{'from_id'} = [split(' ',$3) ];2722$res{'to_id'} =pop@{$res{'from_id'}};2723$res{'status'} = [split('',$4) ];2724$res{'to_file'} = unquote($5);2725}2726# 'c512b523472485aef4fff9e57b229d9d243c967f'2727elsif($line=~m/^([0-9a-fA-F]{40})$/) {2728$res{'commit'} =$1;2729}27302731returnwantarray?%res: \%res;2732}27332734# wrapper: return parsed line of git-diff-tree "raw" output2735# (the argument might be raw line, or parsed info)2736sub parsed_difftree_line {2737my$line_or_ref=shift;27382739if(ref($line_or_ref)eq"HASH") {2740# pre-parsed (or generated by hand)2741return$line_or_ref;2742}else{2743return parse_difftree_raw_line($line_or_ref);2744}2745}27462747# parse line of git-ls-tree output2748sub parse_ls_tree_line {2749my$line=shift;2750my%opts=@_;2751my%res;27522753#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2754$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;27552756$res{'mode'} =$1;2757$res{'type'} =$2;2758$res{'hash'} =$3;2759if($opts{'-z'}) {2760$res{'name'} =$4;2761}else{2762$res{'name'} = unquote($4);2763}27642765returnwantarray?%res: \%res;2766}27672768# generates _two_ hashes, references to which are passed as 2 and 3 argument2769sub parse_from_to_diffinfo {2770my($diffinfo,$from,$to,@parents) =@_;27712772if($diffinfo->{'nparents'}) {2773# combined diff2774$from->{'file'} = [];2775$from->{'href'} = [];2776 fill_from_file_info($diffinfo,@parents)2777unlessexists$diffinfo->{'from_file'};2778for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2779$from->{'file'}[$i] =2780defined$diffinfo->{'from_file'}[$i] ?2781$diffinfo->{'from_file'}[$i] :2782$diffinfo->{'to_file'};2783if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file2784$from->{'href'}[$i] = href(action=>"blob",2785 hash_base=>$parents[$i],2786 hash=>$diffinfo->{'from_id'}[$i],2787 file_name=>$from->{'file'}[$i]);2788}else{2789$from->{'href'}[$i] =undef;2790}2791}2792}else{2793# ordinary (not combined) diff2794$from->{'file'} =$diffinfo->{'from_file'};2795if($diffinfo->{'status'}ne"A") {# not new (added) file2796$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,2797 hash=>$diffinfo->{'from_id'},2798 file_name=>$from->{'file'});2799}else{2800delete$from->{'href'};2801}2802}28032804$to->{'file'} =$diffinfo->{'to_file'};2805if(!is_deleted($diffinfo)) {# file exists in result2806$to->{'href'} = href(action=>"blob", hash_base=>$hash,2807 hash=>$diffinfo->{'to_id'},2808 file_name=>$to->{'file'});2809}else{2810delete$to->{'href'};2811}2812}28132814## ......................................................................2815## parse to array of hashes functions28162817sub git_get_heads_list {2818my$limit=shift;2819my@headslist;28202821open my$fd,'-|', git_cmd(),'for-each-ref',2822($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',2823'--format=%(objectname) %(refname) %(subject)%00%(committer)',2824'refs/heads'2825orreturn;2826while(my$line= <$fd>) {2827my%ref_item;28282829chomp$line;2830my($refinfo,$committerinfo) =split(/\0/,$line);2831my($hash,$name,$title) =split(' ',$refinfo,3);2832my($committer,$epoch,$tz) =2833($committerinfo=~/^(.*) ([0-9]+) (.*)$/);2834$ref_item{'fullname'} =$name;2835$name=~s!^refs/heads/!!;28362837$ref_item{'name'} =$name;2838$ref_item{'id'} =$hash;2839$ref_item{'title'} =$title||'(no commit message)';2840$ref_item{'epoch'} =$epoch;2841if($epoch) {2842$ref_item{'age'} = age_string(time-$ref_item{'epoch'});2843}else{2844$ref_item{'age'} ="unknown";2845}28462847push@headslist, \%ref_item;2848}2849close$fd;28502851returnwantarray?@headslist: \@headslist;2852}28532854sub git_get_tags_list {2855my$limit=shift;2856my@tagslist;28572858open my$fd,'-|', git_cmd(),'for-each-ref',2859($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',2860'--format=%(objectname) %(objecttype) %(refname) '.2861'%(*objectname) %(*objecttype) %(subject)%00%(creator)',2862'refs/tags'2863orreturn;2864while(my$line= <$fd>) {2865my%ref_item;28662867chomp$line;2868my($refinfo,$creatorinfo) =split(/\0/,$line);2869my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);2870my($creator,$epoch,$tz) =2871($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);2872$ref_item{'fullname'} =$name;2873$name=~s!^refs/tags/!!;28742875$ref_item{'type'} =$type;2876$ref_item{'id'} =$id;2877$ref_item{'name'} =$name;2878if($typeeq"tag") {2879$ref_item{'subject'} =$title;2880$ref_item{'reftype'} =$reftype;2881$ref_item{'refid'} =$refid;2882}else{2883$ref_item{'reftype'} =$type;2884$ref_item{'refid'} =$id;2885}28862887if($typeeq"tag"||$typeeq"commit") {2888$ref_item{'epoch'} =$epoch;2889if($epoch) {2890$ref_item{'age'} = age_string(time-$ref_item{'epoch'});2891}else{2892$ref_item{'age'} ="unknown";2893}2894}28952896push@tagslist, \%ref_item;2897}2898close$fd;28992900returnwantarray?@tagslist: \@tagslist;2901}29022903## ----------------------------------------------------------------------2904## filesystem-related functions29052906sub get_file_owner {2907my$path=shift;29082909my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);2910my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);2911if(!defined$gcos) {2912returnundef;2913}2914my$owner=$gcos;2915$owner=~s/[,;].*$//;2916return to_utf8($owner);2917}29182919# assume that file exists2920sub insert_file {2921my$filename=shift;29222923open my$fd,'<',$filename;2924print map{ to_utf8($_) } <$fd>;2925close$fd;2926}29272928## ......................................................................2929## mimetype related functions29302931sub mimetype_guess_file {2932my$filename=shift;2933my$mimemap=shift;2934-r $mimemaporreturnundef;29352936my%mimemap;2937open(my$mh,'<',$mimemap)orreturnundef;2938while(<$mh>) {2939next ifm/^#/;# skip comments2940my($mimetype,$exts) =split(/\t+/);2941if(defined$exts) {2942my@exts=split(/\s+/,$exts);2943foreachmy$ext(@exts) {2944$mimemap{$ext} =$mimetype;2945}2946}2947}2948close($mh);29492950$filename=~/\.([^.]*)$/;2951return$mimemap{$1};2952}29532954sub mimetype_guess {2955my$filename=shift;2956my$mime;2957$filename=~/\./orreturnundef;29582959if($mimetypes_file) {2960my$file=$mimetypes_file;2961if($file!~m!^/!) {# if it is relative path2962# it is relative to project2963$file="$projectroot/$project/$file";2964}2965$mime= mimetype_guess_file($filename,$file);2966}2967$mime||= mimetype_guess_file($filename,'/etc/mime.types');2968return$mime;2969}29702971sub blob_mimetype {2972my$fd=shift;2973my$filename=shift;29742975if($filename) {2976my$mime= mimetype_guess($filename);2977$mimeandreturn$mime;2978}29792980# just in case2981return$default_blob_plain_mimetypeunless$fd;29822983if(-T $fd) {2984return'text/plain';2985}elsif(!$filename) {2986return'application/octet-stream';2987}elsif($filename=~m/\.png$/i) {2988return'image/png';2989}elsif($filename=~m/\.gif$/i) {2990return'image/gif';2991}elsif($filename=~m/\.jpe?g$/i) {2992return'image/jpeg';2993}else{2994return'application/octet-stream';2995}2996}29972998sub blob_contenttype {2999my($fd,$file_name,$type) =@_;30003001$type||= blob_mimetype($fd,$file_name);3002if($typeeq'text/plain'&&defined$default_text_plain_charset) {3003$type.="; charset=$default_text_plain_charset";3004}30053006return$type;3007}30083009## ======================================================================3010## functions printing HTML: header, footer, error page30113012sub git_header_html {3013my$status=shift||"200 OK";3014my$expires=shift;30153016my$title="$site_name";3017if(defined$project) {3018$title.=" - ". to_utf8($project);3019if(defined$action) {3020$title.="/$action";3021if(defined$file_name) {3022$title.=" - ". esc_path($file_name);3023if($actioneq"tree"&&$file_name!~ m|/$|) {3024$title.="/";3025}3026}3027}3028}3029my$content_type;3030# require explicit support from the UA if we are to send the page as3031# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3032# we have to do this because MSIE sometimes globs '*/*', pretending to3033# support xhtml+xml but choking when it gets what it asked for.3034if(defined$cgi->http('HTTP_ACCEPT') &&3035$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3036$cgi->Accept('application/xhtml+xml') !=0) {3037$content_type='application/xhtml+xml';3038}else{3039$content_type='text/html';3040}3041print$cgi->header(-type=>$content_type, -charset =>'utf-8',3042-status=>$status, -expires =>$expires);3043my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3044print<<EOF;3045<?xml version="1.0" encoding="utf-8"?>3046<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3047<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3048<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3049<!-- git core binaries version$git_version-->3050<head>3051<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3052<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3053<meta name="robots" content="index, nofollow"/>3054<title>$title</title>3055EOF3056# the stylesheet, favicon etc urls won't work correctly with path_info3057# unless we set the appropriate base URL3058if($ENV{'PATH_INFO'}) {3059print"<base href=\"".esc_url($base_url)."\"/>\n";3060}3061# print out each stylesheet that exist, providing backwards capability3062# for those people who defined $stylesheet in a config file3063if(defined$stylesheet) {3064print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3065}else{3066foreachmy$stylesheet(@stylesheets) {3067next unless$stylesheet;3068print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3069}3070}3071if(defined$project) {3072my%href_params= get_feed_info();3073if(!exists$href_params{'-title'}) {3074$href_params{'-title'} ='log';3075}30763077foreachmy$formatqw(RSS Atom){3078my$type=lc($format);3079my%link_attr= (3080'-rel'=>'alternate',3081'-title'=>"$project-$href_params{'-title'} -$formatfeed",3082'-type'=>"application/$type+xml"3083);30843085$href_params{'action'} =$type;3086$link_attr{'-href'} = href(%href_params);3087print"<link ".3088"rel=\"$link_attr{'-rel'}\"".3089"title=\"$link_attr{'-title'}\"".3090"href=\"$link_attr{'-href'}\"".3091"type=\"$link_attr{'-type'}\"".3092"/>\n";30933094$href_params{'extra_options'} ='--no-merges';3095$link_attr{'-href'} = href(%href_params);3096$link_attr{'-title'} .=' (no merges)';3097print"<link ".3098"rel=\"$link_attr{'-rel'}\"".3099"title=\"$link_attr{'-title'}\"".3100"href=\"$link_attr{'-href'}\"".3101"type=\"$link_attr{'-type'}\"".3102"/>\n";3103}31043105}else{3106printf('<link rel="alternate" title="%sprojects list" '.3107'href="%s" type="text/plain; charset=utf-8" />'."\n",3108$site_name, href(project=>undef, action=>"project_index"));3109printf('<link rel="alternate" title="%sprojects feeds" '.3110'href="%s" type="text/x-opml" />'."\n",3111$site_name, href(project=>undef, action=>"opml"));3112}3113if(defined$favicon) {3114printqq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);3115}31163117print"</head>\n".3118"<body>\n";31193120if(-f $site_header) {3121 insert_file($site_header);3122}31233124print"<div class=\"page_header\">\n".3125$cgi->a({-href => esc_url($logo_url),3126-title =>$logo_label},3127qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));3128print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3129if(defined$project) {3130print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3131if(defined$action) {3132print" /$action";3133}3134print"\n";3135}3136print"</div>\n";31373138my$have_search= gitweb_check_feature('search');3139if(defined$project&&$have_search) {3140if(!defined$searchtext) {3141$searchtext="";3142}3143my$search_hash;3144if(defined$hash_base) {3145$search_hash=$hash_base;3146}elsif(defined$hash) {3147$search_hash=$hash;3148}else{3149$search_hash="HEAD";3150}3151my$action=$my_uri;3152my$use_pathinfo= gitweb_check_feature('pathinfo');3153if($use_pathinfo) {3154$action.="/".esc_url($project);3155}3156print$cgi->startform(-method=>"get", -action =>$action) .3157"<div class=\"search\">\n".3158(!$use_pathinfo&&3159$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3160$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3161$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3162$cgi->popup_menu(-name =>'st', -default=>'commit',3163-values=> ['commit','grep','author','committer','pickaxe']) .3164$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3165" search:\n",3166$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3167"<span title=\"Extended regular expression\">".3168$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3169-checked =>$search_use_regexp) .3170"</span>".3171"</div>".3172$cgi->end_form() ."\n";3173}3174}31753176sub git_footer_html {3177my$feed_class='rss_logo';31783179print"<div class=\"page_footer\">\n";3180if(defined$project) {3181my$descr= git_get_project_description($project);3182if(defined$descr) {3183print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3184}31853186my%href_params= get_feed_info();3187if(!%href_params) {3188$feed_class.=' generic';3189}3190$href_params{'-title'} ||='log';31913192foreachmy$formatqw(RSS Atom){3193$href_params{'action'} =lc($format);3194print$cgi->a({-href => href(%href_params),3195-title =>"$href_params{'-title'}$formatfeed",3196-class=>$feed_class},$format)."\n";3197}31983199}else{3200print$cgi->a({-href => href(project=>undef, action=>"opml"),3201-class=>$feed_class},"OPML") ." ";3202print$cgi->a({-href => href(project=>undef, action=>"project_index"),3203-class=>$feed_class},"TXT") ."\n";3204}3205print"</div>\n";# class="page_footer"32063207if(-f $site_footer) {3208 insert_file($site_footer);3209}32103211print"</body>\n".3212"</html>";3213}32143215# die_error(<http_status_code>, <error_message>)3216# Example: die_error(404, 'Hash not found')3217# By convention, use the following status codes (as defined in RFC 2616):3218# 400: Invalid or missing CGI parameters, or3219# requested object exists but has wrong type.3220# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3221# this server or project.3222# 404: Requested object/revision/project doesn't exist.3223# 500: The server isn't configured properly, or3224# an internal error occurred (e.g. failed assertions caused by bugs), or3225# an unknown error occurred (e.g. the git binary died unexpectedly).3226sub die_error {3227my$status=shift||500;3228my$error=shift||"Internal server error";32293230my%http_responses= (400=>'400 Bad Request',3231403=>'403 Forbidden',3232404=>'404 Not Found',3233500=>'500 Internal Server Error');3234 git_header_html($http_responses{$status});3235print<<EOF;3236<div class="page_body">3237<br /><br />3238$status-$error3239<br />3240</div>3241EOF3242 git_footer_html();3243exit;3244}32453246## ----------------------------------------------------------------------3247## functions printing or outputting HTML: navigation32483249sub git_print_page_nav {3250my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3251$extra=''if!defined$extra;# pager or formats32523253my@navs=qw(summary shortlog log commit commitdiff tree);3254if($suppress) {3255@navs=grep{$_ne$suppress}@navs;3256}32573258my%arg=map{$_=> {action=>$_} }@navs;3259if(defined$head) {3260for(qw(commit commitdiff)) {3261$arg{$_}{'hash'} =$head;3262}3263if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3264for(qw(shortlog log)) {3265$arg{$_}{'hash'} =$head;3266}3267}3268}32693270$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3271$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;32723273my@actions= gitweb_get_feature('actions');3274my%repl= (3275'%'=>'%',3276'n'=>$project,# project name3277'f'=>$git_dir,# project path within filesystem3278'h'=>$treehead||'',# current hash ('h' parameter)3279'b'=>$treebase||'',# hash base ('hb' parameter)3280);3281while(@actions) {3282my($label,$link,$pos) =splice(@actions,0,3);3283# insert3284@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3285# munch munch3286$link=~s/%([%nfhb])/$repl{$1}/g;3287$arg{$label}{'_href'} =$link;3288}32893290print"<div class=\"page_nav\">\n".3291(join" | ",3292map{$_eq$current?3293$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3294}@navs);3295print"<br/>\n$extra<br/>\n".3296"</div>\n";3297}32983299sub format_paging_nav {3300my($action,$hash,$head,$page,$has_next_link) =@_;3301my$paging_nav;330233033304if($hashne$head||$page) {3305$paging_nav.=$cgi->a({-href => href(action=>$action)},"HEAD");3306}else{3307$paging_nav.="HEAD";3308}33093310if($page>0) {3311$paging_nav.=" ⋅ ".3312$cgi->a({-href => href(-replay=>1, page=>$page-1),3313-accesskey =>"p", -title =>"Alt-p"},"prev");3314}else{3315$paging_nav.=" ⋅ prev";3316}33173318if($has_next_link) {3319$paging_nav.=" ⋅ ".3320$cgi->a({-href => href(-replay=>1, page=>$page+1),3321-accesskey =>"n", -title =>"Alt-n"},"next");3322}else{3323$paging_nav.=" ⋅ next";3324}33253326return$paging_nav;3327}33283329## ......................................................................3330## functions printing or outputting HTML: div33313332sub git_print_header_div {3333my($action,$title,$hash,$hash_base) =@_;3334my%args= ();33353336$args{'action'} =$action;3337$args{'hash'} =$hashif$hash;3338$args{'hash_base'} =$hash_baseif$hash_base;33393340print"<div class=\"header\">\n".3341$cgi->a({-href => href(%args), -class=>"title"},3342$title?$title:$action) .3343"\n</div>\n";3344}33453346sub print_local_time {3347my%date=@_;3348if($date{'hour_local'} <6) {3349printf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3350$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3351}else{3352printf(" (%02d:%02d%s)",3353$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3354}3355}33563357# Outputs the author name and date in long form3358sub git_print_authorship {3359my$co=shift;3360my%opts=@_;3361my$tag=$opts{-tag} ||'div';33623363my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3364print"<$tagclass=\"author_date\">".3365 esc_html($co->{'author_name'}) .3366" [$ad{'rfc2822'}";3367 print_local_time(%ad)if($opts{-localtime});3368print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3369."</$tag>\n";3370}33713372# Outputs table rows containing the full author or committer information,3373# in the format expected for 'commit' view (& similia).3374# Parameters are a commit hash reference, followed by the list of people3375# to output information for. If the list is empty it defalts to both3376# author and committer.3377sub git_print_authorship_rows {3378my$co=shift;3379# too bad we can't use @people = @_ || ('author', 'committer')3380my@people=@_;3381@people= ('author','committer')unless@people;3382foreachmy$who(@people) {3383my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3384print"<tr><td>$who</td><td>". esc_html($co->{$who}) ."</td>".3385"<td rowspan=\"2\">".3386 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3387"</td></tr>\n".3388"<tr>".3389"<td></td><td>$wd{'rfc2822'}";3390 print_local_time(%wd);3391print"</td>".3392"</tr>\n";3393}3394}33953396sub git_print_page_path {3397my$name=shift;3398my$type=shift;3399my$hb=shift;340034013402print"<div class=\"page_path\">";3403print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3404-title =>'tree root'}, to_utf8("[$project]"));3405print" / ";3406if(defined$name) {3407my@dirname=split'/',$name;3408my$basename=pop@dirname;3409my$fullname='';34103411foreachmy$dir(@dirname) {3412$fullname.= ($fullname?'/':'') .$dir;3413print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3414 hash_base=>$hb),3415-title =>$fullname}, esc_path($dir));3416print" / ";3417}3418if(defined$type&&$typeeq'blob') {3419print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3420 hash_base=>$hb),3421-title =>$name}, esc_path($basename));3422}elsif(defined$type&&$typeeq'tree') {3423print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3424 hash_base=>$hb),3425-title =>$name}, esc_path($basename));3426print" / ";3427}else{3428print esc_path($basename);3429}3430}3431print"<br/></div>\n";3432}34333434sub git_print_log {3435my$log=shift;3436my%opts=@_;34373438if($opts{'-remove_title'}) {3439# remove title, i.e. first line of log3440shift@$log;3441}3442# remove leading empty lines3443while(defined$log->[0] &&$log->[0]eq"") {3444shift@$log;3445}34463447# print log3448my$signoff=0;3449my$empty=0;3450foreachmy$line(@$log) {3451if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3452$signoff=1;3453$empty=0;3454if(!$opts{'-remove_signoff'}) {3455print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3456next;3457}else{3458# remove signoff lines3459next;3460}3461}else{3462$signoff=0;3463}34643465# print only one empty line3466# do not print empty line after signoff3467if($lineeq"") {3468next if($empty||$signoff);3469$empty=1;3470}else{3471$empty=0;3472}34733474print format_log_line_html($line) ."<br/>\n";3475}34763477if($opts{'-final_empty_line'}) {3478# end with single empty line3479print"<br/>\n"unless$empty;3480}3481}34823483# return link target (what link points to)3484sub git_get_link_target {3485my$hash=shift;3486my$link_target;34873488# read link3489open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3490orreturn;3491{3492local$/=undef;3493$link_target= <$fd>;3494}3495close$fd3496orreturn;34973498return$link_target;3499}35003501# given link target, and the directory (basedir) the link is in,3502# return target of link relative to top directory (top tree);3503# return undef if it is not possible (including absolute links).3504sub normalize_link_target {3505my($link_target,$basedir) =@_;35063507# absolute symlinks (beginning with '/') cannot be normalized3508return if(substr($link_target,0,1)eq'/');35093510# normalize link target to path from top (root) tree (dir)3511my$path;3512if($basedir) {3513$path=$basedir.'/'.$link_target;3514}else{3515# we are in top (root) tree (dir)3516$path=$link_target;3517}35183519# remove //, /./, and /../3520my@path_parts;3521foreachmy$part(split('/',$path)) {3522# discard '.' and ''3523next if(!$part||$parteq'.');3524# handle '..'3525if($parteq'..') {3526if(@path_parts) {3527pop@path_parts;3528}else{3529# link leads outside repository (outside top dir)3530return;3531}3532}else{3533push@path_parts,$part;3534}3535}3536$path=join('/',@path_parts);35373538return$path;3539}35403541# print tree entry (row of git_tree), but without encompassing <tr> element3542sub git_print_tree_entry {3543my($t,$basedir,$hash_base,$have_blame) =@_;35443545my%base_key= ();3546$base_key{'hash_base'} =$hash_baseifdefined$hash_base;35473548# The format of a table row is: mode list link. Where mode is3549# the mode of the entry, list is the name of the entry, an href,3550# and link is the action links of the entry.35513552print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3553if($t->{'type'}eq"blob") {3554print"<td class=\"list\">".3555$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3556 file_name=>"$basedir$t->{'name'}",%base_key),3557-class=>"list"}, esc_path($t->{'name'}));3558if(S_ISLNK(oct$t->{'mode'})) {3559my$link_target= git_get_link_target($t->{'hash'});3560if($link_target) {3561my$norm_target= normalize_link_target($link_target,$basedir);3562if(defined$norm_target) {3563print" -> ".3564$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,3565 file_name=>$norm_target),3566-title =>$norm_target}, esc_path($link_target));3567}else{3568print" -> ". esc_path($link_target);3569}3570}3571}3572print"</td>\n";3573print"<td class=\"link\">";3574print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3575 file_name=>"$basedir$t->{'name'}",%base_key)},3576"blob");3577if($have_blame) {3578print" | ".3579$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},3580 file_name=>"$basedir$t->{'name'}",%base_key)},3581"blame");3582}3583if(defined$hash_base) {3584print" | ".3585$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,3586 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},3587"history");3588}3589print" | ".3590$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,3591 file_name=>"$basedir$t->{'name'}")},3592"raw");3593print"</td>\n";35943595}elsif($t->{'type'}eq"tree") {3596print"<td class=\"list\">";3597print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},3598 file_name=>"$basedir$t->{'name'}",%base_key)},3599 esc_path($t->{'name'}));3600print"</td>\n";3601print"<td class=\"link\">";3602print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},3603 file_name=>"$basedir$t->{'name'}",%base_key)},3604"tree");3605if(defined$hash_base) {3606print" | ".3607$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,3608 file_name=>"$basedir$t->{'name'}")},3609"history");3610}3611print"</td>\n";3612}else{3613# unknown object: we can only present history for it3614# (this includes 'commit' object, i.e. submodule support)3615print"<td class=\"list\">".3616 esc_path($t->{'name'}) .3617"</td>\n";3618print"<td class=\"link\">";3619if(defined$hash_base) {3620print$cgi->a({-href => href(action=>"history",3621 hash_base=>$hash_base,3622 file_name=>"$basedir$t->{'name'}")},3623"history");3624}3625print"</td>\n";3626}3627}36283629## ......................................................................3630## functions printing large fragments of HTML36313632# get pre-image filenames for merge (combined) diff3633sub fill_from_file_info {3634my($diff,@parents) =@_;36353636$diff->{'from_file'} = [ ];3637$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;3638for(my$i=0;$i<$diff->{'nparents'};$i++) {3639if($diff->{'status'}[$i]eq'R'||3640$diff->{'status'}[$i]eq'C') {3641$diff->{'from_file'}[$i] =3642 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);3643}3644}36453646return$diff;3647}36483649# is current raw difftree line of file deletion3650sub is_deleted {3651my$diffinfo=shift;36523653return$diffinfo->{'to_id'}eq('0' x 40);3654}36553656# does patch correspond to [previous] difftree raw line3657# $diffinfo - hashref of parsed raw diff format3658# $patchinfo - hashref of parsed patch diff format3659# (the same keys as in $diffinfo)3660sub is_patch_split {3661my($diffinfo,$patchinfo) =@_;36623663returndefined$diffinfo&&defined$patchinfo3664&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};3665}366636673668sub git_difftree_body {3669my($difftree,$hash,@parents) =@_;3670my($parent) =$parents[0];3671my$have_blame= gitweb_check_feature('blame');3672print"<div class=\"list_head\">\n";3673if($#{$difftree} >10) {3674print(($#{$difftree} +1) ." files changed:\n");3675}3676print"</div>\n";36773678print"<table class=\"".3679(@parents>1?"combined ":"") .3680"diff_tree\">\n";36813682# header only for combined diff in 'commitdiff' view3683my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';3684if($has_header) {3685# table header3686print"<thead><tr>\n".3687"<th></th><th></th>\n";# filename, patchN link3688for(my$i=0;$i<@parents;$i++) {3689my$par=$parents[$i];3690print"<th>".3691$cgi->a({-href => href(action=>"commitdiff",3692 hash=>$hash, hash_parent=>$par),3693-title =>'commitdiff to parent number '.3694($i+1) .': '.substr($par,0,7)},3695$i+1) .3696" </th>\n";3697}3698print"</tr></thead>\n<tbody>\n";3699}37003701my$alternate=1;3702my$patchno=0;3703foreachmy$line(@{$difftree}) {3704my$diff= parsed_difftree_line($line);37053706if($alternate) {3707print"<tr class=\"dark\">\n";3708}else{3709print"<tr class=\"light\">\n";3710}3711$alternate^=1;37123713if(exists$diff->{'nparents'}) {# combined diff37143715 fill_from_file_info($diff,@parents)3716unlessexists$diff->{'from_file'};37173718if(!is_deleted($diff)) {3719# file exists in the result (child) commit3720print"<td>".3721$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3722 file_name=>$diff->{'to_file'},3723 hash_base=>$hash),3724-class=>"list"}, esc_path($diff->{'to_file'})) .3725"</td>\n";3726}else{3727print"<td>".3728 esc_path($diff->{'to_file'}) .3729"</td>\n";3730}37313732if($actioneq'commitdiff') {3733# link to patch3734$patchno++;3735print"<td class=\"link\">".3736$cgi->a({-href =>"#patch$patchno"},"patch") .3737" | ".3738"</td>\n";3739}37403741my$has_history=0;3742my$not_deleted=0;3743for(my$i=0;$i<$diff->{'nparents'};$i++) {3744my$hash_parent=$parents[$i];3745my$from_hash=$diff->{'from_id'}[$i];3746my$from_path=$diff->{'from_file'}[$i];3747my$status=$diff->{'status'}[$i];37483749$has_history||= ($statusne'A');3750$not_deleted||= ($statusne'D');37513752if($statuseq'A') {3753print"<td class=\"link\"align=\"right\"> | </td>\n";3754}elsif($statuseq'D') {3755print"<td class=\"link\">".3756$cgi->a({-href => href(action=>"blob",3757 hash_base=>$hash,3758 hash=>$from_hash,3759 file_name=>$from_path)},3760"blob". ($i+1)) .3761" | </td>\n";3762}else{3763if($diff->{'to_id'}eq$from_hash) {3764print"<td class=\"link nochange\">";3765}else{3766print"<td class=\"link\">";3767}3768print$cgi->a({-href => href(action=>"blobdiff",3769 hash=>$diff->{'to_id'},3770 hash_parent=>$from_hash,3771 hash_base=>$hash,3772 hash_parent_base=>$hash_parent,3773 file_name=>$diff->{'to_file'},3774 file_parent=>$from_path)},3775"diff". ($i+1)) .3776" | </td>\n";3777}3778}37793780print"<td class=\"link\">";3781if($not_deleted) {3782print$cgi->a({-href => href(action=>"blob",3783 hash=>$diff->{'to_id'},3784 file_name=>$diff->{'to_file'},3785 hash_base=>$hash)},3786"blob");3787print" | "if($has_history);3788}3789if($has_history) {3790print$cgi->a({-href => href(action=>"history",3791 file_name=>$diff->{'to_file'},3792 hash_base=>$hash)},3793"history");3794}3795print"</td>\n";37963797print"</tr>\n";3798next;# instead of 'else' clause, to avoid extra indent3799}3800# else ordinary diff38013802my($to_mode_oct,$to_mode_str,$to_file_type);3803my($from_mode_oct,$from_mode_str,$from_file_type);3804if($diff->{'to_mode'}ne('0' x 6)) {3805$to_mode_oct=oct$diff->{'to_mode'};3806if(S_ISREG($to_mode_oct)) {# only for regular file3807$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits3808}3809$to_file_type= file_type($diff->{'to_mode'});3810}3811if($diff->{'from_mode'}ne('0' x 6)) {3812$from_mode_oct=oct$diff->{'from_mode'};3813if(S_ISREG($to_mode_oct)) {# only for regular file3814$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits3815}3816$from_file_type= file_type($diff->{'from_mode'});3817}38183819if($diff->{'status'}eq"A") {# created3820my$mode_chng="<span class=\"file_status new\">[new$to_file_type";3821$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;3822$mode_chng.="]</span>";3823print"<td>";3824print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3825 hash_base=>$hash, file_name=>$diff->{'file'}),3826-class=>"list"}, esc_path($diff->{'file'}));3827print"</td>\n";3828print"<td>$mode_chng</td>\n";3829print"<td class=\"link\">";3830if($actioneq'commitdiff') {3831# link to patch3832$patchno++;3833print$cgi->a({-href =>"#patch$patchno"},"patch");3834print" | ";3835}3836print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3837 hash_base=>$hash, file_name=>$diff->{'file'})},3838"blob");3839print"</td>\n";38403841}elsif($diff->{'status'}eq"D") {# deleted3842my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";3843print"<td>";3844print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},3845 hash_base=>$parent, file_name=>$diff->{'file'}),3846-class=>"list"}, esc_path($diff->{'file'}));3847print"</td>\n";3848print"<td>$mode_chng</td>\n";3849print"<td class=\"link\">";3850if($actioneq'commitdiff') {3851# link to patch3852$patchno++;3853print$cgi->a({-href =>"#patch$patchno"},"patch");3854print" | ";3855}3856print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},3857 hash_base=>$parent, file_name=>$diff->{'file'})},3858"blob") ." | ";3859if($have_blame) {3860print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,3861 file_name=>$diff->{'file'})},3862"blame") ." | ";3863}3864print$cgi->a({-href => href(action=>"history", hash_base=>$parent,3865 file_name=>$diff->{'file'})},3866"history");3867print"</td>\n";38683869}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed3870my$mode_chnge="";3871if($diff->{'from_mode'} !=$diff->{'to_mode'}) {3872$mode_chnge="<span class=\"file_status mode_chnge\">[changed";3873if($from_file_typene$to_file_type) {3874$mode_chnge.=" from$from_file_typeto$to_file_type";3875}3876if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {3877if($from_mode_str&&$to_mode_str) {3878$mode_chnge.=" mode:$from_mode_str->$to_mode_str";3879}elsif($to_mode_str) {3880$mode_chnge.=" mode:$to_mode_str";3881}3882}3883$mode_chnge.="]</span>\n";3884}3885print"<td>";3886print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3887 hash_base=>$hash, file_name=>$diff->{'file'}),3888-class=>"list"}, esc_path($diff->{'file'}));3889print"</td>\n";3890print"<td>$mode_chnge</td>\n";3891print"<td class=\"link\">";3892if($actioneq'commitdiff') {3893# link to patch3894$patchno++;3895print$cgi->a({-href =>"#patch$patchno"},"patch") .3896" | ";3897}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {3898# "commit" view and modified file (not onlu mode changed)3899print$cgi->a({-href => href(action=>"blobdiff",3900 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},3901 hash_base=>$hash, hash_parent_base=>$parent,3902 file_name=>$diff->{'file'})},3903"diff") .3904" | ";3905}3906print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3907 hash_base=>$hash, file_name=>$diff->{'file'})},3908"blob") ." | ";3909if($have_blame) {3910print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,3911 file_name=>$diff->{'file'})},3912"blame") ." | ";3913}3914print$cgi->a({-href => href(action=>"history", hash_base=>$hash,3915 file_name=>$diff->{'file'})},3916"history");3917print"</td>\n";39183919}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied3920my%status_name= ('R'=>'moved','C'=>'copied');3921my$nstatus=$status_name{$diff->{'status'}};3922my$mode_chng="";3923if($diff->{'from_mode'} !=$diff->{'to_mode'}) {3924# mode also for directories, so we cannot use $to_mode_str3925$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);3926}3927print"<td>".3928$cgi->a({-href => href(action=>"blob", hash_base=>$hash,3929 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),3930-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".3931"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".3932$cgi->a({-href => href(action=>"blob", hash_base=>$parent,3933 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),3934-class=>"list"}, esc_path($diff->{'from_file'})) .3935" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".3936"<td class=\"link\">";3937if($actioneq'commitdiff') {3938# link to patch3939$patchno++;3940print$cgi->a({-href =>"#patch$patchno"},"patch") .3941" | ";3942}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {3943# "commit" view and modified file (not only pure rename or copy)3944print$cgi->a({-href => href(action=>"blobdiff",3945 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},3946 hash_base=>$hash, hash_parent_base=>$parent,3947 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},3948"diff") .3949" | ";3950}3951print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3952 hash_base=>$parent, file_name=>$diff->{'to_file'})},3953"blob") ." | ";3954if($have_blame) {3955print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,3956 file_name=>$diff->{'to_file'})},3957"blame") ." | ";3958}3959print$cgi->a({-href => href(action=>"history", hash_base=>$hash,3960 file_name=>$diff->{'to_file'})},3961"history");3962print"</td>\n";39633964}# we should not encounter Unmerged (U) or Unknown (X) status3965print"</tr>\n";3966}3967print"</tbody>"if$has_header;3968print"</table>\n";3969}39703971sub git_patchset_body {3972my($fd,$difftree,$hash,@hash_parents) =@_;3973my($hash_parent) =$hash_parents[0];39743975my$is_combined= (@hash_parents>1);3976my$patch_idx=0;3977my$patch_number=0;3978my$patch_line;3979my$diffinfo;3980my$to_name;3981my(%from,%to);39823983print"<div class=\"patchset\">\n";39843985# skip to first patch3986while($patch_line= <$fd>) {3987chomp$patch_line;39883989last if($patch_line=~m/^diff /);3990}39913992 PATCH:3993while($patch_line) {39943995# parse "git diff" header line3996if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {3997# $1 is from_name, which we do not use3998$to_name= unquote($2);3999$to_name=~s!^b/!!;4000}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4001# $1 is 'cc' or 'combined', which we do not use4002$to_name= unquote($2);4003}else{4004$to_name=undef;4005}40064007# check if current patch belong to current raw line4008# and parse raw git-diff line if needed4009if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4010# this is continuation of a split patch4011print"<div class=\"patch cont\">\n";4012}else{4013# advance raw git-diff output if needed4014$patch_idx++ifdefined$diffinfo;40154016# read and prepare patch information4017$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);40184019# compact combined diff output can have some patches skipped4020# find which patch (using pathname of result) we are at now;4021if($is_combined) {4022while($to_namene$diffinfo->{'to_file'}) {4023print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4024 format_diff_cc_simplified($diffinfo,@hash_parents) .4025"</div>\n";# class="patch"40264027$patch_idx++;4028$patch_number++;40294030last if$patch_idx>$#$difftree;4031$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4032}4033}40344035# modifies %from, %to hashes4036 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);40374038# this is first patch for raw difftree line with $patch_idx index4039# we index @$difftree array from 0, but number patches from 14040print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4041}40424043# git diff header4044#assert($patch_line =~ m/^diff /) if DEBUG;4045#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4046$patch_number++;4047# print "git diff" header4048print format_git_diff_header_line($patch_line,$diffinfo,4049 \%from, \%to);40504051# print extended diff header4052print"<div class=\"diff extended_header\">\n";4053 EXTENDED_HEADER:4054while($patch_line= <$fd>) {4055chomp$patch_line;40564057last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);40584059print format_extended_diff_header_line($patch_line,$diffinfo,4060 \%from, \%to);4061}4062print"</div>\n";# class="diff extended_header"40634064# from-file/to-file diff header4065if(!$patch_line) {4066print"</div>\n";# class="patch"4067last PATCH;4068}4069next PATCH if($patch_line=~m/^diff /);4070#assert($patch_line =~ m/^---/) if DEBUG;40714072my$last_patch_line=$patch_line;4073$patch_line= <$fd>;4074chomp$patch_line;4075#assert($patch_line =~ m/^\+\+\+/) if DEBUG;40764077print format_diff_from_to_header($last_patch_line,$patch_line,4078$diffinfo, \%from, \%to,4079@hash_parents);40804081# the patch itself4082 LINE:4083while($patch_line= <$fd>) {4084chomp$patch_line;40854086next PATCH if($patch_line=~m/^diff /);40874088print format_diff_line($patch_line, \%from, \%to);4089}40904091}continue{4092print"</div>\n";# class="patch"4093}40944095# for compact combined (--cc) format, with chunk and patch simpliciaction4096# patchset might be empty, but there might be unprocessed raw lines4097for(++$patch_idxif$patch_number>0;4098$patch_idx<@$difftree;4099++$patch_idx) {4100# read and prepare patch information4101$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);41024103# generate anchor for "patch" links in difftree / whatchanged part4104print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4105 format_diff_cc_simplified($diffinfo,@hash_parents) .4106"</div>\n";# class="patch"41074108$patch_number++;4109}41104111if($patch_number==0) {4112if(@hash_parents>1) {4113print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4114}else{4115print"<div class=\"diff nodifferences\">No differences found</div>\n";4116}4117}41184119print"</div>\n";# class="patchset"4120}41214122# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41234124# fills project list info (age, description, owner, forks) for each4125# project in the list, removing invalid projects from returned list4126# NOTE: modifies $projlist, but does not remove entries from it4127sub fill_project_list_info {4128my($projlist,$check_forks) =@_;4129my@projects;41304131my$show_ctags= gitweb_check_feature('ctags');4132 PROJECT:4133foreachmy$pr(@$projlist) {4134my(@activity) = git_get_last_activity($pr->{'path'});4135unless(@activity) {4136next PROJECT;4137}4138($pr->{'age'},$pr->{'age_string'}) =@activity;4139if(!defined$pr->{'descr'}) {4140my$descr= git_get_project_description($pr->{'path'}) ||"";4141$descr= to_utf8($descr);4142$pr->{'descr_long'} =$descr;4143$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4144}4145if(!defined$pr->{'owner'}) {4146$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4147}4148if($check_forks) {4149my$pname=$pr->{'path'};4150if(($pname=~s/\.git$//) &&4151($pname!~/\/$/) &&4152(-d "$projectroot/$pname")) {4153$pr->{'forks'} ="-d$projectroot/$pname";4154}else{4155$pr->{'forks'} =0;4156}4157}4158$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4159push@projects,$pr;4160}41614162return@projects;4163}41644165# print 'sort by' <th> element, generating 'sort by $name' replay link4166# if that order is not selected4167sub print_sort_th {4168my($name,$order,$header) =@_;4169$header||=ucfirst($name);41704171if($ordereq$name) {4172print"<th>$header</th>\n";4173}else{4174print"<th>".4175$cgi->a({-href => href(-replay=>1, order=>$name),4176-class=>"header"},$header) .4177"</th>\n";4178}4179}41804181sub git_project_list_body {4182# actually uses global variable $project4183my($projlist,$order,$from,$to,$extra,$no_header) =@_;41844185my$check_forks= gitweb_check_feature('forks');4186my@projects= fill_project_list_info($projlist,$check_forks);41874188$order||=$default_projects_order;4189$from=0unlessdefined$from;4190$to=$#projectsif(!defined$to||$#projects<$to);41914192my%order_info= (4193 project => { key =>'path', type =>'str'},4194 descr => { key =>'descr_long', type =>'str'},4195 owner => { key =>'owner', type =>'str'},4196 age => { key =>'age', type =>'num'}4197);4198my$oi=$order_info{$order};4199if($oi->{'type'}eq'str') {4200@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4201}else{4202@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4203}42044205my$show_ctags= gitweb_check_feature('ctags');4206if($show_ctags) {4207my%ctags;4208foreachmy$p(@projects) {4209foreachmy$ct(keys%{$p->{'ctags'}}) {4210$ctags{$ct} +=$p->{'ctags'}->{$ct};4211}4212}4213my$cloud= git_populate_project_tagcloud(\%ctags);4214print git_show_project_tagcloud($cloud,64);4215}42164217print"<table class=\"project_list\">\n";4218unless($no_header) {4219print"<tr>\n";4220if($check_forks) {4221print"<th></th>\n";4222}4223 print_sort_th('project',$order,'Project');4224 print_sort_th('descr',$order,'Description');4225 print_sort_th('owner',$order,'Owner');4226 print_sort_th('age',$order,'Last Change');4227print"<th></th>\n".# for links4228"</tr>\n";4229}4230my$alternate=1;4231my$tagfilter=$cgi->param('by_tag');4232for(my$i=$from;$i<=$to;$i++) {4233my$pr=$projects[$i];42344235next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4236next if$searchtextand not$pr->{'path'} =~/$searchtext/4237and not$pr->{'descr_long'} =~/$searchtext/;4238# Weed out forks or non-matching entries of search4239if($check_forks) {4240my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4241$forkbase="^$forkbase"if$forkbase;4242next ifnot$searchtextand not$tagfilterand$show_ctags4243and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4244}42454246if($alternate) {4247print"<tr class=\"dark\">\n";4248}else{4249print"<tr class=\"light\">\n";4250}4251$alternate^=1;4252if($check_forks) {4253print"<td>";4254if($pr->{'forks'}) {4255print"<!--$pr->{'forks'} -->\n";4256print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4257}4258print"</td>\n";4259}4260print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4261-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4262"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4263-class=>"list", -title =>$pr->{'descr_long'}},4264 esc_html($pr->{'descr'})) ."</td>\n".4265"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4266print"<td class=\"". age_class($pr->{'age'}) ."\">".4267(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4268"<td class=\"link\">".4269$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4270$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4271$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4272$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4273($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4274"</td>\n".4275"</tr>\n";4276}4277if(defined$extra) {4278print"<tr>\n";4279if($check_forks) {4280print"<td></td>\n";4281}4282print"<td colspan=\"5\">$extra</td>\n".4283"</tr>\n";4284}4285print"</table>\n";4286}42874288sub git_shortlog_body {4289# uses global variable $project4290my($commitlist,$from,$to,$refs,$extra) =@_;42914292$from=0unlessdefined$from;4293$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);42944295print"<table class=\"shortlog\">\n";4296my$alternate=1;4297for(my$i=$from;$i<=$to;$i++) {4298my%co= %{$commitlist->[$i]};4299my$commit=$co{'id'};4300my$ref= format_ref_marker($refs,$commit);4301if($alternate) {4302print"<tr class=\"dark\">\n";4303}else{4304print"<tr class=\"light\">\n";4305}4306$alternate^=1;4307# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4308print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4309 format_author_html('td', \%co,10) ."<td>";4310print format_subject_html($co{'title'},$co{'title_short'},4311 href(action=>"commit", hash=>$commit),$ref);4312print"</td>\n".4313"<td class=\"link\">".4314$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4315$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4316$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4317my$snapshot_links= format_snapshot_links($commit);4318if(defined$snapshot_links) {4319print" | ".$snapshot_links;4320}4321print"</td>\n".4322"</tr>\n";4323}4324if(defined$extra) {4325print"<tr>\n".4326"<td colspan=\"4\">$extra</td>\n".4327"</tr>\n";4328}4329print"</table>\n";4330}43314332sub git_history_body {4333# Warning: assumes constant type (blob or tree) during history4334my($commitlist,$from,$to,$refs,$hash_base,$ftype,$extra) =@_;43354336$from=0unlessdefined$from;4337$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});43384339print"<table class=\"history\">\n";4340my$alternate=1;4341for(my$i=$from;$i<=$to;$i++) {4342my%co= %{$commitlist->[$i]};4343if(!%co) {4344next;4345}4346my$commit=$co{'id'};43474348my$ref= format_ref_marker($refs,$commit);43494350if($alternate) {4351print"<tr class=\"dark\">\n";4352}else{4353print"<tr class=\"light\">\n";4354}4355$alternate^=1;4356print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4357# shortlog: format_author_html('td', \%co, 10)4358 format_author_html('td', \%co,15,3) ."<td>";4359# originally git_history used chop_str($co{'title'}, 50)4360print format_subject_html($co{'title'},$co{'title_short'},4361 href(action=>"commit", hash=>$commit),$ref);4362print"</td>\n".4363"<td class=\"link\">".4364$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4365$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");43664367if($ftypeeq'blob') {4368my$blob_current= git_get_hash_by_path($hash_base,$file_name);4369my$blob_parent= git_get_hash_by_path($commit,$file_name);4370if(defined$blob_current&&defined$blob_parent&&4371$blob_currentne$blob_parent) {4372print" | ".4373$cgi->a({-href => href(action=>"blobdiff",4374 hash=>$blob_current, hash_parent=>$blob_parent,4375 hash_base=>$hash_base, hash_parent_base=>$commit,4376 file_name=>$file_name)},4377"diff to current");4378}4379}4380print"</td>\n".4381"</tr>\n";4382}4383if(defined$extra) {4384print"<tr>\n".4385"<td colspan=\"4\">$extra</td>\n".4386"</tr>\n";4387}4388print"</table>\n";4389}43904391sub git_tags_body {4392# uses global variable $project4393my($taglist,$from,$to,$extra) =@_;4394$from=0unlessdefined$from;4395$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);43964397print"<table class=\"tags\">\n";4398my$alternate=1;4399for(my$i=$from;$i<=$to;$i++) {4400my$entry=$taglist->[$i];4401my%tag=%$entry;4402my$comment=$tag{'subject'};4403my$comment_short;4404if(defined$comment) {4405$comment_short= chop_str($comment,30,5);4406}4407if($alternate) {4408print"<tr class=\"dark\">\n";4409}else{4410print"<tr class=\"light\">\n";4411}4412$alternate^=1;4413if(defined$tag{'age'}) {4414print"<td><i>$tag{'age'}</i></td>\n";4415}else{4416print"<td></td>\n";4417}4418print"<td>".4419$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4420-class=>"list name"}, esc_html($tag{'name'})) .4421"</td>\n".4422"<td>";4423if(defined$comment) {4424print format_subject_html($comment,$comment_short,4425 href(action=>"tag", hash=>$tag{'id'}));4426}4427print"</td>\n".4428"<td class=\"selflink\">";4429if($tag{'type'}eq"tag") {4430print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4431}else{4432print" ";4433}4434print"</td>\n".4435"<td class=\"link\">"." | ".4436$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4437if($tag{'reftype'}eq"commit") {4438print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4439" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4440}elsif($tag{'reftype'}eq"blob") {4441print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4442}4443print"</td>\n".4444"</tr>";4445}4446if(defined$extra) {4447print"<tr>\n".4448"<td colspan=\"5\">$extra</td>\n".4449"</tr>\n";4450}4451print"</table>\n";4452}44534454sub git_heads_body {4455# uses global variable $project4456my($headlist,$head,$from,$to,$extra) =@_;4457$from=0unlessdefined$from;4458$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);44594460print"<table class=\"heads\">\n";4461my$alternate=1;4462for(my$i=$from;$i<=$to;$i++) {4463my$entry=$headlist->[$i];4464my%ref=%$entry;4465my$curr=$ref{'id'}eq$head;4466if($alternate) {4467print"<tr class=\"dark\">\n";4468}else{4469print"<tr class=\"light\">\n";4470}4471$alternate^=1;4472print"<td><i>$ref{'age'}</i></td>\n".4473($curr?"<td class=\"current_head\">":"<td>") .4474$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4475-class=>"list name"},esc_html($ref{'name'})) .4476"</td>\n".4477"<td class=\"link\">".4478$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4479$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4480$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})},"tree") .4481"</td>\n".4482"</tr>";4483}4484if(defined$extra) {4485print"<tr>\n".4486"<td colspan=\"3\">$extra</td>\n".4487"</tr>\n";4488}4489print"</table>\n";4490}44914492sub git_search_grep_body {4493my($commitlist,$from,$to,$extra) =@_;4494$from=0unlessdefined$from;4495$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);44964497print"<table class=\"commit_search\">\n";4498my$alternate=1;4499for(my$i=$from;$i<=$to;$i++) {4500my%co= %{$commitlist->[$i]};4501if(!%co) {4502next;4503}4504my$commit=$co{'id'};4505if($alternate) {4506print"<tr class=\"dark\">\n";4507}else{4508print"<tr class=\"light\">\n";4509}4510$alternate^=1;4511print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4512 format_author_html('td', \%co,15,5) .4513"<td>".4514$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),4515-class=>"list subject"},4516 chop_and_escape_str($co{'title'},50) ."<br/>");4517my$comment=$co{'comment'};4518foreachmy$line(@$comment) {4519if($line=~m/^(.*?)($search_regexp)(.*)$/i) {4520my($lead,$match,$trail) = ($1,$2,$3);4521$match= chop_str($match,70,5,'center');4522my$contextlen=int((80-length($match))/2);4523$contextlen=30if($contextlen>30);4524$lead= chop_str($lead,$contextlen,10,'left');4525$trail= chop_str($trail,$contextlen,10,'right');45264527$lead= esc_html($lead);4528$match= esc_html($match);4529$trail= esc_html($trail);45304531print"$lead<span class=\"match\">$match</span>$trail<br />";4532}4533}4534print"</td>\n".4535"<td class=\"link\">".4536$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .4537" | ".4538$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .4539" | ".4540$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");4541print"</td>\n".4542"</tr>\n";4543}4544if(defined$extra) {4545print"<tr>\n".4546"<td colspan=\"3\">$extra</td>\n".4547"</tr>\n";4548}4549print"</table>\n";4550}45514552## ======================================================================4553## ======================================================================4554## actions45554556sub git_project_list {4557my$order=$input_params{'order'};4558if(defined$order&&$order!~m/none|project|descr|owner|age/) {4559 die_error(400,"Unknown order parameter");4560}45614562my@list= git_get_projects_list();4563if(!@list) {4564 die_error(404,"No projects found");4565}45664567 git_header_html();4568if(-f $home_text) {4569print"<div class=\"index_include\">\n";4570 insert_file($home_text);4571print"</div>\n";4572}4573print$cgi->startform(-method=>"get") .4574"<p class=\"projsearch\">Search:\n".4575$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".4576"</p>".4577$cgi->end_form() ."\n";4578 git_project_list_body(\@list,$order);4579 git_footer_html();4580}45814582sub git_forks {4583my$order=$input_params{'order'};4584if(defined$order&&$order!~m/none|project|descr|owner|age/) {4585 die_error(400,"Unknown order parameter");4586}45874588my@list= git_get_projects_list($project);4589if(!@list) {4590 die_error(404,"No forks found");4591}45924593 git_header_html();4594 git_print_page_nav('','');4595 git_print_header_div('summary',"$projectforks");4596 git_project_list_body(\@list,$order);4597 git_footer_html();4598}45994600sub git_project_index {4601my@projects= git_get_projects_list($project);46024603print$cgi->header(4604-type =>'text/plain',4605-charset =>'utf-8',4606-content_disposition =>'inline; filename="index.aux"');46074608foreachmy$pr(@projects) {4609if(!exists$pr->{'owner'}) {4610$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");4611}46124613my($path,$owner) = ($pr->{'path'},$pr->{'owner'});4614# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '4615$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;4616$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;4617$path=~s/ /\+/g;4618$owner=~s/ /\+/g;46194620print"$path$owner\n";4621}4622}46234624sub git_summary {4625my$descr= git_get_project_description($project) ||"none";4626my%co= parse_commit("HEAD");4627my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();4628my$head=$co{'id'};46294630my$owner= git_get_project_owner($project);46314632my$refs= git_get_references();4633# These get_*_list functions return one more to allow us to see if4634# there are more ...4635my@taglist= git_get_tags_list(16);4636my@headlist= git_get_heads_list(16);4637my@forklist;4638my$check_forks= gitweb_check_feature('forks');46394640if($check_forks) {4641@forklist= git_get_projects_list($project);4642}46434644 git_header_html();4645 git_print_page_nav('summary','',$head);46464647print"<div class=\"title\"> </div>\n";4648print"<table class=\"projects_list\">\n".4649"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".4650"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";4651if(defined$cd{'rfc2822'}) {4652print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";4653}46544655# use per project git URL list in $projectroot/$project/cloneurl4656# or make project git URL from git base URL and project name4657my$url_tag="URL";4658my@url_list= git_get_project_url_list($project);4659@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;4660foreachmy$git_url(@url_list) {4661next unless$git_url;4662print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";4663$url_tag="";4664}46654666# Tag cloud4667my$show_ctags= gitweb_check_feature('ctags');4668if($show_ctags) {4669my$ctags= git_get_project_ctags($project);4670my$cloud= git_populate_project_tagcloud($ctags);4671print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";4672print"</td>\n<td>"unless%$ctags;4673print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";4674print"</td>\n<td>"if%$ctags;4675print git_show_project_tagcloud($cloud,48);4676print"</td></tr>";4677}46784679print"</table>\n";46804681# If XSS prevention is on, we don't include README.html.4682# TODO: Allow a readme in some safe format.4683if(!$prevent_xss&& -s "$projectroot/$project/README.html") {4684print"<div class=\"title\">readme</div>\n".4685"<div class=\"readme\">\n";4686 insert_file("$projectroot/$project/README.html");4687print"\n</div>\n";# class="readme"4688}46894690# we need to request one more than 16 (0..15) to check if4691# those 16 are all4692my@commitlist=$head? parse_commits($head,17) : ();4693if(@commitlist) {4694 git_print_header_div('shortlog');4695 git_shortlog_body(\@commitlist,0,15,$refs,4696$#commitlist<=15?undef:4697$cgi->a({-href => href(action=>"shortlog")},"..."));4698}46994700if(@taglist) {4701 git_print_header_div('tags');4702 git_tags_body(\@taglist,0,15,4703$#taglist<=15?undef:4704$cgi->a({-href => href(action=>"tags")},"..."));4705}47064707if(@headlist) {4708 git_print_header_div('heads');4709 git_heads_body(\@headlist,$head,0,15,4710$#headlist<=15?undef:4711$cgi->a({-href => href(action=>"heads")},"..."));4712}47134714if(@forklist) {4715 git_print_header_div('forks');4716 git_project_list_body(\@forklist,'age',0,15,4717$#forklist<=15?undef:4718$cgi->a({-href => href(action=>"forks")},"..."),4719'no_header');4720}47214722 git_footer_html();4723}47244725sub git_tag {4726my$head= git_get_head_hash($project);4727 git_header_html();4728 git_print_page_nav('','',$head,undef,$head);4729my%tag= parse_tag($hash);47304731if(!%tag) {4732 die_error(404,"Unknown tag object");4733}47344735 git_print_header_div('commit', esc_html($tag{'name'}),$hash);4736print"<div class=\"title_text\">\n".4737"<table class=\"object_header\">\n".4738"<tr>\n".4739"<td>object</td>\n".4740"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},4741$tag{'object'}) ."</td>\n".4742"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},4743$tag{'type'}) ."</td>\n".4744"</tr>\n";4745if(defined($tag{'author'})) {4746 git_print_authorship_rows(\%tag,'author');4747}4748print"</table>\n\n".4749"</div>\n";4750print"<div class=\"page_body\">";4751my$comment=$tag{'comment'};4752foreachmy$line(@$comment) {4753chomp$line;4754print esc_html($line, -nbsp=>1) ."<br/>\n";4755}4756print"</div>\n";4757 git_footer_html();4758}47594760sub git_blame {4761# permissions4762 gitweb_check_feature('blame')4763or die_error(403,"Blame view not allowed");47644765# error checking4766 die_error(400,"No file name given")unless$file_name;4767$hash_base||= git_get_head_hash($project);4768 die_error(404,"Couldn't find base commit")unless$hash_base;4769my%co= parse_commit($hash_base)4770or die_error(404,"Commit not found");4771my$ftype="blob";4772if(!defined$hash) {4773$hash= git_get_hash_by_path($hash_base,$file_name,"blob")4774or die_error(404,"Error looking up file");4775}else{4776$ftype= git_get_type($hash);4777if($ftype!~"blob") {4778 die_error(400,"Object is not a blob");4779}4780}47814782# run git-blame --porcelain4783open my$fd,"-|", git_cmd(),"blame",'-p',4784$hash_base,'--',$file_name4785or die_error(500,"Open git-blame failed");47864787# page header4788 git_header_html();4789my$formats_nav=4790$cgi->a({-href => href(action=>"blob", -replay=>1)},4791"blob") .4792" | ".4793$cgi->a({-href => href(action=>"history", -replay=>1)},4794"history") .4795" | ".4796$cgi->a({-href => href(action=>"blame", file_name=>$file_name)},4797"HEAD");4798 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);4799 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);4800 git_print_page_path($file_name,$ftype,$hash_base);48014802# page body4803my@rev_color=qw(light2 dark2);4804my$num_colors=scalar(@rev_color);4805my$current_color=0;4806my%metainfo= ();48074808print<<HTML;4809<div class="page_body">4810<table class="blame">4811<tr><th>Commit</th><th>Line</th><th>Data</th></tr>4812HTML4813 LINE:4814while(my$line= <$fd>) {4815chomp$line;4816# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]4817# no <lines in group> for subsequent lines in group of lines4818my($full_rev,$orig_lineno,$lineno,$group_size) =4819($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);4820if(!exists$metainfo{$full_rev}) {4821$metainfo{$full_rev} = {};4822}4823my$meta=$metainfo{$full_rev};4824my$data;4825while($data= <$fd>) {4826chomp$data;4827last if($data=~s/^\t//);# contents of line4828if($data=~/^(\S+) (.*)$/) {4829$meta->{$1} =$2;4830}4831}4832my$short_rev=substr($full_rev,0,8);4833my$author=$meta->{'author'};4834my%date=4835 parse_date($meta->{'author-time'},$meta->{'author-tz'});4836my$date=$date{'iso-tz'};4837if($group_size) {4838$current_color= ($current_color+1) %$num_colors;4839}4840print"<tr id=\"l$lineno\"class=\"$rev_color[$current_color]\">\n";4841if($group_size) {4842print"<td class=\"sha1\"";4843print" title=\"". esc_html($author) .",$date\"";4844print" rowspan=\"$group_size\""if($group_size>1);4845print">";4846print$cgi->a({-href => href(action=>"commit",4847 hash=>$full_rev,4848 file_name=>$file_name)},4849 esc_html($short_rev));4850print"</td>\n";4851}4852my$parent_commit;4853if(!exists$meta->{'parent'}) {4854open(my$dd,"-|", git_cmd(),"rev-parse","$full_rev^")4855or die_error(500,"Open git-rev-parse failed");4856$parent_commit= <$dd>;4857close$dd;4858chomp($parent_commit);4859$meta->{'parent'} =$parent_commit;4860}else{4861$parent_commit=$meta->{'parent'};4862}4863my$blamed= href(action =>'blame',4864 file_name =>$meta->{'filename'},4865 hash_base =>$parent_commit);4866print"<td class=\"linenr\">";4867print$cgi->a({ -href =>"$blamed#l$orig_lineno",4868-class=>"linenr"},4869 esc_html($lineno));4870print"</td>";4871print"<td class=\"pre\">". esc_html($data) ."</td>\n";4872print"</tr>\n";4873}4874print"</table>\n";4875print"</div>";4876close$fd4877or print"Reading blob failed\n";48784879# page footer4880 git_footer_html();4881}48824883sub git_tags {4884my$head= git_get_head_hash($project);4885 git_header_html();4886 git_print_page_nav('','',$head,undef,$head);4887 git_print_header_div('summary',$project);48884889my@tagslist= git_get_tags_list();4890if(@tagslist) {4891 git_tags_body(\@tagslist);4892}4893 git_footer_html();4894}48954896sub git_heads {4897my$head= git_get_head_hash($project);4898 git_header_html();4899 git_print_page_nav('','',$head,undef,$head);4900 git_print_header_div('summary',$project);49014902my@headslist= git_get_heads_list();4903if(@headslist) {4904 git_heads_body(\@headslist,$head);4905}4906 git_footer_html();4907}49084909sub git_blob_plain {4910my$type=shift;4911my$expires;49124913if(!defined$hash) {4914if(defined$file_name) {4915my$base=$hash_base|| git_get_head_hash($project);4916$hash= git_get_hash_by_path($base,$file_name,"blob")4917or die_error(404,"Cannot find file");4918}else{4919 die_error(400,"No file name defined");4920}4921}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {4922# blobs defined by non-textual hash id's can be cached4923$expires="+1d";4924}49254926open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4927or die_error(500,"Open git-cat-file blob '$hash' failed");49284929# content-type (can include charset)4930$type= blob_contenttype($fd,$file_name,$type);49314932# "save as" filename, even when no $file_name is given4933my$save_as="$hash";4934if(defined$file_name) {4935$save_as=$file_name;4936}elsif($type=~m/^text\//) {4937$save_as.='.txt';4938}49394940# With XSS prevention on, blobs of all types except a few known safe4941# ones are served with "Content-Disposition: attachment" to make sure4942# they don't run in our security domain. For certain image types,4943# blob view writes an <img> tag referring to blob_plain view, and we4944# want to be sure not to break that by serving the image as an4945# attachment (though Firefox 3 doesn't seem to care).4946my$sandbox=$prevent_xss&&4947$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;49484949print$cgi->header(4950-type =>$type,4951-expires =>$expires,4952-content_disposition =>4953($sandbox?'attachment':'inline')4954.'; filename="'.$save_as.'"');4955local$/=undef;4956binmode STDOUT,':raw';4957print<$fd>;4958binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi4959close$fd;4960}49614962sub git_blob {4963my$expires;49644965if(!defined$hash) {4966if(defined$file_name) {4967my$base=$hash_base|| git_get_head_hash($project);4968$hash= git_get_hash_by_path($base,$file_name,"blob")4969or die_error(404,"Cannot find file");4970}else{4971 die_error(400,"No file name defined");4972}4973}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {4974# blobs defined by non-textual hash id's can be cached4975$expires="+1d";4976}49774978my$have_blame= gitweb_check_feature('blame');4979open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4980or die_error(500,"Couldn't cat$file_name,$hash");4981my$mimetype= blob_mimetype($fd,$file_name);4982if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {4983close$fd;4984return git_blob_plain($mimetype);4985}4986# we can have blame only for text/* mimetype4987$have_blame&&= ($mimetype=~m!^text/!);49884989 git_header_html(undef,$expires);4990my$formats_nav='';4991if(defined$hash_base&& (my%co= parse_commit($hash_base))) {4992if(defined$file_name) {4993if($have_blame) {4994$formats_nav.=4995$cgi->a({-href => href(action=>"blame", -replay=>1)},4996"blame") .4997" | ";4998}4999$formats_nav.=5000$cgi->a({-href => href(action=>"history", -replay=>1)},5001"history") .5002" | ".5003$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5004"raw") .5005" | ".5006$cgi->a({-href => href(action=>"blob",5007 hash_base=>"HEAD", file_name=>$file_name)},5008"HEAD");5009}else{5010$formats_nav.=5011$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5012"raw");5013}5014 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5015 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5016}else{5017print"<div class=\"page_nav\">\n".5018"<br/><br/></div>\n".5019"<div class=\"title\">$hash</div>\n";5020}5021 git_print_page_path($file_name,"blob",$hash_base);5022print"<div class=\"page_body\">\n";5023if($mimetype=~m!^image/!) {5024print qq!<img type="$mimetype"!;5025if($file_name) {5026print qq! alt="$file_name" title="$file_name"!;5027}5028print qq! src="! .5029 href(action=>"blob_plain", hash=>$hash,5030 hash_base=>$hash_base, file_name=>$file_name) .5031 qq!"/>\n!;5032}else{5033my$nr;5034while(my$line= <$fd>) {5035chomp$line;5036$nr++;5037$line= untabify($line);5038printf"<div class=\"pre\"><a id=\"l%i\"href=\"#l%i\"class=\"linenr\">%4i</a>%s</div>\n",5039$nr,$nr,$nr, esc_html($line, -nbsp=>1);5040}5041}5042close$fd5043or print"Reading blob failed.\n";5044print"</div>";5045 git_footer_html();5046}50475048sub git_tree {5049if(!defined$hash_base) {5050$hash_base="HEAD";5051}5052if(!defined$hash) {5053if(defined$file_name) {5054$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5055}else{5056$hash=$hash_base;5057}5058}5059 die_error(404,"No such tree")unlessdefined($hash);50605061my@entries= ();5062{5063local$/="\0";5064open my$fd,"-|", git_cmd(),"ls-tree",'-z',$hash5065or die_error(500,"Open git-ls-tree failed");5066@entries=map{chomp;$_} <$fd>;5067close$fd5068or die_error(404,"Reading tree failed");5069}50705071my$refs= git_get_references();5072my$ref= format_ref_marker($refs,$hash_base);5073 git_header_html();5074my$basedir='';5075my$have_blame= gitweb_check_feature('blame');5076if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5077my@views_nav= ();5078if(defined$file_name) {5079push@views_nav,5080$cgi->a({-href => href(action=>"history", -replay=>1)},5081"history"),5082$cgi->a({-href => href(action=>"tree",5083 hash_base=>"HEAD", file_name=>$file_name)},5084"HEAD"),5085}5086my$snapshot_links= format_snapshot_links($hash);5087if(defined$snapshot_links) {5088# FIXME: Should be available when we have no hash base as well.5089push@views_nav,$snapshot_links;5090}5091 git_print_page_nav('tree','',$hash_base,undef,undef,join(' | ',@views_nav));5092 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5093}else{5094undef$hash_base;5095print"<div class=\"page_nav\">\n";5096print"<br/><br/></div>\n";5097print"<div class=\"title\">$hash</div>\n";5098}5099if(defined$file_name) {5100$basedir=$file_name;5101if($basedirne''&&substr($basedir, -1)ne'/') {5102$basedir.='/';5103}5104 git_print_page_path($file_name,'tree',$hash_base);5105}5106print"<div class=\"page_body\">\n";5107print"<table class=\"tree\">\n";5108my$alternate=1;5109# '..' (top directory) link if possible5110if(defined$hash_base&&5111defined$file_name&&$file_name=~m![^/]+$!) {5112if($alternate) {5113print"<tr class=\"dark\">\n";5114}else{5115print"<tr class=\"light\">\n";5116}5117$alternate^=1;51185119my$up=$file_name;5120$up=~s!/?[^/]+$!!;5121undef$upunless$up;5122# based on git_print_tree_entry5123print'<td class="mode">'. mode_str('040000') ."</td>\n";5124print'<td class="list">';5125print$cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,5126 file_name=>$up)},5127"..");5128print"</td>\n";5129print"<td class=\"link\"></td>\n";51305131print"</tr>\n";5132}5133foreachmy$line(@entries) {5134my%t= parse_ls_tree_line($line, -z =>1);51355136if($alternate) {5137print"<tr class=\"dark\">\n";5138}else{5139print"<tr class=\"light\">\n";5140}5141$alternate^=1;51425143 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);51445145print"</tr>\n";5146}5147print"</table>\n".5148"</div>";5149 git_footer_html();5150}51515152sub git_snapshot {5153my$format=$input_params{'snapshot_format'};5154if(!@snapshot_fmts) {5155 die_error(403,"Snapshots not allowed");5156}5157# default to first supported snapshot format5158$format||=$snapshot_fmts[0];5159if($format!~m/^[a-z0-9]+$/) {5160 die_error(400,"Invalid snapshot format parameter");5161}elsif(!exists($known_snapshot_formats{$format})) {5162 die_error(400,"Unknown snapshot format");5163}elsif(!grep($_eq$format,@snapshot_fmts)) {5164 die_error(403,"Unsupported snapshot format");5165}51665167if(!defined$hash) {5168$hash= git_get_head_hash($project);5169}51705171my$name=$project;5172$name=~ s,([^/])/*\.git$,$1,;5173$name= basename($name);5174my$filename= to_utf8($name);5175$name=~s/\047/\047\\\047\047/g;5176my$cmd;5177$filename.="-$hash$known_snapshot_formats{$format}{'suffix'}";5178$cmd= quote_command(5179 git_cmd(),'archive',5180"--format=$known_snapshot_formats{$format}{'format'}",5181"--prefix=$name/",$hash);5182if(exists$known_snapshot_formats{$format}{'compressor'}) {5183$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5184}51855186print$cgi->header(5187-type =>$known_snapshot_formats{$format}{'type'},5188-content_disposition =>'inline; filename="'."$filename".'"',5189-status =>'200 OK');51905191open my$fd,"-|",$cmd5192or die_error(500,"Execute git-archive failed");5193binmode STDOUT,':raw';5194print<$fd>;5195binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5196close$fd;5197}51985199sub git_log {5200my$head= git_get_head_hash($project);5201if(!defined$hash) {5202$hash=$head;5203}5204if(!defined$page) {5205$page=0;5206}5207my$refs= git_get_references();52085209my@commitlist= parse_commits($hash,101, (100*$page));52105211my$paging_nav= format_paging_nav('log',$hash,$head,$page,$#commitlist>=100);52125213my($patch_max) = gitweb_get_feature('patches');5214if($patch_max) {5215if($patch_max<0||@commitlist<=$patch_max) {5216$paging_nav.=" ⋅ ".5217$cgi->a({-href => href(action=>"patches", -replay=>1)},5218"patches");5219}5220}52215222 git_header_html();5223 git_print_page_nav('log','',$hash,undef,undef,$paging_nav);52245225if(!@commitlist) {5226my%co= parse_commit($hash);52275228 git_print_header_div('summary',$project);5229print"<div class=\"page_body\"> Last change$co{'age_string'}.<br/><br/></div>\n";5230}5231my$to= ($#commitlist>=99) ? (99) : ($#commitlist);5232for(my$i=0;$i<=$to;$i++) {5233my%co= %{$commitlist[$i]};5234next if!%co;5235my$commit=$co{'id'};5236my$ref= format_ref_marker($refs,$commit);5237my%ad= parse_date($co{'author_epoch'});5238 git_print_header_div('commit',5239"<span class=\"age\">$co{'age_string'}</span>".5240 esc_html($co{'title'}) .$ref,5241$commit);5242print"<div class=\"title_text\">\n".5243"<div class=\"log_link\">\n".5244$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5245" | ".5246$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5247" | ".5248$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5249"<br/>\n".5250"</div>\n";5251 git_print_authorship(\%co, -tag =>'span');5252print"<br/>\n</div>\n";52535254print"<div class=\"log_body\">\n";5255 git_print_log($co{'comment'}, -final_empty_line=>1);5256print"</div>\n";5257}5258if($#commitlist>=100) {5259print"<div class=\"page_nav\">\n";5260print$cgi->a({-href => href(-replay=>1, page=>$page+1),5261-accesskey =>"n", -title =>"Alt-n"},"next");5262print"</div>\n";5263}5264 git_footer_html();5265}52665267sub git_commit {5268$hash||=$hash_base||"HEAD";5269my%co= parse_commit($hash)5270or die_error(404,"Unknown commit object");52715272my$parent=$co{'parent'};5273my$parents=$co{'parents'};# listref52745275# we need to prepare $formats_nav before any parameter munging5276my$formats_nav;5277if(!defined$parent) {5278# --root commitdiff5279$formats_nav.='(initial)';5280}elsif(@$parents==1) {5281# single parent commit5282$formats_nav.=5283'(parent: '.5284$cgi->a({-href => href(action=>"commit",5285 hash=>$parent)},5286 esc_html(substr($parent,0,7))) .5287')';5288}else{5289# merge commit5290$formats_nav.=5291'(merge: '.5292join(' ',map{5293$cgi->a({-href => href(action=>"commit",5294 hash=>$_)},5295 esc_html(substr($_,0,7)));5296}@$parents) .5297')';5298}5299if(gitweb_check_feature('patches')) {5300$formats_nav.=" | ".5301$cgi->a({-href => href(action=>"patch", -replay=>1)},5302"patch");5303}53045305if(!defined$parent) {5306$parent="--root";5307}5308my@difftree;5309open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",5310@diff_opts,5311(@$parents<=1?$parent:'-c'),5312$hash,"--"5313or die_error(500,"Open git-diff-tree failed");5314@difftree=map{chomp;$_} <$fd>;5315close$fdor die_error(404,"Reading git-diff-tree failed");53165317# non-textual hash id's can be cached5318my$expires;5319if($hash=~m/^[0-9a-fA-F]{40}$/) {5320$expires="+1d";5321}5322my$refs= git_get_references();5323my$ref= format_ref_marker($refs,$co{'id'});53245325 git_header_html(undef,$expires);5326 git_print_page_nav('commit','',5327$hash,$co{'tree'},$hash,5328$formats_nav);53295330if(defined$co{'parent'}) {5331 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);5332}else{5333 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);5334}5335print"<div class=\"title_text\">\n".5336"<table class=\"object_header\">\n";5337 git_print_authorship_rows(\%co);5338print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";5339print"<tr>".5340"<td>tree</td>".5341"<td class=\"sha1\">".5342$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),5343class=>"list"},$co{'tree'}) .5344"</td>".5345"<td class=\"link\">".5346$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},5347"tree");5348my$snapshot_links= format_snapshot_links($hash);5349if(defined$snapshot_links) {5350print" | ".$snapshot_links;5351}5352print"</td>".5353"</tr>\n";53545355foreachmy$par(@$parents) {5356print"<tr>".5357"<td>parent</td>".5358"<td class=\"sha1\">".5359$cgi->a({-href => href(action=>"commit", hash=>$par),5360class=>"list"},$par) .5361"</td>".5362"<td class=\"link\">".5363$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .5364" | ".5365$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .5366"</td>".5367"</tr>\n";5368}5369print"</table>".5370"</div>\n";53715372print"<div class=\"page_body\">\n";5373 git_print_log($co{'comment'});5374print"</div>\n";53755376 git_difftree_body(\@difftree,$hash,@$parents);53775378 git_footer_html();5379}53805381sub git_object {5382# object is defined by:5383# - hash or hash_base alone5384# - hash_base and file_name5385my$type;53865387# - hash or hash_base alone5388if($hash|| ($hash_base&& !defined$file_name)) {5389my$object_id=$hash||$hash_base;53905391open my$fd,"-|", quote_command(5392 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'5393or die_error(404,"Object does not exist");5394$type= <$fd>;5395chomp$type;5396close$fd5397or die_error(404,"Object does not exist");53985399# - hash_base and file_name5400}elsif($hash_base&&defined$file_name) {5401$file_name=~ s,/+$,,;54025403system(git_cmd(),"cat-file",'-e',$hash_base) ==05404or die_error(404,"Base object does not exist");54055406# here errors should not hapen5407open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name5408or die_error(500,"Open git-ls-tree failed");5409my$line= <$fd>;5410close$fd;54115412#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'5413unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {5414 die_error(404,"File or directory for given base does not exist");5415}5416$type=$2;5417$hash=$3;5418}else{5419 die_error(400,"Not enough information to find object");5420}54215422print$cgi->redirect(-uri => href(action=>$type, -full=>1,5423 hash=>$hash, hash_base=>$hash_base,5424 file_name=>$file_name),5425-status =>'302 Found');5426}54275428sub git_blobdiff {5429my$format=shift||'html';54305431my$fd;5432my@difftree;5433my%diffinfo;5434my$expires;54355436# preparing $fd and %diffinfo for git_patchset_body5437# new style URI5438if(defined$hash_base&&defined$hash_parent_base) {5439if(defined$file_name) {5440# read raw output5441open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5442$hash_parent_base,$hash_base,5443"--", (defined$file_parent?$file_parent: ()),$file_name5444or die_error(500,"Open git-diff-tree failed");5445@difftree=map{chomp;$_} <$fd>;5446close$fd5447or die_error(404,"Reading git-diff-tree failed");5448@difftree5449or die_error(404,"Blob diff not found");54505451}elsif(defined$hash&&5452$hash=~/[0-9a-fA-F]{40}/) {5453# try to find filename from $hash54545455# read filtered raw output5456open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5457$hash_parent_base,$hash_base,"--"5458or die_error(500,"Open git-diff-tree failed");5459@difftree=5460# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'5461# $hash == to_id5462grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}5463map{chomp;$_} <$fd>;5464close$fd5465or die_error(404,"Reading git-diff-tree failed");5466@difftree5467or die_error(404,"Blob diff not found");54685469}else{5470 die_error(400,"Missing one of the blob diff parameters");5471}54725473if(@difftree>1) {5474 die_error(400,"Ambiguous blob diff specification");5475}54765477%diffinfo= parse_difftree_raw_line($difftree[0]);5478$file_parent||=$diffinfo{'from_file'} ||$file_name;5479$file_name||=$diffinfo{'to_file'};54805481$hash_parent||=$diffinfo{'from_id'};5482$hash||=$diffinfo{'to_id'};54835484# non-textual hash id's can be cached5485if($hash_base=~m/^[0-9a-fA-F]{40}$/&&5486$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {5487$expires='+1d';5488}54895490# open patch output5491open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5492'-p', ($formateq'html'?"--full-index": ()),5493$hash_parent_base,$hash_base,5494"--", (defined$file_parent?$file_parent: ()),$file_name5495or die_error(500,"Open git-diff-tree failed");5496}54975498# old/legacy style URI -- not generated anymore since 1.4.3.5499if(!%diffinfo) {5500 die_error('404 Not Found',"Missing one of the blob diff parameters")5501}55025503# header5504if($formateq'html') {5505my$formats_nav=5506$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},5507"raw");5508 git_header_html(undef,$expires);5509if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5510 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5511 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5512}else{5513print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";5514print"<div class=\"title\">$hashvs$hash_parent</div>\n";5515}5516if(defined$file_name) {5517 git_print_page_path($file_name,"blob",$hash_base);5518}else{5519print"<div class=\"page_path\"></div>\n";5520}55215522}elsif($formateq'plain') {5523print$cgi->header(5524-type =>'text/plain',5525-charset =>'utf-8',5526-expires =>$expires,5527-content_disposition =>'inline; filename="'."$file_name".'.patch"');55285529print"X-Git-Url: ".$cgi->self_url() ."\n\n";55305531}else{5532 die_error(400,"Unknown blobdiff format");5533}55345535# patch5536if($formateq'html') {5537print"<div class=\"page_body\">\n";55385539 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);5540close$fd;55415542print"</div>\n";# class="page_body"5543 git_footer_html();55445545}else{5546while(my$line= <$fd>) {5547$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;5548$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;55495550print$line;55515552last if$line=~m!^\+\+\+!;5553}5554local$/=undef;5555print<$fd>;5556close$fd;5557}5558}55595560sub git_blobdiff_plain {5561 git_blobdiff('plain');5562}55635564sub git_commitdiff {5565my%params=@_;5566my$format=$params{-format} ||'html';55675568my($patch_max) = gitweb_get_feature('patches');5569if($formateq'patch') {5570 die_error(403,"Patch view not allowed")unless$patch_max;5571}55725573$hash||=$hash_base||"HEAD";5574my%co= parse_commit($hash)5575or die_error(404,"Unknown commit object");55765577# choose format for commitdiff for merge5578if(!defined$hash_parent&& @{$co{'parents'}} >1) {5579$hash_parent='--cc';5580}5581# we need to prepare $formats_nav before almost any parameter munging5582my$formats_nav;5583if($formateq'html') {5584$formats_nav=5585$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},5586"raw");5587if($patch_max) {5588$formats_nav.=" | ".5589$cgi->a({-href => href(action=>"patch", -replay=>1)},5590"patch");5591}55925593if(defined$hash_parent&&5594$hash_parentne'-c'&&$hash_parentne'--cc') {5595# commitdiff with two commits given5596my$hash_parent_short=$hash_parent;5597if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {5598$hash_parent_short=substr($hash_parent,0,7);5599}5600$formats_nav.=5601' (from';5602for(my$i=0;$i< @{$co{'parents'}};$i++) {5603if($co{'parents'}[$i]eq$hash_parent) {5604$formats_nav.=' parent '. ($i+1);5605last;5606}5607}5608$formats_nav.=': '.5609$cgi->a({-href => href(action=>"commitdiff",5610 hash=>$hash_parent)},5611 esc_html($hash_parent_short)) .5612')';5613}elsif(!$co{'parent'}) {5614# --root commitdiff5615$formats_nav.=' (initial)';5616}elsif(scalar@{$co{'parents'}} ==1) {5617# single parent commit5618$formats_nav.=5619' (parent: '.5620$cgi->a({-href => href(action=>"commitdiff",5621 hash=>$co{'parent'})},5622 esc_html(substr($co{'parent'},0,7))) .5623')';5624}else{5625# merge commit5626if($hash_parenteq'--cc') {5627$formats_nav.=' | '.5628$cgi->a({-href => href(action=>"commitdiff",5629 hash=>$hash, hash_parent=>'-c')},5630'combined');5631}else{# $hash_parent eq '-c'5632$formats_nav.=' | '.5633$cgi->a({-href => href(action=>"commitdiff",5634 hash=>$hash, hash_parent=>'--cc')},5635'compact');5636}5637$formats_nav.=5638' (merge: '.5639join(' ',map{5640$cgi->a({-href => href(action=>"commitdiff",5641 hash=>$_)},5642 esc_html(substr($_,0,7)));5643} @{$co{'parents'}} ) .5644')';5645}5646}56475648my$hash_parent_param=$hash_parent;5649if(!defined$hash_parent_param) {5650# --cc for multiple parents, --root for parentless5651$hash_parent_param=5652@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';5653}56545655# read commitdiff5656my$fd;5657my@difftree;5658if($formateq'html') {5659open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5660"--no-commit-id","--patch-with-raw","--full-index",5661$hash_parent_param,$hash,"--"5662or die_error(500,"Open git-diff-tree failed");56635664while(my$line= <$fd>) {5665chomp$line;5666# empty line ends raw part of diff-tree output5667last unless$line;5668push@difftree,scalar parse_difftree_raw_line($line);5669}56705671}elsif($formateq'plain') {5672open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5673'-p',$hash_parent_param,$hash,"--"5674or die_error(500,"Open git-diff-tree failed");5675}elsif($formateq'patch') {5676# For commit ranges, we limit the output to the number of5677# patches specified in the 'patches' feature.5678# For single commits, we limit the output to a single patch,5679# diverging from the git-format-patch default.5680my@commit_spec= ();5681if($hash_parent) {5682if($patch_max>0) {5683push@commit_spec,"-$patch_max";5684}5685push@commit_spec,'-n',"$hash_parent..$hash";5686}else{5687if($params{-single}) {5688push@commit_spec,'-1';5689}else{5690if($patch_max>0) {5691push@commit_spec,"-$patch_max";5692}5693push@commit_spec,"-n";5694}5695push@commit_spec,'--root',$hash;5696}5697open$fd,"-|", git_cmd(),"format-patch",'--encoding=utf8',5698'--stdout',@commit_spec5699or die_error(500,"Open git-format-patch failed");5700}else{5701 die_error(400,"Unknown commitdiff format");5702}57035704# non-textual hash id's can be cached5705my$expires;5706if($hash=~m/^[0-9a-fA-F]{40}$/) {5707$expires="+1d";5708}57095710# write commit message5711if($formateq'html') {5712my$refs= git_get_references();5713my$ref= format_ref_marker($refs,$co{'id'});57145715 git_header_html(undef,$expires);5716 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);5717 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);5718print"<div class=\"title_text\">\n".5719"<table class=\"object_header\">\n";5720 git_print_authorship_rows(\%co);5721print"</table>".5722"</div>\n";5723print"<div class=\"page_body\">\n";5724if(@{$co{'comment'}} >1) {5725print"<div class=\"log\">\n";5726 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);5727print"</div>\n";# class="log"5728}57295730}elsif($formateq'plain') {5731my$refs= git_get_references("tags");5732my$tagname= git_get_rev_name_tags($hash);5733my$filename= basename($project) ."-$hash.patch";57345735print$cgi->header(5736-type =>'text/plain',5737-charset =>'utf-8',5738-expires =>$expires,5739-content_disposition =>'inline; filename="'."$filename".'"');5740my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});5741print"From: ". to_utf8($co{'author'}) ."\n";5742print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";5743print"Subject: ". to_utf8($co{'title'}) ."\n";57445745print"X-Git-Tag:$tagname\n"if$tagname;5746print"X-Git-Url: ".$cgi->self_url() ."\n\n";57475748foreachmy$line(@{$co{'comment'}}) {5749print to_utf8($line) ."\n";5750}5751print"---\n\n";5752}elsif($formateq'patch') {5753my$filename= basename($project) ."-$hash.patch";57545755print$cgi->header(5756-type =>'text/plain',5757-charset =>'utf-8',5758-expires =>$expires,5759-content_disposition =>'inline; filename="'."$filename".'"');5760}57615762# write patch5763if($formateq'html') {5764my$use_parents= !defined$hash_parent||5765$hash_parenteq'-c'||$hash_parenteq'--cc';5766 git_difftree_body(\@difftree,$hash,5767$use_parents? @{$co{'parents'}} :$hash_parent);5768print"<br/>\n";57695770 git_patchset_body($fd, \@difftree,$hash,5771$use_parents? @{$co{'parents'}} :$hash_parent);5772close$fd;5773print"</div>\n";# class="page_body"5774 git_footer_html();57755776}elsif($formateq'plain') {5777local$/=undef;5778print<$fd>;5779close$fd5780or print"Reading git-diff-tree failed\n";5781}elsif($formateq'patch') {5782local$/=undef;5783print<$fd>;5784close$fd5785or print"Reading git-format-patch failed\n";5786}5787}57885789sub git_commitdiff_plain {5790 git_commitdiff(-format =>'plain');5791}57925793# format-patch-style patches5794sub git_patch {5795 git_commitdiff(-format =>'patch', -single=>1);5796}57975798sub git_patches {5799 git_commitdiff(-format =>'patch');5800}58015802sub git_history {5803if(!defined$hash_base) {5804$hash_base= git_get_head_hash($project);5805}5806if(!defined$page) {5807$page=0;5808}5809my$ftype;5810my%co= parse_commit($hash_base)5811or die_error(404,"Unknown commit object");58125813my$refs= git_get_references();5814my$limit=sprintf("--max-count=%i", (100* ($page+1)));58155816my@commitlist= parse_commits($hash_base,101, (100*$page),5817$file_name,"--full-history")5818or die_error(404,"No such file or directory on given branch");58195820if(!defined$hash&&defined$file_name) {5821# some commits could have deleted file in question,5822# and not have it in tree, but one of them has to have it5823for(my$i=0;$i<=@commitlist;$i++) {5824$hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5825last ifdefined$hash;5826}5827}5828if(defined$hash) {5829$ftype= git_get_type($hash);5830}5831if(!defined$ftype) {5832 die_error(500,"Unknown type of object");5833}58345835my$paging_nav='';5836if($page>0) {5837$paging_nav.=5838$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,5839 file_name=>$file_name)},5840"first");5841$paging_nav.=" ⋅ ".5842$cgi->a({-href => href(-replay=>1, page=>$page-1),5843-accesskey =>"p", -title =>"Alt-p"},"prev");5844}else{5845$paging_nav.="first";5846$paging_nav.=" ⋅ prev";5847}5848my$next_link='';5849if($#commitlist>=100) {5850$next_link=5851$cgi->a({-href => href(-replay=>1, page=>$page+1),5852-accesskey =>"n", -title =>"Alt-n"},"next");5853$paging_nav.=" ⋅$next_link";5854}else{5855$paging_nav.=" ⋅ next";5856}58575858 git_header_html();5859 git_print_page_nav('history','',$hash_base,$co{'tree'},$hash_base,$paging_nav);5860 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5861 git_print_page_path($file_name,$ftype,$hash_base);58625863 git_history_body(\@commitlist,0,99,5864$refs,$hash_base,$ftype,$next_link);58655866 git_footer_html();5867}58685869sub git_search {5870 gitweb_check_feature('search')or die_error(403,"Search is disabled");5871if(!defined$searchtext) {5872 die_error(400,"Text field is empty");5873}5874if(!defined$hash) {5875$hash= git_get_head_hash($project);5876}5877my%co= parse_commit($hash);5878if(!%co) {5879 die_error(404,"Unknown commit object");5880}5881if(!defined$page) {5882$page=0;5883}58845885$searchtype||='commit';5886if($searchtypeeq'pickaxe') {5887# pickaxe may take all resources of your box and run for several minutes5888# with every query - so decide by yourself how public you make this feature5889 gitweb_check_feature('pickaxe')5890or die_error(403,"Pickaxe is disabled");5891}5892if($searchtypeeq'grep') {5893 gitweb_check_feature('grep')5894or die_error(403,"Grep is disabled");5895}58965897 git_header_html();58985899if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {5900my$greptype;5901if($searchtypeeq'commit') {5902$greptype="--grep=";5903}elsif($searchtypeeq'author') {5904$greptype="--author=";5905}elsif($searchtypeeq'committer') {5906$greptype="--committer=";5907}5908$greptype.=$searchtext;5909my@commitlist= parse_commits($hash,101, (100*$page),undef,5910$greptype,'--regexp-ignore-case',5911$search_use_regexp?'--extended-regexp':'--fixed-strings');59125913my$paging_nav='';5914if($page>0) {5915$paging_nav.=5916$cgi->a({-href => href(action=>"search", hash=>$hash,5917 searchtext=>$searchtext,5918 searchtype=>$searchtype)},5919"first");5920$paging_nav.=" ⋅ ".5921$cgi->a({-href => href(-replay=>1, page=>$page-1),5922-accesskey =>"p", -title =>"Alt-p"},"prev");5923}else{5924$paging_nav.="first";5925$paging_nav.=" ⋅ prev";5926}5927my$next_link='';5928if($#commitlist>=100) {5929$next_link=5930$cgi->a({-href => href(-replay=>1, page=>$page+1),5931-accesskey =>"n", -title =>"Alt-n"},"next");5932$paging_nav.=" ⋅$next_link";5933}else{5934$paging_nav.=" ⋅ next";5935}59365937if($#commitlist>=100) {5938}59395940 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);5941 git_print_header_div('commit', esc_html($co{'title'}),$hash);5942 git_search_grep_body(\@commitlist,0,99,$next_link);5943}59445945if($searchtypeeq'pickaxe') {5946 git_print_page_nav('','',$hash,$co{'tree'},$hash);5947 git_print_header_div('commit', esc_html($co{'title'}),$hash);59485949print"<table class=\"pickaxe search\">\n";5950my$alternate=1;5951local$/="\n";5952open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,5953'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",5954($search_use_regexp?'--pickaxe-regex': ());5955undef%co;5956my@files;5957while(my$line= <$fd>) {5958chomp$line;5959next unless$line;59605961my%set= parse_difftree_raw_line($line);5962if(defined$set{'commit'}) {5963# finish previous commit5964if(%co) {5965print"</td>\n".5966"<td class=\"link\">".5967$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .5968" | ".5969$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");5970print"</td>\n".5971"</tr>\n";5972}59735974if($alternate) {5975print"<tr class=\"dark\">\n";5976}else{5977print"<tr class=\"light\">\n";5978}5979$alternate^=1;5980%co= parse_commit($set{'commit'});5981my$author= chop_and_escape_str($co{'author_name'},15,5);5982print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".5983"<td><i>$author</i></td>\n".5984"<td>".5985$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),5986-class=>"list subject"},5987 chop_and_escape_str($co{'title'},50) ."<br/>");5988}elsif(defined$set{'to_id'}) {5989next if($set{'to_id'} =~m/^0{40}$/);59905991print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},5992 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),5993-class=>"list"},5994"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .5995"<br/>\n";5996}5997}5998close$fd;59996000# finish last commit (warning: repetition!)6001if(%co) {6002print"</td>\n".6003"<td class=\"link\">".6004$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6005" | ".6006$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6007print"</td>\n".6008"</tr>\n";6009}60106011print"</table>\n";6012}60136014if($searchtypeeq'grep') {6015 git_print_page_nav('','',$hash,$co{'tree'},$hash);6016 git_print_header_div('commit', esc_html($co{'title'}),$hash);60176018print"<table class=\"grep_search\">\n";6019my$alternate=1;6020my$matches=0;6021local$/="\n";6022open my$fd,"-|", git_cmd(),'grep','-n',6023$search_use_regexp? ('-E','-i') :'-F',6024$searchtext,$co{'tree'};6025my$lastfile='';6026while(my$line= <$fd>) {6027chomp$line;6028my($file,$lno,$ltext,$binary);6029last if($matches++>1000);6030if($line=~/^Binary file (.+) matches$/) {6031$file=$1;6032$binary=1;6033}else{6034(undef,$file,$lno,$ltext) =split(/:/,$line,4);6035}6036if($filene$lastfile) {6037$lastfileand print"</td></tr>\n";6038if($alternate++) {6039print"<tr class=\"dark\">\n";6040}else{6041print"<tr class=\"light\">\n";6042}6043print"<td class=\"list\">".6044$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6045 file_name=>"$file"),6046-class=>"list"}, esc_path($file));6047print"</td><td>\n";6048$lastfile=$file;6049}6050if($binary) {6051print"<div class=\"binary\">Binary file</div>\n";6052}else{6053$ltext= untabify($ltext);6054if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6055$ltext= esc_html($1, -nbsp=>1);6056$ltext.='<span class="match">';6057$ltext.= esc_html($2, -nbsp=>1);6058$ltext.='</span>';6059$ltext.= esc_html($3, -nbsp=>1);6060}else{6061$ltext= esc_html($ltext, -nbsp=>1);6062}6063print"<div class=\"pre\">".6064$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6065 file_name=>"$file").'#l'.$lno,6066-class=>"linenr"},sprintf('%4i',$lno))6067.' '.$ltext."</div>\n";6068}6069}6070if($lastfile) {6071print"</td></tr>\n";6072if($matches>1000) {6073print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6074}6075}else{6076print"<div class=\"diff nodifferences\">No matches found</div>\n";6077}6078close$fd;60796080print"</table>\n";6081}6082 git_footer_html();6083}60846085sub git_search_help {6086 git_header_html();6087 git_print_page_nav('','',$hash,$hash,$hash);6088print<<EOT;6089<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6090regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6091the pattern entered is recognized as the POSIX extended6092<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6093insensitive).</p>6094<dl>6095<dt><b>commit</b></dt>6096<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6097EOT6098my$have_grep= gitweb_check_feature('grep');6099if($have_grep) {6100print<<EOT;6101<dt><b>grep</b></dt>6102<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6103 a different one) are searched for the given pattern. On large trees, this search can take6104a while and put some strain on the server, so please use it with some consideration. Note that6105due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6106case-sensitive.</dd>6107EOT6108}6109print<<EOT;6110<dt><b>author</b></dt>6111<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6112<dt><b>committer</b></dt>6113<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6114EOT6115my$have_pickaxe= gitweb_check_feature('pickaxe');6116if($have_pickaxe) {6117print<<EOT;6118<dt><b>pickaxe</b></dt>6119<dd>All commits that caused the string to appear or disappear from any file (changes that6120added, removed or "modified" the string) will be listed. This search can take a while and6121takes a lot of strain on the server, so please use it wisely. Note that since you may be6122interested even in changes just changing the case as well, this search is case sensitive.</dd>6123EOT6124}6125print"</dl>\n";6126 git_footer_html();6127}61286129sub git_shortlog {6130my$head= git_get_head_hash($project);6131if(!defined$hash) {6132$hash=$head;6133}6134if(!defined$page) {6135$page=0;6136}6137my$refs= git_get_references();61386139my$commit_hash=$hash;6140if(defined$hash_parent) {6141$commit_hash="$hash_parent..$hash";6142}6143my@commitlist= parse_commits($commit_hash,101, (100*$page));61446145my$paging_nav= format_paging_nav('shortlog',$hash,$head,$page,$#commitlist>=100);6146my$next_link='';6147if($#commitlist>=100) {6148$next_link=6149$cgi->a({-href => href(-replay=>1, page=>$page+1),6150-accesskey =>"n", -title =>"Alt-n"},"next");6151}6152my$patch_max= gitweb_check_feature('patches');6153if($patch_max) {6154if($patch_max<0||@commitlist<=$patch_max) {6155$paging_nav.=" ⋅ ".6156$cgi->a({-href => href(action=>"patches", -replay=>1)},6157"patches");6158}6159}61606161 git_header_html();6162 git_print_page_nav('shortlog','',$hash,$hash,$hash,$paging_nav);6163 git_print_header_div('summary',$project);61646165 git_shortlog_body(\@commitlist,0,99,$refs,$next_link);61666167 git_footer_html();6168}61696170## ......................................................................6171## feeds (RSS, Atom; OPML)61726173sub git_feed {6174my$format=shift||'atom';6175my$have_blame= gitweb_check_feature('blame');61766177# Atom: http://www.atomenabled.org/developers/syndication/6178# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6179if($formatne'rss'&&$formatne'atom') {6180 die_error(400,"Unknown web feed format");6181}61826183# log/feed of current (HEAD) branch, log of given branch, history of file/directory6184my$head=$hash||'HEAD';6185my@commitlist= parse_commits($head,150,0,$file_name);61866187my%latest_commit;6188my%latest_date;6189my$content_type="application/$format+xml";6190if(defined$cgi->http('HTTP_ACCEPT') &&6191$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6192# browser (feed reader) prefers text/xml6193$content_type='text/xml';6194}6195if(defined($commitlist[0])) {6196%latest_commit= %{$commitlist[0]};6197my$latest_epoch=$latest_commit{'committer_epoch'};6198%latest_date= parse_date($latest_epoch);6199my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6200if(defined$if_modified) {6201my$since;6202if(eval{require HTTP::Date;1; }) {6203$since= HTTP::Date::str2time($if_modified);6204}elsif(eval{require Time::ParseDate;1; }) {6205$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6206}6207if(defined$since&&$latest_epoch<=$since) {6208print$cgi->header(6209-type =>$content_type,6210-charset =>'utf-8',6211-last_modified =>$latest_date{'rfc2822'},6212-status =>'304 Not Modified');6213return;6214}6215}6216print$cgi->header(6217-type =>$content_type,6218-charset =>'utf-8',6219-last_modified =>$latest_date{'rfc2822'});6220}else{6221print$cgi->header(6222-type =>$content_type,6223-charset =>'utf-8');6224}62256226# Optimization: skip generating the body if client asks only6227# for Last-Modified date.6228return if($cgi->request_method()eq'HEAD');62296230# header variables6231my$title="$site_name-$project/$action";6232my$feed_type='log';6233if(defined$hash) {6234$title.=" - '$hash'";6235$feed_type='branch log';6236if(defined$file_name) {6237$title.=" ::$file_name";6238$feed_type='history';6239}6240}elsif(defined$file_name) {6241$title.=" -$file_name";6242$feed_type='history';6243}6244$title.="$feed_type";6245my$descr= git_get_project_description($project);6246if(defined$descr) {6247$descr= esc_html($descr);6248}else{6249$descr="$project".6250($formateq'rss'?'RSS':'Atom') .6251" feed";6252}6253my$owner= git_get_project_owner($project);6254$owner= esc_html($owner);62556256#header6257my$alt_url;6258if(defined$file_name) {6259$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6260}elsif(defined$hash) {6261$alt_url= href(-full=>1, action=>"log", hash=>$hash);6262}else{6263$alt_url= href(-full=>1, action=>"summary");6264}6265print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6266if($formateq'rss') {6267print<<XML;6268<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6269<channel>6270XML6271print"<title>$title</title>\n".6272"<link>$alt_url</link>\n".6273"<description>$descr</description>\n".6274"<language>en</language>\n".6275# project owner is responsible for 'editorial' content6276"<managingEditor>$owner</managingEditor>\n";6277if(defined$logo||defined$favicon) {6278# prefer the logo to the favicon, since RSS6279# doesn't allow both6280my$img= esc_url($logo||$favicon);6281print"<image>\n".6282"<url>$img</url>\n".6283"<title>$title</title>\n".6284"<link>$alt_url</link>\n".6285"</image>\n";6286}6287if(%latest_date) {6288print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6289print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6290}6291print"<generator>gitweb v.$version/$git_version</generator>\n";6292}elsif($formateq'atom') {6293print<<XML;6294<feed xmlns="http://www.w3.org/2005/Atom">6295XML6296print"<title>$title</title>\n".6297"<subtitle>$descr</subtitle>\n".6298'<link rel="alternate" type="text/html" href="'.6299$alt_url.'" />'."\n".6300'<link rel="self" type="'.$content_type.'" href="'.6301$cgi->self_url() .'" />'."\n".6302"<id>". href(-full=>1) ."</id>\n".6303# use project owner for feed author6304"<author><name>$owner</name></author>\n";6305if(defined$favicon) {6306print"<icon>". esc_url($favicon) ."</icon>\n";6307}6308if(defined$logo_url) {6309# not twice as wide as tall: 72 x 27 pixels6310print"<logo>". esc_url($logo) ."</logo>\n";6311}6312if(!%latest_date) {6313# dummy date to keep the feed valid until commits trickle in:6314print"<updated>1970-01-01T00:00:00Z</updated>\n";6315}else{6316print"<updated>$latest_date{'iso-8601'}</updated>\n";6317}6318print"<generator version='$version/$git_version'>gitweb</generator>\n";6319}63206321# contents6322for(my$i=0;$i<=$#commitlist;$i++) {6323my%co= %{$commitlist[$i]};6324my$commit=$co{'id'};6325# we read 150, we always show 30 and the ones more recent than 48 hours6326if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6327last;6328}6329my%cd= parse_date($co{'author_epoch'});63306331# get list of changed files6332open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6333$co{'parent'} ||"--root",6334$co{'id'},"--", (defined$file_name?$file_name: ())6335ornext;6336my@difftree=map{chomp;$_} <$fd>;6337close$fd6338ornext;63396340# print element (entry, item)6341my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6342if($formateq'rss') {6343print"<item>\n".6344"<title>". esc_html($co{'title'}) ."</title>\n".6345"<author>". esc_html($co{'author'}) ."</author>\n".6346"<pubDate>$cd{'rfc2822'}</pubDate>\n".6347"<guid isPermaLink=\"true\">$co_url</guid>\n".6348"<link>$co_url</link>\n".6349"<description>". esc_html($co{'title'}) ."</description>\n".6350"<content:encoded>".6351"<![CDATA[\n";6352}elsif($formateq'atom') {6353print"<entry>\n".6354"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6355"<updated>$cd{'iso-8601'}</updated>\n".6356"<author>\n".6357" <name>". esc_html($co{'author_name'}) ."</name>\n";6358if($co{'author_email'}) {6359print" <email>". esc_html($co{'author_email'}) ."</email>\n";6360}6361print"</author>\n".6362# use committer for contributor6363"<contributor>\n".6364" <name>". esc_html($co{'committer_name'}) ."</name>\n";6365if($co{'committer_email'}) {6366print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6367}6368print"</contributor>\n".6369"<published>$cd{'iso-8601'}</published>\n".6370"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6371"<id>$co_url</id>\n".6372"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6373"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6374}6375my$comment=$co{'comment'};6376print"<pre>\n";6377foreachmy$line(@$comment) {6378$line= esc_html($line);6379print"$line\n";6380}6381print"</pre><ul>\n";6382foreachmy$difftree_line(@difftree) {6383my%difftree= parse_difftree_raw_line($difftree_line);6384next if!$difftree{'from_id'};63856386my$file=$difftree{'file'} ||$difftree{'to_file'};63876388print"<li>".6389"[".6390$cgi->a({-href => href(-full=>1, action=>"blobdiff",6391 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6392 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},6393 file_name=>$file, file_parent=>$difftree{'from_file'}),6394-title =>"diff"},'D');6395if($have_blame) {6396print$cgi->a({-href => href(-full=>1, action=>"blame",6397 file_name=>$file, hash_base=>$commit),6398-title =>"blame"},'B');6399}6400# if this is not a feed of a file history6401if(!defined$file_name||$file_namene$file) {6402print$cgi->a({-href => href(-full=>1, action=>"history",6403 file_name=>$file, hash=>$commit),6404-title =>"history"},'H');6405}6406$file= esc_path($file);6407print"] ".6408"$file</li>\n";6409}6410if($formateq'rss') {6411print"</ul>]]>\n".6412"</content:encoded>\n".6413"</item>\n";6414}elsif($formateq'atom') {6415print"</ul>\n</div>\n".6416"</content>\n".6417"</entry>\n";6418}6419}64206421# end of feed6422if($formateq'rss') {6423print"</channel>\n</rss>\n";6424}elsif($formateq'atom') {6425print"</feed>\n";6426}6427}64286429sub git_rss {6430 git_feed('rss');6431}64326433sub git_atom {6434 git_feed('atom');6435}64366437sub git_opml {6438my@list= git_get_projects_list();64396440print$cgi->header(6441-type =>'text/xml',6442-charset =>'utf-8',6443-content_disposition =>'inline; filename="opml.xml"');64446445print<<XML;6446<?xml version="1.0" encoding="utf-8"?>6447<opml version="1.0">6448<head>6449 <title>$site_nameOPML Export</title>6450</head>6451<body>6452<outline text="git RSS feeds">6453XML64546455foreachmy$pr(@list) {6456my%proj=%$pr;6457my$head= git_get_head_hash($proj{'path'});6458if(!defined$head) {6459next;6460}6461$git_dir="$projectroot/$proj{'path'}";6462my%co= parse_commit($head);6463if(!%co) {6464next;6465}64666467my$path= esc_html(chop_str($proj{'path'},25,5));6468my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);6469my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);6470print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";6471}6472print<<XML;6473</outline>6474</body>6475</opml>6476XML6477}