45c9e356c1e8d329a730ef2fedcaf128bde15863
[catagits/Gitalist.git] / lib / Gitalist / Model / CollectionOfRepos.pm
1 package Gitalist::Model::CollectionOfRepos;
2
3 use Moose;
4 use Gitalist::Git::CollectionOfRepositories::FromDirectoryRecursive;
5 use Gitalist::Git::CollectionOfRepositories::FromListOfDirectories;
6 use MooseX::Types::Moose qw/Maybe ArrayRef/;
7 use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
8 use Moose::Util::TypeConstraints;
9 use Moose::Autobox;
10 use namespace::autoclean;
11
12 extends 'Catalyst::Model';
13
14 with 'Catalyst::Component::InstancePerContext';
15
16 my $repo_dir_t = subtype NonEmptySimpleStr,
17     where { -d $_ },
18     message { 'Cannot find repository dir: "' . $_ . '", please set up gitalist.conf, or set GITALIST_REPO_DIR environment or pass the --repo_dir parameter when starting the application' };
19
20 my $arrayof_repos_dir_t = subtype ArrayRef[$repo_dir_t],
21     where { 1 },
22     message { 'Cannot find repository directories listed in config - these are invalid directories: ' . join(', ', $_->flatten) };
23
24 coerce $arrayof_repos_dir_t,
25     from NonEmptySimpleStr,
26     via { [ $_ ] };
27
28 has config_repo_dir => (
29     isa => NonEmptySimpleStr,
30     is => 'ro',
31     init_arg => 'repo_dir',
32     predicate => 'has_config_repo_dir',
33 );
34
35 has repo_dir => (
36     isa => $repo_dir_t,
37     is => 'ro',
38     lazy_build => 1
39 );
40
41 has repos => (
42     isa => $arrayof_repos_dir_t,
43     is => 'ro',
44     default => sub { [] },
45     traits => ['Array'],
46     handles => {
47         _repos_count => 'count',
48     },
49     coerce => 1,
50 );
51
52 sub _build_repo_dir {
53     my $self = shift;
54     $ENV{GITALIST_REPO_DIR} ?
55         $ENV{GITALIST_REPO_DIR}
56       : $self->has_config_repo_dir
57       ? $self->config_repo_dir
58         : '';
59 }
60
61 after BUILD => sub {
62     my $self = shift;
63     # Explode loudly at app startup time if there is no list of
64     # repositories or repos dir, rather than on first hit
65     $self->_repos_count || $self->repo_dir;
66 };
67
68 sub build_per_context_instance {
69     my ($self, $app) = @_;
70     if ($self->_repos_count) {
71         Gitalist::Git::CollectionOfRepositories::FromListOfDirectories->new(repos => $self->repos);
72     }
73     else {
74         Gitalist::Git::CollectionOfRepositories::FromDirectoryRecursive->new(repo_dir => $self->repo_dir);
75     }
76 }
77
78 __PACKAGE__->meta->make_immutable;
79
80 __END__
81
82 =head1 AUTHORS
83
84 See L<Gitalist> for authors.
85
86 =head1 LICENSE
87
88 See L<Gitalist> for the license.
89
90 =cut