Gave Repo a method to return a Project.
[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 Path::Class;
6     use Gitalist::Git::Project;
7     has repo_dir => ( isa => NonEmptySimpleStr,
8                       is => 'ro',
9                       required => 1 );
10
11     method project (NonEmptySimpleStr $project) {
12         my $pd = $self->dir_from_project_name($project);
13         return Gitalist::Git::Project->new(
14             name => $project,
15             path => $pd,
16         );
17     }
18
19
20 =head2 _is_git_repo
21
22 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
23 C<git> repo.
24
25 =cut
26
27     method _is_git_repo ($dir) {
28         return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
29     }
30
31 =head2 project_dir
32
33 The directory under which the given project will reside i.e C<.git/..>
34
35 =cut
36
37     method project_dir ($project) {
38         my $dir = blessed($project) && $project->isa('Path::Class::Dir')
39             ? $project->stringify
40                 : $self->dir_from_project_name($project);
41
42         $dir .= '/.git'
43             if -f dir($dir)->file('.git/HEAD');
44
45         return $dir;
46     }
47
48 =head2 list_projects
49
50 For the C<repo_dir> specified in the config return an array of projects where
51 each item will contain the contents of L</project_info>.
52
53 =cut
54
55     method list_projects {
56         my $base = dir($self->repo_dir);
57         my @ret;
58         my $dh = $base->open || die "Could not open $base";
59         while (my $file = $dh->read) {
60             next if $file =~ /^.{1,2}$/;
61
62             my $obj = $base->subdir($file);
63             next unless -d $obj;
64             next unless $self->_is_git_repo($obj);
65
66             # XXX Leaky abstraction alert!
67             my $is_bare = !-d $obj->subdir('.git');
68
69             my $name = (File::Spec->splitdir($obj))[-1];
70             push @ret, Gitalist::Git::Project->new( name => $name,
71                                      path => $obj,
72                                  );
73         }
74
75         return [sort { $a->{name} cmp $b->{name} } @ret];
76     }
77
78 =head2 dir_from_project_name
79
80 Get the corresponding directory of a given project.
81
82 =cut
83
84     method dir_from_project_name (Str $project) {
85         return dir($self->repo_dir)->subdir($project);
86     }
87
88
89
90 }                               # end class