summaryrefslogtreecommitdiff
path: root/lib/perl5/Local/MrRepo/Repo/Git/Annex.pm
blob: d3fa4ead74531802efc6a0f4f7f57d797534cc7b (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
package Local::MrRepo::Repo::Git::Annex;

# Copyright (C) 2019 Sean Whitton
#
# 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/>.

use 5.018;
use strict;
use warnings;
use lib "$ENV{HOME}/lib/perl5";
use parent 'Local::MrRepo::Repo::Git';

use Exporter 'import';
use File::Spec::Functions qw(rel2abs);
use Git::Wrapper;
use JSON;
use Local::ScriptStatus;
use Try::Tiny;
use Term::ReadKey;
use Local::Interactive qw(prompt);

our @EXPORT_OK = ();

# public methods
sub review {
    my $self = shift;

    my $issues = $self->SUPER::review(@_);

    # if there were git issues, fail now, as the annex issues can
    # produce copious output and it is nice to know there were no git
    # issues when reviewing the annex issues
    return $issues if $issues;

    # another command we could consider running is `git annex fsck --fast`

    # 1. Check for files stored only locally where that's not okay
    my @annex_find_output = $self->git->annex("find", "--json",
  "--in", "here", "--and", "--not", "--copies=2", "--and", "--lackingcopies=1");
    unless (@annex_find_output == 0) {
        say_spaced_bullet("Some annex content is present only locally:");
        say "  $_" for map { ${decode_json($_)}{file} } @annex_find_output;
        print "\n";
        say_bold
          ("  use `git annex sync --content' to fix this (`mr push' should be");
        say_bold
          ("  configured to run that command with the right remotes)");
        $issues = 1;
    }
    # 2. Check for unused files which we should be able to clean up
    my ($review_unused) = $self->git->config(qw(--local --get --type=bool
                                                --default true
                                                mrrepo.review-unused));
    $issues = $self->review_unused(interactive => 0) || $issues
      if $review_unused eq 'true';

    return $issues;
}

sub review_unused {
    my $self = shift;
    my %opts = @_;
    $opts{interactive}  //= 0;
    $opts{used_refspec} //= "+refs/heads/*:-refs/heads/synced/*";

    my %unused_args     = (used_refspec => $opts{used_refspec});
    my %dropunused_args = (force        => 1);
    $unused_args{from} = $dropunused_args{from} = $opts{from}
      if defined $opts{from};

    my @to_drop      = ();
    my @unused_files = @{ $self->get_unused(\%unused_args) };
    $self->log_unused(\@unused_files);
    return 0 if @unused_files == 0;
    unless ($opts{interactive}) {
        say_spaced_bullet("There are unused files you can drop with"
              . " `git annex dropunused':");
        say "    " . $_->{number} . "     " . $_->{key} for @unused_files;
        print "\n";
    }

    my $i = 0;
  UNUSED: while ($i < @unused_files) {
        my $unused_file = $unused_files[$i];
        system('clear', '-x') if $opts{interactive};
        say_bold("unused file #" . $unused_file->{number} . ":");

        if ($unused_file->{bad} || $unused_file->{tmp}) {
            say "  looks like stale tmp or bad file, with key "
              . $unused_file->{key};
        } else {
            my @log_lines = @{ $unused_file->{log_lines} };
            if ($opts{interactive}) {
                # truncate log output if necessary to ensure user's
                # terminal does not scroll
                my (undef, $height, undef, undef) = GetTerminalSize();
                splice @log_lines, (($height - 5) - @log_lines)
                  if @log_lines > ($height - 5);
            }
            print "\n";
            say for @log_lines;
            if ($opts{interactive}) {
                my $response;
                while (1) {
                    # before prompting, clear out stdin, to avoid
                    # registered a keypress more than once
                    ReadMode 4;
                    while (defined ReadKey(-1)) { }

                    $i > 0
                      ? print "Drop this unused file?  (y/n/o/d/b) "
                      : print "Drop this unused file?  (y/n/o) ";

                    # Term::ReadKey docs recommend ReadKey(-1) but
                    # that means we need an infinite loop calling
                    # ReadKey(-1) over and over, which ramps up system
                    # load
                    my $response = ReadKey(0);
                    ReadMode 0;

                    # respond to C-c
                    exit 0 if ord($response) == 3;

                    say $response;
                    $response = lc($response);
                    if ($response eq 'y') {
                        push @to_drop, $unused_file->{number};
                        last;
                    } elsif ($response eq 'n') {
                        last;
                    } elsif ($response eq 'o') {
                        system('xdg-open',
                            $self->abs_contentlocation($unused_file->{key}));
                    } elsif ($response eq 'b' and $i > 0) {
                        pop @to_drop
                          if $to_drop[$#to_drop] eq
                          $unused_files[--$i]->{number};
                        next UNUSED;
                    } elsif ($response eq 'd' and $i > 0) {
                        # user wants to drop the list we've
                        # accumulated up until now and get out of this
                        # script
                        last UNUSED;
                    } else {
                        say "invalid response";
                    }
                }
            }
        }
        print "\n";
        $i++;
    }

    $self->git->annex("dropunused", \%dropunused_args, @to_drop) if @to_drop;
    # return boolean value representing whether or not there are any
    # unused files left after this run.  note in non-interactive mode
    # @to_drop will be empty so will always return 1 if we got this
    # far in the subroutine
    return @to_drop != @unused_files;
}

sub get_unused {
    my $self = shift;

    my @unused_files;
    my ($bad, $tmp) = (0, 0);
    foreach ($self->git->annex("unused", @_)) {
        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 @unused_files,
              { number => $1, key => $2, bad => $bad, tmp => $tmp };
        }
    }
    return \@unused_files;
}

sub log_unused {
    my $self         = shift;
    my $unused_files = shift;

    foreach my $unused_file (@$unused_files) {
        # 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} } = map { s/^/  /r } $self->git->RUN(
            "-c",
            "diff.renameLimit=3000",
            "log",
            {
                stat        => 1,
                no_textconv => 1
            },
            "--color=always",
            "-S",
            $unused_file->{key});
    }
}

sub abs_contentlocation {
    my $self = shift;
    my $key  = shift;

    my ($contentlocation)
      = $self->git->annex("contentlocation", $key);
    return rel2abs($contentlocation, $self->toplevel);
}

1;