18c7ecdac981798392d92e137e97b1be7d6e832a
[catagits/Gitalist.git] / lib / Gitalist / Git / Repo.pm
1 use MooseX::Declare;
2
3 class Gitalist::Git::Repo {
4     use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
5     use MooseX::Types::Path::Class qw/Dir/;
6     use MooseX::Types::Moose qw/ArrayRef/;
7     use aliased 'Gitalist::Git::Project';
8
9     has repo_dir => (
10         isa => Dir,
11         is => 'ro',
12         required => 1,
13         coerce => 1,
14     );
15
16     has projects => (
17         is => 'ro',
18         isa => ArrayRef['Gitalist::Git::Project'],
19         required => 1,
20         lazy_build => 1,
21     );
22
23     ## Public methods
24     method project (NonEmptySimpleStr $project) {
25         my $path = $self->repo_dir->subdir($project)->resolve;
26         die "Directory traversal prohibited" unless $self->repo_dir->contains($path);
27         die "Not a valid Project" unless $self->_is_git_repo($path);
28         return Project->new( $self->repo_dir->subdir($project) );
29     }
30
31     ## Builders
32     method _build_projects {
33         my $base = $self->repo_dir;
34         my $dh = $base->open || die "Could not open $base";
35         my @ret;
36         while (my $file = $dh->read) {
37             next if $file =~ /^.{1,2}$/;
38
39             my $obj = $base->subdir($file);
40             next unless -d $obj;
41             next unless $self->_is_git_repo($obj);
42
43             push @ret, $self->project($file);
44         }
45
46         return [sort { $a->name cmp $b->name } @ret];
47     }
48
49     ## Private methods
50     # Determine whether a given directory is a git repo.
51     method _is_git_repo ($dir) {
52         return -f $dir->file('HEAD') || -f $dir->file('.git', 'HEAD');
53     }
54 }                               # end class
55
56 __END__
57
58 =head1 NAME
59
60 Gitalist::Git::Repo - Model of a repository directory
61
62 =head1 SYNOPSIS
63
64     my $repo = Gitalist::Git::Repo->new( repo_dir => $Dir );
65     my $project_list = $repo->projects;
66     my $first_project = @$project_list[0];
67     my $named_project = $repo->project('Gitalist');
68
69 =head1 DESCRIPTION
70
71 This class models a Gitalist Repo, which is a collection of
72 Projects (git repositories).  It is used for creating Project
73 objects to work with.
74
75 =cut
76
77 =head1 ATTRIBUTES
78
79 =head2 repo_dir
80
81 L<Path::Class::Dir> for the root of the Repo.
82
83 =cut
84
85 =head2 projects
86
87 An array of L<Gitalist::Git::Project> for each valid git repo
88 found in repo_dir.
89
90 =cut
91
92
93 =head1 METHODS
94
95 =head2 project (NonEmptySimpleStr $project)
96
97 Returns a L<Gitalist::Git::Project> for the specified project
98 name.
99
100 =cut
101
102 =head1 SEE ALSO
103
104 L<Gitalist::Git::Project>
105
106 =head1 AUTHORS
107
108 See L<Gitalist> for authors.
109
110 =head1 LICENSE
111
112 See L<Gitalist> for the license.
113
114 =cut