gitweb/lib - Cache captured output (using get/set)
[git/jnareb-git.git] / gitweb / lib / GitwebCache / CacheOutput.pm
blob458e3142362d013413efe9bcf4b7d0a3cf2c0e8d
1 # gitweb - simple web interface to track changes in git repositories
3 # (C) 2010, Jakub Narebski <jnareb@gmail.com>
4 # (C) 2006, John 'Warthog9' Hawley <warthog19@eaglescrag.net>
6 # This program is licensed under the GPLv2
9 # Capturing and caching (gitweb) output
12 # Capture output, save it in cache and print it, or retrieve it from
13 # cache and print it.
15 package GitwebCache::CacheOutput;
17 use strict;
18 use warnings;
20 use Exporter qw(import);
21 our @EXPORT = qw(cache_output capture_stop);
22 our %EXPORT_TAGS = (all => [ @EXPORT ]);
24 # cache_output($cache, $capture, $key, $action_code);
26 # Attempts to get $key from $cache; if successful, prints the value.
27 # Otherwise, calls $action_code, capture its output using $capture,
28 # and use the captured output as the new value for $key in $cache,
29 # then print captured output.
31 # It is assumed that captured data is already converted and it is
32 # in ':raw' format (and thus restored in ':raw' from cache)
34 # default capture class (engine), if none provided
35 our $DEFAULT_CAPTURE_CLASS = 'GitwebCache::Capture::Simple';
36 sub cache_output {
37 my ($cache, $capture, $key, $code) = @_;
39 $capture = setup_capture($capture);
41 # check if data is in the cache
42 my $data = $cache->get($key);
44 # capture and cache output, if there was nothing in the cache
45 if (!defined $data) {
46 $data = $capture->capture($code);
47 $cache->set($key, $data) if defined $data;
50 # print cached data
51 if (defined $data) {
52 binmode STDOUT, ':raw';
53 print $data;
56 return $data;
59 # capture_stop($cache, $capture);
61 # Stops capturing output; to be used in die_error, so that error pages
62 # are not cached (not captured and cached).
63 sub capture_stop {
64 my ($cache, $capture) = @_;
66 if (defined $capture) {
67 return $capture->capture_stop();
69 return;
72 # ......................................................................
73 # helper subroutines
75 # setup capture engine
76 sub setup_capture {
77 my $capture = shift;
79 $capture ||= $DEFAULT_CAPTURE_CLASS;
80 if (!ref($capture)) {
81 eval "require $capture;" or die $@;
82 $capture = $capture->new();
85 return $capture;
89 __END__
90 # end of package GitwebCache::CacheOutput