summaryrefslogtreecommitdiff
path: root/lib/Git/Annex.pm
blob: fd574642853dc5e5792469aa082cf5137821475e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package Git::Annex;
# ABSTRACT: Perl interface to git-annex repositories
#
# Copyright (C) 2019-2020  Sean Whitton <spwhitton@spwhitton.name>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

=head1 SYNOPSIS

  my $annex = Git::Annex->new("/home/spwhitton/annex");

  # run `git annex unused` and then `git log` to get information about
  # unused git annex keys
  my $unused_files
    = $self->unused(used_refspec => "+refs/heads/master", log => 1);
  for my $unused_file (@$unused_files) {
      say "unused file " . $unused_file->{key} . ":";
      say "";
      say "  $_" for $unused_file->{log_lines};
      say "";
      say "you can drop it with: `git annex dropunused "
        . $unused_file->{number} . "`";
      say "";
  }

  # embedded Git::Wrapper instance with shortcut to access annex subcommands
  say for $annex->annex->find(qw(--not --in here));
  $annex->annex->copy(qw(-t cloud --in here --and --lackingcopies=1));

=head1 DESCRIPTION

An instance of the Git::Annex class represents a git repository in
which C<git annex init> has been run.  This module provides some
useful methods for working with such repositories from Perl.  See
L<https://git-annex.branchable.com/> for more information on
git-annex.

=cut

use 5.028;
use strict;
use warnings;

use Cwd;
use File::chdir;
use Git::Wrapper;
use Git::Repository;
use Try::Tiny;
use File::Spec::Functions qw(catfile rel2abs);
use Storable;
use Data::Compare;
use List::Util qw(all);
use Time::HiRes qw(stat time);
use Git::Annex::BatchCommand;
use IPC::System::Simple qw(capturex);

=method new($dir)

Instantiate an object representing a git-annex located in C<$dir>.

=cut

sub new {
    my ($class, $toplevel) = @_;

    $toplevel = $toplevel ? rel2abs($toplevel) : getcwd;

    # if we're in a working tree, rise up to the root of the working
    # tree -- for flexibility, don't require that we're actually in a
    # git repo at all
    my $pid = fork;
    die "fork() failed: $!" unless defined $pid;
    if ($pid) {
        wait;
        chomp($toplevel = capturex "git",
            "-C", $toplevel, "rev-parse", "--show-toplevel")
          if $?;
    } else {
        close STDERR;
        my $output;
        try {
            $output = capturex "git", "-C", $toplevel, "rev-parse",
              "--is-inside-work-tree";
        };
        exit($output and $output =~ /true/);
    }

    bless { toplevel => $toplevel } => $class;
}

=cut

=attr toplevel

The root of the repository.

=cut

sub toplevel { shift->{toplevel} }

=attr git

An instance of L<Git::Wrapper> initialised in the repository.

=cut

sub git {
    my $self = shift;
    $self->{git} //= Git::Wrapper->new($self->toplevel);
}

# =attr repo

# Returns an instance of L<Git::Repository> initialised in the repository.

# =cut

# has repo => (
#     is => 'lazy',
#     # we don't know (here) whether our repo is bare or not, so we
#     # don't know whether to use the git_dir or work_tree arguments to
#     # Git::Repository::new, so we chdir and let call without arguments
#     default => sub { local $CWD = shift->toplevel; Git::Repository->new });

=method unused(%opts)

Runs C<git annex unused> and returns a hashref containing information
on unused files.

The information is cached inside the C<.git/annex> directory.  This
means that a user can keep running your script without repeatedly
executing expensive C<git annex> and C<git log> commands.

Optional arguments:

=over

=item log

If true, run C<git log --stat -S> on each unused file, to see what
filenames the unused data had if and when it was used data in the
annex.

Defaults to false, but if there is log data in the cache it will
always be returned.

=item from

Corresponds to the C<--from> option to C<git annex unused>.

=item used_refspec

Corresponds to the C<--used-refspec> option to C<git annex unused>.

