4b9ed856fed77b182ed768c160aedfeb9cba7e1e
[catagits/Gitalist.git] / lib / Gitalist / Model / GitRepos.pm
1 package Gitalist::Model::GitRepos;
2
3 use Moose;
4 use Gitalist::Git::Repo;
5 use Gitalist::Git::CollectionOfProjects::FromListOfDirectories;
6 use MooseX::Types::Moose qw/Maybe ArrayRef/;
7 use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
8 use Moose::Util::TypeConstraints;
9 use namespace::autoclean;
10
11 extends 'Catalyst::Model';
12
13 with 'Catalyst::Component::InstancePerContext';
14
15 my $repo_dir_t = subtype NonEmptySimpleStr,
16     where { -d $_ },
17     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' };
18
19 has config_repo_dir => (
20     isa => NonEmptySimpleStr,
21     is => 'ro',
22     init_arg => 'repo_dir',
23     predicate => 'has_config_repo_dir',
24 );
25
26 has repo_dir => (
27     isa => Maybe[$repo_dir_t],
28     is => 'ro',
29     lazy_build => 1
30 );
31
32 has repos => (
33     isa => ArrayRef[$repo_dir_t],
34     is => 'ro',
35     default => sub { [] },
36     traits => ['Array'],
37     handles => {
38         _repos_count => 'count',
39     },
40 );
41
42 sub _build_repo_dir {
43     my $self = shift;
44     $ENV{GITALIST_REPO_DIR} ?
45         $ENV{GITALIST_REPO_DIR}
46       : $self->has_config_repo_dir
47       ? $self->config_repo_dir
48         : '';
49 }
50
51 after BUILD => sub {
52     my $self = shift;
53     # Explode loudly at app startup time if there is no list of
54     # projects or repos dir, rather than on first hit
55     $self->_repos_count || $self->repo_dir;
56 };
57
58 sub build_per_context_instance {
59     my ($self, $app) = @_;
60     if ($self->_repos_count) {
61         Gitalist::Git::CollectionOfProjects::FromListOfDirectories->new(repos => $self->repos);
62     }
63     else {
64         Gitalist::Git::Repo->new(repo_dir => $self->repo_dir);
65     }
66 }
67
68 __PACKAGE__->meta->make_immutable;
69
70 __END__
71
72 =head1 AUTHORS
73
74 See L<Gitalist> for authors.
75
76 =head1 LICENSE
77
78 See L<Gitalist> for the license.
79
80 =cut