git-instaweb: Move all actions at the end of script
[git] / git-instaweb.sh
1 #!/bin/sh
2 #
3 # Copyright (c) 2006 Eric Wong
4 #
5
6 PERL='@@PERL@@'
7 OPTIONS_KEEPDASHDASH=
8 OPTIONS_SPEC="\
9 git instaweb [options] (--start | --stop | --restart)
10 --
11 l,local        only bind on 127.0.0.1
12 p,port=        the port to bind to
13 d,httpd=       the command to launch
14 b,browser=     the browser to launch
15 m,module-path= the module path (only needed for apache2)
16  Action
17 stop           stop the web server
18 start          start the web server
19 restart        restart the web server
20 "
21
22 . git-sh-setup
23
24 fqgitdir="$GIT_DIR"
25 local="$(git config --bool --get instaweb.local)"
26 httpd="$(git config --get instaweb.httpd)"
27 root="$(git config --get instaweb.gitwebdir)"
28 port=$(git config --get instaweb.port)
29 module_path="$(git config --get instaweb.modulepath)"
30 action="browse"
31
32 conf="$GIT_DIR/gitweb/httpd.conf"
33
34 # Defaults:
35
36 # if installed, it doesn't need further configuration (module_path)
37 test -z "$httpd" && httpd='lighttpd -f'
38
39 # Default is @@GITWEBDIR@@
40 test -z "$root" && root='@@GITWEBDIR@@'
41
42 # any untaken local port will do...
43 test -z "$port" && port=1234
44
45 resolve_full_httpd () {
46         case "$httpd" in
47         *apache2*|*lighttpd*|*httpd*)
48                 # yes, *httpd* covers *lighttpd* above, but it is there for clarity
49                 # ensure that the apache2/lighttpd command ends with "-f"
50                 if ! echo "$httpd" | sane_grep -- '-f *$' >/dev/null 2>&1
51                 then
52                         httpd="$httpd -f"
53                 fi
54                 ;;
55         *plackup*)
56                 # server is started by running via generated gitweb.psgi in $fqgitdir/gitweb
57                 full_httpd="$fqgitdir/gitweb/gitweb.psgi"
58                 httpd_only="${httpd%% *}" # cut on first space
59                 return
60                 ;;
61         *webrick*)
62                 # server is started by running via generated webrick.rb in
63                 # $fqgitdir/gitweb
64                 full_httpd="$fqgitdir/gitweb/webrick.rb"
65                 httpd_only="${httpd%% *}" # cut on first space
66                 return
67                 ;;
68         esac
69
70         httpd_only="$(echo $httpd | cut -f1 -d' ')"
71         if case "$httpd_only" in /*) : ;; *) which $httpd_only >/dev/null 2>&1;; esac
72         then
73                 full_httpd=$httpd
74         else
75                 # many httpds are installed in /usr/sbin or /usr/local/sbin
76                 # these days and those are not in most users $PATHs
77                 # in addition, we may have generated a server script
78                 # in $fqgitdir/gitweb.
79                 for i in /usr/local/sbin /usr/sbin "$root" "$fqgitdir/gitweb"
80                 do
81                         if test -x "$i/$httpd_only"
82                         then
83                                 full_httpd=$i/$httpd
84                                 return
85                         fi
86                 done
87
88                 echo >&2 "$httpd_only not found. Install $httpd_only or use" \
89                      "--httpd to specify another httpd daemon."
90                 exit 1
91         fi
92 }
93
94 start_httpd () {
95         if test -f "$fqgitdir/pid"; then
96                 say "Instance already running. Restarting..."
97                 stop_httpd
98         fi
99
100         # here $httpd should have a meaningful value
101         resolve_full_httpd
102
103         # don't quote $full_httpd, there can be arguments to it (-f)
104         case "$httpd" in
105         *mongoose*|*plackup*)
106                 #These servers don't have a daemon mode so we'll have to fork it
107                 $full_httpd "$conf" &
108                 #Save the pid before doing anything else (we'll print it later)
109                 pid=$!
110
111                 if test $? != 0; then
112                         echo "Could not execute http daemon $httpd."
113                         exit 1
114                 fi
115
116                 cat > "$fqgitdir/pid" <<EOF
117 $pid
118 EOF
119                 ;;
120         *)
121                 $full_httpd "$conf"
122                 if test $? != 0; then
123                         echo "Could not execute http daemon $httpd."
124                         exit 1
125                 fi
126                 ;;
127         esac
128 }
129
130 stop_httpd () {
131         test -f "$fqgitdir/pid" && kill $(cat "$fqgitdir/pid")
132         rm -f "$fqgitdir/pid"
133 }
134
135 httpd_is_ready () {
136         "$PERL" -MIO::Socket::INET -e "
137 local \$| = 1; # turn on autoflush
138 exit if (IO::Socket::INET->new('127.0.0.1:$port'));
139 print 'Waiting for \'$httpd\' to start ..';
140 do {
141         print '.';
142         sleep(1);
143 } until (IO::Socket::INET->new('127.0.0.1:$port'));
144 print qq! (done)\n!;
145 "
146 }
147
148 while test $# != 0
149 do
150         case "$1" in
151         --stop|stop)
152                 action="stop"
153                 ;;
154         --start|start)
155                 action="start"
156                 ;;
157         --restart|restart)
158                 action="restart"
159                 ;;
160         -l|--local)
161                 local=true
162                 ;;
163         -d|--httpd)
164                 shift
165                 httpd="$1"
166                 ;;
167         -b|--browser)
168                 shift
169                 browser="$1"
170                 ;;
171         -p|--port)
172                 shift
173                 port="$1"
174                 ;;
175         -m|--module-path)
176                 shift
177                 module_path="$1"
178                 ;;
179         --)
180                 ;;
181         *)
182                 usage
183                 ;;
184         esac
185         shift
186 done
187
188 mkdir -p "$GIT_DIR/gitweb/tmp"
189 GIT_EXEC_PATH="$(git --exec-path)"
190 GIT_DIR="$fqgitdir"
191 GITWEB_CONFIG="$fqgitdir/gitweb/gitweb_config.perl"
192 export GIT_EXEC_PATH GIT_DIR GITWEB_CONFIG
193
194 webrick_conf () {
195         # webrick seems to have no way of passing arbitrary environment
196         # variables to the underlying CGI executable, so we wrap the
197         # actual gitweb.cgi using a shell script to force it
198   wrapper="$fqgitdir/gitweb/$httpd/wrapper.sh"
199         cat > "$wrapper" <<EOF
200 #!/bin/sh
201 # we use this shell script wrapper around the real gitweb.cgi since
202 # there appears to be no other way to pass arbitrary environment variables
203 # into the CGI process
204 GIT_EXEC_PATH=$GIT_EXEC_PATH GIT_DIR=$GIT_DIR GITWEB_CONFIG=$GITWEB_CONFIG
205 export GIT_EXEC_PATH GIT_DIR GITWEB_CONFIG
206 exec $root/gitweb.cgi
207 EOF
208         chmod +x "$wrapper"
209
210         # This assumes _ruby_ is in the user's $PATH. that's _one_
211         # portable way to run ruby, which could be installed anywhere, really.
212         # generate a standalone server script in $fqgitdir/gitweb.
213         cat >"$fqgitdir/gitweb/$httpd.rb" <<EOF
214 #!/usr/bin/env ruby
215 require 'webrick'
216 require 'logger'
217 options = {
218   :Port => $port,
219   :DocumentRoot => "$root",
220   :Logger => Logger.new('$fqgitdir/gitweb/error.log'),
221   :AccessLog => [
222     [ Logger.new('$fqgitdir/gitweb/access.log'),
223       WEBrick::AccessLog::COMBINED_LOG_FORMAT ]
224   ],
225   :DirectoryIndex => ["gitweb.cgi"],
226   :CGIInterpreter => "$wrapper",
227   :StartCallback => lambda do
228     File.open("$fqgitdir/pid", "w") { |f| f.puts Process.pid }
229   end,
230   :ServerType => WEBrick::Daemon,
231 }
232 options[:BindAddress] = '127.0.0.1' if "$local" == "true"
233 server = WEBrick::HTTPServer.new(options)
234 ['INT', 'TERM'].each do |signal|
235   trap(signal) {server.shutdown}
236 end
237 server.start
238 EOF
239         chmod +x "$fqgitdir/gitweb/$httpd.rb"
240         # configuration is embedded in server script file, webrick.rb
241         rm -f "$conf"
242 }
243
244 lighttpd_conf () {
245         cat > "$conf" <<EOF
246 server.document-root = "$root"
247 server.port = $port
248 server.modules = ( "mod_setenv", "mod_cgi" )
249 server.indexfiles = ( "gitweb.cgi" )
250 server.pid-file = "$fqgitdir/pid"
251 server.errorlog = "$fqgitdir/gitweb/$httpd_only/error.log"
252
253 # to enable, add "mod_access", "mod_accesslog" to server.modules
254 # variable above and uncomment this
255 #accesslog.filename = "$fqgitdir/gitweb/$httpd_only/access.log"
256
257 setenv.add-environment = ( "PATH" => env.PATH, "GITWEB_CONFIG" => env.GITWEB_CONFIG )
258
259 cgi.assign = ( ".cgi" => "" )
260
261 # mimetype mapping
262 mimetype.assign             = (
263   ".pdf"          =>      "application/pdf",
264   ".sig"          =>      "application/pgp-signature",
265   ".spl"          =>      "application/futuresplash",
266   ".class"        =>      "application/octet-stream",
267   ".ps"           =>      "application/postscript",
268   ".torrent"      =>      "application/x-bittorrent",
269   ".dvi"          =>      "application/x-dvi",
270   ".gz"           =>      "application/x-gzip",
271   ".pac"          =>      "application/x-ns-proxy-autoconfig",
272   ".swf"          =>      "application/x-shockwave-flash",
273   ".tar.gz"       =>      "application/x-tgz",
274   ".tgz"          =>      "application/x-tgz",
275   ".tar"          =>      "application/x-tar",
276   ".zip"          =>      "application/zip",
277   ".mp3"          =>      "audio/mpeg",
278   ".m3u"          =>      "audio/x-mpegurl",
279   ".wma"          =>      "audio/x-ms-wma",
280   ".wax"          =>      "audio/x-ms-wax",
281   ".ogg"          =>      "application/ogg",
282   ".wav"          =>      "audio/x-wav",
283   ".gif"          =>      "image/gif",
284   ".jpg"          =>      "image/jpeg",
285   ".jpeg"         =>      "image/jpeg",
286   ".png"          =>      "image/png",
287   ".xbm"          =>      "image/x-xbitmap",
288   ".xpm"          =>      "image/x-xpixmap",
289   ".xwd"          =>      "image/x-xwindowdump",
290   ".css"          =>      "text/css",
291   ".html"         =>      "text/html",
292   ".htm"          =>      "text/html",
293   ".js"           =>      "text/javascript",
294   ".asc"          =>      "text/plain",
295   ".c"            =>      "text/plain",
296   ".cpp"          =>      "text/plain",
297   ".log"          =>      "text/plain",
298   ".conf"         =>      "text/plain",
299   ".text"         =>      "text/plain",
300   ".txt"          =>      "text/plain",
301   ".dtd"          =>      "text/xml",
302   ".xml"          =>      "text/xml",
303   ".mpeg"         =>      "video/mpeg",
304   ".mpg"          =>      "video/mpeg",
305   ".mov"          =>      "video/quicktime",
306   ".qt"           =>      "video/quicktime",
307   ".avi"          =>      "video/x-msvideo",
308   ".asf"          =>      "video/x-ms-asf",
309   ".asx"          =>      "video/x-ms-asf",
310   ".wmv"          =>      "video/x-ms-wmv",
311   ".bz2"          =>      "application/x-bzip",
312   ".tbz"          =>      "application/x-bzip-compressed-tar",
313   ".tar.bz2"      =>      "application/x-bzip-compressed-tar",
314   ""              =>      "text/plain"
315  )
316 EOF
317         test x"$local" = xtrue && echo 'server.bind = "127.0.0.1"' >> "$conf"
318 }
319
320 apache2_conf () {
321         if test -z "$module_path"
322         then
323                 test -d "/usr/lib/httpd/modules" &&
324                         module_path="/usr/lib/httpd/modules"
325                 test -d "/usr/lib/apache2/modules" &&
326                         module_path="/usr/lib/apache2/modules"
327         fi
328         bind=
329         test x"$local" = xtrue && bind='127.0.0.1:'
330         echo 'text/css css' > "$fqgitdir/mime.types"
331         cat > "$conf" <<EOF
332 ServerName "git-instaweb"
333 ServerRoot "$root"
334 DocumentRoot "$root"
335 ErrorLog "$fqgitdir/gitweb/$httpd_only/error.log"
336 CustomLog "$fqgitdir/gitweb/$httpd_only/access.log" combined
337 PidFile "$fqgitdir/pid"
338 Listen $bind$port
339 EOF
340
341         for mod in mime dir env log_config
342         do
343                 if test -e $module_path/mod_${mod}.so
344                 then
345                         echo "LoadModule ${mod}_module " \
346                              "$module_path/mod_${mod}.so" >> "$conf"
347                 fi
348         done
349         cat >> "$conf" <<EOF
350 TypesConfig "$fqgitdir/mime.types"
351 DirectoryIndex gitweb.cgi
352 EOF
353
354         # check to see if Dennis Stosberg's mod_perl compatibility patch
355         # (<20060621130708.Gcbc6e5c@leonov.stosberg.net>) has been applied
356         if test -f "$module_path/mod_perl.so" &&
357            sane_grep 'MOD_PERL' "$root/gitweb.cgi" >/dev/null
358         then
359                 # favor mod_perl if available
360                 cat >> "$conf" <<EOF
361 LoadModule perl_module $module_path/mod_perl.so
362 PerlPassEnv GIT_DIR
363 PerlPassEnv GIT_EXEC_PATH
364 PerlPassEnv GITWEB_CONFIG
365 <Location /gitweb.cgi>
366         SetHandler perl-script
367         PerlResponseHandler ModPerl::Registry
368         PerlOptions +ParseHeaders
369         Options +ExecCGI
370 </Location>
371 EOF
372         else
373                 # plain-old CGI
374                 resolve_full_httpd
375                 list_mods=$(echo "$full_httpd" | sed 's/-f$/-l/')
376                 $list_mods | sane_grep 'mod_cgi\.c' >/dev/null 2>&1 || \
377                 if test -f "$module_path/mod_cgi.so"
378                 then
379                         echo "LoadModule cgi_module $module_path/mod_cgi.so" >> "$conf"
380                 else
381                         $list_mods | grep 'mod_cgid\.c' >/dev/null 2>&1 || \
382                         if test -f "$module_path/mod_cgid.so"
383                         then
384                                 echo "LoadModule cgid_module $module_path/mod_cgid.so" \
385                                         >> "$conf"
386                         else
387                                 echo "You have no CGI support!"
388                                 exit 2
389                         fi
390                         echo "ScriptSock logs/gitweb.sock" >> "$conf"
391                 fi
392                 cat >> "$conf" <<EOF
393 PassEnv GIT_DIR
394 PassEnv GIT_EXEC_PATH
395 PassEnv GITWEB_CONFIG
396 AddHandler cgi-script .cgi
397 <Location /gitweb.cgi>
398         Options +ExecCGI
399 </Location>
400 EOF
401         fi
402 }
403
404 mongoose_conf() {
405         cat > "$conf" <<EOF
406 # Mongoose web server configuration file.
407 # Lines starting with '#' and empty lines are ignored.
408 # For detailed description of every option, visit
409 # http://code.google.com/p/mongoose/wiki/MongooseManual
410
411 root            $root
412 ports           $port
413 index_files     gitweb.cgi
414 #ssl_cert       $fqgitdir/gitweb/ssl_cert.pem
415 error_log       $fqgitdir/gitweb/$httpd_only/error.log
416 access_log      $fqgitdir/gitweb/$httpd_only/access.log
417
418 #cgi setup
419 cgi_env         PATH=$PATH,GIT_DIR=$GIT_DIR,GIT_EXEC_PATH=$GIT_EXEC_PATH,GITWEB_CONFIG=$GITWEB_CONFIG
420 cgi_interp      $PERL
421 cgi_ext         cgi,pl
422
423 # mimetype mapping
424 mime_types      .gz=application/x-gzip,.tar.gz=application/x-tgz,.tgz=application/x-tgz,.tar=application/x-tar,.zip=application/zip,.gif=image/gif,.jpg=image/jpeg,.jpeg=image/jpeg,.png=image/png,.css=text/css,.html=text/html,.htm=text/html,.js=text/javascript,.c=text/plain,.cpp=text/plain,.log=text/plain,.conf=text/plain,.text=text/plain,.txt=text/plain,.dtd=text/xml,.bz2=application/x-bzip,.tbz=application/x-bzip-compressed-tar,.tar.bz2=application/x-bzip-compressed-tar
425 EOF
426 }
427
428 plackup_conf () {
429         # generate a standalone 'plackup' server script in $fqgitdir/gitweb
430         # with embedded configuration; it does not use "$conf" file
431         cat > "$fqgitdir/gitweb/gitweb.psgi" <<EOF
432 #!$PERL
433
434 # gitweb - simple web interface to track changes in git repositories
435 #          PSGI wrapper and server starter (see http://plackperl.org)
436
437 use strict;
438
439 use IO::Handle;
440 use Plack::MIME;
441 use Plack::Builder;
442 use Plack::App::WrapCGI;
443 use CGI::Emulate::PSGI 0.07; # minimum version required to work with gitweb
444
445 # mimetype mapping (from lighttpd_conf)
446 Plack::MIME->add_type(
447         ".pdf"          =>      "application/pdf",
448         ".sig"          =>      "application/pgp-signature",
449         ".spl"          =>      "application/futuresplash",
450         ".class"        =>      "application/octet-stream",
451         ".ps"           =>      "application/postscript",
452         ".torrent"      =>      "application/x-bittorrent",
453         ".dvi"          =>      "application/x-dvi",
454         ".gz"           =>      "application/x-gzip",
455         ".pac"          =>      "application/x-ns-proxy-autoconfig",
456         ".swf"          =>      "application/x-shockwave-flash",
457         ".tar.gz"       =>      "application/x-tgz",
458         ".tgz"          =>      "application/x-tgz",
459         ".tar"          =>      "application/x-tar",
460         ".zip"          =>      "application/zip",
461         ".mp3"          =>      "audio/mpeg",
462         ".m3u"          =>      "audio/x-mpegurl",
463         ".wma"          =>      "audio/x-ms-wma",
464         ".wax"          =>      "audio/x-ms-wax",
465         ".ogg"          =>      "application/ogg",
466         ".wav"          =>      "audio/x-wav",
467         ".gif"          =>      "image/gif",
468         ".jpg"          =>      "image/jpeg",
469         ".jpeg"         =>      "image/jpeg",
470         ".png"          =>      "image/png",
471         ".xbm"          =>      "image/x-xbitmap",
472         ".xpm"          =>      "image/x-xpixmap",
473         ".xwd"          =>      "image/x-xwindowdump",
474         ".css"          =>      "text/css",
475         ".html"         =>      "text/html",
476         ".htm"          =>      "text/html",
477         ".js"           =>      "text/javascript",
478         ".asc"          =>      "text/plain",
479         ".c"            =>      "text/plain",
480         ".cpp"          =>      "text/plain",
481         ".log"          =>      "text/plain",
482         ".conf"         =>      "text/plain",
483         ".text"         =>      "text/plain",
484         ".txt"          =>      "text/plain",
485         ".dtd"          =>      "text/xml",
486         ".xml"          =>      "text/xml",
487         ".mpeg"         =>      "video/mpeg",
488         ".mpg"          =>      "video/mpeg",
489         ".mov"          =>      "video/quicktime",
490         ".qt"           =>      "video/quicktime",
491         ".avi"          =>      "video/x-msvideo",
492         ".asf"          =>      "video/x-ms-asf",
493         ".asx"          =>      "video/x-ms-asf",
494         ".wmv"          =>      "video/x-ms-wmv",
495         ".bz2"          =>      "application/x-bzip",
496         ".tbz"          =>      "application/x-bzip-compressed-tar",
497         ".tar.bz2"      =>      "application/x-bzip-compressed-tar",
498         ""              =>      "text/plain"
499 );
500
501 my \$app = builder {
502         # to be able to override \$SIG{__WARN__} to log build time warnings
503         use CGI::Carp; # it sets \$SIG{__WARN__} itself
504
505         my \$logdir = "$fqgitdir/gitweb/$httpd_only";
506         open my \$access_log_fh, '>>', "\$logdir/access.log"
507                 or die "Couldn't open access log '\$logdir/access.log': \$!";
508         open my \$error_log_fh,  '>>', "\$logdir/error.log"
509                 or die "Couldn't open error log '\$logdir/error.log': \$!";
510
511         \$access_log_fh->autoflush(1);
512         \$error_log_fh->autoflush(1);
513
514         # redirect build time warnings to error.log
515         \$SIG{'__WARN__'} = sub {
516                 my \$msg = shift;
517                 # timestamp warning like in CGI::Carp::warn
518                 my \$stamp = CGI::Carp::stamp();
519                 \$msg =~ s/^/\$stamp/gm;
520                 print \$error_log_fh \$msg;
521         };
522
523         # write errors to error.log, access to access.log
524         enable 'AccessLog',
525                 format => "combined",
526                 logger => sub { print \$access_log_fh @_; };
527         enable sub {
528                 my \$app = shift;
529                 sub {
530                         my \$env = shift;
531                         \$env->{'psgi.errors'} = \$error_log_fh;
532                         \$app->(\$env);
533                 }
534         };
535         # gitweb currently doesn't work with $SIG{CHLD} set to 'IGNORE',
536         # because it uses 'close $fd or die...' on piped filehandle $fh
537         # (which causes the parent process to wait for child to finish).
538         enable_if { \$SIG{'CHLD'} eq 'IGNORE' } sub {
539                 my \$app = shift;
540                 sub {
541                         my \$env = shift;
542                         local \$SIG{'CHLD'} = 'DEFAULT';
543                         local \$SIG{'CLD'}  = 'DEFAULT';
544                         \$app->(\$env);
545                 }
546         };
547         # serve static files, i.e. stylesheet, images, script
548         enable 'Static',
549                 path => sub { m!\.(js|css|png)\$! && s!^/gitweb/!! },
550                 root => "$root/",
551                 encoding => 'utf-8'; # encoding for 'text/plain' files
552         # convert CGI application to PSGI app
553         Plack::App::WrapCGI->new(script => "$root/gitweb.cgi")->to_app;
554 };
555
556 # make it runnable as standalone app,
557 # like it would be run via 'plackup' utility
558 if (caller) {
559         return \$app;
560 } else {
561         require Plack::Runner;
562
563         my \$runner = Plack::Runner->new();
564         \$runner->parse_options(qw(--env deployment --port $port),
565                                 "$local" ? qw(--host 127.0.0.1) : ());
566         \$runner->run(\$app);
567 }
568 __END__
569 EOF
570
571         chmod a+x "$fqgitdir/gitweb/gitweb.psgi"
572         # configuration is embedded in server script file, gitweb.psgi
573         rm -f "$conf"
574 }
575
576 gitweb_conf() {
577         cat > "$fqgitdir/gitweb/gitweb_config.perl" <<EOF
578 #!/usr/bin/perl
579 our \$projectroot = "$(dirname "$fqgitdir")";
580 our \$git_temp = "$fqgitdir/gitweb/tmp";
581 our \$projects_list = \$projectroot;
582
583 \$feature{'remote_heads'}{'default'} = [1];
584 EOF
585 }
586
587 configure_httpd() {
588         case "$httpd" in
589         *lighttpd*)
590                 lighttpd_conf
591                 ;;
592         *apache2*|*httpd*)
593                 apache2_conf
594                 ;;
595         webrick)
596                 webrick_conf
597                 ;;
598         *mongoose*)
599                 mongoose_conf
600                 ;;
601         *plackup*)
602                 plackup_conf
603                 ;;
604         *)
605                 echo "Unknown httpd specified: $httpd"
606                 exit 1
607                 ;;
608         esac
609 }
610
611 case "$action" in
612 stop)
613         stop_httpd
614         exit 0
615         ;;
616 start)
617         start_httpd
618         exit 0
619         ;;
620 restart)
621         stop_httpd
622         start_httpd
623         exit 0
624         ;;
625 esac
626
627 gitweb_conf
628
629 resolve_full_httpd
630 mkdir -p "$fqgitdir/gitweb/$httpd_only"
631
632 configure_httpd
633
634 start_httpd
635 url=http://127.0.0.1:$port
636
637 if test -n "$browser"; then
638         httpd_is_ready && git web--browse -b "$browser" $url || echo $url
639 else
640         httpd_is_ready && git web--browse -c "instaweb.browser" $url || echo $url
641 fi