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# 'disabled' => boolean (optional)} 165# 166'tgz'=> { 167'display'=>'tar.gz', 168'type'=>'application/x-gzip', 169'suffix'=>'.tar.gz', 170'format'=>'tar', 171'compressor'=> ['gzip']}, 172 173'tbz2'=> { 174'display'=>'tar.bz2', 175'type'=>'application/x-bzip2', 176'suffix'=>'.tar.bz2', 177'format'=>'tar', 178'compressor'=> ['bzip2']}, 179 180'txz'=> { 181'display'=>'tar.xz', 182'type'=>'application/x-xz', 183'suffix'=>'.tar.xz', 184'format'=>'tar', 185'compressor'=> ['xz'], 186'disabled'=>1}, 187 188'zip'=> { 189'display'=>'zip', 190'type'=>'application/x-zip', 191'suffix'=>'.zip', 192'format'=>'zip'}, 193); 194 195# Aliases so we understand old gitweb.snapshot values in repository 196# configuration. 197our%known_snapshot_format_aliases= ( 198'gzip'=>'tgz', 199'bzip2'=>'tbz2', 200'xz'=>'txz', 201 202# backward compatibility: legacy gitweb config support 203'x-gzip'=>undef,'gz'=>undef, 204'x-bzip2'=>undef,'bz2'=>undef, 205'x-zip'=>undef,''=>undef, 206); 207 208# Pixel sizes for icons and avatars. If the default font sizes or lineheights 209# are changed, it may be appropriate to change these values too via 210# $GITWEB_CONFIG. 211our%avatar_size= ( 212'default'=>16, 213'double'=>32 214); 215 216# You define site-wide feature defaults here; override them with 217# $GITWEB_CONFIG as necessary. 218our%feature= ( 219# feature => { 220# 'sub' => feature-sub (subroutine), 221# 'override' => allow-override (boolean), 222# 'default' => [ default options...] (array reference)} 223# 224# if feature is overridable (it means that allow-override has true value), 225# then feature-sub will be called with default options as parameters; 226# return value of feature-sub indicates if to enable specified feature 227# 228# if there is no 'sub' key (no feature-sub), then feature cannot be 229# overriden 230# 231# use gitweb_get_feature(<feature>) to retrieve the <feature> value 232# (an array) or gitweb_check_feature(<feature>) to check if <feature> 233# is enabled 234 235# Enable the 'blame' blob view, showing the last commit that modified 236# each line in the file. This can be very CPU-intensive. 237 238# To enable system wide have in $GITWEB_CONFIG 239# $feature{'blame'}{'default'} = [1]; 240# To have project specific config enable override in $GITWEB_CONFIG 241# $feature{'blame'}{'override'} = 1; 242# and in project config gitweb.blame = 0|1; 243'blame'=> { 244'sub'=>sub{ feature_bool('blame',@_) }, 245'override'=>0, 246'default'=> [0]}, 247 248# Enable the 'snapshot' link, providing a compressed archive of any 249# tree. This can potentially generate high traffic if you have large 250# project. 251 252# Value is a list of formats defined in %known_snapshot_formats that 253# you wish to offer. 254# To disable system wide have in $GITWEB_CONFIG 255# $feature{'snapshot'}{'default'} = []; 256# To have project specific config enable override in $GITWEB_CONFIG 257# $feature{'snapshot'}{'override'} = 1; 258# and in project config, a comma-separated list of formats or "none" 259# to disable. Example: gitweb.snapshot = tbz2,zip; 260'snapshot'=> { 261'sub'=> \&feature_snapshot, 262'override'=>0, 263'default'=> ['tgz']}, 264 265# Enable text search, which will list the commits which match author, 266# committer or commit text to a given string. Enabled by default. 267# Project specific override is not supported. 268'search'=> { 269'override'=>0, 270'default'=> [1]}, 271 272# Enable grep search, which will list the files in currently selected 273# tree containing the given string. Enabled by default. This can be 274# potentially CPU-intensive, of course. 275 276# To enable system wide have in $GITWEB_CONFIG 277# $feature{'grep'}{'default'} = [1]; 278# To have project specific config enable override in $GITWEB_CONFIG 279# $feature{'grep'}{'override'} = 1; 280# and in project config gitweb.grep = 0|1; 281'grep'=> { 282'sub'=>sub{ feature_bool('grep',@_) }, 283'override'=>0, 284'default'=> [1]}, 285 286# Enable the pickaxe search, which will list the commits that modified 287# a given string in a file. This can be practical and quite faster 288# alternative to 'blame', but still potentially CPU-intensive. 289 290# To enable system wide have in $GITWEB_CONFIG 291# $feature{'pickaxe'}{'default'} = [1]; 292# To have project specific config enable override in $GITWEB_CONFIG 293# $feature{'pickaxe'}{'override'} = 1; 294# and in project config gitweb.pickaxe = 0|1; 295'pickaxe'=> { 296'sub'=>sub{ feature_bool('pickaxe',@_) }, 297'override'=>0, 298'default'=> [1]}, 299 300# Make gitweb use an alternative format of the URLs which can be 301# more readable and natural-looking: project name is embedded 302# directly in the path and the query string contains other 303# auxiliary information. All gitweb installations recognize 304# URL in either format; this configures in which formats gitweb 305# generates links. 306 307# To enable system wide have in $GITWEB_CONFIG 308# $feature{'pathinfo'}{'default'} = [1]; 309# Project specific override is not supported. 310 311# Note that you will need to change the default location of CSS, 312# favicon, logo and possibly other files to an absolute URL. Also, 313# if gitweb.cgi serves as your indexfile, you will need to force 314# $my_uri to contain the script name in your $GITWEB_CONFIG. 315'pathinfo'=> { 316'override'=>0, 317'default'=> [0]}, 318 319# Make gitweb consider projects in project root subdirectories 320# to be forks of existing projects. Given project $projname.git, 321# projects matching $projname/*.git will not be shown in the main 322# projects list, instead a '+' mark will be added to $projname 323# there and a 'forks' view will be enabled for the project, listing 324# all the forks. If project list is taken from a file, forks have 325# to be listed after the main project. 326 327# To enable system wide have in $GITWEB_CONFIG 328# $feature{'forks'}{'default'} = [1]; 329# Project specific override is not supported. 330'forks'=> { 331'override'=>0, 332'default'=> [0]}, 333 334# Insert custom links to the action bar of all project pages. 335# This enables you mainly to link to third-party scripts integrating 336# into gitweb; e.g. git-browser for graphical history representation 337# or custom web-based repository administration interface. 338 339# The 'default' value consists of a list of triplets in the form 340# (label, link, position) where position is the label after which 341# to insert the link and link is a format string where %n expands 342# to the project name, %f to the project path within the filesystem, 343# %h to the current hash (h gitweb parameter) and %b to the current 344# hash base (hb gitweb parameter); %% expands to %. 345 346# To enable system wide have in $GITWEB_CONFIG e.g. 347# $feature{'actions'}{'default'} = [('graphiclog', 348# '/git-browser/by-commit.html?r=%n', 'summary')]; 349# Project specific override is not supported. 350'actions'=> { 351'override'=>0, 352'default'=> []}, 353 354# Allow gitweb scan project content tags described in ctags/ 355# of project repository, and display the popular Web 2.0-ish 356# "tag cloud" near the project list. Note that this is something 357# COMPLETELY different from the normal Git tags. 358 359# gitweb by itself can show existing tags, but it does not handle 360# tagging itself; you need an external application for that. 361# For an example script, check Girocco's cgi/tagproj.cgi. 362# You may want to install the HTML::TagCloud Perl module to get 363# a pretty tag cloud instead of just a list of tags. 364 365# To enable system wide have in $GITWEB_CONFIG 366# $feature{'ctags'}{'default'} = ['path_to_tag_script']; 367# Project specific override is not supported. 368'ctags'=> { 369'override'=>0, 370'default'=> [0]}, 371 372# The maximum number of patches in a patchset generated in patch 373# view. Set this to 0 or undef to disable patch view, or to a 374# negative number to remove any limit. 375 376# To disable system wide have in $GITWEB_CONFIG 377# $feature{'patches'}{'default'} = [0]; 378# To have project specific config enable override in $GITWEB_CONFIG 379# $feature{'patches'}{'override'} = 1; 380# and in project config gitweb.patches = 0|n; 381# where n is the maximum number of patches allowed in a patchset. 382'patches'=> { 383'sub'=> \&feature_patches, 384'override'=>0, 385'default'=> [16]}, 386 387# Avatar support. When this feature is enabled, views such as 388# shortlog or commit will display an avatar associated with 389# the email of the committer(s) and/or author(s). 390 391# Currently available providers are gravatar and picon. 392# If an unknown provider is specified, the feature is disabled. 393 394# Gravatar depends on Digest::MD5. 395# Picon currently relies on the indiana.edu database. 396 397# To enable system wide have in $GITWEB_CONFIG 398# $feature{'avatar'}{'default'} = ['<provider>']; 399# where <provider> is either gravatar or picon. 400# To have project specific config enable override in $GITWEB_CONFIG 401# $feature{'avatar'}{'override'} = 1; 402# and in project config gitweb.avatar = <provider>; 403'avatar'=> { 404'sub'=> \&feature_avatar, 405'override'=>0, 406'default'=> ['']}, 407); 408 409sub gitweb_get_feature { 410my($name) =@_; 411return unlessexists$feature{$name}; 412my($sub,$override,@defaults) = ( 413$feature{$name}{'sub'}, 414$feature{$name}{'override'}, 415@{$feature{$name}{'default'}}); 416if(!$override) {return@defaults; } 417if(!defined$sub) { 418warn"feature$nameis not overridable"; 419return@defaults; 420} 421return$sub->(@defaults); 422} 423 424# A wrapper to check if a given feature is enabled. 425# With this, you can say 426# 427# my $bool_feat = gitweb_check_feature('bool_feat'); 428# gitweb_check_feature('bool_feat') or somecode; 429# 430# instead of 431# 432# my ($bool_feat) = gitweb_get_feature('bool_feat'); 433# (gitweb_get_feature('bool_feat'))[0] or somecode; 434# 435sub gitweb_check_feature { 436return(gitweb_get_feature(@_))[0]; 437} 438 439 440sub feature_bool { 441my$key=shift; 442my($val) = git_get_project_config($key,'--bool'); 443 444if(!defined$val) { 445return($_[0]); 446}elsif($valeq'true') { 447return(1); 448}elsif($valeq'false') { 449return(0); 450} 451} 452 453sub feature_snapshot { 454my(@fmts) =@_; 455 456my($val) = git_get_project_config('snapshot'); 457 458if($val) { 459@fmts= ($valeq'none'? () :split/\s*[,\s]\s*/,$val); 460} 461 462return@fmts; 463} 464 465sub feature_patches { 466my@val= (git_get_project_config('patches','--int')); 467 468if(@val) { 469return@val; 470} 471 472return($_[0]); 473} 474 475sub feature_avatar { 476my@val= (git_get_project_config('avatar')); 477 478return@val?@val:@_; 479} 480 481# checking HEAD file with -e is fragile if the repository was 482# initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed 483# and then pruned. 484sub check_head_link { 485my($dir) =@_; 486my$headfile="$dir/HEAD"; 487return((-e $headfile) || 488(-l $headfile&&readlink($headfile) =~/^refs\/heads\//)); 489} 490 491sub check_export_ok { 492my($dir) =@_; 493return(check_head_link($dir) && 494(!$export_ok|| -e "$dir/$export_ok") && 495(!$export_auth_hook||$export_auth_hook->($dir))); 496} 497 498# process alternate names for backward compatibility 499# filter out unsupported (unknown) snapshot formats 500sub filter_snapshot_fmts { 501my@fmts=@_; 502 503@fmts=map{ 504exists$known_snapshot_format_aliases{$_} ? 505$known_snapshot_format_aliases{$_} :$_}@fmts; 506@fmts=grep{ 507exists$known_snapshot_formats{$_} && 508!$known_snapshot_formats{$_}{'disabled'}}@fmts; 509} 510 511our$GITWEB_CONFIG=$ENV{'GITWEB_CONFIG'} ||"++GITWEB_CONFIG++"; 512if(-e $GITWEB_CONFIG) { 513do$GITWEB_CONFIG; 514}else{ 515our$GITWEB_CONFIG_SYSTEM=$ENV{'GITWEB_CONFIG_SYSTEM'} ||"++GITWEB_CONFIG_SYSTEM++"; 516do$GITWEB_CONFIG_SYSTEMif-e $GITWEB_CONFIG_SYSTEM; 517} 518 519# version of the core git binary 520our$git_version=qx("$GIT" --version)=~m/git version (.*)$/?$1:"unknown"; 521 522$projects_list||=$projectroot; 523 524# ====================================================================== 525# input validation and dispatch 526 527# input parameters can be collected from a variety of sources (presently, CGI 528# and PATH_INFO), so we define an %input_params hash that collects them all 529# together during validation: this allows subsequent uses (e.g. href()) to be 530# agnostic of the parameter origin 531 532our%input_params= (); 533 534# input parameters are stored with the long parameter name as key. This will 535# also be used in the href subroutine to convert parameters to their CGI 536# equivalent, and since the href() usage is the most frequent one, we store 537# the name -> CGI key mapping here, instead of the reverse. 538# 539# XXX: Warning: If you touch this, check the search form for updating, 540# too. 541 542our@cgi_param_mapping= ( 543 project =>"p", 544 action =>"a", 545 file_name =>"f", 546 file_parent =>"fp", 547 hash =>"h", 548 hash_parent =>"hp", 549 hash_base =>"hb", 550 hash_parent_base =>"hpb", 551 page =>"pg", 552 order =>"o", 553 searchtext =>"s", 554 searchtype =>"st", 555 snapshot_format =>"sf", 556 extra_options =>"opt", 557 search_use_regexp =>"sr", 558); 559our%cgi_param_mapping=@cgi_param_mapping; 560 561# we will also need to know the possible actions, for validation 562our%actions= ( 563"blame"=> \&git_blame, 564"blobdiff"=> \&git_blobdiff, 565"blobdiff_plain"=> \&git_blobdiff_plain, 566"blob"=> \&git_blob, 567"blob_plain"=> \&git_blob_plain, 568"commitdiff"=> \&git_commitdiff, 569"commitdiff_plain"=> \&git_commitdiff_plain, 570"commit"=> \&git_commit, 571"forks"=> \&git_forks, 572"heads"=> \&git_heads, 573"history"=> \&git_history, 574"log"=> \&git_log, 575"patch"=> \&git_patch, 576"patches"=> \&git_patches, 577"rss"=> \&git_rss, 578"atom"=> \&git_atom, 579"search"=> \&git_search, 580"search_help"=> \&git_search_help, 581"shortlog"=> \&git_shortlog, 582"summary"=> \&git_summary, 583"tag"=> \&git_tag, 584"tags"=> \&git_tags, 585"tree"=> \&git_tree, 586"snapshot"=> \&git_snapshot, 587"object"=> \&git_object, 588# those below don't need $project 589"opml"=> \&git_opml, 590"project_list"=> \&git_project_list, 591"project_index"=> \&git_project_index, 592); 593 594# finally, we have the hash of allowed extra_options for the commands that 595# allow them 596our%allowed_options= ( 597"--no-merges"=> [qw(rss atom log shortlog history)], 598); 599 600# fill %input_params with the CGI parameters. All values except for 'opt' 601# should be single values, but opt can be an array. We should probably 602# build an array of parameters that can be multi-valued, but since for the time 603# being it's only this one, we just single it out 604while(my($name,$symbol) =each%cgi_param_mapping) { 605if($symboleq'opt') { 606$input_params{$name} = [$cgi->param($symbol) ]; 607}else{ 608$input_params{$name} =$cgi->param($symbol); 609} 610} 611 612# now read PATH_INFO and update the parameter list for missing parameters 613sub evaluate_path_info { 614return ifdefined$input_params{'project'}; 615return if!$path_info; 616$path_info=~ s,^/+,,; 617return if!$path_info; 618 619# find which part of PATH_INFO is project 620my$project=$path_info; 621$project=~ s,/+$,,; 622while($project&& !check_head_link("$projectroot/$project")) { 623$project=~ s,/*[^/]*$,,; 624} 625return unless$project; 626$input_params{'project'} =$project; 627 628# do not change any parameters if an action is given using the query string 629return if$input_params{'action'}; 630$path_info=~ s,^\Q$project\E/*,,; 631 632# next, check if we have an action 633my$action=$path_info; 634$action=~ s,/.*$,,; 635if(exists$actions{$action}) { 636$path_info=~ s,^$action/*,,; 637$input_params{'action'} =$action; 638} 639 640# list of actions that want hash_base instead of hash, but can have no 641# pathname (f) parameter 642my@wants_base= ( 643'tree', 644'history', 645); 646 647# we want to catch 648# [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name] 649my($parentrefname,$parentpathname,$refname,$pathname) = 650($path_info=~/^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/); 651 652# first, analyze the 'current' part 653if(defined$pathname) { 654# we got "branch:filename" or "branch:dir/" 655# we could use git_get_type(branch:pathname), but: 656# - it needs $git_dir 657# - it does a git() call 658# - the convention of terminating directories with a slash 659# makes it superfluous 660# - embedding the action in the PATH_INFO would make it even 661# more superfluous 662$pathname=~ s,^/+,,; 663if(!$pathname||substr($pathname, -1)eq"/") { 664$input_params{'action'} ||="tree"; 665$pathname=~ s,/$,,; 666}else{ 667# the default action depends on whether we had parent info 668# or not 669if($parentrefname) { 670$input_params{'action'} ||="blobdiff_plain"; 671}else{ 672$input_params{'action'} ||="blob_plain"; 673} 674} 675$input_params{'hash_base'} ||=$refname; 676$input_params{'file_name'} ||=$pathname; 677}elsif(defined$refname) { 678# we got "branch". In this case we have to choose if we have to 679# set hash or hash_base. 680# 681# Most of the actions without a pathname only want hash to be 682# set, except for the ones specified in @wants_base that want 683# hash_base instead. It should also be noted that hand-crafted 684# links having 'history' as an action and no pathname or hash 685# set will fail, but that happens regardless of PATH_INFO. 686$input_params{'action'} ||="shortlog"; 687if(grep{$_eq$input_params{'action'} }@wants_base) { 688$input_params{'hash_base'} ||=$refname; 689}else{ 690$input_params{'hash'} ||=$refname; 691} 692} 693 694# next, handle the 'parent' part, if present 695if(defined$parentrefname) { 696# a missing pathspec defaults to the 'current' filename, allowing e.g. 697# someproject/blobdiff/oldrev..newrev:/filename 698if($parentpathname) { 699$parentpathname=~ s,^/+,,; 700$parentpathname=~ s,/$,,; 701$input_params{'file_parent'} ||=$parentpathname; 702}else{ 703$input_params{'file_parent'} ||=$input_params{'file_name'}; 704} 705# we assume that hash_parent_base is wanted if a path was specified, 706# or if the action wants hash_base instead of hash 707if(defined$input_params{'file_parent'} || 708grep{$_eq$input_params{'action'} }@wants_base) { 709$input_params{'hash_parent_base'} ||=$parentrefname; 710}else{ 711$input_params{'hash_parent'} ||=$parentrefname; 712} 713} 714 715# for the snapshot action, we allow URLs in the form 716# $project/snapshot/$hash.ext 717# where .ext determines the snapshot and gets removed from the 718# passed $refname to provide the $hash. 719# 720# To be able to tell that $refname includes the format extension, we 721# require the following two conditions to be satisfied: 722# - the hash input parameter MUST have been set from the $refname part 723# of the URL (i.e. they must be equal) 724# - the snapshot format MUST NOT have been defined already (e.g. from 725# CGI parameter sf) 726# It's also useless to try any matching unless $refname has a dot, 727# so we check for that too 728if(defined$input_params{'action'} && 729$input_params{'action'}eq'snapshot'&& 730defined$refname&&index($refname,'.') != -1&& 731$refnameeq$input_params{'hash'} && 732!defined$input_params{'snapshot_format'}) { 733# We loop over the known snapshot formats, checking for 734# extensions. Allowed extensions are both the defined suffix 735# (which includes the initial dot already) and the snapshot 736# format key itself, with a prepended dot 737while(my($fmt,$opt) =each%known_snapshot_formats) { 738my$hash=$refname; 739unless($hash=~s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) { 740next; 741} 742my$sfx=$1; 743# a valid suffix was found, so set the snapshot format 744# and reset the hash parameter 745$input_params{'snapshot_format'} =$fmt; 746$input_params{'hash'} =$hash; 747# we also set the format suffix to the one requested 748# in the URL: this way a request for e.g. .tgz returns 749# a .tgz instead of a .tar.gz 750$known_snapshot_formats{$fmt}{'suffix'} =$sfx; 751last; 752} 753} 754} 755evaluate_path_info(); 756 757our$action=$input_params{'action'}; 758if(defined$action) { 759if(!validate_action($action)) { 760 die_error(400,"Invalid action parameter"); 761} 762} 763 764# parameters which are pathnames 765our$project=$input_params{'project'}; 766if(defined$project) { 767if(!validate_project($project)) { 768undef$project; 769 die_error(404,"No such project"); 770} 771} 772 773our$file_name=$input_params{'file_name'}; 774if(defined$file_name) { 775if(!validate_pathname($file_name)) { 776 die_error(400,"Invalid file parameter"); 777} 778} 779 780our$file_parent=$input_params{'file_parent'}; 781if(defined$file_parent) { 782if(!validate_pathname($file_parent)) { 783 die_error(400,"Invalid file parent parameter"); 784} 785} 786 787# parameters which are refnames 788our$hash=$input_params{'hash'}; 789if(defined$hash) { 790if(!validate_refname($hash)) { 791 die_error(400,"Invalid hash parameter"); 792} 793} 794 795our$hash_parent=$input_params{'hash_parent'}; 796if(defined$hash_parent) { 797if(!validate_refname($hash_parent)) { 798 die_error(400,"Invalid hash parent parameter"); 799} 800} 801 802our$hash_base=$input_params{'hash_base'}; 803if(defined$hash_base) { 804if(!validate_refname($hash_base)) { 805 die_error(400,"Invalid hash base parameter"); 806} 807} 808 809our@extra_options= @{$input_params{'extra_options'}}; 810# @extra_options is always defined, since it can only be (currently) set from 811# CGI, and $cgi->param() returns the empty array in array context if the param 812# is not set 813foreachmy$opt(@extra_options) { 814if(not exists$allowed_options{$opt}) { 815 die_error(400,"Invalid option parameter"); 816} 817if(not grep(/^$action$/, @{$allowed_options{$opt}})) { 818 die_error(400,"Invalid option parameter for this action"); 819} 820} 821 822our$hash_parent_base=$input_params{'hash_parent_base'}; 823if(defined$hash_parent_base) { 824if(!validate_refname($hash_parent_base)) { 825 die_error(400,"Invalid hash parent base parameter"); 826} 827} 828 829# other parameters 830our$page=$input_params{'page'}; 831if(defined$page) { 832if($page=~m/[^0-9]/) { 833 die_error(400,"Invalid page parameter"); 834} 835} 836 837our$searchtype=$input_params{'searchtype'}; 838if(defined$searchtype) { 839if($searchtype=~m/[^a-z]/) { 840 die_error(400,"Invalid searchtype parameter"); 841} 842} 843 844our$search_use_regexp=$input_params{'search_use_regexp'}; 845 846our$searchtext=$input_params{'searchtext'}; 847our$search_regexp; 848if(defined$searchtext) { 849if(length($searchtext) <2) { 850 die_error(403,"At least two characters are required for search parameter"); 851} 852$search_regexp=$search_use_regexp?$searchtext:quotemeta$searchtext; 853} 854 855# path to the current git repository 856our$git_dir; 857$git_dir="$projectroot/$project"if$project; 858 859# list of supported snapshot formats 860our@snapshot_fmts= gitweb_get_feature('snapshot'); 861@snapshot_fmts= filter_snapshot_fmts(@snapshot_fmts); 862 863# check that the avatar feature is set to a known provider name, 864# and for each provider check if the dependencies are satisfied. 865# if the provider name is invalid or the dependencies are not met, 866# reset $git_avatar to the empty string. 867our($git_avatar) = gitweb_get_feature('avatar'); 868if($git_avatareq'gravatar') { 869$git_avatar=''unless(eval{require Digest::MD5;1; }); 870}elsif($git_avatareq'picon') { 871# no dependencies 872}else{ 873$git_avatar=''; 874} 875 876# dispatch 877if(!defined$action) { 878if(defined$hash) { 879$action= git_get_type($hash); 880}elsif(defined$hash_base&&defined$file_name) { 881$action= git_get_type("$hash_base:$file_name"); 882}elsif(defined$project) { 883$action='summary'; 884}else{ 885$action='project_list'; 886} 887} 888if(!defined($actions{$action})) { 889 die_error(400,"Unknown action"); 890} 891if($action!~m/^(?:opml|project_list|project_index)$/&& 892!$project) { 893 die_error(400,"Project needed"); 894} 895$actions{$action}->(); 896exit; 897 898## ====================================================================== 899## action links 900 901sub href { 902my%params=@_; 903# default is to use -absolute url() i.e. $my_uri 904my$href=$params{-full} ?$my_url:$my_uri; 905 906$params{'project'} =$projectunlessexists$params{'project'}; 907 908if($params{-replay}) { 909while(my($name,$symbol) =each%cgi_param_mapping) { 910if(!exists$params{$name}) { 911$params{$name} =$input_params{$name}; 912} 913} 914} 915 916my$use_pathinfo= gitweb_check_feature('pathinfo'); 917if($use_pathinfoand defined$params{'project'}) { 918# try to put as many parameters as possible in PATH_INFO: 919# - project name 920# - action 921# - hash_parent or hash_parent_base:/file_parent 922# - hash or hash_base:/filename 923# - the snapshot_format as an appropriate suffix 924 925# When the script is the root DirectoryIndex for the domain, 926# $href here would be something like http://gitweb.example.com/ 927# Thus, we strip any trailing / from $href, to spare us double 928# slashes in the final URL 929$href=~ s,/$,,; 930 931# Then add the project name, if present 932$href.="/".esc_url($params{'project'}); 933delete$params{'project'}; 934 935# since we destructively absorb parameters, we keep this 936# boolean that remembers if we're handling a snapshot 937my$is_snapshot=$params{'action'}eq'snapshot'; 938 939# Summary just uses the project path URL, any other action is 940# added to the URL 941if(defined$params{'action'}) { 942$href.="/".esc_url($params{'action'})unless$params{'action'}eq'summary'; 943delete$params{'action'}; 944} 945 946# Next, we put hash_parent_base:/file_parent..hash_base:/file_name, 947# stripping nonexistent or useless pieces 948$href.="/"if($params{'hash_base'} ||$params{'hash_parent_base'} 949||$params{'hash_parent'} ||$params{'hash'}); 950if(defined$params{'hash_base'}) { 951if(defined$params{'hash_parent_base'}) { 952$href.= esc_url($params{'hash_parent_base'}); 953# skip the file_parent if it's the same as the file_name 954if(defined$params{'file_parent'}) { 955if(defined$params{'file_name'} &&$params{'file_parent'}eq$params{'file_name'}) { 956delete$params{'file_parent'}; 957}elsif($params{'file_parent'} !~/\.\./) { 958$href.=":/".esc_url($params{'file_parent'}); 959delete$params{'file_parent'}; 960} 961} 962$href.=".."; 963delete$params{'hash_parent'}; 964delete$params{'hash_parent_base'}; 965}elsif(defined$params{'hash_parent'}) { 966$href.= esc_url($params{'hash_parent'}).".."; 967delete$params{'hash_parent'}; 968} 969 970$href.= esc_url($params{'hash_base'}); 971if(defined$params{'file_name'} &&$params{'file_name'} !~/\.\./) { 972$href.=":/".esc_url($params{'file_name'}); 973delete$params{'file_name'}; 974} 975delete$params{'hash'}; 976delete$params{'hash_base'}; 977}elsif(defined$params{'hash'}) { 978$href.= esc_url($params{'hash'}); 979delete$params{'hash'}; 980} 981 982# If the action was a snapshot, we can absorb the 983# snapshot_format parameter too 984if($is_snapshot) { 985my$fmt=$params{'snapshot_format'}; 986# snapshot_format should always be defined when href() 987# is called, but just in case some code forgets, we 988# fall back to the default 989$fmt||=$snapshot_fmts[0]; 990$href.=$known_snapshot_formats{$fmt}{'suffix'}; 991delete$params{'snapshot_format'}; 992} 993} 994 995# now encode the parameters explicitly 996my@result= (); 997for(my$i=0;$i<@cgi_param_mapping;$i+=2) { 998my($name,$symbol) = ($cgi_param_mapping[$i],$cgi_param_mapping[$i+1]); 999if(defined$params{$name}) {1000if(ref($params{$name})eq"ARRAY") {1001foreachmy$par(@{$params{$name}}) {1002push@result,$symbol."=". esc_param($par);1003}1004}else{1005push@result,$symbol."=". esc_param($params{$name});1006}1007}1008}1009$href.="?".join(';',@result)ifscalar@result;10101011return$href;1012}101310141015## ======================================================================1016## validation, quoting/unquoting and escaping10171018sub validate_action {1019my$input=shift||returnundef;1020returnundefunlessexists$actions{$input};1021return$input;1022}10231024sub validate_project {1025my$input=shift||returnundef;1026if(!validate_pathname($input) ||1027!(-d "$projectroot/$input") ||1028!check_export_ok("$projectroot/$input") ||1029($strict_export&& !project_in_list($input))) {1030returnundef;1031}else{1032return$input;1033}1034}10351036sub validate_pathname {1037my$input=shift||returnundef;10381039# no '.' or '..' as elements of path, i.e. no '.' nor '..'1040# at the beginning, at the end, and between slashes.1041# also this catches doubled slashes1042if($input=~m!(^|/)(|\.|\.\.)(/|$)!) {1043returnundef;1044}1045# no null characters1046if($input=~m!\0!) {1047returnundef;1048}1049return$input;1050}10511052sub validate_refname {1053my$input=shift||returnundef;10541055# textual hashes are O.K.1056if($input=~m/^[0-9a-fA-F]{40}$/) {1057return$input;1058}1059# it must be correct pathname1060$input= validate_pathname($input)1061orreturnundef;1062# restrictions on ref name according to git-check-ref-format1063if($input=~m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {1064returnundef;1065}1066return$input;1067}10681069# decode sequences of octets in utf8 into Perl's internal form,1070# which is utf-8 with utf8 flag set if needed. gitweb writes out1071# in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning1072sub to_utf8 {1073my$str=shift;1074if(utf8::valid($str)) {1075 utf8::decode($str);1076return$str;1077}else{1078return decode($fallback_encoding,$str, Encode::FB_DEFAULT);1079}1080}10811082# quote unsafe chars, but keep the slash, even when it's not1083# correct, but quoted slashes look too horrible in bookmarks1084sub esc_param {1085my$str=shift;1086$str=~s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;1087$str=~s/ /\+/g;1088return$str;1089}10901091# quote unsafe chars in whole URL, so some charactrs cannot be quoted1092sub esc_url {1093my$str=shift;1094$str=~s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X",ord($1))/eg;1095$str=~s/\+/%2B/g;1096$str=~s/ /\+/g;1097return$str;1098}10991100# replace invalid utf8 character with SUBSTITUTION sequence1101sub esc_html {1102my$str=shift;1103my%opts=@_;11041105$str= to_utf8($str);1106$str=$cgi->escapeHTML($str);1107if($opts{'-nbsp'}) {1108$str=~s/ / /g;1109}1110$str=~ s|([[:cntrl:]])|(($1ne"\t") ? quot_cec($1) :$1)|eg;1111return$str;1112}11131114# quote control characters and escape filename to HTML1115sub esc_path {1116my$str=shift;1117my%opts=@_;11181119$str= to_utf8($str);1120$str=$cgi->escapeHTML($str);1121if($opts{'-nbsp'}) {1122$str=~s/ / /g;1123}1124$str=~ s|([[:cntrl:]])|quot_cec($1)|eg;1125return$str;1126}11271128# Make control characters "printable", using character escape codes (CEC)1129sub quot_cec {1130my$cntrl=shift;1131my%opts=@_;1132my%es= (# character escape codes, aka escape sequences1133"\t"=>'\t',# tab (HT)1134"\n"=>'\n',# line feed (LF)1135"\r"=>'\r',# carrige return (CR)1136"\f"=>'\f',# form feed (FF)1137"\b"=>'\b',# backspace (BS)1138"\a"=>'\a',# alarm (bell) (BEL)1139"\e"=>'\e',# escape (ESC)1140"\013"=>'\v',# vertical tab (VT)1141"\000"=>'\0',# nul character (NUL)1142);1143my$chr= ( (exists$es{$cntrl})1144?$es{$cntrl}1145:sprintf('\%2x',ord($cntrl)) );1146if($opts{-nohtml}) {1147return$chr;1148}else{1149return"<span class=\"cntrl\">$chr</span>";1150}1151}11521153# Alternatively use unicode control pictures codepoints,1154# Unicode "printable representation" (PR)1155sub quot_upr {1156my$cntrl=shift;1157my%opts=@_;11581159my$chr=sprintf('&#%04d;',0x2400+ord($cntrl));1160if($opts{-nohtml}) {1161return$chr;1162}else{1163return"<span class=\"cntrl\">$chr</span>";1164}1165}11661167# git may return quoted and escaped filenames1168sub unquote {1169my$str=shift;11701171sub unq {1172my$seq=shift;1173my%es= (# character escape codes, aka escape sequences1174't'=>"\t",# tab (HT, TAB)1175'n'=>"\n",# newline (NL)1176'r'=>"\r",# return (CR)1177'f'=>"\f",# form feed (FF)1178'b'=>"\b",# backspace (BS)1179'a'=>"\a",# alarm (bell) (BEL)1180'e'=>"\e",# escape (ESC)1181'v'=>"\013",# vertical tab (VT)1182);11831184if($seq=~m/^[0-7]{1,3}$/) {1185# octal char sequence1186returnchr(oct($seq));1187}elsif(exists$es{$seq}) {1188# C escape sequence, aka character escape code1189return$es{$seq};1190}1191# quoted ordinary character1192return$seq;1193}11941195if($str=~m/^"(.*)"$/) {1196# needs unquoting1197$str=$1;1198$str=~s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;1199}1200return$str;1201}12021203# escape tabs (convert tabs to spaces)1204sub untabify {1205my$line=shift;12061207while((my$pos=index($line,"\t")) != -1) {1208if(my$count= (8- ($pos%8))) {1209my$spaces=' ' x $count;1210$line=~s/\t/$spaces/;1211}1212}12131214return$line;1215}12161217sub project_in_list {1218my$project=shift;1219my@list= git_get_projects_list();1220return@list&&scalar(grep{$_->{'path'}eq$project}@list);1221}12221223## ----------------------------------------------------------------------1224## HTML aware string manipulation12251226# Try to chop given string on a word boundary between position1227# $len and $len+$add_len. If there is no word boundary there,1228# chop at $len+$add_len. Do not chop if chopped part plus ellipsis1229# (marking chopped part) would be longer than given string.1230sub chop_str {1231my$str=shift;1232my$len=shift;1233my$add_len=shift||10;1234my$where=shift||'right';# 'left' | 'center' | 'right'12351236# Make sure perl knows it is utf8 encoded so we don't1237# cut in the middle of a utf8 multibyte char.1238$str= to_utf8($str);12391240# allow only $len chars, but don't cut a word if it would fit in $add_len1241# if it doesn't fit, cut it if it's still longer than the dots we would add1242# remove chopped character entities entirely12431244# when chopping in the middle, distribute $len into left and right part1245# return early if chopping wouldn't make string shorter1246if($whereeq'center') {1247return$strif($len+5>=length($str));# filler is length 51248$len=int($len/2);1249}else{1250return$strif($len+4>=length($str));# filler is length 41251}12521253# regexps: ending and beginning with word part up to $add_len1254my$endre=qr/.{$len}\w{0,$add_len}/;1255my$begre=qr/\w{0,$add_len}.{$len}/;12561257if($whereeq'left') {1258$str=~m/^(.*?)($begre)$/;1259my($lead,$body) = ($1,$2);1260if(length($lead) >4) {1261$body=~s/^[^;]*;//if($lead=~m/&[^;]*$/);1262$lead=" ...";1263}1264return"$lead$body";12651266}elsif($whereeq'center') {1267$str=~m/^($endre)(.*)$/;1268my($left,$str) = ($1,$2);1269$str=~m/^(.*?)($begre)$/;1270my($mid,$right) = ($1,$2);1271if(length($mid) >5) {1272$left=~s/&[^;]*$//;1273$right=~s/^[^;]*;//if($mid=~m/&[^;]*$/);1274$mid=" ... ";1275}1276return"$left$mid$right";12771278}else{1279$str=~m/^($endre)(.*)$/;1280my$body=$1;1281my$tail=$2;1282if(length($tail) >4) {1283$body=~s/&[^;]*$//;1284$tail="... ";1285}1286return"$body$tail";1287}1288}12891290# takes the same arguments as chop_str, but also wraps a <span> around the1291# result with a title attribute if it does get chopped. Additionally, the1292# string is HTML-escaped.1293sub chop_and_escape_str {1294my($str) =@_;12951296my$chopped= chop_str(@_);1297if($choppedeq$str) {1298return esc_html($chopped);1299}else{1300$str=~s/[[:cntrl:]]/?/g;1301return$cgi->span({-title=>$str}, esc_html($chopped));1302}1303}13041305## ----------------------------------------------------------------------1306## functions returning short strings13071308# CSS class for given age value (in seconds)1309sub age_class {1310my$age=shift;13111312if(!defined$age) {1313return"noage";1314}elsif($age<60*60*2) {1315return"age0";1316}elsif($age<60*60*24*2) {1317return"age1";1318}else{1319return"age2";1320}1321}13221323# convert age in seconds to "nn units ago" string1324sub age_string {1325my$age=shift;1326my$age_str;13271328if($age>60*60*24*365*2) {1329$age_str= (int$age/60/60/24/365);1330$age_str.=" years ago";1331}elsif($age>60*60*24*(365/12)*2) {1332$age_str=int$age/60/60/24/(365/12);1333$age_str.=" months ago";1334}elsif($age>60*60*24*7*2) {1335$age_str=int$age/60/60/24/7;1336$age_str.=" weeks ago";1337}elsif($age>60*60*24*2) {1338$age_str=int$age/60/60/24;1339$age_str.=" days ago";1340}elsif($age>60*60*2) {1341$age_str=int$age/60/60;1342$age_str.=" hours ago";1343}elsif($age>60*2) {1344$age_str=int$age/60;1345$age_str.=" min ago";1346}elsif($age>2) {1347$age_str=int$age;1348$age_str.=" sec ago";1349}else{1350$age_str.=" right now";1351}1352return$age_str;1353}13541355useconstant{1356 S_IFINVALID =>0030000,1357 S_IFGITLINK =>0160000,1358};13591360# submodule/subproject, a commit object reference1361sub S_ISGITLINK {1362my$mode=shift;13631364return(($mode& S_IFMT) == S_IFGITLINK)1365}13661367# convert file mode in octal to symbolic file mode string1368sub mode_str {1369my$mode=oct shift;13701371if(S_ISGITLINK($mode)) {1372return'm---------';1373}elsif(S_ISDIR($mode& S_IFMT)) {1374return'drwxr-xr-x';1375}elsif(S_ISLNK($mode)) {1376return'lrwxrwxrwx';1377}elsif(S_ISREG($mode)) {1378# git cares only about the executable bit1379if($mode& S_IXUSR) {1380return'-rwxr-xr-x';1381}else{1382return'-rw-r--r--';1383};1384}else{1385return'----------';1386}1387}13881389# convert file mode in octal to file type string1390sub file_type {1391my$mode=shift;13921393if($mode!~m/^[0-7]+$/) {1394return$mode;1395}else{1396$mode=oct$mode;1397}13981399if(S_ISGITLINK($mode)) {1400return"submodule";1401}elsif(S_ISDIR($mode& S_IFMT)) {1402return"directory";1403}elsif(S_ISLNK($mode)) {1404return"symlink";1405}elsif(S_ISREG($mode)) {1406return"file";1407}else{1408return"unknown";1409}1410}14111412# convert file mode in octal to file type description string1413sub file_type_long {1414my$mode=shift;14151416if($mode!~m/^[0-7]+$/) {1417return$mode;1418}else{1419$mode=oct$mode;1420}14211422if(S_ISGITLINK($mode)) {1423return"submodule";1424}elsif(S_ISDIR($mode& S_IFMT)) {1425return"directory";1426}elsif(S_ISLNK($mode)) {1427return"symlink";1428}elsif(S_ISREG($mode)) {1429if($mode& S_IXUSR) {1430return"executable";1431}else{1432return"file";1433};1434}else{1435return"unknown";1436}1437}143814391440## ----------------------------------------------------------------------1441## functions returning short HTML fragments, or transforming HTML fragments1442## which don't belong to other sections14431444# format line of commit message.1445sub format_log_line_html {1446my$line=shift;14471448$line= esc_html($line, -nbsp=>1);1449$line=~ s{\b([0-9a-fA-F]{8,40})\b}{1450$cgi->a({-href => href(action=>"object", hash=>$1),1451-class=>"text"},$1);1452}eg;14531454return$line;1455}14561457# format marker of refs pointing to given object14581459# the destination action is chosen based on object type and current context:1460# - for annotated tags, we choose the tag view unless it's the current view1461# already, in which case we go to shortlog view1462# - for other refs, we keep the current view if we're in history, shortlog or1463# log view, and select shortlog otherwise1464sub format_ref_marker {1465my($refs,$id) =@_;1466my$markers='';14671468if(defined$refs->{$id}) {1469foreachmy$ref(@{$refs->{$id}}) {1470# this code exploits the fact that non-lightweight tags are the1471# only indirect objects, and that they are the only objects for which1472# we want to use tag instead of shortlog as action1473my($type,$name) =qw();1474my$indirect= ($ref=~s/\^\{\}$//);1475# e.g. tags/v2.6.11 or heads/next1476if($ref=~m!^(.*?)s?/(.*)$!) {1477$type=$1;1478$name=$2;1479}else{1480$type="ref";1481$name=$ref;1482}14831484my$class=$type;1485$class.=" indirect"if$indirect;14861487my$dest_action="shortlog";14881489if($indirect) {1490$dest_action="tag"unless$actioneq"tag";1491}elsif($action=~/^(history|(short)?log)$/) {1492$dest_action=$action;1493}14941495my$dest="";1496$dest.="refs/"unless$ref=~ m!^refs/!;1497$dest.=$ref;14981499my$link=$cgi->a({1500-href => href(1501 action=>$dest_action,1502 hash=>$dest1503)},$name);15041505$markers.=" <span class=\"$class\"title=\"$ref\">".1506$link."</span>";1507}1508}15091510if($markers) {1511return' <span class="refs">'.$markers.'</span>';1512}else{1513return"";1514}1515}15161517# format, perhaps shortened and with markers, title line1518sub format_subject_html {1519my($long,$short,$href,$extra) =@_;1520$extra=''unlessdefined($extra);15211522if(length($short) <length($long)) {1523$long=~s/[[:cntrl:]]/?/g;1524return$cgi->a({-href =>$href, -class=>"list subject",1525-title => to_utf8($long)},1526 esc_html($short)) .$extra;1527}else{1528return$cgi->a({-href =>$href, -class=>"list subject"},1529 esc_html($long)) .$extra;1530}1531}15321533# Rather than recomputing the url for an email multiple times, we cache it1534# after the first hit. This gives a visible benefit in views where the avatar1535# for the same email is used repeatedly (e.g. shortlog).1536# The cache is shared by all avatar engines (currently gravatar only), which1537# are free to use it as preferred. Since only one avatar engine is used for any1538# given page, there's no risk for cache conflicts.1539our%avatar_cache= ();15401541# Compute the picon url for a given email, by using the picon search service over at1542# http://www.cs.indiana.edu/picons/search.html1543sub picon_url {1544my$email=lc shift;1545if(!$avatar_cache{$email}) {1546my($user,$domain) =split('@',$email);1547$avatar_cache{$email} =1548"http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/".1549"$domain/$user/".1550"users+domains+unknown/up/single";1551}1552return$avatar_cache{$email};1553}15541555# Compute the gravatar url for a given email, if it's not in the cache already.1556# Gravatar stores only the part of the URL before the size, since that's the1557# one computationally more expensive. This also allows reuse of the cache for1558# different sizes (for this particular engine).1559sub gravatar_url {1560my$email=lc shift;1561my$size=shift;1562$avatar_cache{$email} ||=1563"http://www.gravatar.com/avatar/".1564 Digest::MD5::md5_hex($email) ."?s=";1565return$avatar_cache{$email} .$size;1566}15671568# Insert an avatar for the given $email at the given $size if the feature1569# is enabled.1570sub git_get_avatar {1571my($email,%opts) =@_;1572my$pre_white= ($opts{-pad_before} ?" ":"");1573my$post_white= ($opts{-pad_after} ?" ":"");1574$opts{-size} ||='default';1575my$size=$avatar_size{$opts{-size}} ||$avatar_size{'default'};1576my$url="";1577if($git_avatareq'gravatar') {1578$url= gravatar_url($email,$size);1579}elsif($git_avatareq'picon') {1580$url= picon_url($email);1581}1582# Other providers can be added by extending the if chain, defining $url1583# as needed. If no variant puts something in $url, we assume avatars1584# are completely disabled/unavailable.1585if($url) {1586return$pre_white.1587"<img width=\"$size\"".1588"class=\"avatar\"".1589"src=\"$url\"".1590"alt=\"\"".1591"/>".$post_white;1592}else{1593return"";1594}1595}15961597# format the author name of the given commit with the given tag1598# the author name is chopped and escaped according to the other1599# optional parameters (see chop_str).1600sub format_author_html {1601my$tag=shift;1602my$co=shift;1603my$author= chop_and_escape_str($co->{'author_name'},@_);1604return"<$tagclass=\"author\">".1605 git_get_avatar($co->{'author_email'}, -pad_after =>1) .1606$author."</$tag>";1607}16081609# format git diff header line, i.e. "diff --(git|combined|cc) ..."1610sub format_git_diff_header_line {1611my$line=shift;1612my$diffinfo=shift;1613my($from,$to) =@_;16141615if($diffinfo->{'nparents'}) {1616# combined diff1617$line=~s!^(diff (.*?) )"?.*$!$1!;1618if($to->{'href'}) {1619$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1620 esc_path($to->{'file'}));1621}else{# file was deleted (no href)1622$line.= esc_path($to->{'file'});1623}1624}else{1625# "ordinary" diff1626$line=~s!^(diff (.*?) )"?a/.*$!$1!;1627if($from->{'href'}) {1628$line.=$cgi->a({-href =>$from->{'href'}, -class=>"path"},1629'a/'. esc_path($from->{'file'}));1630}else{# file was added (no href)1631$line.='a/'. esc_path($from->{'file'});1632}1633$line.=' ';1634if($to->{'href'}) {1635$line.=$cgi->a({-href =>$to->{'href'}, -class=>"path"},1636'b/'. esc_path($to->{'file'}));1637}else{# file was deleted1638$line.='b/'. esc_path($to->{'file'});1639}1640}16411642return"<div class=\"diff header\">$line</div>\n";1643}16441645# format extended diff header line, before patch itself1646sub format_extended_diff_header_line {1647my$line=shift;1648my$diffinfo=shift;1649my($from,$to) =@_;16501651# match <path>1652if($line=~s!^((copy|rename) from ).*$!$1!&&$from->{'href'}) {1653$line.=$cgi->a({-href=>$from->{'href'}, -class=>"path"},1654 esc_path($from->{'file'}));1655}1656if($line=~s!^((copy|rename) to ).*$!$1!&&$to->{'href'}) {1657$line.=$cgi->a({-href=>$to->{'href'}, -class=>"path"},1658 esc_path($to->{'file'}));1659}1660# match single <mode>1661if($line=~m/\s(\d{6})$/) {1662$line.='<span class="info"> ('.1663 file_type_long($1) .1664')</span>';1665}1666# match <hash>1667if($line=~m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {1668# can match only for combined diff1669$line='index ';1670for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1671if($from->{'href'}[$i]) {1672$line.=$cgi->a({-href=>$from->{'href'}[$i],1673-class=>"hash"},1674substr($diffinfo->{'from_id'}[$i],0,7));1675}else{1676$line.='0' x 7;1677}1678# separator1679$line.=','if($i<$diffinfo->{'nparents'} -1);1680}1681$line.='..';1682if($to->{'href'}) {1683$line.=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1684substr($diffinfo->{'to_id'},0,7));1685}else{1686$line.='0' x 7;1687}16881689}elsif($line=~m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {1690# can match only for ordinary diff1691my($from_link,$to_link);1692if($from->{'href'}) {1693$from_link=$cgi->a({-href=>$from->{'href'}, -class=>"hash"},1694substr($diffinfo->{'from_id'},0,7));1695}else{1696$from_link='0' x 7;1697}1698if($to->{'href'}) {1699$to_link=$cgi->a({-href=>$to->{'href'}, -class=>"hash"},1700substr($diffinfo->{'to_id'},0,7));1701}else{1702$to_link='0' x 7;1703}1704my($from_id,$to_id) = ($diffinfo->{'from_id'},$diffinfo->{'to_id'});1705$line=~s!$from_id\.\.$to_id!$from_link..$to_link!;1706}17071708return$line."<br/>\n";1709}17101711# format from-file/to-file diff header1712sub format_diff_from_to_header {1713my($from_line,$to_line,$diffinfo,$from,$to,@parents) =@_;1714my$line;1715my$result='';17161717$line=$from_line;1718#assert($line =~ m/^---/) if DEBUG;1719# no extra formatting for "^--- /dev/null"1720if(!$diffinfo->{'nparents'}) {1721# ordinary (single parent) diff1722if($line=~m!^--- "?a/!) {1723if($from->{'href'}) {1724$line='--- a/'.1725$cgi->a({-href=>$from->{'href'}, -class=>"path"},1726 esc_path($from->{'file'}));1727}else{1728$line='--- a/'.1729 esc_path($from->{'file'});1730}1731}1732$result.= qq!<div class="diff from_file">$line</div>\n!;17331734}else{1735# combined diff (merge commit)1736for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {1737if($from->{'href'}[$i]) {1738$line='--- '.1739$cgi->a({-href=>href(action=>"blobdiff",1740 hash_parent=>$diffinfo->{'from_id'}[$i],1741 hash_parent_base=>$parents[$i],1742 file_parent=>$from->{'file'}[$i],1743 hash=>$diffinfo->{'to_id'},1744 hash_base=>$hash,1745 file_name=>$to->{'file'}),1746-class=>"path",1747-title=>"diff". ($i+1)},1748$i+1) .1749'/'.1750$cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},1751 esc_path($from->{'file'}[$i]));1752}else{1753$line='--- /dev/null';1754}1755$result.= qq!<div class="diff from_file">$line</div>\n!;1756}1757}17581759$line=$to_line;1760#assert($line =~ m/^\+\+\+/) if DEBUG;1761# no extra formatting for "^+++ /dev/null"1762if($line=~m!^\+\+\+ "?b/!) {1763if($to->{'href'}) {1764$line='+++ b/'.1765$cgi->a({-href=>$to->{'href'}, -class=>"path"},1766 esc_path($to->{'file'}));1767}else{1768$line='+++ b/'.1769 esc_path($to->{'file'});1770}1771}1772$result.= qq!<div class="diff to_file">$line</div>\n!;17731774return$result;1775}17761777# create note for patch simplified by combined diff1778sub format_diff_cc_simplified {1779my($diffinfo,@parents) =@_;1780my$result='';17811782$result.="<div class=\"diff header\">".1783"diff --cc ";1784if(!is_deleted($diffinfo)) {1785$result.=$cgi->a({-href => href(action=>"blob",1786 hash_base=>$hash,1787 hash=>$diffinfo->{'to_id'},1788 file_name=>$diffinfo->{'to_file'}),1789-class=>"path"},1790 esc_path($diffinfo->{'to_file'}));1791}else{1792$result.= esc_path($diffinfo->{'to_file'});1793}1794$result.="</div>\n".# class="diff header"1795"<div class=\"diff nodifferences\">".1796"Simple merge".1797"</div>\n";# class="diff nodifferences"17981799return$result;1800}18011802# format patch (diff) line (not to be used for diff headers)1803sub format_diff_line {1804my$line=shift;1805my($from,$to) =@_;1806my$diff_class="";18071808chomp$line;18091810if($from&&$to&&ref($from->{'href'})eq"ARRAY") {1811# combined diff1812my$prefix=substr($line,0,scalar@{$from->{'href'}});1813if($line=~m/^\@{3}/) {1814$diff_class=" chunk_header";1815}elsif($line=~m/^\\/) {1816$diff_class=" incomplete";1817}elsif($prefix=~tr/+/+/) {1818$diff_class=" add";1819}elsif($prefix=~tr/-/-/) {1820$diff_class=" rem";1821}1822}else{1823# assume ordinary diff1824my$char=substr($line,0,1);1825if($chareq'+') {1826$diff_class=" add";1827}elsif($chareq'-') {1828$diff_class=" rem";1829}elsif($chareq'@') {1830$diff_class=" chunk_header";1831}elsif($chareq"\\") {1832$diff_class=" incomplete";1833}1834}1835$line= untabify($line);1836if($from&&$to&&$line=~m/^\@{2} /) {1837my($from_text,$from_start,$from_lines,$to_text,$to_start,$to_lines,$section) =1838$line=~m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;18391840$from_lines=0unlessdefined$from_lines;1841$to_lines=0unlessdefined$to_lines;18421843if($from->{'href'}) {1844$from_text=$cgi->a({-href=>"$from->{'href'}#l$from_start",1845-class=>"list"},$from_text);1846}1847if($to->{'href'}) {1848$to_text=$cgi->a({-href=>"$to->{'href'}#l$to_start",1849-class=>"list"},$to_text);1850}1851$line="<span class=\"chunk_info\">@@$from_text$to_text@@</span>".1852"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";1853return"<div class=\"diff$diff_class\">$line</div>\n";1854}elsif($from&&$to&&$line=~m/^\@{3}/) {1855my($prefix,$ranges,$section) =$line=~m/^(\@+) (.*?) \@+(.*)$/;1856my(@from_text,@from_start,@from_nlines,$to_text,$to_start,$to_nlines);18571858@from_text=split(' ',$ranges);1859for(my$i=0;$i<@from_text; ++$i) {1860($from_start[$i],$from_nlines[$i]) =1861(split(',',substr($from_text[$i],1)),0);1862}18631864$to_text=pop@from_text;1865$to_start=pop@from_start;1866$to_nlines=pop@from_nlines;18671868$line="<span class=\"chunk_info\">$prefix";1869for(my$i=0;$i<@from_text; ++$i) {1870if($from->{'href'}[$i]) {1871$line.=$cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",1872-class=>"list"},$from_text[$i]);1873}else{1874$line.=$from_text[$i];1875}1876$line.=" ";1877}1878if($to->{'href'}) {1879$line.=$cgi->a({-href=>"$to->{'href'}#l$to_start",1880-class=>"list"},$to_text);1881}else{1882$line.=$to_text;1883}1884$line.="$prefix</span>".1885"<span class=\"section\">". esc_html($section, -nbsp=>1) ."</span>";1886return"<div class=\"diff$diff_class\">$line</div>\n";1887}1888return"<div class=\"diff$diff_class\">". esc_html($line, -nbsp=>1) ."</div>\n";1889}18901891# Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",1892# linked. Pass the hash of the tree/commit to snapshot.1893sub format_snapshot_links {1894my($hash) =@_;1895my$num_fmts=@snapshot_fmts;1896if($num_fmts>1) {1897# A parenthesized list of links bearing format names.1898# e.g. "snapshot (_tar.gz_ _zip_)"1899return"snapshot (".join(' ',map1900$cgi->a({1901-href => href(1902 action=>"snapshot",1903 hash=>$hash,1904 snapshot_format=>$_1905)1906},$known_snapshot_formats{$_}{'display'})1907,@snapshot_fmts) .")";1908}elsif($num_fmts==1) {1909# A single "snapshot" link whose tooltip bears the format name.1910# i.e. "_snapshot_"1911my($fmt) =@snapshot_fmts;1912return1913$cgi->a({1914-href => href(1915 action=>"snapshot",1916 hash=>$hash,1917 snapshot_format=>$fmt1918),1919-title =>"in format:$known_snapshot_formats{$fmt}{'display'}"1920},"snapshot");1921}else{# $num_fmts == 01922returnundef;1923}1924}19251926## ......................................................................1927## functions returning values to be passed, perhaps after some1928## transformation, to other functions; e.g. returning arguments to href()19291930# returns hash to be passed to href to generate gitweb URL1931# in -title key it returns description of link1932sub get_feed_info {1933my$format=shift||'Atom';1934my%res= (action =>lc($format));19351936# feed links are possible only for project views1937return unless(defined$project);1938# some views should link to OPML, or to generic project feed,1939# or don't have specific feed yet (so they should use generic)1940return if($action=~/^(?:tags|heads|forks|tag|search)$/x);19411942my$branch;1943# branches refs uses 'refs/heads/' prefix (fullname) to differentiate1944# from tag links; this also makes possible to detect branch links1945if((defined$hash_base&&$hash_base=~m!^refs/heads/(.*)$!) ||1946(defined$hash&&$hash=~m!^refs/heads/(.*)$!)) {1947$branch=$1;1948}1949# find log type for feed description (title)1950my$type='log';1951if(defined$file_name) {1952$type="history of$file_name";1953$type.="/"if($actioneq'tree');1954$type.=" on '$branch'"if(defined$branch);1955}else{1956$type="log of$branch"if(defined$branch);1957}19581959$res{-title} =$type;1960$res{'hash'} = (defined$branch?"refs/heads/$branch":undef);1961$res{'file_name'} =$file_name;19621963return%res;1964}19651966## ----------------------------------------------------------------------1967## git utility subroutines, invoking git commands19681969# returns path to the core git executable and the --git-dir parameter as list1970sub git_cmd {1971return$GIT,'--git-dir='.$git_dir;1972}19731974# quote the given arguments for passing them to the shell1975# quote_command("command", "arg 1", "arg with ' and ! characters")1976# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"1977# Try to avoid using this function wherever possible.1978sub quote_command {1979returnjoin(' ',1980map{my$a=$_;$a=~s/(['!])/'\\$1'/g;"'$a'"}@_);1981}19821983# get HEAD ref of given project as hash1984sub git_get_head_hash {1985my$project=shift;1986my$o_git_dir=$git_dir;1987my$retval=undef;1988$git_dir="$projectroot/$project";1989if(open my$fd,"-|", git_cmd(),"rev-parse","--verify","HEAD") {1990my$head= <$fd>;1991close$fd;1992if(defined$head&&$head=~/^([0-9a-fA-F]{40})$/) {1993$retval=$1;1994}1995}1996if(defined$o_git_dir) {1997$git_dir=$o_git_dir;1998}1999return$retval;2000}20012002# get type of given object2003sub git_get_type {2004my$hash=shift;20052006open my$fd,"-|", git_cmd(),"cat-file",'-t',$hashorreturn;2007my$type= <$fd>;2008close$fdorreturn;2009chomp$type;2010return$type;2011}20122013# repository configuration2014our$config_file='';2015our%config;20162017# store multiple values for single key as anonymous array reference2018# single values stored directly in the hash, not as [ <value> ]2019sub hash_set_multi {2020my($hash,$key,$value) =@_;20212022if(!exists$hash->{$key}) {2023$hash->{$key} =$value;2024}elsif(!ref$hash->{$key}) {2025$hash->{$key} = [$hash->{$key},$value];2026}else{2027push@{$hash->{$key}},$value;2028}2029}20302031# return hash of git project configuration2032# optionally limited to some section, e.g. 'gitweb'2033sub git_parse_project_config {2034my$section_regexp=shift;2035my%config;20362037local$/="\0";20382039open my$fh,"-|", git_cmd(),"config",'-z','-l',2040orreturn;20412042while(my$keyval= <$fh>) {2043chomp$keyval;2044my($key,$value) =split(/\n/,$keyval,2);20452046 hash_set_multi(\%config,$key,$value)2047if(!defined$section_regexp||$key=~/^(?:$section_regexp)\./o);2048}2049close$fh;20502051return%config;2052}20532054# convert config value to boolean: 'true' or 'false'2055# no value, number > 0, 'true' and 'yes' values are true2056# rest of values are treated as false (never as error)2057sub config_to_bool {2058my$val=shift;20592060return1if!defined$val;# section.key20612062# strip leading and trailing whitespace2063$val=~s/^\s+//;2064$val=~s/\s+$//;20652066return(($val=~/^\d+$/&&$val) ||# section.key = 12067($val=~/^(?:true|yes)$/i));# section.key = true2068}20692070# convert config value to simple decimal number2071# an optional value suffix of 'k', 'm', or 'g' will cause the value2072# to be multiplied by 1024, 1048576, or 10737418242073sub config_to_int {2074my$val=shift;20752076# strip leading and trailing whitespace2077$val=~s/^\s+//;2078$val=~s/\s+$//;20792080if(my($num,$unit) = ($val=~/^([0-9]*)([kmg])$/i)) {2081$unit=lc($unit);2082# unknown unit is treated as 12083return$num* ($uniteq'g'?1073741824:2084$uniteq'm'?1048576:2085$uniteq'k'?1024:1);2086}2087return$val;2088}20892090# convert config value to array reference, if needed2091sub config_to_multi {2092my$val=shift;20932094returnref($val) ?$val: (defined($val) ? [$val] : []);2095}20962097sub git_get_project_config {2098my($key,$type) =@_;20992100# key sanity check2101return unless($key);2102$key=~s/^gitweb\.//;2103return if($key=~m/\W/);21042105# type sanity check2106if(defined$type) {2107$type=~s/^--//;2108$type=undef2109unless($typeeq'bool'||$typeeq'int');2110}21112112# get config2113if(!defined$config_file||2114$config_filene"$git_dir/config") {2115%config= git_parse_project_config('gitweb');2116$config_file="$git_dir/config";2117}21182119# check if config variable (key) exists2120return unlessexists$config{"gitweb.$key"};21212122# ensure given type2123if(!defined$type) {2124return$config{"gitweb.$key"};2125}elsif($typeeq'bool') {2126# backward compatibility: 'git config --bool' returns true/false2127return config_to_bool($config{"gitweb.$key"}) ?'true':'false';2128}elsif($typeeq'int') {2129return config_to_int($config{"gitweb.$key"});2130}2131return$config{"gitweb.$key"};2132}21332134# get hash of given path at given ref2135sub git_get_hash_by_path {2136my$base=shift;2137my$path=shift||returnundef;2138my$type=shift;21392140$path=~ s,/+$,,;21412142open my$fd,"-|", git_cmd(),"ls-tree",$base,"--",$path2143or die_error(500,"Open git-ls-tree failed");2144my$line= <$fd>;2145close$fdorreturnundef;21462147if(!defined$line) {2148# there is no tree or hash given by $path at $base2149returnundef;2150}21512152#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2153$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;2154if(defined$type&&$typene$2) {2155# type doesn't match2156returnundef;2157}2158return$3;2159}21602161# get path of entry with given hash at given tree-ish (ref)2162# used to get 'from' filename for combined diff (merge commit) for renames2163sub git_get_path_by_hash {2164my$base=shift||return;2165my$hash=shift||return;21662167local$/="\0";21682169open my$fd,"-|", git_cmd(),"ls-tree",'-r','-t','-z',$base2170orreturnundef;2171while(my$line= <$fd>) {2172chomp$line;21732174#'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'2175#'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'2176if($line=~m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {2177close$fd;2178return$1;2179}2180}2181close$fd;2182returnundef;2183}21842185## ......................................................................2186## git utility functions, directly accessing git repository21872188sub git_get_project_description {2189my$path=shift;21902191$git_dir="$projectroot/$path";2192open my$fd,'<',"$git_dir/description"2193orreturn git_get_project_config('description');2194my$descr= <$fd>;2195close$fd;2196if(defined$descr) {2197chomp$descr;2198}2199return$descr;2200}22012202sub git_get_project_ctags {2203my$path=shift;2204my$ctags= {};22052206$git_dir="$projectroot/$path";2207opendir my$dh,"$git_dir/ctags"2208orreturn$ctags;2209foreach(grep{ -f $_}map{"$git_dir/ctags/$_"}readdir($dh)) {2210open my$ct,'<',$_ornext;2211my$val= <$ct>;2212chomp$val;2213close$ct;2214my$ctag=$_;$ctag=~ s#.*/##;2215$ctags->{$ctag} =$val;2216}2217closedir$dh;2218$ctags;2219}22202221sub git_populate_project_tagcloud {2222my$ctags=shift;22232224# First, merge different-cased tags; tags vote on casing2225my%ctags_lc;2226foreach(keys%$ctags) {2227$ctags_lc{lc$_}->{count} +=$ctags->{$_};2228if(not$ctags_lc{lc$_}->{topcount}2229or$ctags_lc{lc$_}->{topcount} <$ctags->{$_}) {2230$ctags_lc{lc$_}->{topcount} =$ctags->{$_};2231$ctags_lc{lc$_}->{topname} =$_;2232}2233}22342235my$cloud;2236if(eval{require HTML::TagCloud;1; }) {2237$cloud= HTML::TagCloud->new;2238foreach(sort keys%ctags_lc) {2239# Pad the title with spaces so that the cloud looks2240# less crammed.2241my$title=$ctags_lc{$_}->{topname};2242$title=~s/ / /g;2243$title=~s/^/ /g;2244$title=~s/$/ /g;2245$cloud->add($title,$home_link."?by_tag=".$_,$ctags_lc{$_}->{count});2246}2247}else{2248$cloud= \%ctags_lc;2249}2250$cloud;2251}22522253sub git_show_project_tagcloud {2254my($cloud,$count) =@_;2255print STDERR ref($cloud)."..\n";2256if(ref$cloudeq'HTML::TagCloud') {2257return$cloud->html_and_css($count);2258}else{2259my@tags=sort{$cloud->{$a}->{count} <=>$cloud->{$b}->{count} }keys%$cloud;2260return'<p align="center">'.join(', ',map{2261"<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"2262}splice(@tags,0,$count)) .'</p>';2263}2264}22652266sub git_get_project_url_list {2267my$path=shift;22682269$git_dir="$projectroot/$path";2270open my$fd,'<',"$git_dir/cloneurl"2271orreturnwantarray?2272@{ config_to_multi(git_get_project_config('url')) } :2273 config_to_multi(git_get_project_config('url'));2274my@git_project_url_list=map{chomp;$_} <$fd>;2275close$fd;22762277returnwantarray?@git_project_url_list: \@git_project_url_list;2278}22792280sub git_get_projects_list {2281my($filter) =@_;2282my@list;22832284$filter||='';2285$filter=~s/\.git$//;22862287my$check_forks= gitweb_check_feature('forks');22882289if(-d $projects_list) {2290# search in directory2291my$dir=$projects_list. ($filter?"/$filter":'');2292# remove the trailing "/"2293$dir=~s!/+$!!;2294my$pfxlen=length("$dir");2295my$pfxdepth= ($dir=~tr!/!!);22962297 File::Find::find({2298 follow_fast =>1,# follow symbolic links2299 follow_skip =>2,# ignore duplicates2300 dangling_symlinks =>0,# ignore dangling symlinks, silently2301 wanted =>sub{2302# skip project-list toplevel, if we get it.2303return if(m!^[/.]$!);2304# only directories can be git repositories2305return unless(-d $_);2306# don't traverse too deep (Find is super slow on os x)2307if(($File::Find::name =~tr!/!!) -$pfxdepth>$project_maxdepth) {2308$File::Find::prune =1;2309return;2310}23112312my$subdir=substr($File::Find::name,$pfxlen+1);2313# we check related file in $projectroot2314my$path= ($filter?"$filter/":'') .$subdir;2315if(check_export_ok("$projectroot/$path")) {2316push@list, { path =>$path};2317$File::Find::prune =1;2318}2319},2320},"$dir");23212322}elsif(-f $projects_list) {2323# read from file(url-encoded):2324# 'git%2Fgit.git Linus+Torvalds'2325# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2326# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2327my%paths;2328open my$fd,'<',$projects_listorreturn;2329 PROJECT:2330while(my$line= <$fd>) {2331chomp$line;2332my($path,$owner) =split' ',$line;2333$path= unescape($path);2334$owner= unescape($owner);2335if(!defined$path) {2336next;2337}2338if($filterne'') {2339# looking for forks;2340my$pfx=substr($path,0,length($filter));2341if($pfxne$filter) {2342next PROJECT;2343}2344my$sfx=substr($path,length($filter));2345if($sfx!~/^\/.*\.git$/) {2346next PROJECT;2347}2348}elsif($check_forks) {2349 PATH:2350foreachmy$filter(keys%paths) {2351# looking for forks;2352my$pfx=substr($path,0,length($filter));2353if($pfxne$filter) {2354next PATH;2355}2356my$sfx=substr($path,length($filter));2357if($sfx!~/^\/.*\.git$/) {2358next PATH;2359}2360# is a fork, don't include it in2361# the list2362next PROJECT;2363}2364}2365if(check_export_ok("$projectroot/$path")) {2366my$pr= {2367 path =>$path,2368 owner => to_utf8($owner),2369};2370push@list,$pr;2371(my$forks_path=$path) =~s/\.git$//;2372$paths{$forks_path}++;2373}2374}2375close$fd;2376}2377return@list;2378}23792380our$gitweb_project_owner=undef;2381sub git_get_project_list_from_file {23822383return if(defined$gitweb_project_owner);23842385$gitweb_project_owner= {};2386# read from file (url-encoded):2387# 'git%2Fgit.git Linus+Torvalds'2388# 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'2389# 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'2390if(-f $projects_list) {2391open(my$fd,'<',$projects_list);2392while(my$line= <$fd>) {2393chomp$line;2394my($pr,$ow) =split' ',$line;2395$pr= unescape($pr);2396$ow= unescape($ow);2397$gitweb_project_owner->{$pr} = to_utf8($ow);2398}2399close$fd;2400}2401}24022403sub git_get_project_owner {2404my$project=shift;2405my$owner;24062407returnundefunless$project;2408$git_dir="$projectroot/$project";24092410if(!defined$gitweb_project_owner) {2411 git_get_project_list_from_file();2412}24132414if(exists$gitweb_project_owner->{$project}) {2415$owner=$gitweb_project_owner->{$project};2416}2417if(!defined$owner){2418$owner= git_get_project_config('owner');2419}2420if(!defined$owner) {2421$owner= get_file_owner("$git_dir");2422}24232424return$owner;2425}24262427sub git_get_last_activity {2428my($path) =@_;2429my$fd;24302431$git_dir="$projectroot/$path";2432open($fd,"-|", git_cmd(),'for-each-ref',2433'--format=%(committer)',2434'--sort=-committerdate',2435'--count=1',2436'refs/heads')orreturn;2437my$most_recent= <$fd>;2438close$fdorreturn;2439if(defined$most_recent&&2440$most_recent=~/ (\d+) [-+][01]\d\d\d$/) {2441my$timestamp=$1;2442my$age=time-$timestamp;2443return($age, age_string($age));2444}2445return(undef,undef);2446}24472448sub git_get_references {2449my$type=shift||"";2450my%refs;2451# 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.112452# c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}2453open my$fd,"-|", git_cmd(),"show-ref","--dereference",2454($type? ("--","refs/$type") : ())# use -- <pattern> if $type2455orreturn;24562457while(my$line= <$fd>) {2458chomp$line;2459if($line=~m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {2460if(defined$refs{$1}) {2461push@{$refs{$1}},$2;2462}else{2463$refs{$1} = [$2];2464}2465}2466}2467close$fdorreturn;2468return \%refs;2469}24702471sub git_get_rev_name_tags {2472my$hash=shift||returnundef;24732474open my$fd,"-|", git_cmd(),"name-rev","--tags",$hash2475orreturn;2476my$name_rev= <$fd>;2477close$fd;24782479if($name_rev=~ m|^$hash tags/(.*)$|) {2480return$1;2481}else{2482# catches also '$hash undefined' output2483returnundef;2484}2485}24862487## ----------------------------------------------------------------------2488## parse to hash functions24892490sub parse_date {2491my$epoch=shift;2492my$tz=shift||"-0000";24932494my%date;2495my@months= ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");2496my@days= ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");2497my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($epoch);2498$date{'hour'} =$hour;2499$date{'minute'} =$min;2500$date{'mday'} =$mday;2501$date{'day'} =$days[$wday];2502$date{'month'} =$months[$mon];2503$date{'rfc2822'} =sprintf"%s,%d%s%4d%02d:%02d:%02d+0000",2504$days[$wday],$mday,$months[$mon],1900+$year,$hour,$min,$sec;2505$date{'mday-time'} =sprintf"%d%s%02d:%02d",2506$mday,$months[$mon],$hour,$min;2507$date{'iso-8601'} =sprintf"%04d-%02d-%02dT%02d:%02d:%02dZ",25081900+$year,1+$mon,$mday,$hour,$min,$sec;25092510$tz=~m/^([+\-][0-9][0-9])([0-9][0-9])$/;2511my$local=$epoch+ ((int$1+ ($2/60)) *3600);2512($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($local);2513$date{'hour_local'} =$hour;2514$date{'minute_local'} =$min;2515$date{'tz_local'} =$tz;2516$date{'iso-tz'} =sprintf("%04d-%02d-%02d%02d:%02d:%02d%s",25171900+$year,$mon+1,$mday,2518$hour,$min,$sec,$tz);2519return%date;2520}25212522sub parse_tag {2523my$tag_id=shift;2524my%tag;2525my@comment;25262527open my$fd,"-|", git_cmd(),"cat-file","tag",$tag_idorreturn;2528$tag{'id'} =$tag_id;2529while(my$line= <$fd>) {2530chomp$line;2531if($line=~m/^object ([0-9a-fA-F]{40})$/) {2532$tag{'object'} =$1;2533}elsif($line=~m/^type (.+)$/) {2534$tag{'type'} =$1;2535}elsif($line=~m/^tag (.+)$/) {2536$tag{'name'} =$1;2537}elsif($line=~m/^tagger (.*) ([0-9]+) (.*)$/) {2538$tag{'author'} =$1;2539$tag{'author_epoch'} =$2;2540$tag{'author_tz'} =$3;2541if($tag{'author'} =~m/^([^<]+) <([^>]*)>/) {2542$tag{'author_name'} =$1;2543$tag{'author_email'} =$2;2544}else{2545$tag{'author_name'} =$tag{'author'};2546}2547}elsif($line=~m/--BEGIN/) {2548push@comment,$line;2549last;2550}elsif($lineeq"") {2551last;2552}2553}2554push@comment, <$fd>;2555$tag{'comment'} = \@comment;2556close$fdorreturn;2557if(!defined$tag{'name'}) {2558return2559};2560return%tag2561}25622563sub parse_commit_text {2564my($commit_text,$withparents) =@_;2565my@commit_lines=split'\n',$commit_text;2566my%co;25672568pop@commit_lines;# Remove '\0'25692570if(!@commit_lines) {2571return;2572}25732574my$header=shift@commit_lines;2575if($header!~m/^[0-9a-fA-F]{40}/) {2576return;2577}2578($co{'id'},my@parents) =split' ',$header;2579while(my$line=shift@commit_lines) {2580last if$lineeq"\n";2581if($line=~m/^tree ([0-9a-fA-F]{40})$/) {2582$co{'tree'} =$1;2583}elsif((!defined$withparents) && ($line=~m/^parent ([0-9a-fA-F]{40})$/)) {2584push@parents,$1;2585}elsif($line=~m/^author (.*) ([0-9]+) (.*)$/) {2586$co{'author'} = to_utf8($1);2587$co{'author_epoch'} =$2;2588$co{'author_tz'} =$3;2589if($co{'author'} =~m/^([^<]+) <([^>]*)>/) {2590$co{'author_name'} =$1;2591$co{'author_email'} =$2;2592}else{2593$co{'author_name'} =$co{'author'};2594}2595}elsif($line=~m/^committer (.*) ([0-9]+) (.*)$/) {2596$co{'committer'} = to_utf8($1);2597$co{'committer_epoch'} =$2;2598$co{'committer_tz'} =$3;2599if($co{'committer'} =~m/^([^<]+) <([^>]*)>/) {2600$co{'committer_name'} =$1;2601$co{'committer_email'} =$2;2602}else{2603$co{'committer_name'} =$co{'committer'};2604}2605}2606}2607if(!defined$co{'tree'}) {2608return;2609};2610$co{'parents'} = \@parents;2611$co{'parent'} =$parents[0];26122613foreachmy$title(@commit_lines) {2614$title=~s/^ //;2615if($titlene"") {2616$co{'title'} = chop_str($title,80,5);2617# remove leading stuff of merges to make the interesting part visible2618if(length($title) >50) {2619$title=~s/^Automatic //;2620$title=~s/^merge (of|with) /Merge ... /i;2621if(length($title) >50) {2622$title=~s/(http|rsync):\/\///;2623}2624if(length($title) >50) {2625$title=~s/(master|www|rsync)\.//;2626}2627if(length($title) >50) {2628$title=~s/kernel.org:?//;2629}2630if(length($title) >50) {2631$title=~s/\/pub\/scm//;2632}2633}2634$co{'title_short'} = chop_str($title,50,5);2635last;2636}2637}2638if(!defined$co{'title'} ||$co{'title'}eq"") {2639$co{'title'} =$co{'title_short'} ='(no commit message)';2640}2641# remove added spaces2642foreachmy$line(@commit_lines) {2643$line=~s/^ //;2644}2645$co{'comment'} = \@commit_lines;26462647my$age=time-$co{'committer_epoch'};2648$co{'age'} =$age;2649$co{'age_string'} = age_string($age);2650my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =gmtime($co{'committer_epoch'});2651if($age>60*60*24*7*2) {2652$co{'age_string_date'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2653$co{'age_string_age'} =$co{'age_string'};2654}else{2655$co{'age_string_date'} =$co{'age_string'};2656$co{'age_string_age'} =sprintf"%4i-%02u-%02i",1900+$year,$mon+1,$mday;2657}2658return%co;2659}26602661sub parse_commit {2662my($commit_id) =@_;2663my%co;26642665local$/="\0";26662667open my$fd,"-|", git_cmd(),"rev-list",2668"--parents",2669"--header",2670"--max-count=1",2671$commit_id,2672"--",2673or die_error(500,"Open git-rev-list failed");2674%co= parse_commit_text(<$fd>,1);2675close$fd;26762677return%co;2678}26792680sub parse_commits {2681my($commit_id,$maxcount,$skip,$filename,@args) =@_;2682my@cos;26832684$maxcount||=1;2685$skip||=0;26862687local$/="\0";26882689open my$fd,"-|", git_cmd(),"rev-list",2690"--header",2691@args,2692("--max-count=".$maxcount),2693("--skip=".$skip),2694@extra_options,2695$commit_id,2696"--",2697($filename? ($filename) : ())2698or die_error(500,"Open git-rev-list failed");2699while(my$line= <$fd>) {2700my%co= parse_commit_text($line);2701push@cos, \%co;2702}2703close$fd;27042705returnwantarray?@cos: \@cos;2706}27072708# parse line of git-diff-tree "raw" output2709sub parse_difftree_raw_line {2710my$line=shift;2711my%res;27122713# ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'2714# ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'2715if($line=~m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {2716$res{'from_mode'} =$1;2717$res{'to_mode'} =$2;2718$res{'from_id'} =$3;2719$res{'to_id'} =$4;2720$res{'status'} =$5;2721$res{'similarity'} =$6;2722if($res{'status'}eq'R'||$res{'status'}eq'C') {# renamed or copied2723($res{'from_file'},$res{'to_file'}) =map{ unquote($_) }split("\t",$7);2724}else{2725$res{'from_file'} =$res{'to_file'} =$res{'file'} = unquote($7);2726}2727}2728# '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'2729# combined diff (for merge commit)2730elsif($line=~s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {2731$res{'nparents'} =length($1);2732$res{'from_mode'} = [split(' ',$2) ];2733$res{'to_mode'} =pop@{$res{'from_mode'}};2734$res{'from_id'} = [split(' ',$3) ];2735$res{'to_id'} =pop@{$res{'from_id'}};2736$res{'status'} = [split('',$4) ];2737$res{'to_file'} = unquote($5);2738}2739# 'c512b523472485aef4fff9e57b229d9d243c967f'2740elsif($line=~m/^([0-9a-fA-F]{40})$/) {2741$res{'commit'} =$1;2742}27432744returnwantarray?%res: \%res;2745}27462747# wrapper: return parsed line of git-diff-tree "raw" output2748# (the argument might be raw line, or parsed info)2749sub parsed_difftree_line {2750my$line_or_ref=shift;27512752if(ref($line_or_ref)eq"HASH") {2753# pre-parsed (or generated by hand)2754return$line_or_ref;2755}else{2756return parse_difftree_raw_line($line_or_ref);2757}2758}27592760# parse line of git-ls-tree output2761sub parse_ls_tree_line {2762my$line=shift;2763my%opts=@_;2764my%res;27652766#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'2767$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;27682769$res{'mode'} =$1;2770$res{'type'} =$2;2771$res{'hash'} =$3;2772if($opts{'-z'}) {2773$res{'name'} =$4;2774}else{2775$res{'name'} = unquote($4);2776}27772778returnwantarray?%res: \%res;2779}27802781# generates _two_ hashes, references to which are passed as 2 and 3 argument2782sub parse_from_to_diffinfo {2783my($diffinfo,$from,$to,@parents) =@_;27842785if($diffinfo->{'nparents'}) {2786# combined diff2787$from->{'file'} = [];2788$from->{'href'} = [];2789 fill_from_file_info($diffinfo,@parents)2790unlessexists$diffinfo->{'from_file'};2791for(my$i=0;$i<$diffinfo->{'nparents'};$i++) {2792$from->{'file'}[$i] =2793defined$diffinfo->{'from_file'}[$i] ?2794$diffinfo->{'from_file'}[$i] :2795$diffinfo->{'to_file'};2796if($diffinfo->{'status'}[$i]ne"A") {# not new (added) file2797$from->{'href'}[$i] = href(action=>"blob",2798 hash_base=>$parents[$i],2799 hash=>$diffinfo->{'from_id'}[$i],2800 file_name=>$from->{'file'}[$i]);2801}else{2802$from->{'href'}[$i] =undef;2803}2804}2805}else{2806# ordinary (not combined) diff2807$from->{'file'} =$diffinfo->{'from_file'};2808if($diffinfo->{'status'}ne"A") {# not new (added) file2809$from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,2810 hash=>$diffinfo->{'from_id'},2811 file_name=>$from->{'file'});2812}else{2813delete$from->{'href'};2814}2815}28162817$to->{'file'} =$diffinfo->{'to_file'};2818if(!is_deleted($diffinfo)) {# file exists in result2819$to->{'href'} = href(action=>"blob", hash_base=>$hash,2820 hash=>$diffinfo->{'to_id'},2821 file_name=>$to->{'file'});2822}else{2823delete$to->{'href'};2824}2825}28262827## ......................................................................2828## parse to array of hashes functions28292830sub git_get_heads_list {2831my$limit=shift;2832my@headslist;28332834open my$fd,'-|', git_cmd(),'for-each-ref',2835($limit?'--count='.($limit+1) : ()),'--sort=-committerdate',2836'--format=%(objectname) %(refname) %(subject)%00%(committer)',2837'refs/heads'2838orreturn;2839while(my$line= <$fd>) {2840my%ref_item;28412842chomp$line;2843my($refinfo,$committerinfo) =split(/\0/,$line);2844my($hash,$name,$title) =split(' ',$refinfo,3);2845my($committer,$epoch,$tz) =2846($committerinfo=~/^(.*) ([0-9]+) (.*)$/);2847$ref_item{'fullname'} =$name;2848$name=~s!^refs/heads/!!;28492850$ref_item{'name'} =$name;2851$ref_item{'id'} =$hash;2852$ref_item{'title'} =$title||'(no commit message)';2853$ref_item{'epoch'} =$epoch;2854if($epoch) {2855$ref_item{'age'} = age_string(time-$ref_item{'epoch'});2856}else{2857$ref_item{'age'} ="unknown";2858}28592860push@headslist, \%ref_item;2861}2862close$fd;28632864returnwantarray?@headslist: \@headslist;2865}28662867sub git_get_tags_list {2868my$limit=shift;2869my@tagslist;28702871open my$fd,'-|', git_cmd(),'for-each-ref',2872($limit?'--count='.($limit+1) : ()),'--sort=-creatordate',2873'--format=%(objectname) %(objecttype) %(refname) '.2874'%(*objectname) %(*objecttype) %(subject)%00%(creator)',2875'refs/tags'2876orreturn;2877while(my$line= <$fd>) {2878my%ref_item;28792880chomp$line;2881my($refinfo,$creatorinfo) =split(/\0/,$line);2882my($id,$type,$name,$refid,$reftype,$title) =split(' ',$refinfo,6);2883my($creator,$epoch,$tz) =2884($creatorinfo=~/^(.*) ([0-9]+) (.*)$/);2885$ref_item{'fullname'} =$name;2886$name=~s!^refs/tags/!!;28872888$ref_item{'type'} =$type;2889$ref_item{'id'} =$id;2890$ref_item{'name'} =$name;2891if($typeeq"tag") {2892$ref_item{'subject'} =$title;2893$ref_item{'reftype'} =$reftype;2894$ref_item{'refid'} =$refid;2895}else{2896$ref_item{'reftype'} =$type;2897$ref_item{'refid'} =$id;2898}28992900if($typeeq"tag"||$typeeq"commit") {2901$ref_item{'epoch'} =$epoch;2902if($epoch) {2903$ref_item{'age'} = age_string(time-$ref_item{'epoch'});2904}else{2905$ref_item{'age'} ="unknown";2906}2907}29082909push@tagslist, \%ref_item;2910}2911close$fd;29122913returnwantarray?@tagslist: \@tagslist;2914}29152916## ----------------------------------------------------------------------2917## filesystem-related functions29182919sub get_file_owner {2920my$path=shift;29212922my($dev,$ino,$mode,$nlink,$st_uid,$st_gid,$rdev,$size) =stat($path);2923my($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) =getpwuid($st_uid);2924if(!defined$gcos) {2925returnundef;2926}2927my$owner=$gcos;2928$owner=~s/[,;].*$//;2929return to_utf8($owner);2930}29312932# assume that file exists2933sub insert_file {2934my$filename=shift;29352936open my$fd,'<',$filename;2937print map{ to_utf8($_) } <$fd>;2938close$fd;2939}29402941## ......................................................................2942## mimetype related functions29432944sub mimetype_guess_file {2945my$filename=shift;2946my$mimemap=shift;2947-r $mimemaporreturnundef;29482949my%mimemap;2950open(my$mh,'<',$mimemap)orreturnundef;2951while(<$mh>) {2952next ifm/^#/;# skip comments2953my($mimetype,$exts) =split(/\t+/);2954if(defined$exts) {2955my@exts=split(/\s+/,$exts);2956foreachmy$ext(@exts) {2957$mimemap{$ext} =$mimetype;2958}2959}2960}2961close($mh);29622963$filename=~/\.([^.]*)$/;2964return$mimemap{$1};2965}29662967sub mimetype_guess {2968my$filename=shift;2969my$mime;2970$filename=~/\./orreturnundef;29712972if($mimetypes_file) {2973my$file=$mimetypes_file;2974if($file!~m!^/!) {# if it is relative path2975# it is relative to project2976$file="$projectroot/$project/$file";2977}2978$mime= mimetype_guess_file($filename,$file);2979}2980$mime||= mimetype_guess_file($filename,'/etc/mime.types');2981return$mime;2982}29832984sub blob_mimetype {2985my$fd=shift;2986my$filename=shift;29872988if($filename) {2989my$mime= mimetype_guess($filename);2990$mimeandreturn$mime;2991}29922993# just in case2994return$default_blob_plain_mimetypeunless$fd;29952996if(-T $fd) {2997return'text/plain';2998}elsif(!$filename) {2999return'application/octet-stream';3000}elsif($filename=~m/\.png$/i) {3001return'image/png';3002}elsif($filename=~m/\.gif$/i) {3003return'image/gif';3004}elsif($filename=~m/\.jpe?g$/i) {3005return'image/jpeg';3006}else{3007return'application/octet-stream';3008}3009}30103011sub blob_contenttype {3012my($fd,$file_name,$type) =@_;30133014$type||= blob_mimetype($fd,$file_name);3015if($typeeq'text/plain'&&defined$default_text_plain_charset) {3016$type.="; charset=$default_text_plain_charset";3017}30183019return$type;3020}30213022## ======================================================================3023## functions printing HTML: header, footer, error page30243025sub git_header_html {3026my$status=shift||"200 OK";3027my$expires=shift;30283029my$title="$site_name";3030if(defined$project) {3031$title.=" - ". to_utf8($project);3032if(defined$action) {3033$title.="/$action";3034if(defined$file_name) {3035$title.=" - ". esc_path($file_name);3036if($actioneq"tree"&&$file_name!~ m|/$|) {3037$title.="/";3038}3039}3040}3041}3042my$content_type;3043# require explicit support from the UA if we are to send the page as3044# 'application/xhtml+xml', otherwise send it as plain old 'text/html'.3045# we have to do this because MSIE sometimes globs '*/*', pretending to3046# support xhtml+xml but choking when it gets what it asked for.3047if(defined$cgi->http('HTTP_ACCEPT') &&3048$cgi->http('HTTP_ACCEPT') =~m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&3049$cgi->Accept('application/xhtml+xml') !=0) {3050$content_type='application/xhtml+xml';3051}else{3052$content_type='text/html';3053}3054print$cgi->header(-type=>$content_type, -charset =>'utf-8',3055-status=>$status, -expires =>$expires);3056my$mod_perl_version=$ENV{'MOD_PERL'} ?"$ENV{'MOD_PERL'}":'';3057print<<EOF;3058<?xml version="1.0" encoding="utf-8"?>3059<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">3060<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">3061<!-- git web interface version$version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->3062<!-- git core binaries version$git_version-->3063<head>3064<meta http-equiv="content-type" content="$content_type; charset=utf-8"/>3065<meta name="generator" content="gitweb/$versiongit/$git_version$mod_perl_version"/>3066<meta name="robots" content="index, nofollow"/>3067<title>$title</title>3068EOF3069# the stylesheet, favicon etc urls won't work correctly with path_info3070# unless we set the appropriate base URL3071if($ENV{'PATH_INFO'}) {3072print"<base href=\"".esc_url($base_url)."\"/>\n";3073}3074# print out each stylesheet that exist, providing backwards capability3075# for those people who defined $stylesheet in a config file3076if(defined$stylesheet) {3077print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3078}else{3079foreachmy$stylesheet(@stylesheets) {3080next unless$stylesheet;3081print'<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";3082}3083}3084if(defined$project) {3085my%href_params= get_feed_info();3086if(!exists$href_params{'-title'}) {3087$href_params{'-title'} ='log';3088}30893090foreachmy$formatqw(RSS Atom){3091my$type=lc($format);3092my%link_attr= (3093'-rel'=>'alternate',3094'-title'=>"$project-$href_params{'-title'} -$formatfeed",3095'-type'=>"application/$type+xml"3096);30973098$href_params{'action'} =$type;3099$link_attr{'-href'} = href(%href_params);3100print"<link ".3101"rel=\"$link_attr{'-rel'}\"".3102"title=\"$link_attr{'-title'}\"".3103"href=\"$link_attr{'-href'}\"".3104"type=\"$link_attr{'-type'}\"".3105"/>\n";31063107$href_params{'extra_options'} ='--no-merges';3108$link_attr{'-href'} = href(%href_params);3109$link_attr{'-title'} .=' (no merges)';3110print"<link ".3111"rel=\"$link_attr{'-rel'}\"".3112"title=\"$link_attr{'-title'}\"".3113"href=\"$link_attr{'-href'}\"".3114"type=\"$link_attr{'-type'}\"".3115"/>\n";3116}31173118}else{3119printf('<link rel="alternate" title="%sprojects list" '.3120'href="%s" type="text/plain; charset=utf-8" />'."\n",3121$site_name, href(project=>undef, action=>"project_index"));3122printf('<link rel="alternate" title="%sprojects feeds" '.3123'href="%s" type="text/x-opml" />'."\n",3124$site_name, href(project=>undef, action=>"opml"));3125}3126if(defined$favicon) {3127printqq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);3128}31293130print"</head>\n".3131"<body>\n";31323133if(-f $site_header) {3134 insert_file($site_header);3135}31363137print"<div class=\"page_header\">\n".3138$cgi->a({-href => esc_url($logo_url),3139-title =>$logo_label},3140qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));3141print$cgi->a({-href => esc_url($home_link)},$home_link_str) ." / ";3142if(defined$project) {3143print$cgi->a({-href => href(action=>"summary")}, esc_html($project));3144if(defined$action) {3145print" /$action";3146}3147print"\n";3148}3149print"</div>\n";31503151my$have_search= gitweb_check_feature('search');3152if(defined$project&&$have_search) {3153if(!defined$searchtext) {3154$searchtext="";3155}3156my$search_hash;3157if(defined$hash_base) {3158$search_hash=$hash_base;3159}elsif(defined$hash) {3160$search_hash=$hash;3161}else{3162$search_hash="HEAD";3163}3164my$action=$my_uri;3165my$use_pathinfo= gitweb_check_feature('pathinfo');3166if($use_pathinfo) {3167$action.="/".esc_url($project);3168}3169print$cgi->startform(-method=>"get", -action =>$action) .3170"<div class=\"search\">\n".3171(!$use_pathinfo&&3172$cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) ."\n") .3173$cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) ."\n".3174$cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) ."\n".3175$cgi->popup_menu(-name =>'st', -default=>'commit',3176-values=> ['commit','grep','author','committer','pickaxe']) .3177$cgi->sup($cgi->a({-href => href(action=>"search_help")},"?")) .3178" search:\n",3179$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".3180"<span title=\"Extended regular expression\">".3181$cgi->checkbox(-name =>'sr', -value =>1, -label =>'re',3182-checked =>$search_use_regexp) .3183"</span>".3184"</div>".3185$cgi->end_form() ."\n";3186}3187}31883189sub git_footer_html {3190my$feed_class='rss_logo';31913192print"<div class=\"page_footer\">\n";3193if(defined$project) {3194my$descr= git_get_project_description($project);3195if(defined$descr) {3196print"<div class=\"page_footer_text\">". esc_html($descr) ."</div>\n";3197}31983199my%href_params= get_feed_info();3200if(!%href_params) {3201$feed_class.=' generic';3202}3203$href_params{'-title'} ||='log';32043205foreachmy$formatqw(RSS Atom){3206$href_params{'action'} =lc($format);3207print$cgi->a({-href => href(%href_params),3208-title =>"$href_params{'-title'}$formatfeed",3209-class=>$feed_class},$format)."\n";3210}32113212}else{3213print$cgi->a({-href => href(project=>undef, action=>"opml"),3214-class=>$feed_class},"OPML") ." ";3215print$cgi->a({-href => href(project=>undef, action=>"project_index"),3216-class=>$feed_class},"TXT") ."\n";3217}3218print"</div>\n";# class="page_footer"32193220if(-f $site_footer) {3221 insert_file($site_footer);3222}32233224print"</body>\n".3225"</html>";3226}32273228# die_error(<http_status_code>, <error_message>)3229# Example: die_error(404, 'Hash not found')3230# By convention, use the following status codes (as defined in RFC 2616):3231# 400: Invalid or missing CGI parameters, or3232# requested object exists but has wrong type.3233# 403: Requested feature (like "pickaxe" or "snapshot") not enabled on3234# this server or project.3235# 404: Requested object/revision/project doesn't exist.3236# 500: The server isn't configured properly, or3237# an internal error occurred (e.g. failed assertions caused by bugs), or3238# an unknown error occurred (e.g. the git binary died unexpectedly).3239sub die_error {3240my$status=shift||500;3241my$error=shift||"Internal server error";32423243my%http_responses= (400=>'400 Bad Request',3244403=>'403 Forbidden',3245404=>'404 Not Found',3246500=>'500 Internal Server Error');3247 git_header_html($http_responses{$status});3248print<<EOF;3249<div class="page_body">3250<br /><br />3251$status-$error3252<br />3253</div>3254EOF3255 git_footer_html();3256exit;3257}32583259## ----------------------------------------------------------------------3260## functions printing or outputting HTML: navigation32613262sub git_print_page_nav {3263my($current,$suppress,$head,$treehead,$treebase,$extra) =@_;3264$extra=''if!defined$extra;# pager or formats32653266my@navs=qw(summary shortlog log commit commitdiff tree);3267if($suppress) {3268@navs=grep{$_ne$suppress}@navs;3269}32703271my%arg=map{$_=> {action=>$_} }@navs;3272if(defined$head) {3273for(qw(commit commitdiff)) {3274$arg{$_}{'hash'} =$head;3275}3276if($current=~m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {3277for(qw(shortlog log)) {3278$arg{$_}{'hash'} =$head;3279}3280}3281}32823283$arg{'tree'}{'hash'} =$treeheadifdefined$treehead;3284$arg{'tree'}{'hash_base'} =$treebaseifdefined$treebase;32853286my@actions= gitweb_get_feature('actions');3287my%repl= (3288'%'=>'%',3289'n'=>$project,# project name3290'f'=>$git_dir,# project path within filesystem3291'h'=>$treehead||'',# current hash ('h' parameter)3292'b'=>$treebase||'',# hash base ('hb' parameter)3293);3294while(@actions) {3295my($label,$link,$pos) =splice(@actions,0,3);3296# insert3297@navs=map{$_eq$pos? ($_,$label) :$_}@navs;3298# munch munch3299$link=~s/%([%nfhb])/$repl{$1}/g;3300$arg{$label}{'_href'} =$link;3301}33023303print"<div class=\"page_nav\">\n".3304(join" | ",3305map{$_eq$current?3306$_:$cgi->a({-href => ($arg{$_}{_href} ?$arg{$_}{_href} : href(%{$arg{$_}}))},"$_")3307}@navs);3308print"<br/>\n$extra<br/>\n".3309"</div>\n";3310}33113312sub format_paging_nav {3313my($action,$hash,$head,$page,$has_next_link) =@_;3314my$paging_nav;331533163317if($hashne$head||$page) {3318$paging_nav.=$cgi->a({-href => href(action=>$action)},"HEAD");3319}else{3320$paging_nav.="HEAD";3321}33223323if($page>0) {3324$paging_nav.=" ⋅ ".3325$cgi->a({-href => href(-replay=>1, page=>$page-1),3326-accesskey =>"p", -title =>"Alt-p"},"prev");3327}else{3328$paging_nav.=" ⋅ prev";3329}33303331if($has_next_link) {3332$paging_nav.=" ⋅ ".3333$cgi->a({-href => href(-replay=>1, page=>$page+1),3334-accesskey =>"n", -title =>"Alt-n"},"next");3335}else{3336$paging_nav.=" ⋅ next";3337}33383339return$paging_nav;3340}33413342## ......................................................................3343## functions printing or outputting HTML: div33443345sub git_print_header_div {3346my($action,$title,$hash,$hash_base) =@_;3347my%args= ();33483349$args{'action'} =$action;3350$args{'hash'} =$hashif$hash;3351$args{'hash_base'} =$hash_baseif$hash_base;33523353print"<div class=\"header\">\n".3354$cgi->a({-href => href(%args), -class=>"title"},3355$title?$title:$action) .3356"\n</div>\n";3357}33583359sub print_local_time {3360my%date=@_;3361if($date{'hour_local'} <6) {3362printf(" (<span class=\"atnight\">%02d:%02d</span>%s)",3363$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3364}else{3365printf(" (%02d:%02d%s)",3366$date{'hour_local'},$date{'minute_local'},$date{'tz_local'});3367}3368}33693370# Outputs the author name and date in long form3371sub git_print_authorship {3372my$co=shift;3373my%opts=@_;3374my$tag=$opts{-tag} ||'div';33753376my%ad= parse_date($co->{'author_epoch'},$co->{'author_tz'});3377print"<$tagclass=\"author_date\">".3378 esc_html($co->{'author_name'}) .3379" [$ad{'rfc2822'}";3380 print_local_time(%ad)if($opts{-localtime});3381print"]". git_get_avatar($co->{'author_email'}, -pad_before =>1)3382."</$tag>\n";3383}33843385# Outputs table rows containing the full author or committer information,3386# in the format expected for 'commit' view (& similia).3387# Parameters are a commit hash reference, followed by the list of people3388# to output information for. If the list is empty it defalts to both3389# author and committer.3390sub git_print_authorship_rows {3391my$co=shift;3392# too bad we can't use @people = @_ || ('author', 'committer')3393my@people=@_;3394@people= ('author','committer')unless@people;3395foreachmy$who(@people) {3396my%wd= parse_date($co->{"${who}_epoch"},$co->{"${who}_tz"});3397print"<tr><td>$who</td><td>". esc_html($co->{$who}) ."</td>".3398"<td rowspan=\"2\">".3399 git_get_avatar($co->{"${who}_email"}, -size =>'double') .3400"</td></tr>\n".3401"<tr>".3402"<td></td><td>$wd{'rfc2822'}";3403 print_local_time(%wd);3404print"</td>".3405"</tr>\n";3406}3407}34083409sub git_print_page_path {3410my$name=shift;3411my$type=shift;3412my$hb=shift;341334143415print"<div class=\"page_path\">";3416print$cgi->a({-href => href(action=>"tree", hash_base=>$hb),3417-title =>'tree root'}, to_utf8("[$project]"));3418print" / ";3419if(defined$name) {3420my@dirname=split'/',$name;3421my$basename=pop@dirname;3422my$fullname='';34233424foreachmy$dir(@dirname) {3425$fullname.= ($fullname?'/':'') .$dir;3426print$cgi->a({-href => href(action=>"tree", file_name=>$fullname,3427 hash_base=>$hb),3428-title =>$fullname}, esc_path($dir));3429print" / ";3430}3431if(defined$type&&$typeeq'blob') {3432print$cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,3433 hash_base=>$hb),3434-title =>$name}, esc_path($basename));3435}elsif(defined$type&&$typeeq'tree') {3436print$cgi->a({-href => href(action=>"tree", file_name=>$file_name,3437 hash_base=>$hb),3438-title =>$name}, esc_path($basename));3439print" / ";3440}else{3441print esc_path($basename);3442}3443}3444print"<br/></div>\n";3445}34463447sub git_print_log {3448my$log=shift;3449my%opts=@_;34503451if($opts{'-remove_title'}) {3452# remove title, i.e. first line of log3453shift@$log;3454}3455# remove leading empty lines3456while(defined$log->[0] &&$log->[0]eq"") {3457shift@$log;3458}34593460# print log3461my$signoff=0;3462my$empty=0;3463foreachmy$line(@$log) {3464if($line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {3465$signoff=1;3466$empty=0;3467if(!$opts{'-remove_signoff'}) {3468print"<span class=\"signoff\">". esc_html($line) ."</span><br/>\n";3469next;3470}else{3471# remove signoff lines3472next;3473}3474}else{3475$signoff=0;3476}34773478# print only one empty line3479# do not print empty line after signoff3480if($lineeq"") {3481next if($empty||$signoff);3482$empty=1;3483}else{3484$empty=0;3485}34863487print format_log_line_html($line) ."<br/>\n";3488}34893490if($opts{'-final_empty_line'}) {3491# end with single empty line3492print"<br/>\n"unless$empty;3493}3494}34953496# return link target (what link points to)3497sub git_get_link_target {3498my$hash=shift;3499my$link_target;35003501# read link3502open my$fd,"-|", git_cmd(),"cat-file","blob",$hash3503orreturn;3504{3505local$/=undef;3506$link_target= <$fd>;3507}3508close$fd3509orreturn;35103511return$link_target;3512}35133514# given link target, and the directory (basedir) the link is in,3515# return target of link relative to top directory (top tree);3516# return undef if it is not possible (including absolute links).3517sub normalize_link_target {3518my($link_target,$basedir) =@_;35193520# absolute symlinks (beginning with '/') cannot be normalized3521return if(substr($link_target,0,1)eq'/');35223523# normalize link target to path from top (root) tree (dir)3524my$path;3525if($basedir) {3526$path=$basedir.'/'.$link_target;3527}else{3528# we are in top (root) tree (dir)3529$path=$link_target;3530}35313532# remove //, /./, and /../3533my@path_parts;3534foreachmy$part(split('/',$path)) {3535# discard '.' and ''3536next if(!$part||$parteq'.');3537# handle '..'3538if($parteq'..') {3539if(@path_parts) {3540pop@path_parts;3541}else{3542# link leads outside repository (outside top dir)3543return;3544}3545}else{3546push@path_parts,$part;3547}3548}3549$path=join('/',@path_parts);35503551return$path;3552}35533554# print tree entry (row of git_tree), but without encompassing <tr> element3555sub git_print_tree_entry {3556my($t,$basedir,$hash_base,$have_blame) =@_;35573558my%base_key= ();3559$base_key{'hash_base'} =$hash_baseifdefined$hash_base;35603561# The format of a table row is: mode list link. Where mode is3562# the mode of the entry, list is the name of the entry, an href,3563# and link is the action links of the entry.35643565print"<td class=\"mode\">". mode_str($t->{'mode'}) ."</td>\n";3566if($t->{'type'}eq"blob") {3567print"<td class=\"list\">".3568$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3569 file_name=>"$basedir$t->{'name'}",%base_key),3570-class=>"list"}, esc_path($t->{'name'}));3571if(S_ISLNK(oct$t->{'mode'})) {3572my$link_target= git_get_link_target($t->{'hash'});3573if($link_target) {3574my$norm_target= normalize_link_target($link_target,$basedir);3575if(defined$norm_target) {3576print" -> ".3577$cgi->a({-href => href(action=>"object", hash_base=>$hash_base,3578 file_name=>$norm_target),3579-title =>$norm_target}, esc_path($link_target));3580}else{3581print" -> ". esc_path($link_target);3582}3583}3584}3585print"</td>\n";3586print"<td class=\"link\">";3587print$cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},3588 file_name=>"$basedir$t->{'name'}",%base_key)},3589"blob");3590if($have_blame) {3591print" | ".3592$cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},3593 file_name=>"$basedir$t->{'name'}",%base_key)},3594"blame");3595}3596if(defined$hash_base) {3597print" | ".3598$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,3599 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},3600"history");3601}3602print" | ".3603$cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,3604 file_name=>"$basedir$t->{'name'}")},3605"raw");3606print"</td>\n";36073608}elsif($t->{'type'}eq"tree") {3609print"<td class=\"list\">";3610print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},3611 file_name=>"$basedir$t->{'name'}",%base_key)},3612 esc_path($t->{'name'}));3613print"</td>\n";3614print"<td class=\"link\">";3615print$cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},3616 file_name=>"$basedir$t->{'name'}",%base_key)},3617"tree");3618if(defined$hash_base) {3619print" | ".3620$cgi->a({-href => href(action=>"history", hash_base=>$hash_base,3621 file_name=>"$basedir$t->{'name'}")},3622"history");3623}3624print"</td>\n";3625}else{3626# unknown object: we can only present history for it3627# (this includes 'commit' object, i.e. submodule support)3628print"<td class=\"list\">".3629 esc_path($t->{'name'}) .3630"</td>\n";3631print"<td class=\"link\">";3632if(defined$hash_base) {3633print$cgi->a({-href => href(action=>"history",3634 hash_base=>$hash_base,3635 file_name=>"$basedir$t->{'name'}")},3636"history");3637}3638print"</td>\n";3639}3640}36413642## ......................................................................3643## functions printing large fragments of HTML36443645# get pre-image filenames for merge (combined) diff3646sub fill_from_file_info {3647my($diff,@parents) =@_;36483649$diff->{'from_file'} = [ ];3650$diff->{'from_file'}[$diff->{'nparents'} -1] =undef;3651for(my$i=0;$i<$diff->{'nparents'};$i++) {3652if($diff->{'status'}[$i]eq'R'||3653$diff->{'status'}[$i]eq'C') {3654$diff->{'from_file'}[$i] =3655 git_get_path_by_hash($parents[$i],$diff->{'from_id'}[$i]);3656}3657}36583659return$diff;3660}36613662# is current raw difftree line of file deletion3663sub is_deleted {3664my$diffinfo=shift;36653666return$diffinfo->{'to_id'}eq('0' x 40);3667}36683669# does patch correspond to [previous] difftree raw line3670# $diffinfo - hashref of parsed raw diff format3671# $patchinfo - hashref of parsed patch diff format3672# (the same keys as in $diffinfo)3673sub is_patch_split {3674my($diffinfo,$patchinfo) =@_;36753676returndefined$diffinfo&&defined$patchinfo3677&&$diffinfo->{'to_file'}eq$patchinfo->{'to_file'};3678}367936803681sub git_difftree_body {3682my($difftree,$hash,@parents) =@_;3683my($parent) =$parents[0];3684my$have_blame= gitweb_check_feature('blame');3685print"<div class=\"list_head\">\n";3686if($#{$difftree} >10) {3687print(($#{$difftree} +1) ." files changed:\n");3688}3689print"</div>\n";36903691print"<table class=\"".3692(@parents>1?"combined ":"") .3693"diff_tree\">\n";36943695# header only for combined diff in 'commitdiff' view3696my$has_header=@$difftree&&@parents>1&&$actioneq'commitdiff';3697if($has_header) {3698# table header3699print"<thead><tr>\n".3700"<th></th><th></th>\n";# filename, patchN link3701for(my$i=0;$i<@parents;$i++) {3702my$par=$parents[$i];3703print"<th>".3704$cgi->a({-href => href(action=>"commitdiff",3705 hash=>$hash, hash_parent=>$par),3706-title =>'commitdiff to parent number '.3707($i+1) .': '.substr($par,0,7)},3708$i+1) .3709" </th>\n";3710}3711print"</tr></thead>\n<tbody>\n";3712}37133714my$alternate=1;3715my$patchno=0;3716foreachmy$line(@{$difftree}) {3717my$diff= parsed_difftree_line($line);37183719if($alternate) {3720print"<tr class=\"dark\">\n";3721}else{3722print"<tr class=\"light\">\n";3723}3724$alternate^=1;37253726if(exists$diff->{'nparents'}) {# combined diff37273728 fill_from_file_info($diff,@parents)3729unlessexists$diff->{'from_file'};37303731if(!is_deleted($diff)) {3732# file exists in the result (child) commit3733print"<td>".3734$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3735 file_name=>$diff->{'to_file'},3736 hash_base=>$hash),3737-class=>"list"}, esc_path($diff->{'to_file'})) .3738"</td>\n";3739}else{3740print"<td>".3741 esc_path($diff->{'to_file'}) .3742"</td>\n";3743}37443745if($actioneq'commitdiff') {3746# link to patch3747$patchno++;3748print"<td class=\"link\">".3749$cgi->a({-href =>"#patch$patchno"},"patch") .3750" | ".3751"</td>\n";3752}37533754my$has_history=0;3755my$not_deleted=0;3756for(my$i=0;$i<$diff->{'nparents'};$i++) {3757my$hash_parent=$parents[$i];3758my$from_hash=$diff->{'from_id'}[$i];3759my$from_path=$diff->{'from_file'}[$i];3760my$status=$diff->{'status'}[$i];37613762$has_history||= ($statusne'A');3763$not_deleted||= ($statusne'D');37643765if($statuseq'A') {3766print"<td class=\"link\"align=\"right\"> | </td>\n";3767}elsif($statuseq'D') {3768print"<td class=\"link\">".3769$cgi->a({-href => href(action=>"blob",3770 hash_base=>$hash,3771 hash=>$from_hash,3772 file_name=>$from_path)},3773"blob". ($i+1)) .3774" | </td>\n";3775}else{3776if($diff->{'to_id'}eq$from_hash) {3777print"<td class=\"link nochange\">";3778}else{3779print"<td class=\"link\">";3780}3781print$cgi->a({-href => href(action=>"blobdiff",3782 hash=>$diff->{'to_id'},3783 hash_parent=>$from_hash,3784 hash_base=>$hash,3785 hash_parent_base=>$hash_parent,3786 file_name=>$diff->{'to_file'},3787 file_parent=>$from_path)},3788"diff". ($i+1)) .3789" | </td>\n";3790}3791}37923793print"<td class=\"link\">";3794if($not_deleted) {3795print$cgi->a({-href => href(action=>"blob",3796 hash=>$diff->{'to_id'},3797 file_name=>$diff->{'to_file'},3798 hash_base=>$hash)},3799"blob");3800print" | "if($has_history);3801}3802if($has_history) {3803print$cgi->a({-href => href(action=>"history",3804 file_name=>$diff->{'to_file'},3805 hash_base=>$hash)},3806"history");3807}3808print"</td>\n";38093810print"</tr>\n";3811next;# instead of 'else' clause, to avoid extra indent3812}3813# else ordinary diff38143815my($to_mode_oct,$to_mode_str,$to_file_type);3816my($from_mode_oct,$from_mode_str,$from_file_type);3817if($diff->{'to_mode'}ne('0' x 6)) {3818$to_mode_oct=oct$diff->{'to_mode'};3819if(S_ISREG($to_mode_oct)) {# only for regular file3820$to_mode_str=sprintf("%04o",$to_mode_oct&0777);# permission bits3821}3822$to_file_type= file_type($diff->{'to_mode'});3823}3824if($diff->{'from_mode'}ne('0' x 6)) {3825$from_mode_oct=oct$diff->{'from_mode'};3826if(S_ISREG($to_mode_oct)) {# only for regular file3827$from_mode_str=sprintf("%04o",$from_mode_oct&0777);# permission bits3828}3829$from_file_type= file_type($diff->{'from_mode'});3830}38313832if($diff->{'status'}eq"A") {# created3833my$mode_chng="<span class=\"file_status new\">[new$to_file_type";3834$mode_chng.=" with mode:$to_mode_str"if$to_mode_str;3835$mode_chng.="]</span>";3836print"<td>";3837print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3838 hash_base=>$hash, file_name=>$diff->{'file'}),3839-class=>"list"}, esc_path($diff->{'file'}));3840print"</td>\n";3841print"<td>$mode_chng</td>\n";3842print"<td class=\"link\">";3843if($actioneq'commitdiff') {3844# link to patch3845$patchno++;3846print$cgi->a({-href =>"#patch$patchno"},"patch");3847print" | ";3848}3849print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3850 hash_base=>$hash, file_name=>$diff->{'file'})},3851"blob");3852print"</td>\n";38533854}elsif($diff->{'status'}eq"D") {# deleted3855my$mode_chng="<span class=\"file_status deleted\">[deleted$from_file_type]</span>";3856print"<td>";3857print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},3858 hash_base=>$parent, file_name=>$diff->{'file'}),3859-class=>"list"}, esc_path($diff->{'file'}));3860print"</td>\n";3861print"<td>$mode_chng</td>\n";3862print"<td class=\"link\">";3863if($actioneq'commitdiff') {3864# link to patch3865$patchno++;3866print$cgi->a({-href =>"#patch$patchno"},"patch");3867print" | ";3868}3869print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},3870 hash_base=>$parent, file_name=>$diff->{'file'})},3871"blob") ." | ";3872if($have_blame) {3873print$cgi->a({-href => href(action=>"blame", hash_base=>$parent,3874 file_name=>$diff->{'file'})},3875"blame") ." | ";3876}3877print$cgi->a({-href => href(action=>"history", hash_base=>$parent,3878 file_name=>$diff->{'file'})},3879"history");3880print"</td>\n";38813882}elsif($diff->{'status'}eq"M"||$diff->{'status'}eq"T") {# modified, or type changed3883my$mode_chnge="";3884if($diff->{'from_mode'} !=$diff->{'to_mode'}) {3885$mode_chnge="<span class=\"file_status mode_chnge\">[changed";3886if($from_file_typene$to_file_type) {3887$mode_chnge.=" from$from_file_typeto$to_file_type";3888}3889if(($from_mode_oct&0777) != ($to_mode_oct&0777)) {3890if($from_mode_str&&$to_mode_str) {3891$mode_chnge.=" mode:$from_mode_str->$to_mode_str";3892}elsif($to_mode_str) {3893$mode_chnge.=" mode:$to_mode_str";3894}3895}3896$mode_chnge.="]</span>\n";3897}3898print"<td>";3899print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3900 hash_base=>$hash, file_name=>$diff->{'file'}),3901-class=>"list"}, esc_path($diff->{'file'}));3902print"</td>\n";3903print"<td>$mode_chnge</td>\n";3904print"<td class=\"link\">";3905if($actioneq'commitdiff') {3906# link to patch3907$patchno++;3908print$cgi->a({-href =>"#patch$patchno"},"patch") .3909" | ";3910}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {3911# "commit" view and modified file (not onlu mode changed)3912print$cgi->a({-href => href(action=>"blobdiff",3913 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},3914 hash_base=>$hash, hash_parent_base=>$parent,3915 file_name=>$diff->{'file'})},3916"diff") .3917" | ";3918}3919print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3920 hash_base=>$hash, file_name=>$diff->{'file'})},3921"blob") ." | ";3922if($have_blame) {3923print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,3924 file_name=>$diff->{'file'})},3925"blame") ." | ";3926}3927print$cgi->a({-href => href(action=>"history", hash_base=>$hash,3928 file_name=>$diff->{'file'})},3929"history");3930print"</td>\n";39313932}elsif($diff->{'status'}eq"R"||$diff->{'status'}eq"C") {# renamed or copied3933my%status_name= ('R'=>'moved','C'=>'copied');3934my$nstatus=$status_name{$diff->{'status'}};3935my$mode_chng="";3936if($diff->{'from_mode'} !=$diff->{'to_mode'}) {3937# mode also for directories, so we cannot use $to_mode_str3938$mode_chng=sprintf(", mode:%04o",$to_mode_oct&0777);3939}3940print"<td>".3941$cgi->a({-href => href(action=>"blob", hash_base=>$hash,3942 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),3943-class=>"list"}, esc_path($diff->{'to_file'})) ."</td>\n".3944"<td><span class=\"file_status$nstatus\">[$nstatusfrom ".3945$cgi->a({-href => href(action=>"blob", hash_base=>$parent,3946 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),3947-class=>"list"}, esc_path($diff->{'from_file'})) .3948" with ". (int$diff->{'similarity'}) ."% similarity$mode_chng]</span></td>\n".3949"<td class=\"link\">";3950if($actioneq'commitdiff') {3951# link to patch3952$patchno++;3953print$cgi->a({-href =>"#patch$patchno"},"patch") .3954" | ";3955}elsif($diff->{'to_id'}ne$diff->{'from_id'}) {3956# "commit" view and modified file (not only pure rename or copy)3957print$cgi->a({-href => href(action=>"blobdiff",3958 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},3959 hash_base=>$hash, hash_parent_base=>$parent,3960 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},3961"diff") .3962" | ";3963}3964print$cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},3965 hash_base=>$parent, file_name=>$diff->{'to_file'})},3966"blob") ." | ";3967if($have_blame) {3968print$cgi->a({-href => href(action=>"blame", hash_base=>$hash,3969 file_name=>$diff->{'to_file'})},3970"blame") ." | ";3971}3972print$cgi->a({-href => href(action=>"history", hash_base=>$hash,3973 file_name=>$diff->{'to_file'})},3974"history");3975print"</td>\n";39763977}# we should not encounter Unmerged (U) or Unknown (X) status3978print"</tr>\n";3979}3980print"</tbody>"if$has_header;3981print"</table>\n";3982}39833984sub git_patchset_body {3985my($fd,$difftree,$hash,@hash_parents) =@_;3986my($hash_parent) =$hash_parents[0];39873988my$is_combined= (@hash_parents>1);3989my$patch_idx=0;3990my$patch_number=0;3991my$patch_line;3992my$diffinfo;3993my$to_name;3994my(%from,%to);39953996print"<div class=\"patchset\">\n";39973998# skip to first patch3999while($patch_line= <$fd>) {4000chomp$patch_line;40014002last if($patch_line=~m/^diff /);4003}40044005 PATCH:4006while($patch_line) {40074008# parse "git diff" header line4009if($patch_line=~m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {4010# $1 is from_name, which we do not use4011$to_name= unquote($2);4012$to_name=~s!^b/!!;4013}elsif($patch_line=~m/^diff --(cc|combined) ("?.*"?)$/) {4014# $1 is 'cc' or 'combined', which we do not use4015$to_name= unquote($2);4016}else{4017$to_name=undef;4018}40194020# check if current patch belong to current raw line4021# and parse raw git-diff line if needed4022if(is_patch_split($diffinfo, {'to_file'=>$to_name})) {4023# this is continuation of a split patch4024print"<div class=\"patch cont\">\n";4025}else{4026# advance raw git-diff output if needed4027$patch_idx++ifdefined$diffinfo;40284029# read and prepare patch information4030$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);40314032# compact combined diff output can have some patches skipped4033# find which patch (using pathname of result) we are at now;4034if($is_combined) {4035while($to_namene$diffinfo->{'to_file'}) {4036print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4037 format_diff_cc_simplified($diffinfo,@hash_parents) .4038"</div>\n";# class="patch"40394040$patch_idx++;4041$patch_number++;40424043last if$patch_idx>$#$difftree;4044$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);4045}4046}40474048# modifies %from, %to hashes4049 parse_from_to_diffinfo($diffinfo, \%from, \%to,@hash_parents);40504051# this is first patch for raw difftree line with $patch_idx index4052# we index @$difftree array from 0, but number patches from 14053print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n";4054}40554056# git diff header4057#assert($patch_line =~ m/^diff /) if DEBUG;4058#assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed4059$patch_number++;4060# print "git diff" header4061print format_git_diff_header_line($patch_line,$diffinfo,4062 \%from, \%to);40634064# print extended diff header4065print"<div class=\"diff extended_header\">\n";4066 EXTENDED_HEADER:4067while($patch_line= <$fd>) {4068chomp$patch_line;40694070last EXTENDED_HEADER if($patch_line=~m/^--- |^diff /);40714072print format_extended_diff_header_line($patch_line,$diffinfo,4073 \%from, \%to);4074}4075print"</div>\n";# class="diff extended_header"40764077# from-file/to-file diff header4078if(!$patch_line) {4079print"</div>\n";# class="patch"4080last PATCH;4081}4082next PATCH if($patch_line=~m/^diff /);4083#assert($patch_line =~ m/^---/) if DEBUG;40844085my$last_patch_line=$patch_line;4086$patch_line= <$fd>;4087chomp$patch_line;4088#assert($patch_line =~ m/^\+\+\+/) if DEBUG;40894090print format_diff_from_to_header($last_patch_line,$patch_line,4091$diffinfo, \%from, \%to,4092@hash_parents);40934094# the patch itself4095 LINE:4096while($patch_line= <$fd>) {4097chomp$patch_line;40984099next PATCH if($patch_line=~m/^diff /);41004101print format_diff_line($patch_line, \%from, \%to);4102}41034104}continue{4105print"</div>\n";# class="patch"4106}41074108# for compact combined (--cc) format, with chunk and patch simpliciaction4109# patchset might be empty, but there might be unprocessed raw lines4110for(++$patch_idxif$patch_number>0;4111$patch_idx<@$difftree;4112++$patch_idx) {4113# read and prepare patch information4114$diffinfo= parsed_difftree_line($difftree->[$patch_idx]);41154116# generate anchor for "patch" links in difftree / whatchanged part4117print"<div class=\"patch\"id=\"patch". ($patch_idx+1) ."\">\n".4118 format_diff_cc_simplified($diffinfo,@hash_parents) .4119"</div>\n";# class="patch"41204121$patch_number++;4122}41234124if($patch_number==0) {4125if(@hash_parents>1) {4126print"<div class=\"diff nodifferences\">Trivial merge</div>\n";4127}else{4128print"<div class=\"diff nodifferences\">No differences found</div>\n";4129}4130}41314132print"</div>\n";# class="patchset"4133}41344135# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41364137# fills project list info (age, description, owner, forks) for each4138# project in the list, removing invalid projects from returned list4139# NOTE: modifies $projlist, but does not remove entries from it4140sub fill_project_list_info {4141my($projlist,$check_forks) =@_;4142my@projects;41434144my$show_ctags= gitweb_check_feature('ctags');4145 PROJECT:4146foreachmy$pr(@$projlist) {4147my(@activity) = git_get_last_activity($pr->{'path'});4148unless(@activity) {4149next PROJECT;4150}4151($pr->{'age'},$pr->{'age_string'}) =@activity;4152if(!defined$pr->{'descr'}) {4153my$descr= git_get_project_description($pr->{'path'}) ||"";4154$descr= to_utf8($descr);4155$pr->{'descr_long'} =$descr;4156$pr->{'descr'} = chop_str($descr,$projects_list_description_width,5);4157}4158if(!defined$pr->{'owner'}) {4159$pr->{'owner'} = git_get_project_owner("$pr->{'path'}") ||"";4160}4161if($check_forks) {4162my$pname=$pr->{'path'};4163if(($pname=~s/\.git$//) &&4164($pname!~/\/$/) &&4165(-d "$projectroot/$pname")) {4166$pr->{'forks'} ="-d$projectroot/$pname";4167}else{4168$pr->{'forks'} =0;4169}4170}4171$show_ctagsand$pr->{'ctags'} = git_get_project_ctags($pr->{'path'});4172push@projects,$pr;4173}41744175return@projects;4176}41774178# print 'sort by' <th> element, generating 'sort by $name' replay link4179# if that order is not selected4180sub print_sort_th {4181my($name,$order,$header) =@_;4182$header||=ucfirst($name);41834184if($ordereq$name) {4185print"<th>$header</th>\n";4186}else{4187print"<th>".4188$cgi->a({-href => href(-replay=>1, order=>$name),4189-class=>"header"},$header) .4190"</th>\n";4191}4192}41934194sub git_project_list_body {4195# actually uses global variable $project4196my($projlist,$order,$from,$to,$extra,$no_header) =@_;41974198my$check_forks= gitweb_check_feature('forks');4199my@projects= fill_project_list_info($projlist,$check_forks);42004201$order||=$default_projects_order;4202$from=0unlessdefined$from;4203$to=$#projectsif(!defined$to||$#projects<$to);42044205my%order_info= (4206 project => { key =>'path', type =>'str'},4207 descr => { key =>'descr_long', type =>'str'},4208 owner => { key =>'owner', type =>'str'},4209 age => { key =>'age', type =>'num'}4210);4211my$oi=$order_info{$order};4212if($oi->{'type'}eq'str') {4213@projects=sort{$a->{$oi->{'key'}}cmp$b->{$oi->{'key'}}}@projects;4214}else{4215@projects=sort{$a->{$oi->{'key'}} <=>$b->{$oi->{'key'}}}@projects;4216}42174218my$show_ctags= gitweb_check_feature('ctags');4219if($show_ctags) {4220my%ctags;4221foreachmy$p(@projects) {4222foreachmy$ct(keys%{$p->{'ctags'}}) {4223$ctags{$ct} +=$p->{'ctags'}->{$ct};4224}4225}4226my$cloud= git_populate_project_tagcloud(\%ctags);4227print git_show_project_tagcloud($cloud,64);4228}42294230print"<table class=\"project_list\">\n";4231unless($no_header) {4232print"<tr>\n";4233if($check_forks) {4234print"<th></th>\n";4235}4236 print_sort_th('project',$order,'Project');4237 print_sort_th('descr',$order,'Description');4238 print_sort_th('owner',$order,'Owner');4239 print_sort_th('age',$order,'Last Change');4240print"<th></th>\n".# for links4241"</tr>\n";4242}4243my$alternate=1;4244my$tagfilter=$cgi->param('by_tag');4245for(my$i=$from;$i<=$to;$i++) {4246my$pr=$projects[$i];42474248next if$tagfilterand$show_ctagsand not grep{lc$_eq lc$tagfilter}keys%{$pr->{'ctags'}};4249next if$searchtextand not$pr->{'path'} =~/$searchtext/4250and not$pr->{'descr_long'} =~/$searchtext/;4251# Weed out forks or non-matching entries of search4252if($check_forks) {4253my$forkbase=$project;$forkbase||='';$forkbase=~ s#\.git$#/#;4254$forkbase="^$forkbase"if$forkbase;4255next ifnot$searchtextand not$tagfilterand$show_ctags4256and$pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe4257}42584259if($alternate) {4260print"<tr class=\"dark\">\n";4261}else{4262print"<tr class=\"light\">\n";4263}4264$alternate^=1;4265if($check_forks) {4266print"<td>";4267if($pr->{'forks'}) {4268print"<!--$pr->{'forks'} -->\n";4269print$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"+");4270}4271print"</td>\n";4272}4273print"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4274-class=>"list"}, esc_html($pr->{'path'})) ."</td>\n".4275"<td>".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),4276-class=>"list", -title =>$pr->{'descr_long'}},4277 esc_html($pr->{'descr'})) ."</td>\n".4278"<td><i>". chop_and_escape_str($pr->{'owner'},15) ."</i></td>\n";4279print"<td class=\"". age_class($pr->{'age'}) ."\">".4280(defined$pr->{'age_string'} ?$pr->{'age_string'} :"No commits") ."</td>\n".4281"<td class=\"link\">".4282$cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")},"summary") ." | ".4283$cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")},"shortlog") ." | ".4284$cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")},"log") ." | ".4285$cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")},"tree") .4286($pr->{'forks'} ?" | ".$cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")},"forks") :'') .4287"</td>\n".4288"</tr>\n";4289}4290if(defined$extra) {4291print"<tr>\n";4292if($check_forks) {4293print"<td></td>\n";4294}4295print"<td colspan=\"5\">$extra</td>\n".4296"</tr>\n";4297}4298print"</table>\n";4299}43004301sub git_shortlog_body {4302# uses global variable $project4303my($commitlist,$from,$to,$refs,$extra) =@_;43044305$from=0unlessdefined$from;4306$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);43074308print"<table class=\"shortlog\">\n";4309my$alternate=1;4310for(my$i=$from;$i<=$to;$i++) {4311my%co= %{$commitlist->[$i]};4312my$commit=$co{'id'};4313my$ref= format_ref_marker($refs,$commit);4314if($alternate) {4315print"<tr class=\"dark\">\n";4316}else{4317print"<tr class=\"light\">\n";4318}4319$alternate^=1;4320# git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .4321print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4322 format_author_html('td', \%co,10) ."<td>";4323print format_subject_html($co{'title'},$co{'title_short'},4324 href(action=>"commit", hash=>$commit),$ref);4325print"</td>\n".4326"<td class=\"link\">".4327$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") ." | ".4328$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") ." | ".4329$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree");4330my$snapshot_links= format_snapshot_links($commit);4331if(defined$snapshot_links) {4332print" | ".$snapshot_links;4333}4334print"</td>\n".4335"</tr>\n";4336}4337if(defined$extra) {4338print"<tr>\n".4339"<td colspan=\"4\">$extra</td>\n".4340"</tr>\n";4341}4342print"</table>\n";4343}43444345sub git_history_body {4346# Warning: assumes constant type (blob or tree) during history4347my($commitlist,$from,$to,$refs,$hash_base,$ftype,$extra) =@_;43484349$from=0unlessdefined$from;4350$to=$#{$commitlist}unless(defined$to&&$to<=$#{$commitlist});43514352print"<table class=\"history\">\n";4353my$alternate=1;4354for(my$i=$from;$i<=$to;$i++) {4355my%co= %{$commitlist->[$i]};4356if(!%co) {4357next;4358}4359my$commit=$co{'id'};43604361my$ref= format_ref_marker($refs,$commit);43624363if($alternate) {4364print"<tr class=\"dark\">\n";4365}else{4366print"<tr class=\"light\">\n";4367}4368$alternate^=1;4369print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4370# shortlog: format_author_html('td', \%co, 10)4371 format_author_html('td', \%co,15,3) ."<td>";4372# originally git_history used chop_str($co{'title'}, 50)4373print format_subject_html($co{'title'},$co{'title_short'},4374 href(action=>"commit", hash=>$commit),$ref);4375print"</td>\n".4376"<td class=\"link\">".4377$cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)},$ftype) ." | ".4378$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff");43794380if($ftypeeq'blob') {4381my$blob_current= git_get_hash_by_path($hash_base,$file_name);4382my$blob_parent= git_get_hash_by_path($commit,$file_name);4383if(defined$blob_current&&defined$blob_parent&&4384$blob_currentne$blob_parent) {4385print" | ".4386$cgi->a({-href => href(action=>"blobdiff",4387 hash=>$blob_current, hash_parent=>$blob_parent,4388 hash_base=>$hash_base, hash_parent_base=>$commit,4389 file_name=>$file_name)},4390"diff to current");4391}4392}4393print"</td>\n".4394"</tr>\n";4395}4396if(defined$extra) {4397print"<tr>\n".4398"<td colspan=\"4\">$extra</td>\n".4399"</tr>\n";4400}4401print"</table>\n";4402}44034404sub git_tags_body {4405# uses global variable $project4406my($taglist,$from,$to,$extra) =@_;4407$from=0unlessdefined$from;4408$to=$#{$taglist}if(!defined$to||$#{$taglist} <$to);44094410print"<table class=\"tags\">\n";4411my$alternate=1;4412for(my$i=$from;$i<=$to;$i++) {4413my$entry=$taglist->[$i];4414my%tag=%$entry;4415my$comment=$tag{'subject'};4416my$comment_short;4417if(defined$comment) {4418$comment_short= chop_str($comment,30,5);4419}4420if($alternate) {4421print"<tr class=\"dark\">\n";4422}else{4423print"<tr class=\"light\">\n";4424}4425$alternate^=1;4426if(defined$tag{'age'}) {4427print"<td><i>$tag{'age'}</i></td>\n";4428}else{4429print"<td></td>\n";4430}4431print"<td>".4432$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),4433-class=>"list name"}, esc_html($tag{'name'})) .4434"</td>\n".4435"<td>";4436if(defined$comment) {4437print format_subject_html($comment,$comment_short,4438 href(action=>"tag", hash=>$tag{'id'}));4439}4440print"</td>\n".4441"<td class=\"selflink\">";4442if($tag{'type'}eq"tag") {4443print$cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})},"tag");4444}else{4445print" ";4446}4447print"</td>\n".4448"<td class=\"link\">"." | ".4449$cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})},$tag{'reftype'});4450if($tag{'reftype'}eq"commit") {4451print" | ".$cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})},"shortlog") .4452" | ".$cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})},"log");4453}elsif($tag{'reftype'}eq"blob") {4454print" | ".$cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})},"raw");4455}4456print"</td>\n".4457"</tr>";4458}4459if(defined$extra) {4460print"<tr>\n".4461"<td colspan=\"5\">$extra</td>\n".4462"</tr>\n";4463}4464print"</table>\n";4465}44664467sub git_heads_body {4468# uses global variable $project4469my($headlist,$head,$from,$to,$extra) =@_;4470$from=0unlessdefined$from;4471$to=$#{$headlist}if(!defined$to||$#{$headlist} <$to);44724473print"<table class=\"heads\">\n";4474my$alternate=1;4475for(my$i=$from;$i<=$to;$i++) {4476my$entry=$headlist->[$i];4477my%ref=%$entry;4478my$curr=$ref{'id'}eq$head;4479if($alternate) {4480print"<tr class=\"dark\">\n";4481}else{4482print"<tr class=\"light\">\n";4483}4484$alternate^=1;4485print"<td><i>$ref{'age'}</i></td>\n".4486($curr?"<td class=\"current_head\">":"<td>") .4487$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),4488-class=>"list name"},esc_html($ref{'name'})) .4489"</td>\n".4490"<td class=\"link\">".4491$cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})},"shortlog") ." | ".4492$cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})},"log") ." | ".4493$cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})},"tree") .4494"</td>\n".4495"</tr>";4496}4497if(defined$extra) {4498print"<tr>\n".4499"<td colspan=\"3\">$extra</td>\n".4500"</tr>\n";4501}4502print"</table>\n";4503}45044505sub git_search_grep_body {4506my($commitlist,$from,$to,$extra) =@_;4507$from=0unlessdefined$from;4508$to=$#{$commitlist}if(!defined$to||$#{$commitlist} <$to);45094510print"<table class=\"commit_search\">\n";4511my$alternate=1;4512for(my$i=$from;$i<=$to;$i++) {4513my%co= %{$commitlist->[$i]};4514if(!%co) {4515next;4516}4517my$commit=$co{'id'};4518if($alternate) {4519print"<tr class=\"dark\">\n";4520}else{4521print"<tr class=\"light\">\n";4522}4523$alternate^=1;4524print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".4525 format_author_html('td', \%co,15,5) .4526"<td>".4527$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),4528-class=>"list subject"},4529 chop_and_escape_str($co{'title'},50) ."<br/>");4530my$comment=$co{'comment'};4531foreachmy$line(@$comment) {4532if($line=~m/^(.*?)($search_regexp)(.*)$/i) {4533my($lead,$match,$trail) = ($1,$2,$3);4534$match= chop_str($match,70,5,'center');4535my$contextlen=int((80-length($match))/2);4536$contextlen=30if($contextlen>30);4537$lead= chop_str($lead,$contextlen,10,'left');4538$trail= chop_str($trail,$contextlen,10,'right');45394540$lead= esc_html($lead);4541$match= esc_html($match);4542$trail= esc_html($trail);45434544print"$lead<span class=\"match\">$match</span>$trail<br />";4545}4546}4547print"</td>\n".4548"<td class=\"link\">".4549$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .4550" | ".4551$cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})},"commitdiff") .4552" | ".4553$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");4554print"</td>\n".4555"</tr>\n";4556}4557if(defined$extra) {4558print"<tr>\n".4559"<td colspan=\"3\">$extra</td>\n".4560"</tr>\n";4561}4562print"</table>\n";4563}45644565## ======================================================================4566## ======================================================================4567## actions45684569sub git_project_list {4570my$order=$input_params{'order'};4571if(defined$order&&$order!~m/none|project|descr|owner|age/) {4572 die_error(400,"Unknown order parameter");4573}45744575my@list= git_get_projects_list();4576if(!@list) {4577 die_error(404,"No projects found");4578}45794580 git_header_html();4581if(-f $home_text) {4582print"<div class=\"index_include\">\n";4583 insert_file($home_text);4584print"</div>\n";4585}4586print$cgi->startform(-method=>"get") .4587"<p class=\"projsearch\">Search:\n".4588$cgi->textfield(-name =>"s", -value =>$searchtext) ."\n".4589"</p>".4590$cgi->end_form() ."\n";4591 git_project_list_body(\@list,$order);4592 git_footer_html();4593}45944595sub git_forks {4596my$order=$input_params{'order'};4597if(defined$order&&$order!~m/none|project|descr|owner|age/) {4598 die_error(400,"Unknown order parameter");4599}46004601my@list= git_get_projects_list($project);4602if(!@list) {4603 die_error(404,"No forks found");4604}46054606 git_header_html();4607 git_print_page_nav('','');4608 git_print_header_div('summary',"$projectforks");4609 git_project_list_body(\@list,$order);4610 git_footer_html();4611}46124613sub git_project_index {4614my@projects= git_get_projects_list($project);46154616print$cgi->header(4617-type =>'text/plain',4618-charset =>'utf-8',4619-content_disposition =>'inline; filename="index.aux"');46204621foreachmy$pr(@projects) {4622if(!exists$pr->{'owner'}) {4623$pr->{'owner'} = git_get_project_owner("$pr->{'path'}");4624}46254626my($path,$owner) = ($pr->{'path'},$pr->{'owner'});4627# quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '4628$path=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;4629$owner=~s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X",ord($1))/eg;4630$path=~s/ /\+/g;4631$owner=~s/ /\+/g;46324633print"$path$owner\n";4634}4635}46364637sub git_summary {4638my$descr= git_get_project_description($project) ||"none";4639my%co= parse_commit("HEAD");4640my%cd=%co? parse_date($co{'committer_epoch'},$co{'committer_tz'}) : ();4641my$head=$co{'id'};46424643my$owner= git_get_project_owner($project);46444645my$refs= git_get_references();4646# These get_*_list functions return one more to allow us to see if4647# there are more ...4648my@taglist= git_get_tags_list(16);4649my@headlist= git_get_heads_list(16);4650my@forklist;4651my$check_forks= gitweb_check_feature('forks');46524653if($check_forks) {4654@forklist= git_get_projects_list($project);4655}46564657 git_header_html();4658 git_print_page_nav('summary','',$head);46594660print"<div class=\"title\"> </div>\n";4661print"<table class=\"projects_list\">\n".4662"<tr id=\"metadata_desc\"><td>description</td><td>". esc_html($descr) ."</td></tr>\n".4663"<tr id=\"metadata_owner\"><td>owner</td><td>". esc_html($owner) ."</td></tr>\n";4664if(defined$cd{'rfc2822'}) {4665print"<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";4666}46674668# use per project git URL list in $projectroot/$project/cloneurl4669# or make project git URL from git base URL and project name4670my$url_tag="URL";4671my@url_list= git_get_project_url_list($project);4672@url_list=map{"$_/$project"}@git_base_url_listunless@url_list;4673foreachmy$git_url(@url_list) {4674next unless$git_url;4675print"<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";4676$url_tag="";4677}46784679# Tag cloud4680my$show_ctags= gitweb_check_feature('ctags');4681if($show_ctags) {4682my$ctags= git_get_project_ctags($project);4683my$cloud= git_populate_project_tagcloud($ctags);4684print"<tr id=\"metadata_ctags\"><td>Content tags:<br />";4685print"</td>\n<td>"unless%$ctags;4686print"<form action=\"$show_ctags\"method=\"post\"><input type=\"hidden\"name=\"p\"value=\"$project\"/>Add: <input type=\"text\"name=\"t\"size=\"8\"/></form>";4687print"</td>\n<td>"if%$ctags;4688print git_show_project_tagcloud($cloud,48);4689print"</td></tr>";4690}46914692print"</table>\n";46934694# If XSS prevention is on, we don't include README.html.4695# TODO: Allow a readme in some safe format.4696if(!$prevent_xss&& -s "$projectroot/$project/README.html") {4697print"<div class=\"title\">readme</div>\n".4698"<div class=\"readme\">\n";4699 insert_file("$projectroot/$project/README.html");4700print"\n</div>\n";# class="readme"4701}47024703# we need to request one more than 16 (0..15) to check if4704# those 16 are all4705my@commitlist=$head? parse_commits($head,17) : ();4706if(@commitlist) {4707 git_print_header_div('shortlog');4708 git_shortlog_body(\@commitlist,0,15,$refs,4709$#commitlist<=15?undef:4710$cgi->a({-href => href(action=>"shortlog")},"..."));4711}47124713if(@taglist) {4714 git_print_header_div('tags');4715 git_tags_body(\@taglist,0,15,4716$#taglist<=15?undef:4717$cgi->a({-href => href(action=>"tags")},"..."));4718}47194720if(@headlist) {4721 git_print_header_div('heads');4722 git_heads_body(\@headlist,$head,0,15,4723$#headlist<=15?undef:4724$cgi->a({-href => href(action=>"heads")},"..."));4725}47264727if(@forklist) {4728 git_print_header_div('forks');4729 git_project_list_body(\@forklist,'age',0,15,4730$#forklist<=15?undef:4731$cgi->a({-href => href(action=>"forks")},"..."),4732'no_header');4733}47344735 git_footer_html();4736}47374738sub git_tag {4739my$head= git_get_head_hash($project);4740 git_header_html();4741 git_print_page_nav('','',$head,undef,$head);4742my%tag= parse_tag($hash);47434744if(!%tag) {4745 die_error(404,"Unknown tag object");4746}47474748 git_print_header_div('commit', esc_html($tag{'name'}),$hash);4749print"<div class=\"title_text\">\n".4750"<table class=\"object_header\">\n".4751"<tr>\n".4752"<td>object</td>\n".4753"<td>".$cgi->a({-class=>"list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},4754$tag{'object'}) ."</td>\n".4755"<td class=\"link\">".$cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},4756$tag{'type'}) ."</td>\n".4757"</tr>\n";4758if(defined($tag{'author'})) {4759 git_print_authorship_rows(\%tag,'author');4760}4761print"</table>\n\n".4762"</div>\n";4763print"<div class=\"page_body\">";4764my$comment=$tag{'comment'};4765foreachmy$line(@$comment) {4766chomp$line;4767print esc_html($line, -nbsp=>1) ."<br/>\n";4768}4769print"</div>\n";4770 git_footer_html();4771}47724773sub git_blame {4774# permissions4775 gitweb_check_feature('blame')4776or die_error(403,"Blame view not allowed");47774778# error checking4779 die_error(400,"No file name given")unless$file_name;4780$hash_base||= git_get_head_hash($project);4781 die_error(404,"Couldn't find base commit")unless$hash_base;4782my%co= parse_commit($hash_base)4783or die_error(404,"Commit not found");4784my$ftype="blob";4785if(!defined$hash) {4786$hash= git_get_hash_by_path($hash_base,$file_name,"blob")4787or die_error(404,"Error looking up file");4788}else{4789$ftype= git_get_type($hash);4790if($ftype!~"blob") {4791 die_error(400,"Object is not a blob");4792}4793}47944795# run git-blame --porcelain4796open my$fd,"-|", git_cmd(),"blame",'-p',4797$hash_base,'--',$file_name4798or die_error(500,"Open git-blame failed");47994800# page header4801 git_header_html();4802my$formats_nav=4803$cgi->a({-href => href(action=>"blob", -replay=>1)},4804"blob") .4805" | ".4806$cgi->a({-href => href(action=>"history", -replay=>1)},4807"history") .4808" | ".4809$cgi->a({-href => href(action=>"blame", file_name=>$file_name)},4810"HEAD");4811 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);4812 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);4813 git_print_page_path($file_name,$ftype,$hash_base);48144815# page body4816my@rev_color=qw(light dark);4817my$num_colors=scalar(@rev_color);4818my$current_color=0;4819my%metainfo= ();48204821print<<HTML;4822<div class="page_body">4823<table class="blame">4824<tr><th>Commit</th><th>Line</th><th>Data</th></tr>4825HTML4826 LINE:4827while(my$line= <$fd>) {4828chomp$line;4829# the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]4830# no <lines in group> for subsequent lines in group of lines4831my($full_rev,$orig_lineno,$lineno,$group_size) =4832($line=~/^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);4833if(!exists$metainfo{$full_rev}) {4834$metainfo{$full_rev} = {'nprevious'=>0};4835}4836my$meta=$metainfo{$full_rev};4837my$data;4838while($data= <$fd>) {4839chomp$data;4840last if($data=~s/^\t//);# contents of line4841if($data=~/^(\S+)(?: (.*))?$/) {4842$meta->{$1} =$2unlessexists$meta->{$1};4843}4844if($data=~/^previous /) {4845$meta->{'nprevious'}++;4846}4847}4848my$short_rev=substr($full_rev,0,8);4849my$author=$meta->{'author'};4850my%date=4851 parse_date($meta->{'author-time'},$meta->{'author-tz'});4852my$date=$date{'iso-tz'};4853if($group_size) {4854$current_color= ($current_color+1) %$num_colors;4855}4856my$tr_class=$rev_color[$current_color];4857$tr_class.=' boundary'if(exists$meta->{'boundary'});4858$tr_class.=' no-previous'if($meta->{'nprevious'} ==0);4859$tr_class.=' multiple-previous'if($meta->{'nprevious'} >1);4860print"<tr id=\"l$lineno\"class=\"$tr_class\">\n";4861if($group_size) {4862print"<td class=\"sha1\"";4863print" title=\"". esc_html($author) .",$date\"";4864print" rowspan=\"$group_size\""if($group_size>1);4865print">";4866print$cgi->a({-href => href(action=>"commit",4867 hash=>$full_rev,4868 file_name=>$file_name)},4869 esc_html($short_rev));4870if($group_size>=2) {4871my@author_initials= ($author=~/\b([[:upper:]])\B/g);4872if(@author_initials) {4873print"<br />".4874 esc_html(join('',@author_initials));4875# or join('.', ...)4876}4877}4878print"</td>\n";4879}4880# 'previous' <sha1 of parent commit> <filename at commit>4881if(exists$meta->{'previous'} &&4882$meta->{'previous'} =~/^([a-fA-F0-9]{40}) (.*)$/) {4883$meta->{'parent'} =$1;4884$meta->{'file_parent'} = unquote($2);4885}4886my$linenr_commit=4887exists($meta->{'parent'}) ?4888$meta->{'parent'} :$full_rev;4889my$linenr_filename=4890exists($meta->{'file_parent'}) ?4891$meta->{'file_parent'} : unquote($meta->{'filename'});4892my$blamed= href(action =>'blame',4893 file_name =>$linenr_filename,4894 hash_base =>$linenr_commit);4895print"<td class=\"linenr\">";4896print$cgi->a({ -href =>"$blamed#l$orig_lineno",4897-class=>"linenr"},4898 esc_html($lineno));4899print"</td>";4900print"<td class=\"pre\">". esc_html($data) ."</td>\n";4901print"</tr>\n";4902}4903print"</table>\n";4904print"</div>";4905close$fd4906or print"Reading blob failed\n";49074908# page footer4909 git_footer_html();4910}49114912sub git_tags {4913my$head= git_get_head_hash($project);4914 git_header_html();4915 git_print_page_nav('','',$head,undef,$head);4916 git_print_header_div('summary',$project);49174918my@tagslist= git_get_tags_list();4919if(@tagslist) {4920 git_tags_body(\@tagslist);4921}4922 git_footer_html();4923}49244925sub git_heads {4926my$head= git_get_head_hash($project);4927 git_header_html();4928 git_print_page_nav('','',$head,undef,$head);4929 git_print_header_div('summary',$project);49304931my@headslist= git_get_heads_list();4932if(@headslist) {4933 git_heads_body(\@headslist,$head);4934}4935 git_footer_html();4936}49374938sub git_blob_plain {4939my$type=shift;4940my$expires;49414942if(!defined$hash) {4943if(defined$file_name) {4944my$base=$hash_base|| git_get_head_hash($project);4945$hash= git_get_hash_by_path($base,$file_name,"blob")4946or die_error(404,"Cannot find file");4947}else{4948 die_error(400,"No file name defined");4949}4950}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {4951# blobs defined by non-textual hash id's can be cached4952$expires="+1d";4953}49544955open my$fd,"-|", git_cmd(),"cat-file","blob",$hash4956or die_error(500,"Open git-cat-file blob '$hash' failed");49574958# content-type (can include charset)4959$type= blob_contenttype($fd,$file_name,$type);49604961# "save as" filename, even when no $file_name is given4962my$save_as="$hash";4963if(defined$file_name) {4964$save_as=$file_name;4965}elsif($type=~m/^text\//) {4966$save_as.='.txt';4967}49684969# With XSS prevention on, blobs of all types except a few known safe4970# ones are served with "Content-Disposition: attachment" to make sure4971# they don't run in our security domain. For certain image types,4972# blob view writes an <img> tag referring to blob_plain view, and we4973# want to be sure not to break that by serving the image as an4974# attachment (though Firefox 3 doesn't seem to care).4975my$sandbox=$prevent_xss&&4976$type!~m!^(?:text/plain|image/(?:gif|png|jpeg))$!;49774978print$cgi->header(4979-type =>$type,4980-expires =>$expires,4981-content_disposition =>4982($sandbox?'attachment':'inline')4983.'; filename="'.$save_as.'"');4984local$/=undef;4985binmode STDOUT,':raw';4986print<$fd>;4987binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi4988close$fd;4989}49904991sub git_blob {4992my$expires;49934994if(!defined$hash) {4995if(defined$file_name) {4996my$base=$hash_base|| git_get_head_hash($project);4997$hash= git_get_hash_by_path($base,$file_name,"blob")4998or die_error(404,"Cannot find file");4999}else{5000 die_error(400,"No file name defined");5001}5002}elsif($hash=~m/^[0-9a-fA-F]{40}$/) {5003# blobs defined by non-textual hash id's can be cached5004$expires="+1d";5005}50065007my$have_blame= gitweb_check_feature('blame');5008open my$fd,"-|", git_cmd(),"cat-file","blob",$hash5009or die_error(500,"Couldn't cat$file_name,$hash");5010my$mimetype= blob_mimetype($fd,$file_name);5011if($mimetype!~m!^(?:text/|image/(?:gif|png|jpeg)$)!&& -B $fd) {5012close$fd;5013return git_blob_plain($mimetype);5014}5015# we can have blame only for text/* mimetype5016$have_blame&&= ($mimetype=~m!^text/!);50175018 git_header_html(undef,$expires);5019my$formats_nav='';5020if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5021if(defined$file_name) {5022if($have_blame) {5023$formats_nav.=5024$cgi->a({-href => href(action=>"blame", -replay=>1)},5025"blame") .5026" | ";5027}5028$formats_nav.=5029$cgi->a({-href => href(action=>"history", -replay=>1)},5030"history") .5031" | ".5032$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5033"raw") .5034" | ".5035$cgi->a({-href => href(action=>"blob",5036 hash_base=>"HEAD", file_name=>$file_name)},5037"HEAD");5038}else{5039$formats_nav.=5040$cgi->a({-href => href(action=>"blob_plain", -replay=>1)},5041"raw");5042}5043 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5044 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5045}else{5046print"<div class=\"page_nav\">\n".5047"<br/><br/></div>\n".5048"<div class=\"title\">$hash</div>\n";5049}5050 git_print_page_path($file_name,"blob",$hash_base);5051print"<div class=\"page_body\">\n";5052if($mimetype=~m!^image/!) {5053print qq!<img type="$mimetype"!;5054if($file_name) {5055print qq! alt="$file_name" title="$file_name"!;5056}5057print qq! src="! .5058 href(action=>"blob_plain", hash=>$hash,5059 hash_base=>$hash_base, file_name=>$file_name) .5060 qq!"/>\n!;5061}else{5062my$nr;5063while(my$line= <$fd>) {5064chomp$line;5065$nr++;5066$line= untabify($line);5067printf"<div class=\"pre\"><a id=\"l%i\"href=\"". href(-replay =>1)5068."#l%i\"class=\"linenr\">%4i</a>%s</div>\n",5069$nr,$nr,$nr, esc_html($line, -nbsp=>1);5070}5071}5072close$fd5073or print"Reading blob failed.\n";5074print"</div>";5075 git_footer_html();5076}50775078sub git_tree {5079if(!defined$hash_base) {5080$hash_base="HEAD";5081}5082if(!defined$hash) {5083if(defined$file_name) {5084$hash= git_get_hash_by_path($hash_base,$file_name,"tree");5085}else{5086$hash=$hash_base;5087}5088}5089 die_error(404,"No such tree")unlessdefined($hash);50905091my@entries= ();5092{5093local$/="\0";5094open my$fd,"-|", git_cmd(),"ls-tree",'-z',$hash5095or die_error(500,"Open git-ls-tree failed");5096@entries=map{chomp;$_} <$fd>;5097close$fd5098or die_error(404,"Reading tree failed");5099}51005101my$refs= git_get_references();5102my$ref= format_ref_marker($refs,$hash_base);5103 git_header_html();5104my$basedir='';5105my$have_blame= gitweb_check_feature('blame');5106if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5107my@views_nav= ();5108if(defined$file_name) {5109push@views_nav,5110$cgi->a({-href => href(action=>"history", -replay=>1)},5111"history"),5112$cgi->a({-href => href(action=>"tree",5113 hash_base=>"HEAD", file_name=>$file_name)},5114"HEAD"),5115}5116my$snapshot_links= format_snapshot_links($hash);5117if(defined$snapshot_links) {5118# FIXME: Should be available when we have no hash base as well.5119push@views_nav,$snapshot_links;5120}5121 git_print_page_nav('tree','',$hash_base,undef,undef,join(' | ',@views_nav));5122 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash_base);5123}else{5124undef$hash_base;5125print"<div class=\"page_nav\">\n";5126print"<br/><br/></div>\n";5127print"<div class=\"title\">$hash</div>\n";5128}5129if(defined$file_name) {5130$basedir=$file_name;5131if($basedirne''&&substr($basedir, -1)ne'/') {5132$basedir.='/';5133}5134 git_print_page_path($file_name,'tree',$hash_base);5135}5136print"<div class=\"page_body\">\n";5137print"<table class=\"tree\">\n";5138my$alternate=1;5139# '..' (top directory) link if possible5140if(defined$hash_base&&5141defined$file_name&&$file_name=~m![^/]+$!) {5142if($alternate) {5143print"<tr class=\"dark\">\n";5144}else{5145print"<tr class=\"light\">\n";5146}5147$alternate^=1;51485149my$up=$file_name;5150$up=~s!/?[^/]+$!!;5151undef$upunless$up;5152# based on git_print_tree_entry5153print'<td class="mode">'. mode_str('040000') ."</td>\n";5154print'<td class="list">';5155print$cgi->a({-href => href(action=>"tree", hash_base=>$hash_base,5156 file_name=>$up)},5157"..");5158print"</td>\n";5159print"<td class=\"link\"></td>\n";51605161print"</tr>\n";5162}5163foreachmy$line(@entries) {5164my%t= parse_ls_tree_line($line, -z =>1);51655166if($alternate) {5167print"<tr class=\"dark\">\n";5168}else{5169print"<tr class=\"light\">\n";5170}5171$alternate^=1;51725173 git_print_tree_entry(\%t,$basedir,$hash_base,$have_blame);51745175print"</tr>\n";5176}5177print"</table>\n".5178"</div>";5179 git_footer_html();5180}51815182sub git_snapshot {5183my$format=$input_params{'snapshot_format'};5184if(!@snapshot_fmts) {5185 die_error(403,"Snapshots not allowed");5186}5187# default to first supported snapshot format5188$format||=$snapshot_fmts[0];5189if($format!~m/^[a-z0-9]+$/) {5190 die_error(400,"Invalid snapshot format parameter");5191}elsif(!exists($known_snapshot_formats{$format})) {5192 die_error(400,"Unknown snapshot format");5193}elsif($known_snapshot_formats{$format}{'disabled'}) {5194 die_error(403,"Snapshot format not allowed");5195}elsif(!grep($_eq$format,@snapshot_fmts)) {5196 die_error(403,"Unsupported snapshot format");5197}51985199if(!defined$hash) {5200$hash= git_get_head_hash($project);5201}52025203my$name=$project;5204$name=~ s,([^/])/*\.git$,$1,;5205$name= basename($name);5206my$filename= to_utf8($name);5207$name=~s/\047/\047\\\047\047/g;5208my$cmd;5209$filename.="-$hash$known_snapshot_formats{$format}{'suffix'}";5210$cmd= quote_command(5211 git_cmd(),'archive',5212"--format=$known_snapshot_formats{$format}{'format'}",5213"--prefix=$name/",$hash);5214if(exists$known_snapshot_formats{$format}{'compressor'}) {5215$cmd.=' | '. quote_command(@{$known_snapshot_formats{$format}{'compressor'}});5216}52175218print$cgi->header(5219-type =>$known_snapshot_formats{$format}{'type'},5220-content_disposition =>'inline; filename="'."$filename".'"',5221-status =>'200 OK');52225223open my$fd,"-|",$cmd5224or die_error(500,"Execute git-archive failed");5225binmode STDOUT,':raw';5226print<$fd>;5227binmode STDOUT,':utf8';# as set at the beginning of gitweb.cgi5228close$fd;5229}52305231sub git_log {5232my$head= git_get_head_hash($project);5233if(!defined$hash) {5234$hash=$head;5235}5236if(!defined$page) {5237$page=0;5238}5239my$refs= git_get_references();52405241my@commitlist= parse_commits($hash,101, (100*$page));52425243my$paging_nav= format_paging_nav('log',$hash,$head,$page,$#commitlist>=100);52445245my($patch_max) = gitweb_get_feature('patches');5246if($patch_max) {5247if($patch_max<0||@commitlist<=$patch_max) {5248$paging_nav.=" ⋅ ".5249$cgi->a({-href => href(action=>"patches", -replay=>1)},5250"patches");5251}5252}52535254 git_header_html();5255 git_print_page_nav('log','',$hash,undef,undef,$paging_nav);52565257if(!@commitlist) {5258my%co= parse_commit($hash);52595260 git_print_header_div('summary',$project);5261print"<div class=\"page_body\"> Last change$co{'age_string'}.<br/><br/></div>\n";5262}5263my$to= ($#commitlist>=99) ? (99) : ($#commitlist);5264for(my$i=0;$i<=$to;$i++) {5265my%co= %{$commitlist[$i]};5266next if!%co;5267my$commit=$co{'id'};5268my$ref= format_ref_marker($refs,$commit);5269my%ad= parse_date($co{'author_epoch'});5270 git_print_header_div('commit',5271"<span class=\"age\">$co{'age_string'}</span>".5272 esc_html($co{'title'}) .$ref,5273$commit);5274print"<div class=\"title_text\">\n".5275"<div class=\"log_link\">\n".5276$cgi->a({-href => href(action=>"commit", hash=>$commit)},"commit") .5277" | ".5278$cgi->a({-href => href(action=>"commitdiff", hash=>$commit)},"commitdiff") .5279" | ".5280$cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)},"tree") .5281"<br/>\n".5282"</div>\n";5283 git_print_authorship(\%co, -tag =>'span');5284print"<br/>\n</div>\n";52855286print"<div class=\"log_body\">\n";5287 git_print_log($co{'comment'}, -final_empty_line=>1);5288print"</div>\n";5289}5290if($#commitlist>=100) {5291print"<div class=\"page_nav\">\n";5292print$cgi->a({-href => href(-replay=>1, page=>$page+1),5293-accesskey =>"n", -title =>"Alt-n"},"next");5294print"</div>\n";5295}5296 git_footer_html();5297}52985299sub git_commit {5300$hash||=$hash_base||"HEAD";5301my%co= parse_commit($hash)5302or die_error(404,"Unknown commit object");53035304my$parent=$co{'parent'};5305my$parents=$co{'parents'};# listref53065307# we need to prepare $formats_nav before any parameter munging5308my$formats_nav;5309if(!defined$parent) {5310# --root commitdiff5311$formats_nav.='(initial)';5312}elsif(@$parents==1) {5313# single parent commit5314$formats_nav.=5315'(parent: '.5316$cgi->a({-href => href(action=>"commit",5317 hash=>$parent)},5318 esc_html(substr($parent,0,7))) .5319')';5320}else{5321# merge commit5322$formats_nav.=5323'(merge: '.5324join(' ',map{5325$cgi->a({-href => href(action=>"commit",5326 hash=>$_)},5327 esc_html(substr($_,0,7)));5328}@$parents) .5329')';5330}5331if(gitweb_check_feature('patches') &&@$parents<=1) {5332$formats_nav.=" | ".5333$cgi->a({-href => href(action=>"patch", -replay=>1)},5334"patch");5335}53365337if(!defined$parent) {5338$parent="--root";5339}5340my@difftree;5341open my$fd,"-|", git_cmd(),"diff-tree",'-r',"--no-commit-id",5342@diff_opts,5343(@$parents<=1?$parent:'-c'),5344$hash,"--"5345or die_error(500,"Open git-diff-tree failed");5346@difftree=map{chomp;$_} <$fd>;5347close$fdor die_error(404,"Reading git-diff-tree failed");53485349# non-textual hash id's can be cached5350my$expires;5351if($hash=~m/^[0-9a-fA-F]{40}$/) {5352$expires="+1d";5353}5354my$refs= git_get_references();5355my$ref= format_ref_marker($refs,$co{'id'});53565357 git_header_html(undef,$expires);5358 git_print_page_nav('commit','',5359$hash,$co{'tree'},$hash,5360$formats_nav);53615362if(defined$co{'parent'}) {5363 git_print_header_div('commitdiff', esc_html($co{'title'}) .$ref,$hash);5364}else{5365 git_print_header_div('tree', esc_html($co{'title'}) .$ref,$co{'tree'},$hash);5366}5367print"<div class=\"title_text\">\n".5368"<table class=\"object_header\">\n";5369 git_print_authorship_rows(\%co);5370print"<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";5371print"<tr>".5372"<td>tree</td>".5373"<td class=\"sha1\">".5374$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),5375class=>"list"},$co{'tree'}) .5376"</td>".5377"<td class=\"link\">".5378$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},5379"tree");5380my$snapshot_links= format_snapshot_links($hash);5381if(defined$snapshot_links) {5382print" | ".$snapshot_links;5383}5384print"</td>".5385"</tr>\n";53865387foreachmy$par(@$parents) {5388print"<tr>".5389"<td>parent</td>".5390"<td class=\"sha1\">".5391$cgi->a({-href => href(action=>"commit", hash=>$par),5392class=>"list"},$par) .5393"</td>".5394"<td class=\"link\">".5395$cgi->a({-href => href(action=>"commit", hash=>$par)},"commit") .5396" | ".5397$cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)},"diff") .5398"</td>".5399"</tr>\n";5400}5401print"</table>".5402"</div>\n";54035404print"<div class=\"page_body\">\n";5405 git_print_log($co{'comment'});5406print"</div>\n";54075408 git_difftree_body(\@difftree,$hash,@$parents);54095410 git_footer_html();5411}54125413sub git_object {5414# object is defined by:5415# - hash or hash_base alone5416# - hash_base and file_name5417my$type;54185419# - hash or hash_base alone5420if($hash|| ($hash_base&& !defined$file_name)) {5421my$object_id=$hash||$hash_base;54225423open my$fd,"-|", quote_command(5424 git_cmd(),'cat-file','-t',$object_id) .' 2> /dev/null'5425or die_error(404,"Object does not exist");5426$type= <$fd>;5427chomp$type;5428close$fd5429or die_error(404,"Object does not exist");54305431# - hash_base and file_name5432}elsif($hash_base&&defined$file_name) {5433$file_name=~ s,/+$,,;54345435system(git_cmd(),"cat-file",'-e',$hash_base) ==05436or die_error(404,"Base object does not exist");54375438# here errors should not hapen5439open my$fd,"-|", git_cmd(),"ls-tree",$hash_base,"--",$file_name5440or die_error(500,"Open git-ls-tree failed");5441my$line= <$fd>;5442close$fd;54435444#'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'5445unless($line&&$line=~m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {5446 die_error(404,"File or directory for given base does not exist");5447}5448$type=$2;5449$hash=$3;5450}else{5451 die_error(400,"Not enough information to find object");5452}54535454print$cgi->redirect(-uri => href(action=>$type, -full=>1,5455 hash=>$hash, hash_base=>$hash_base,5456 file_name=>$file_name),5457-status =>'302 Found');5458}54595460sub git_blobdiff {5461my$format=shift||'html';54625463my$fd;5464my@difftree;5465my%diffinfo;5466my$expires;54675468# preparing $fd and %diffinfo for git_patchset_body5469# new style URI5470if(defined$hash_base&&defined$hash_parent_base) {5471if(defined$file_name) {5472# read raw output5473open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5474$hash_parent_base,$hash_base,5475"--", (defined$file_parent?$file_parent: ()),$file_name5476or die_error(500,"Open git-diff-tree failed");5477@difftree=map{chomp;$_} <$fd>;5478close$fd5479or die_error(404,"Reading git-diff-tree failed");5480@difftree5481or die_error(404,"Blob diff not found");54825483}elsif(defined$hash&&5484$hash=~/[0-9a-fA-F]{40}/) {5485# try to find filename from $hash54865487# read filtered raw output5488open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5489$hash_parent_base,$hash_base,"--"5490or die_error(500,"Open git-diff-tree failed");5491@difftree=5492# ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'5493# $hash == to_id5494grep{/^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/}5495map{chomp;$_} <$fd>;5496close$fd5497or die_error(404,"Reading git-diff-tree failed");5498@difftree5499or die_error(404,"Blob diff not found");55005501}else{5502 die_error(400,"Missing one of the blob diff parameters");5503}55045505if(@difftree>1) {5506 die_error(400,"Ambiguous blob diff specification");5507}55085509%diffinfo= parse_difftree_raw_line($difftree[0]);5510$file_parent||=$diffinfo{'from_file'} ||$file_name;5511$file_name||=$diffinfo{'to_file'};55125513$hash_parent||=$diffinfo{'from_id'};5514$hash||=$diffinfo{'to_id'};55155516# non-textual hash id's can be cached5517if($hash_base=~m/^[0-9a-fA-F]{40}$/&&5518$hash_parent_base=~m/^[0-9a-fA-F]{40}$/) {5519$expires='+1d';5520}55215522# open patch output5523open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5524'-p', ($formateq'html'?"--full-index": ()),5525$hash_parent_base,$hash_base,5526"--", (defined$file_parent?$file_parent: ()),$file_name5527or die_error(500,"Open git-diff-tree failed");5528}55295530# old/legacy style URI -- not generated anymore since 1.4.3.5531if(!%diffinfo) {5532 die_error('404 Not Found',"Missing one of the blob diff parameters")5533}55345535# header5536if($formateq'html') {5537my$formats_nav=5538$cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},5539"raw");5540 git_header_html(undef,$expires);5541if(defined$hash_base&& (my%co= parse_commit($hash_base))) {5542 git_print_page_nav('','',$hash_base,$co{'tree'},$hash_base,$formats_nav);5543 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5544}else{5545print"<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";5546print"<div class=\"title\">$hashvs$hash_parent</div>\n";5547}5548if(defined$file_name) {5549 git_print_page_path($file_name,"blob",$hash_base);5550}else{5551print"<div class=\"page_path\"></div>\n";5552}55535554}elsif($formateq'plain') {5555print$cgi->header(5556-type =>'text/plain',5557-charset =>'utf-8',5558-expires =>$expires,5559-content_disposition =>'inline; filename="'."$file_name".'.patch"');55605561print"X-Git-Url: ".$cgi->self_url() ."\n\n";55625563}else{5564 die_error(400,"Unknown blobdiff format");5565}55665567# patch5568if($formateq'html') {5569print"<div class=\"page_body\">\n";55705571 git_patchset_body($fd, [ \%diffinfo],$hash_base,$hash_parent_base);5572close$fd;55735574print"</div>\n";# class="page_body"5575 git_footer_html();55765577}else{5578while(my$line= <$fd>) {5579$line=~s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;5580$line=~s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;55815582print$line;55835584last if$line=~m!^\+\+\+!;5585}5586local$/=undef;5587print<$fd>;5588close$fd;5589}5590}55915592sub git_blobdiff_plain {5593 git_blobdiff('plain');5594}55955596sub git_commitdiff {5597my%params=@_;5598my$format=$params{-format} ||'html';55995600my($patch_max) = gitweb_get_feature('patches');5601if($formateq'patch') {5602 die_error(403,"Patch view not allowed")unless$patch_max;5603}56045605$hash||=$hash_base||"HEAD";5606my%co= parse_commit($hash)5607or die_error(404,"Unknown commit object");56085609# choose format for commitdiff for merge5610if(!defined$hash_parent&& @{$co{'parents'}} >1) {5611$hash_parent='--cc';5612}5613# we need to prepare $formats_nav before almost any parameter munging5614my$formats_nav;5615if($formateq'html') {5616$formats_nav=5617$cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},5618"raw");5619if($patch_max&& @{$co{'parents'}} <=1) {5620$formats_nav.=" | ".5621$cgi->a({-href => href(action=>"patch", -replay=>1)},5622"patch");5623}56245625if(defined$hash_parent&&5626$hash_parentne'-c'&&$hash_parentne'--cc') {5627# commitdiff with two commits given5628my$hash_parent_short=$hash_parent;5629if($hash_parent=~m/^[0-9a-fA-F]{40}$/) {5630$hash_parent_short=substr($hash_parent,0,7);5631}5632$formats_nav.=5633' (from';5634for(my$i=0;$i< @{$co{'parents'}};$i++) {5635if($co{'parents'}[$i]eq$hash_parent) {5636$formats_nav.=' parent '. ($i+1);5637last;5638}5639}5640$formats_nav.=': '.5641$cgi->a({-href => href(action=>"commitdiff",5642 hash=>$hash_parent)},5643 esc_html($hash_parent_short)) .5644')';5645}elsif(!$co{'parent'}) {5646# --root commitdiff5647$formats_nav.=' (initial)';5648}elsif(scalar@{$co{'parents'}} ==1) {5649# single parent commit5650$formats_nav.=5651' (parent: '.5652$cgi->a({-href => href(action=>"commitdiff",5653 hash=>$co{'parent'})},5654 esc_html(substr($co{'parent'},0,7))) .5655')';5656}else{5657# merge commit5658if($hash_parenteq'--cc') {5659$formats_nav.=' | '.5660$cgi->a({-href => href(action=>"commitdiff",5661 hash=>$hash, hash_parent=>'-c')},5662'combined');5663}else{# $hash_parent eq '-c'5664$formats_nav.=' | '.5665$cgi->a({-href => href(action=>"commitdiff",5666 hash=>$hash, hash_parent=>'--cc')},5667'compact');5668}5669$formats_nav.=5670' (merge: '.5671join(' ',map{5672$cgi->a({-href => href(action=>"commitdiff",5673 hash=>$_)},5674 esc_html(substr($_,0,7)));5675} @{$co{'parents'}} ) .5676')';5677}5678}56795680my$hash_parent_param=$hash_parent;5681if(!defined$hash_parent_param) {5682# --cc for multiple parents, --root for parentless5683$hash_parent_param=5684@{$co{'parents'}} >1?'--cc':$co{'parent'} ||'--root';5685}56865687# read commitdiff5688my$fd;5689my@difftree;5690if($formateq'html') {5691open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5692"--no-commit-id","--patch-with-raw","--full-index",5693$hash_parent_param,$hash,"--"5694or die_error(500,"Open git-diff-tree failed");56955696while(my$line= <$fd>) {5697chomp$line;5698# empty line ends raw part of diff-tree output5699last unless$line;5700push@difftree,scalar parse_difftree_raw_line($line);5701}57025703}elsif($formateq'plain') {5704open$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,5705'-p',$hash_parent_param,$hash,"--"5706or die_error(500,"Open git-diff-tree failed");5707}elsif($formateq'patch') {5708# For commit ranges, we limit the output to the number of5709# patches specified in the 'patches' feature.5710# For single commits, we limit the output to a single patch,5711# diverging from the git-format-patch default.5712my@commit_spec= ();5713if($hash_parent) {5714if($patch_max>0) {5715push@commit_spec,"-$patch_max";5716}5717push@commit_spec,'-n',"$hash_parent..$hash";5718}else{5719if($params{-single}) {5720push@commit_spec,'-1';5721}else{5722if($patch_max>0) {5723push@commit_spec,"-$patch_max";5724}5725push@commit_spec,"-n";5726}5727push@commit_spec,'--root',$hash;5728}5729open$fd,"-|", git_cmd(),"format-patch",'--encoding=utf8',5730'--stdout',@commit_spec5731or die_error(500,"Open git-format-patch failed");5732}else{5733 die_error(400,"Unknown commitdiff format");5734}57355736# non-textual hash id's can be cached5737my$expires;5738if($hash=~m/^[0-9a-fA-F]{40}$/) {5739$expires="+1d";5740}57415742# write commit message5743if($formateq'html') {5744my$refs= git_get_references();5745my$ref= format_ref_marker($refs,$co{'id'});57465747 git_header_html(undef,$expires);5748 git_print_page_nav('commitdiff','',$hash,$co{'tree'},$hash,$formats_nav);5749 git_print_header_div('commit', esc_html($co{'title'}) .$ref,$hash);5750print"<div class=\"title_text\">\n".5751"<table class=\"object_header\">\n";5752 git_print_authorship_rows(\%co);5753print"</table>".5754"</div>\n";5755print"<div class=\"page_body\">\n";5756if(@{$co{'comment'}} >1) {5757print"<div class=\"log\">\n";5758 git_print_log($co{'comment'}, -final_empty_line=>1, -remove_title =>1);5759print"</div>\n";# class="log"5760}57615762}elsif($formateq'plain') {5763my$refs= git_get_references("tags");5764my$tagname= git_get_rev_name_tags($hash);5765my$filename= basename($project) ."-$hash.patch";57665767print$cgi->header(5768-type =>'text/plain',5769-charset =>'utf-8',5770-expires =>$expires,5771-content_disposition =>'inline; filename="'."$filename".'"');5772my%ad= parse_date($co{'author_epoch'},$co{'author_tz'});5773print"From: ". to_utf8($co{'author'}) ."\n";5774print"Date:$ad{'rfc2822'} ($ad{'tz_local'})\n";5775print"Subject: ". to_utf8($co{'title'}) ."\n";57765777print"X-Git-Tag:$tagname\n"if$tagname;5778print"X-Git-Url: ".$cgi->self_url() ."\n\n";57795780foreachmy$line(@{$co{'comment'}}) {5781print to_utf8($line) ."\n";5782}5783print"---\n\n";5784}elsif($formateq'patch') {5785my$filename= basename($project) ."-$hash.patch";57865787print$cgi->header(5788-type =>'text/plain',5789-charset =>'utf-8',5790-expires =>$expires,5791-content_disposition =>'inline; filename="'."$filename".'"');5792}57935794# write patch5795if($formateq'html') {5796my$use_parents= !defined$hash_parent||5797$hash_parenteq'-c'||$hash_parenteq'--cc';5798 git_difftree_body(\@difftree,$hash,5799$use_parents? @{$co{'parents'}} :$hash_parent);5800print"<br/>\n";58015802 git_patchset_body($fd, \@difftree,$hash,5803$use_parents? @{$co{'parents'}} :$hash_parent);5804close$fd;5805print"</div>\n";# class="page_body"5806 git_footer_html();58075808}elsif($formateq'plain') {5809local$/=undef;5810print<$fd>;5811close$fd5812or print"Reading git-diff-tree failed\n";5813}elsif($formateq'patch') {5814local$/=undef;5815print<$fd>;5816close$fd5817or print"Reading git-format-patch failed\n";5818}5819}58205821sub git_commitdiff_plain {5822 git_commitdiff(-format =>'plain');5823}58245825# format-patch-style patches5826sub git_patch {5827 git_commitdiff(-format =>'patch', -single =>1);5828}58295830sub git_patches {5831 git_commitdiff(-format =>'patch');5832}58335834sub git_history {5835if(!defined$hash_base) {5836$hash_base= git_get_head_hash($project);5837}5838if(!defined$page) {5839$page=0;5840}5841my$ftype;5842my%co= parse_commit($hash_base)5843or die_error(404,"Unknown commit object");58445845my$refs= git_get_references();5846my$limit=sprintf("--max-count=%i", (100* ($page+1)));58475848my@commitlist= parse_commits($hash_base,101, (100*$page),5849$file_name,"--full-history")5850or die_error(404,"No such file or directory on given branch");58515852if(!defined$hash&&defined$file_name) {5853# some commits could have deleted file in question,5854# and not have it in tree, but one of them has to have it5855for(my$i=0;$i<=@commitlist;$i++) {5856$hash= git_get_hash_by_path($commitlist[$i]{'id'},$file_name);5857last ifdefined$hash;5858}5859}5860if(defined$hash) {5861$ftype= git_get_type($hash);5862}5863if(!defined$ftype) {5864 die_error(500,"Unknown type of object");5865}58665867my$paging_nav='';5868if($page>0) {5869$paging_nav.=5870$cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,5871 file_name=>$file_name)},5872"first");5873$paging_nav.=" ⋅ ".5874$cgi->a({-href => href(-replay=>1, page=>$page-1),5875-accesskey =>"p", -title =>"Alt-p"},"prev");5876}else{5877$paging_nav.="first";5878$paging_nav.=" ⋅ prev";5879}5880my$next_link='';5881if($#commitlist>=100) {5882$next_link=5883$cgi->a({-href => href(-replay=>1, page=>$page+1),5884-accesskey =>"n", -title =>"Alt-n"},"next");5885$paging_nav.=" ⋅$next_link";5886}else{5887$paging_nav.=" ⋅ next";5888}58895890 git_header_html();5891 git_print_page_nav('history','',$hash_base,$co{'tree'},$hash_base,$paging_nav);5892 git_print_header_div('commit', esc_html($co{'title'}),$hash_base);5893 git_print_page_path($file_name,$ftype,$hash_base);58945895 git_history_body(\@commitlist,0,99,5896$refs,$hash_base,$ftype,$next_link);58975898 git_footer_html();5899}59005901sub git_search {5902 gitweb_check_feature('search')or die_error(403,"Search is disabled");5903if(!defined$searchtext) {5904 die_error(400,"Text field is empty");5905}5906if(!defined$hash) {5907$hash= git_get_head_hash($project);5908}5909my%co= parse_commit($hash);5910if(!%co) {5911 die_error(404,"Unknown commit object");5912}5913if(!defined$page) {5914$page=0;5915}59165917$searchtype||='commit';5918if($searchtypeeq'pickaxe') {5919# pickaxe may take all resources of your box and run for several minutes5920# with every query - so decide by yourself how public you make this feature5921 gitweb_check_feature('pickaxe')5922or die_error(403,"Pickaxe is disabled");5923}5924if($searchtypeeq'grep') {5925 gitweb_check_feature('grep')5926or die_error(403,"Grep is disabled");5927}59285929 git_header_html();59305931if($searchtypeeq'commit'or$searchtypeeq'author'or$searchtypeeq'committer') {5932my$greptype;5933if($searchtypeeq'commit') {5934$greptype="--grep=";5935}elsif($searchtypeeq'author') {5936$greptype="--author=";5937}elsif($searchtypeeq'committer') {5938$greptype="--committer=";5939}5940$greptype.=$searchtext;5941my@commitlist= parse_commits($hash,101, (100*$page),undef,5942$greptype,'--regexp-ignore-case',5943$search_use_regexp?'--extended-regexp':'--fixed-strings');59445945my$paging_nav='';5946if($page>0) {5947$paging_nav.=5948$cgi->a({-href => href(action=>"search", hash=>$hash,5949 searchtext=>$searchtext,5950 searchtype=>$searchtype)},5951"first");5952$paging_nav.=" ⋅ ".5953$cgi->a({-href => href(-replay=>1, page=>$page-1),5954-accesskey =>"p", -title =>"Alt-p"},"prev");5955}else{5956$paging_nav.="first";5957$paging_nav.=" ⋅ prev";5958}5959my$next_link='';5960if($#commitlist>=100) {5961$next_link=5962$cgi->a({-href => href(-replay=>1, page=>$page+1),5963-accesskey =>"n", -title =>"Alt-n"},"next");5964$paging_nav.=" ⋅$next_link";5965}else{5966$paging_nav.=" ⋅ next";5967}59685969if($#commitlist>=100) {5970}59715972 git_print_page_nav('','',$hash,$co{'tree'},$hash,$paging_nav);5973 git_print_header_div('commit', esc_html($co{'title'}),$hash);5974 git_search_grep_body(\@commitlist,0,99,$next_link);5975}59765977if($searchtypeeq'pickaxe') {5978 git_print_page_nav('','',$hash,$co{'tree'},$hash);5979 git_print_header_div('commit', esc_html($co{'title'}),$hash);59805981print"<table class=\"pickaxe search\">\n";5982my$alternate=1;5983local$/="\n";5984open my$fd,'-|', git_cmd(),'--no-pager','log',@diff_opts,5985'--pretty=format:%H','--no-abbrev','--raw',"-S$searchtext",5986($search_use_regexp?'--pickaxe-regex': ());5987undef%co;5988my@files;5989while(my$line= <$fd>) {5990chomp$line;5991next unless$line;59925993my%set= parse_difftree_raw_line($line);5994if(defined$set{'commit'}) {5995# finish previous commit5996if(%co) {5997print"</td>\n".5998"<td class=\"link\">".5999$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6000" | ".6001$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6002print"</td>\n".6003"</tr>\n";6004}60056006if($alternate) {6007print"<tr class=\"dark\">\n";6008}else{6009print"<tr class=\"light\">\n";6010}6011$alternate^=1;6012%co= parse_commit($set{'commit'});6013my$author= chop_and_escape_str($co{'author_name'},15,5);6014print"<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n".6015"<td><i>$author</i></td>\n".6016"<td>".6017$cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),6018-class=>"list subject"},6019 chop_and_escape_str($co{'title'},50) ."<br/>");6020}elsif(defined$set{'to_id'}) {6021next if($set{'to_id'} =~m/^0{40}$/);60226023print$cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},6024 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),6025-class=>"list"},6026"<span class=\"match\">". esc_path($set{'file'}) ."</span>") .6027"<br/>\n";6028}6029}6030close$fd;60316032# finish last commit (warning: repetition!)6033if(%co) {6034print"</td>\n".6035"<td class=\"link\">".6036$cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},"commit") .6037" | ".6038$cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})},"tree");6039print"</td>\n".6040"</tr>\n";6041}60426043print"</table>\n";6044}60456046if($searchtypeeq'grep') {6047 git_print_page_nav('','',$hash,$co{'tree'},$hash);6048 git_print_header_div('commit', esc_html($co{'title'}),$hash);60496050print"<table class=\"grep_search\">\n";6051my$alternate=1;6052my$matches=0;6053local$/="\n";6054open my$fd,"-|", git_cmd(),'grep','-n',6055$search_use_regexp? ('-E','-i') :'-F',6056$searchtext,$co{'tree'};6057my$lastfile='';6058while(my$line= <$fd>) {6059chomp$line;6060my($file,$lno,$ltext,$binary);6061last if($matches++>1000);6062if($line=~/^Binary file (.+) matches$/) {6063$file=$1;6064$binary=1;6065}else{6066(undef,$file,$lno,$ltext) =split(/:/,$line,4);6067}6068if($filene$lastfile) {6069$lastfileand print"</td></tr>\n";6070if($alternate++) {6071print"<tr class=\"dark\">\n";6072}else{6073print"<tr class=\"light\">\n";6074}6075print"<td class=\"list\">".6076$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6077 file_name=>"$file"),6078-class=>"list"}, esc_path($file));6079print"</td><td>\n";6080$lastfile=$file;6081}6082if($binary) {6083print"<div class=\"binary\">Binary file</div>\n";6084}else{6085$ltext= untabify($ltext);6086if($ltext=~m/^(.*)($search_regexp)(.*)$/i) {6087$ltext= esc_html($1, -nbsp=>1);6088$ltext.='<span class="match">';6089$ltext.= esc_html($2, -nbsp=>1);6090$ltext.='</span>';6091$ltext.= esc_html($3, -nbsp=>1);6092}else{6093$ltext= esc_html($ltext, -nbsp=>1);6094}6095print"<div class=\"pre\">".6096$cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},6097 file_name=>"$file").'#l'.$lno,6098-class=>"linenr"},sprintf('%4i',$lno))6099.' '.$ltext."</div>\n";6100}6101}6102if($lastfile) {6103print"</td></tr>\n";6104if($matches>1000) {6105print"<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";6106}6107}else{6108print"<div class=\"diff nodifferences\">No matches found</div>\n";6109}6110close$fd;61116112print"</table>\n";6113}6114 git_footer_html();6115}61166117sub git_search_help {6118 git_header_html();6119 git_print_page_nav('','',$hash,$hash,$hash);6120print<<EOT;6121<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without6122regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,6123the pattern entered is recognized as the POSIX extended6124<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case6125insensitive).</p>6126<dl>6127<dt><b>commit</b></dt>6128<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>6129EOT6130my$have_grep= gitweb_check_feature('grep');6131if($have_grep) {6132print<<EOT;6133<dt><b>grep</b></dt>6134<dd>All files in the currently selected tree (HEAD unless you are explicitly browsing6135 a different one) are searched for the given pattern. On large trees, this search can take6136a while and put some strain on the server, so please use it with some consideration. Note that6137due to git-grep peculiarity, currently if regexp mode is turned off, the matches are6138case-sensitive.</dd>6139EOT6140}6141print<<EOT;6142<dt><b>author</b></dt>6143<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>6144<dt><b>committer</b></dt>6145<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>6146EOT6147my$have_pickaxe= gitweb_check_feature('pickaxe');6148if($have_pickaxe) {6149print<<EOT;6150<dt><b>pickaxe</b></dt>6151<dd>All commits that caused the string to appear or disappear from any file (changes that6152added, removed or "modified" the string) will be listed. This search can take a while and6153takes a lot of strain on the server, so please use it wisely. Note that since you may be6154interested even in changes just changing the case as well, this search is case sensitive.</dd>6155EOT6156}6157print"</dl>\n";6158 git_footer_html();6159}61606161sub git_shortlog {6162my$head= git_get_head_hash($project);6163if(!defined$hash) {6164$hash=$head;6165}6166if(!defined$page) {6167$page=0;6168}6169my$refs= git_get_references();61706171my$commit_hash=$hash;6172if(defined$hash_parent) {6173$commit_hash="$hash_parent..$hash";6174}6175my@commitlist= parse_commits($commit_hash,101, (100*$page));61766177my$paging_nav= format_paging_nav('shortlog',$hash,$head,$page,$#commitlist>=100);6178my$next_link='';6179if($#commitlist>=100) {6180$next_link=6181$cgi->a({-href => href(-replay=>1, page=>$page+1),6182-accesskey =>"n", -title =>"Alt-n"},"next");6183}6184my$patch_max= gitweb_check_feature('patches');6185if($patch_max) {6186if($patch_max<0||@commitlist<=$patch_max) {6187$paging_nav.=" ⋅ ".6188$cgi->a({-href => href(action=>"patches", -replay=>1)},6189"patches");6190}6191}61926193 git_header_html();6194 git_print_page_nav('shortlog','',$hash,$hash,$hash,$paging_nav);6195 git_print_header_div('summary',$project);61966197 git_shortlog_body(\@commitlist,0,99,$refs,$next_link);61986199 git_footer_html();6200}62016202## ......................................................................6203## feeds (RSS, Atom; OPML)62046205sub git_feed {6206my$format=shift||'atom';6207my$have_blame= gitweb_check_feature('blame');62086209# Atom: http://www.atomenabled.org/developers/syndication/6210# RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ6211if($formatne'rss'&&$formatne'atom') {6212 die_error(400,"Unknown web feed format");6213}62146215# log/feed of current (HEAD) branch, log of given branch, history of file/directory6216my$head=$hash||'HEAD';6217my@commitlist= parse_commits($head,150,0,$file_name);62186219my%latest_commit;6220my%latest_date;6221my$content_type="application/$format+xml";6222if(defined$cgi->http('HTTP_ACCEPT') &&6223$cgi->Accept('text/xml') >$cgi->Accept($content_type)) {6224# browser (feed reader) prefers text/xml6225$content_type='text/xml';6226}6227if(defined($commitlist[0])) {6228%latest_commit= %{$commitlist[0]};6229my$latest_epoch=$latest_commit{'committer_epoch'};6230%latest_date= parse_date($latest_epoch);6231my$if_modified=$cgi->http('IF_MODIFIED_SINCE');6232if(defined$if_modified) {6233my$since;6234if(eval{require HTTP::Date;1; }) {6235$since= HTTP::Date::str2time($if_modified);6236}elsif(eval{require Time::ParseDate;1; }) {6237$since= Time::ParseDate::parsedate($if_modified, GMT =>1);6238}6239if(defined$since&&$latest_epoch<=$since) {6240print$cgi->header(6241-type =>$content_type,6242-charset =>'utf-8',6243-last_modified =>$latest_date{'rfc2822'},6244-status =>'304 Not Modified');6245return;6246}6247}6248print$cgi->header(6249-type =>$content_type,6250-charset =>'utf-8',6251-last_modified =>$latest_date{'rfc2822'});6252}else{6253print$cgi->header(6254-type =>$content_type,6255-charset =>'utf-8');6256}62576258# Optimization: skip generating the body if client asks only6259# for Last-Modified date.6260return if($cgi->request_method()eq'HEAD');62616262# header variables6263my$title="$site_name-$project/$action";6264my$feed_type='log';6265if(defined$hash) {6266$title.=" - '$hash'";6267$feed_type='branch log';6268if(defined$file_name) {6269$title.=" ::$file_name";6270$feed_type='history';6271}6272}elsif(defined$file_name) {6273$title.=" -$file_name";6274$feed_type='history';6275}6276$title.="$feed_type";6277my$descr= git_get_project_description($project);6278if(defined$descr) {6279$descr= esc_html($descr);6280}else{6281$descr="$project".6282($formateq'rss'?'RSS':'Atom') .6283" feed";6284}6285my$owner= git_get_project_owner($project);6286$owner= esc_html($owner);62876288#header6289my$alt_url;6290if(defined$file_name) {6291$alt_url= href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);6292}elsif(defined$hash) {6293$alt_url= href(-full=>1, action=>"log", hash=>$hash);6294}else{6295$alt_url= href(-full=>1, action=>"summary");6296}6297print qq!<?xml version="1.0" encoding="utf-8"?>\n!;6298if($formateq'rss') {6299print<<XML;6300<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">6301<channel>6302XML6303print"<title>$title</title>\n".6304"<link>$alt_url</link>\n".6305"<description>$descr</description>\n".6306"<language>en</language>\n".6307# project owner is responsible for 'editorial' content6308"<managingEditor>$owner</managingEditor>\n";6309if(defined$logo||defined$favicon) {6310# prefer the logo to the favicon, since RSS6311# doesn't allow both6312my$img= esc_url($logo||$favicon);6313print"<image>\n".6314"<url>$img</url>\n".6315"<title>$title</title>\n".6316"<link>$alt_url</link>\n".6317"</image>\n";6318}6319if(%latest_date) {6320print"<pubDate>$latest_date{'rfc2822'}</pubDate>\n";6321print"<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";6322}6323print"<generator>gitweb v.$version/$git_version</generator>\n";6324}elsif($formateq'atom') {6325print<<XML;6326<feed xmlns="http://www.w3.org/2005/Atom">6327XML6328print"<title>$title</title>\n".6329"<subtitle>$descr</subtitle>\n".6330'<link rel="alternate" type="text/html" href="'.6331$alt_url.'" />'."\n".6332'<link rel="self" type="'.$content_type.'" href="'.6333$cgi->self_url() .'" />'."\n".6334"<id>". href(-full=>1) ."</id>\n".6335# use project owner for feed author6336"<author><name>$owner</name></author>\n";6337if(defined$favicon) {6338print"<icon>". esc_url($favicon) ."</icon>\n";6339}6340if(defined$logo_url) {6341# not twice as wide as tall: 72 x 27 pixels6342print"<logo>". esc_url($logo) ."</logo>\n";6343}6344if(!%latest_date) {6345# dummy date to keep the feed valid until commits trickle in:6346print"<updated>1970-01-01T00:00:00Z</updated>\n";6347}else{6348print"<updated>$latest_date{'iso-8601'}</updated>\n";6349}6350print"<generator version='$version/$git_version'>gitweb</generator>\n";6351}63526353# contents6354for(my$i=0;$i<=$#commitlist;$i++) {6355my%co= %{$commitlist[$i]};6356my$commit=$co{'id'};6357# we read 150, we always show 30 and the ones more recent than 48 hours6358if(($i>=20) && ((time-$co{'author_epoch'}) >48*60*60)) {6359last;6360}6361my%cd= parse_date($co{'author_epoch'});63626363# get list of changed files6364open my$fd,"-|", git_cmd(),"diff-tree",'-r',@diff_opts,6365$co{'parent'} ||"--root",6366$co{'id'},"--", (defined$file_name?$file_name: ())6367ornext;6368my@difftree=map{chomp;$_} <$fd>;6369close$fd6370ornext;63716372# print element (entry, item)6373my$co_url= href(-full=>1, action=>"commitdiff", hash=>$commit);6374if($formateq'rss') {6375print"<item>\n".6376"<title>". esc_html($co{'title'}) ."</title>\n".6377"<author>". esc_html($co{'author'}) ."</author>\n".6378"<pubDate>$cd{'rfc2822'}</pubDate>\n".6379"<guid isPermaLink=\"true\">$co_url</guid>\n".6380"<link>$co_url</link>\n".6381"<description>". esc_html($co{'title'}) ."</description>\n".6382"<content:encoded>".6383"<![CDATA[\n";6384}elsif($formateq'atom') {6385print"<entry>\n".6386"<title type=\"html\">". esc_html($co{'title'}) ."</title>\n".6387"<updated>$cd{'iso-8601'}</updated>\n".6388"<author>\n".6389" <name>". esc_html($co{'author_name'}) ."</name>\n";6390if($co{'author_email'}) {6391print" <email>". esc_html($co{'author_email'}) ."</email>\n";6392}6393print"</author>\n".6394# use committer for contributor6395"<contributor>\n".6396" <name>". esc_html($co{'committer_name'}) ."</name>\n";6397if($co{'committer_email'}) {6398print" <email>". esc_html($co{'committer_email'}) ."</email>\n";6399}6400print"</contributor>\n".6401"<published>$cd{'iso-8601'}</published>\n".6402"<link rel=\"alternate\"type=\"text/html\"href=\"$co_url\"/>\n".6403"<id>$co_url</id>\n".6404"<content type=\"xhtml\"xml:base=\"". esc_url($my_url) ."\">\n".6405"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";6406}6407my$comment=$co{'comment'};6408print"<pre>\n";6409foreachmy$line(@$comment) {6410$line= esc_html($line);6411print"$line\n";6412}6413print"</pre><ul>\n";6414foreachmy$difftree_line(@difftree) {6415my%difftree= parse_difftree_raw_line($difftree_line);6416next if!$difftree{'from_id'};64176418my$file=$difftree{'file'} ||$difftree{'to_file'};64196420print"<li>".6421"[".6422$cgi->a({-href => href(-full=>1, action=>"blobdiff",6423 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},6424 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},6425 file_name=>$file, file_parent=>$difftree{'from_file'}),6426-title =>"diff"},'D');6427if($have_blame) {6428print$cgi->a({-href => href(-full=>1, action=>"blame",6429 file_name=>$file, hash_base=>$commit),6430-title =>"blame"},'B');6431}6432# if this is not a feed of a file history6433if(!defined$file_name||$file_namene$file) {6434print$cgi->a({-href => href(-full=>1, action=>"history",6435 file_name=>$file, hash=>$commit),6436-title =>"history"},'H');6437}6438$file= esc_path($file);6439print"] ".6440"$file</li>\n";6441}6442if($formateq'rss') {6443print"</ul>]]>\n".6444"</content:encoded>\n".6445"</item>\n";6446}elsif($formateq'atom') {6447print"</ul>\n</div>\n".6448"</content>\n".6449"</entry>\n";6450}6451}64526453# end of feed6454if($formateq'rss') {6455print"</channel>\n</rss>\n";6456}elsif($formateq'atom') {6457print"</feed>\n";6458}6459}64606461sub git_rss {6462 git_feed('rss');6463}64646465sub git_atom {6466 git_feed('atom');6467}64686469sub git_opml {6470my@list= git_get_projects_list();64716472print$cgi->header(6473-type =>'text/xml',6474-charset =>'utf-8',6475-content_disposition =>'inline; filename="opml.xml"');64766477print<<XML;6478<?xml version="1.0" encoding="utf-8"?>6479<opml version="1.0">6480<head>6481 <title>$site_nameOPML Export</title>6482</head>6483<body>6484<outline text="git RSS feeds">6485XML64866487foreachmy$pr(@list) {6488my%proj=%$pr;6489my$head= git_get_head_hash($proj{'path'});6490if(!defined$head) {6491next;6492}6493$git_dir="$projectroot/$proj{'path'}";6494my%co= parse_commit($head);6495if(!%co) {6496next;6497}64986499my$path= esc_html(chop_str($proj{'path'},25,5));6500my$rss= href('project'=>$proj{'path'},'action'=>'rss', -full =>1);6501my$html= href('project'=>$proj{'path'},'action'=>'summary', -full =>1);6502print"<outline type=\"rss\"text=\"$path\"title=\"$path\"xmlUrl=\"$rss\"htmlUrl=\"$html\"/>\n";6503}6504print<<XML;6505</outline>6506</body>6507</opml>6508XML6509}