Defaults to the C<annex.used-refspec> git config key if set, or
C<+refs/heads/*:-refs/heads/synced/*>.

=back

=cut

sub unused {
    my ($self, %opts) = @_;
    $opts{log} //= 0;
    my $used_refspec_config;
    try { ($used_refspec_config) = $self->git->config("annex.used-refspec") };
    $opts{used_refspec}
      //= ($used_refspec_config // "+refs/heads/*:-refs/heads/synced/*");

    my %unused_args;
    for (qw(from used_refspec)) {
        $unused_args{$_} = $opts{$_} if defined $opts{$_};
    }

    $self->{_unused} //= retrieve $self->_unused_cache
      if -e $self->_unused_cache;
    # see if cache needs to be invalidated, whether or not we just
    # retrieved it
    if (defined $self->{_unused}) {
        my $git_annex_unused = $self->_git_path(qw(annex unused));
        my $last_unused      = (stat $git_annex_unused)[9];
        my %branch_timestamps
          = map { split }
          $self->git->for_each_ref(
            { format => '%(refname:short) %(committerdate:unix)' },
            "refs/heads/");

        # we don't need to invalidate the cache if the git-annex
        # branch has changed, because the worst that can happen is we
        # try to drop a file which has already been dropped
        delete $branch_timestamps{'git-annex'};

        $self->_clear_unused_cache
          unless $last_unused <= $self->{_unused}{timestamp}
          and Compare(\%unused_args, $self->{_unused}{unused_args})
          and all { $_ < $last_unused } values %branch_timestamps;
    }

    # get the unused info if we couldn't load from the cache or had to
    # invalidate it
    unless (defined $self->{_unused}) {
        my ($bad, $tmp) = (0, 0);
        $self->{_unused}{unused_args} = \%unused_args;
        # make a copy of %unused_args because Git::Wrapper will remove
        # them from the hash
        for ($self->annex->unused({%unused_args})) {
            if (
/Some corrupted files have been preserved by fsck, just in case/
            ) {
                ($bad, $tmp) = (1, 0);
            } elsif (
                /Some partially transferred data exists in temporary files/) {
                ($bad, $tmp) = (0, 1);
            } elsif (/^    ([0-9]+) +([^ ]+)$/) {
                push @{ $self->{_unused}{unused} },
                  { number => $1, key => $2, bad => $bad, tmp => $tmp };
            }
        }
        $self->_store_unused_cache;
    }

    # run any needed calls to git-log(1)
    if ($opts{log}) {
        my $changed = 0;
        foreach my $unused_file (@{ $self->{_unused}{unused} }) {
            next
              if defined $unused_file->{log_lines}
              or $unused_file->{bad}
              or $unused_file->{tmp};
            $changed = 1;
            # We need the RUN here to avoid special postprocessing but
            # also to get the -c option passed -- unclear how to pass
            # short options to git itself, not the 'log' subcommand,
            # with Git::Wrapper except by using RUN (passing long
            # options to git itself is easy, per Git::Wrapper docs)
            @{ $unused_file->{log_lines} } = $self->git->RUN(
                "-c",
                "diff.renameLimit=3000",
                "log",
                {
                    stat        => 1,
                    no_textconv => 1
                },
                "--color=always",
                "-S",
                $unused_file->{key});
        }
        $self->_store_unused_cache if $changed;
    }

    return $self->{_unused}{unused};
}

sub _unused_cache {
    my $self = shift;
    $self->{_unused_cache} //= $self->_git_path(qw(annex unused_info));
}

sub _store_unused_cache {
    my $self = shift;
    $self->{_unused}{timestamp} = time;
    store $self->{_unused}, $self->_unused_cache;
}

sub _clear_unused_cache {
    my $self = shift;
    delete $self->{_unused};
    unlink $self->_unused_cache;
}

=method abs_contentlocation($key)

Returns an absolute path to the content for git-annex key C<$key>.

=cut

sub abs_contentlocation {
    my ($self, $key) = @_;
    my $contentlocation;
    try { ($contentlocation) = $self->annex->contentlocation($key) };
    $contentlocation ? rel2abs($contentlocation, $self->toplevel) : undef;
}

=method batch($cmd, @args)

Instantiate a C<Git::Annex::BatchCommand> object by starting up a
git-annex C<--batch> command.

  my $batch = $annex->batch("find", "--in=here");
  say "foo/bar annexed content is present in this repo"
    if $batch->say("foo/bar");

  # kill the batch process:
  undef $batch;

=cut

sub batch { Git::Annex::BatchCommand->new(@_) }

sub _git_path {
    my ($self, @input) = @_;
    my ($path) = $self->git->rev_parse({ git_path => 1 }, catfile @input);
    rel2abs $path, $self->toplevel;
}

package Git::Annex::Wrapper {

    AUTOLOAD {
        my $self = shift;
        (my $subcommand = our $AUTOLOAD) =~ s/.+:://;
        return if $subcommand eq "DESTROY";
        $subcommand =~ tr/_/-/;
        $$self->git->RUN("annex", $subcommand, @_);
    }
}

=attr annex

Gives access to git-annex subcommands in the same way that
Git::Annex::git gives access to git subcommands.  So

    $self->git->annex("contentlocation", $key);

may be written

    $self->annex->contentlocation($key);

=cut

# credits to Git::Wrapper's author for the idea of accessing
# subcommands in this way; I've just extended that idea to
# subsubcommands of git
sub annex {
    my $self = shift;
    $self->{annex} //= bless \$self => "Git::Annex::Wrapper";
}

1;