Refactor somewhat
[catagits/Gitalist.git] / lib / Gitalist / Git / Object.pm
1 use MooseX::Declare;
2 use Moose::Autobox;
3
4 class Gitalist::Git::Object {
5     use MooseX::Types::Moose qw/Str Int/;
6     use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
7     use File::Stat::ModeString qw/mode_to_string/;
8     # project and sha1 are required initargs
9     has project => ( isa => 'Gitalist::Git::Project',
10                      required => 1,
11                      is => 'ro',
12                      weak_ref => 1,
13                      handles => [ 'run_cmd' ],
14                  );
15     has sha1 => ( isa => NonEmptySimpleStr,
16                required => 1,
17                is => 'ro' );
18
19     has $_ => ( isa => NonEmptySimpleStr,
20                   required => 1,
21                   is => 'ro',
22                   lazy_build => 1 )
23         for qw/type modestr size/;
24
25     # objects can't determine their mode or filename
26     has file => ( isa => NonEmptySimpleStr,
27                   required => 0,
28                   is => 'ro' );
29     has mode => ( isa => Int,
30                 required => 1,
31                 default => 0,
32                 is => 'ro' );
33
34     method BUILD { $self->$_() for qw/type size modestr/ }
35
36     foreach my $key (qw/ type size /) {
37         method "_build_$key" {
38             $self->_cat_file_with_flag(substr($key, 0, 1))->chomp;
39         }
40     }
41
42     method _build_modestr {
43         my $modestr = mode_to_string($self->mode);
44         return $modestr;
45     }
46
47     method _cat_file_with_flag ($flag) {
48         $self->run_cmd('cat-file', '-' . $flag, $self->{sha1})
49     }
50
51 =head2 contents
52
53 Return the contents of a given file.
54
55 =cut
56
57     # FIXME - Should be an attribute so it gets cached?
58     method contents {
59         if ( $self->type ne 'blob' ) {
60             die "object $self->sha1 is not a file\n"
61         }
62
63         $self->_cat_file_with_flag('p');
64     }
65
66 } # end class