GitRepositories.pm untested

filter: Statementstmt 0.0% 0 / 329 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 422 CC 24 SCAR 46.0
CC
24
Cov
0%
generate
272.0
genBranchTree
42.0
migrate
12.0
CRAP 99.8
1 package HiD::Generator::GitRepositories;
2 # ABSTRACT: HiD GitRepository listing generator
3 use Moose;
4 with 'HiD::Generator';
5 use HiD::Generator::GitRepositories::GitRepository;
6 use File::Basename;
7 use Text::Markdown;
8 use Try::Tiny;
9 use DateTime;
10 use DateTime::TimeZone;
11 use DBI;
12 use DBD::SQLite;
13 use DBIx::Migration;
14 use File::ShareDir ':ALL';
15 use Text::VimColor;
16 use Image::WordCloud;
17 use strict;
18 use warnings;
19  
20 our $VERSION = "0.3";
21  
22 has 'dbh' => (is=>'rw');
23  
24 has 'dbfile' => (is => 'rw');
25  
26 has 'repo_dir' => (is => 'rw');
27  
28 has 'list_layout' => (is => 'rw');
29  
30 has 'repo_layout' => (is => 'rw');
31  
32 has 'index_layout' => (is => 'rw');
33  
34 has 'base_url' => (is => 'rw');
35  
36  
37 has 'destination' => (is => 'rw');
38  
39 has 'share_dir' => (is => 'rw');
40  
41 has 'git_base_http_url' => (is => 'rw');
42  
43  
44 has 'git_base_ssh_url' => (is => 'rw');
45  
46 sub migrate
47 {
48 my $self = shift;
49  
50 die("No database file available") unless $self->dbfile();
51 my $m = DBIx::Migration->new(
52 {
53 dsn => "dbi:SQLite:dbname=" . $self->dbfile(),
54 dir => $self->share_dir() . "/migration/"
55 }
56 );
57  
58 if ( $m->version != 1 )
59 {
60 $m->migrate(1);
61 }
62  
63 }
64  
65 sub refresh_database
66 {
67 my $self = shift;
68  
69 my $sth = $self->dbh()->prepare("SELECT dir, reponame from repository");
70 $sth->execute();
71  
72 while (my $row=$sth->fetchrow_hashref)
73 {
74 if (! -d $row->{dir})
75 {
76 my $sth2 = $self->dbh()->prepare("DELETE FROM repository where reponame=?");
77 $sth2->execute($row->{reponame});
78 $sth2->finish;
79  
80 $sth2 = $self->dbh()->prepare("DELETE FROM repository_tags where reponame=?");
81 $sth2->execute($row->{reponame});
82 $sth2->finish;
83  
84 $sth2 = $self->dbh()->prepare("DELETE FROM repository_languages where reponame=?");
85 $sth2->execute($row->{reponame});
86 $sth2->finish;
87  
88 }
89 }
90  
91 $sth->finish;
92  
93 }
94  
95  
96 sub removeRepo
97 {
98 my $self = shift;
99 my $reponame = shift;
100  
101  
102 my $sth = $self->dbh()->prepare("DELETE FROM repository where reponame=?");
103 $sth->execute($reponame);
104 $sth->finish;
105  
106 $sth = $self->dbh()->prepare("DELETE FROM repository_tags where reponame=?");
107 $sth->execute($reponame);
108 $sth->finish;
109  
110 $sth = $self->dbh()->prepare("DELETE FROM repository_languages where reponame=?");
111 $sth->execute($reponame);
112 $sth->finish;
113  
114 }
115  
116 sub addRepo
117 {
118 my $self = shift;
119 my $repo = shift;
120  
121 my $sth = $self->dbh()->prepare("INSERT into repository(reponame, dir, description, lastchange) VALUES(?,?,?,?)");
122 $sth->execute($repo->name, $repo->git_dir, $repo->description, $repo->lastChange()->epoch);
123 $sth->finish;
124  
125 for my $t ($repo->tags)
126 {
127 $sth = $self->dbh()->prepare("INSERT into repository_tags(reponame, tag) VALUES(?,?)");
128 $sth->execute($repo->name, $t);
129 $sth->finish;
130 }
131  
132 for my $l (@{$repo->languages})
133 {
134 $sth = $self->dbh()->prepare("INSERT into repository_languages(reponame, language) VALUES(?,?)");
135 $sth->execute($repo->name, $l);
136 $sth->finish;
137 }
138  
139 }
140  
141  
142 sub getRepos
143 {
144 my $self = shift;
145 my $order = shift || "name";
146 my $dir = shift || "DESC";
147 my @repos;
148  
149 my $sth = $self->dbh()->prepare("SELECT repository.reponame as name, repository.dir as dir,
150 repository.description as description,
151 repository.lastchange as lastchange from repository order by " . $order . " ". $dir );
152 $sth->execute();
153  
154 my $tz=DateTime::TimeZone->new( name => 'local' );
155 my $count=0;
156  
157 while (my $repo = $sth->fetchrow_hashref)
158 {
159 $count++;
160 $repo->{count}=$count;
161 $repo->{lastchange} = DateTime->from_epoch( epoch => $repo->{lastchange}, time_zone=>$tz)->ymd();
162 my $sth2 = $self->dbh()->prepare("SELECT tag from repository_tags where reponame = ?");
163 $sth2->execute($repo->{name});
164  
165 my @tags;
166 while (my $row=$sth2->fetchrow_hashref)
167 {
168 push(@tags, $row->{tag});
169 }
170 $sth2->finish;
171 $repo->{tags}=\@tags;
172  
173 $sth2 = $self->dbh()->prepare("SELECT language from repository_languages where reponame = ?");
174 $sth2->execute($repo->{name});
175  
176 my @languages;
177 while (my $row=$sth2->fetchrow_hashref)
178 {
179 push(@languages, $row->{language});
180 }
181 $sth2->finish;
182 $repo->{languages}=\@languages;
183  
184  
185 push(@repos, $repo);
186 }
187  
188 $sth->finish;
189  
190 return \@repos;
191 }
192  
193 sub getAllTags
194 {
195 my $self = shift;
196 my @tags;
197  
198 my $sth = $self->dbh()->prepare("SELECT tag from repository_tags");
199 $sth->execute();
200 while (my $row = $sth->fetchrow_hashref)
201 {
202 push(@tags, $row->{tag});
203 }
204  
205 return @tags;
206 }
207  
208 sub getAllLangs
209 {
210 my $self = shift;
211 my @langs;
212  
213 my $sth = $self->dbh()->prepare("SELECT language from repository_languages");
214 $sth->execute();
215 while (my $row = $sth->fetchrow_hashref)
216 {
217 push(@langs, $row->{language});
218 }
219  
220 return @langs;
221 }
222  
223 sub generate {
224 my( $self , $site ) = @_;
225  
226 # do nothing if generation is not enabled
227 return unless $site->config->{gitrepositories}{generate};
228  
229 $self->share_dir(dist_dir('HiD-Generator-GitRepositories'));
230  
231 # fetch the directory containing all the git repositories from the config file
232 $self->repo_dir($site->config->{gitrepositories}{dir});
233 die "directory holding the git repositories not given" unless $self->repo_dir();
234  
235 # check if repository directory exist
236 die("GitRepository directory does not exist") unless -d $self->repo_dir();
237  
238 # fetch the list layout file from config file
239 $self->list_layout($site->config->{gitrepositories}{list_layout});
240 die "Must define gitrepositories.list_layout in config" unless $self->list_layout();
241  
242 # fetch the repo layout file from config file
243 $self->repo_layout($site->config->{gitrepositories}{repo_layout});
244 die "Must define gitrepositories.repo_layout in config" unless $self->repo_layout();
245  
246 # fetch the index layout file from config file
247 $self->index_layout($site->config->{gitrepositories}{index_layout});
248 die "Must define gitrepositories.index_layout in config" unless $self->index_layout();
249  
250 # fetch the base url from the config file
251 $self->base_url($site->config->{gitrepositories}{url});
252 $self->base_url('repositories/') unless $self->base_url();
253  
254 # fetch the destination from the config file
255 $self->destination($site->config->{gitrepositories}{destination});
256 $self->destination($site->destination) unless $self->destination();
257 $self->_create_destination_directory_if_needed( $self->destination() );
258  
259 # fetch the database file from config file
260 $self->dbfile($site->config->{gitrepositories}{dbfile});
261 $self->dbfile($site->config->{source} ."/_gitrepos.db") unless $self->dbfile();
262  
263 # fetch the git_base_http_url from config file
264 $self->git_base_http_url($site->config->{gitrepositories}{git_base_http_url});
265  
266 # fetch the git_base_ssh_url from config file
267 $self->git_base_ssh_url($site->config->{gitrepositories}{git_base_ssh_url});
268  
269 # open the database file
270 $self->dbh(DBI->connect("dbi:SQLite:dbname=" . $self->dbfile(),"",""));
271 die("Can not connect to database " . $self->dbfile()) unless $self->dbh();
272  
273 # update database schema
274 $self->migrate();
275  
276 # remove non existing repositories from database
277 $self->refresh_database();
278  
279 #search all repositories within repo_dir
280 my @dirs = glob($self->repo_dir() . "/*");
281  
282 # array for all repos which should be reprocessed
283 my @repos;
284  
285  
286 for my $d (@dirs)
287 {
288  
289 my $gitRepo;
290  
291 # check if the directory is a git repository and return a git repository object
292 try {
293 $gitRepo = HiD::Generator::GitRepositories::GitRepository->new(
294 git_dir => $d
295 );
296 } catch {
297 warn "caught error: $_"; # not $@
298 };
299  
300 if (defined($gitRepo)) {
301 if ($gitRepo->hasMetaData) {
302  
303 my $generate=1;
304 # check if the file already exist and ist newer than last repo change
305 if ( -e $self->destination() . "/". $self->base_url() . "index.html")
306 {
307 open my $fh,"<", $self->destination() . "/" . $self->base_url() . "index.html";
308 my $epoch_timestamp = (stat($fh))[9];
309 close $fh;
310 my $tz=DateTime::TimeZone->new( name => 'local' );
311 my $file = DateTime->from_epoch( epoch => $epoch_timestamp, time_zone=>$tz );
312 my $repo = $gitRepo->lastChange();
313  
314 # if file is newer than last change do not generate repo files
315 if (DateTime->compare( $file, $repo ) == 1)
316 {
317 $generate=0;
318 }
319 }
320  
321 if ($generate)
322 {
323 # for regeneration we have to first remove repo from database
324 $self->removeRepo($gitRepo->name);
325  
326 # parse for programming languages
327 $gitRepo->parse_languages();
328  
329 # now update repository data in database
330 $self->addRepo($gitRepo);
331  
332 push(@repos, $gitRepo);
333 }
334 }
335 }
336 }
337  
338 my $dbrepos = $self->getRepos();
339 my $nrrepos = @{$dbrepos};
340  
341 #create word cloud image for all tags
342 my $font_dir = "/usr/share/fonts/truetype/freefont/";
343 my $wc_tags = Image::WordCloud->new(font_path => $font_dir, background=>[255,255,255], font=>"FreeSans.ttf", image_size=>[300,300] );
344 $wc_tags->words(join ( ' ', $self->getAllTags ));
345 my $gd_tags = $wc_tags->cloud();
346 #make image background transparent
347 my $white = $gd_tags->colorAllocate(255,255,255);
348 $gd_tags->transparent($white);
349  
350 readpipe("mkdir -p " . $self->destination() . "/images/");
351 open(my $fh, '>', $self->destination()."/images/wc_tags.png");
352 binmode $fh;
353 print $fh $gd_tags->png();
354 close($fh);
355  
356 #create word cloud image for all languages
357 my $wc_langs = Image::WordCloud->new(font_path => $font_dir, background=>[255,255,255], font=>"FreeSans.ttf", image_size=>[300,300] );
358 $wc_langs->words(join ( ' ', $self->getAllLangs ));
359 my $gd_langs = $wc_langs->cloud();
360 #make image background transparent
361 $white = $gd_langs->colorAllocate(255,255,255);
362 $gd_langs->transparent($white);
363  
364 open($fh, '>', $self->destination()."/images/wc_langs.png");
365 binmode $fh;
366 print $fh $gd_langs->png();
367 close($fh);
368  
369  
370 # create the index.htm page
371 my $index = HiD::Page->new({
372 dest_dir => $self->destination(),
373 hid => $site,
374 url => "/index.htm",
375 input_filename => $self->index_layout(),
376 layouts => $site->layouts,
377 });
378 my $last_repos = $self->getRepos("lastchange", "DESC");
379 splice @{$last_repos}, 6;
380  
381 $index->metadata->{repos} = $last_repos;
382 $index->metadata->{nrrepos} = $nrrepos;
383 $index->metadata->{tagcloud}="/images/wc_tags.png";
384 $index->metadata->{langcloud}="/images/wc_langs.png";
385 $site->add_input( "INDEX" => 'page' );
386 $site->add_object( $index );
387 $site->INFO( "* Injected Index Page");
388  
389 # create the repository listing page
390 my $page = HiD::Page->new({
391 dest_dir => $self->destination(),
392 hid => $site,
393 url => $self->base_url(),
394 input_filename => $self->list_layout(),
395 layouts => $site->layouts,
396 });
397  
398 $page->metadata->{repositories} = $dbrepos;
399 $page->metadata->{nrrepos} = $nrrepos;
400  
401 $site->add_input( "Repositories" => 'page' );
402 $site->add_object( $page );
403  
404 $site->INFO( "* Injected GitRepository Listing");
405  
406 # now create a page for each repository
407 for my $repo (@repos)
408 {
409 for my $branch (@{$repo->branches})
410 {
411 $self->genBranchTree($site, $self->base_url(), $self->destination(), $self->repo_layout(), $repo, $branch->{name},"");
412 }
413  
414 }
415  
416  
417 }
418  
419 sub genBranchTree
420 {
421 my $self = shift;
422 my $site = shift;
423 my $url = shift;
424 my $destination = shift;
425 my $page_file = shift;
426 my $repo = shift;
427 my $branch = shift;
428 my $base = shift;
429 my $root = shift || $base;
430 my $type = shift || "tree";
431 my $ref = shift;
432  
433  
434 #only generate tree of branch if last branch activity is newer than existing files
435  
436 if($type eq "tree") {
437 my $page = HiD::Page->new({
438 dest_dir => $self->destination() ,
439 hid => $site,
440 url => $self->base_url() . "/" . $repo->name ."/" . $branch . "/" . $root . "/" ,
441 input_filename => $self->repo_layout() ,
442 layouts => $site->layouts ,
443 });
444  
445 $page->metadata->{repository} = $repo;
446 my @tree = $repo->getTree($branch, $root);
447 if ($root ne $base)
448 {
449 my $entry = {
450 name => "..",
451 path => "..",
452 type => "tree",
453 date => 0
454 };
455 unshift(@tree, $entry);
456 }
457 my @log=$repo->getFileLog($branch, $root, 1);
458 $page->metadata->{latest_commit}=$log[0];
459 $page->metadata->{tree} = \@tree;
460 $page->metadata->{currentroot} = $root;
461 $page->metadata->{currentbranch} = $branch;
462 $page->metadata->{branches} = $repo->branches;
463 $page->metadata->{git_base_http_url} = $self->git_base_http_url();
464 $page->metadata->{git_base_ssh_url} = $self->git_base_ssh_url();
465 my $dbrepos = $self->getRepos();
466 my $nrrepos = @{$dbrepos};
467 $page->metadata->{nrrepos} = $nrrepos;
468 # check for a readme.md file in current tree and render it
469 for my $t (@tree)
470 {
471 if (lc($t->{name}) eq "readme.md")
472 {
473 my $m = Text::Markdown->new;
474 my $html = $m->markdown($repo->getBlob($t->{ref}));
475 $page->metadata->{content_name} = $t->{name};
476 $page->metadata->{content} = $html;
477 }
478 }
479  
480 $site->add_input( "Repositories" => 'page' );
481 $site->add_object( $page );
482 $site->INFO( "* Injected GitRepository page for repo " . $repo->name . " Branch: " . $branch . " Path: " . $root);
483  
484 for my $t (@tree)
485 {
486 next unless $t->{name} ne "..";
487 my $newroot=$base . $t->{path} . "/";
488 $self->genBranchTree($site, $url, $destination, $page_file, $repo, $branch,$base, $newroot, $t->{type}, $t->{ref});
489 }
490 }
491 else
492 {
493 my $page = HiD::Page->new({
494 dest_dir => $self->destination(),
495 hid => $site ,
496 url => $self->base_url() . "/" . $repo->name ."/" . $branch . "/" . $root . "/" ,
497 input_filename => $self->repo_layout() ,
498 layouts => $site->layouts ,
499 });
500 $page->metadata->{repository} = $repo;
501 $page->metadata->{currentroot} = $root;
502 $page->metadata->{currentbranch} = $branch;
503 my $dbrepos = $self->getRepos();
504 my $nrrepos = @{$dbrepos};
505 $page->metadata->{nrrepos} = $nrrepos;
506  
507 my $file=$root;
508 $file =~s/\/$//;
509 $file="/tmp/" . fileparse($file);
510  
511 my $blob=$repo->getBlob($ref);
512 $blob=~s/^[\n\s]*//g;
513 my $syntax;
514 my $html;
515 if (length($blob) < 100000)
516 {
517 open my $tmp, ">", $file;
518 print $tmp $blob;
519 close $tmp;
520 $syntax = Text::VimColor->new(
521 file => $file,
522 );
523 $html=$syntax->html();
524 } else {
525 $html=$blob;
526 }
527  
528 $page->metadata->{content_name} = $root;
529 $page->metadata->{content_type} = "code";
530 $page->metadata->{content} = $html;
531 $page->metadata->{git_base_http_url} = $self->git_base_http_url();
532 $page->metadata->{git_base_ssh_url} = $self->git_base_ssh_url();
533  
534 $site->add_input( "Repositories" => 'page' );
535 $site->add_object( $page );
536 $site->INFO( "* Injected GitRepository page for repo " . $repo->name . " Branch: " . $branch . " Path: " . $root);
537 }
538 }
539  
540 1;
541  
542 __END__