-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnapshot
executable file
·494 lines (405 loc) · 11 KB
/
snapshot
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#!/usr/bin/perl
# Simple utility which uses diff/patch to snapshot
# a single text file without touching the original file.
use Getopt::Long;
use Pod::Usage;
use Switch;
use File::Spec;
#use Data::Dumper;
my $help;
my $man;
my $message;
my $restore_time;
my $operation;
my $grep_args;
my $filename;
my $snapshot_dir;
my $original_snapshot;
my $patch_filename;
my $loglevel = 1;
my $cpargs = "-a";
sub info($);
sub verbose($);
sub debug($);
sub error($);
parameters();
switch($operation)
{
case "save"
{ do_save(); }
case "restore"
{ do_restore(); }
case "view"
{ do_view(); }
case "list"
{ do_list(); }
case "grep"
{ do_grep(); }
}
#################### functions ########################
sub do_grep()
{
check_filename();
foreach my $patch (`ls -tr $snapshot_dir`)
{
chomp $patch;
my $patchfile = "${snapshot_dir}/${patch}";
if ( $patch eq "original" )
{
system("grep $grep_args $patchfile");
}
else
{
system("grep -E '^-|^\\+' '${snapshot_dir}/${patch}' | grep -Ev '^---|^\\+\\+\\+' | cut -c 2- | grep $grep_args ");
}
}
}
sub do_list()
{
check_filename();
info sprintf "%-32s%s\n", "Patch Time", "Comment";
my $datestr = epoch2date( mod_timestamp( "${snapshot_dir}/original") );
info sprintf "%-32s%s", $datestr, "Original Snapshot";
foreach my $patch (`ls -tr $snapshot_dir`)
{
chomp $patch;
next if ($patch eq "original");
my $this_timestamp = $patch;
$this_timestamp =~ s/\.patch$//;
my $comment = get_comment($patch);
my $datestr = epoch2date($this_timestamp);
info sprintf "%-32s%s", $datestr, $comment;
}
}
sub do_view()
{
my $tempfile = do_restore();
unless($ENV{EDITOR})
{
error "You don't have your environment \$EDITOR set";
exit(1);
}
system($ENV{EDITOR}, "$tempfile");
system("rm", "-v", $tempfile);
}
sub do_save()
{
check_filename();
my ($tempfile, $timestamp) = roll_patches("last");
my $diff = `diff -uN "$tempfile" "$filename"`;
unlink($tempfile);
if ($diff eq undef)
{
verbose "No changes found in $filename";
exit(0);
}
if ($message ne undef)
{
$diff = "@@ " . $message . " @@\n" . $diff;
}
debug "$patch_filename: $diff";
open(my $fd, "> $patch_filename") or die "Can't create patch file $patch_filename\n";
print $fd $diff;
close($fd);
chmod(0400, $patch_filename);
verbose "Saved patch $patch_filename";
}
sub do_restore()
{
check_filename();
my ($tempfile, $timestamp) = roll_patches($restore_time);
my $datestr = epoch2date($timestamp);
info "File $tempfile is restored to time $datestr";
return($tempfile);
}
# Roll through the patches and create a temp file
# for a specific snapshot. Either a unix epoch
# for a patch file, or special macros "last"
# for the most recent snapshot, or any
# Linux `date --date` strings like "last Thursday"
sub roll_patches()
{
my ($when) = @_;
my $tempfile = `mktemp`;
chomp $tempfile;
chmod(0600, $tempfile);
if ($when eq "last")
{
$when = `ls -t $snapshot_dir |grep -v original | head -1`;
$when =~ s/\.patch$//;
}
elsif (not $when =~ /^\d+$/)
{
$when = `date --date="$when" "+%s"`;
chomp $when;
}
verbose "Searching for patch time " . epoch2date($when) if ($when);
system("cp", "-a", "$original_snapshot", "$tempfile");
chmod(0600, $tempfile);
my $recent_timestamp = mod_timestamp($original_snapshot);
foreach my $patch (`ls -tr $snapshot_dir`)
{
chomp $patch;
next if ($patch eq "original");
my $this_timestamp = $patch;
$this_timestamp =~ s/\.patch$//;
if (int $this_timestamp > int $when)
{
debug "Skipping $this_timestamp";
last;
}
debug "Rolling through '$patch'";
system("patch \"$tempfile\" \"${snapshot_dir}/${patch}\" 1>/dev/null 2>/dev/null");
$recent_timestamp = $this_timestamp;
}
return($tempfile, $recent_timestamp);
}
# Perform checks, set up informational variables
sub check_filename()
{
$filename = shift @ARGV;
unless ( -r $filename )
{
error "Can't read file $filename";
exit(1);
}
unless ( -f $filename )
{
error "$filename is not a plain file";
exit(1);
}
unless($snapshot_dir)
{
my $abs_path = File::Spec->rel2abs( $filename );
my($vol,$dir,$file) = File::Spec->splitpath($abs_path);
$snapshot_dir = "${dir}.${\sanitize_filename($file)}-snapshot/";
}
unless (-e -d $snapshot_dir)
{
if ( $operation eq "restore" || $operation eq "list" || $operation eq "view" )
{
error "Snapshot directory $snapshot_dir doesn't exist?";
exit(2);
}
else
{
mkdir($snapshot_dir) or die "Can't create directory $snapshot_dir";
chmod(0700, $snapshot_dir);
}
}
$original_snapshot = "${snapshot_dir}/original";
unless (-e $original_snapshot)
{
# create original base file
system("cp", $cpargs, "$filename", "$original_snapshot");
chmod(0400, $original_snapshot);
}
if ( $operation eq "save" )
{
my $mtime = mod_timestamp($filename);
$patch_filename = "${snapshot_dir}/${mtime}.patch";
}
}
# nested parameters for each operation command
sub parameters()
{
my %params = (
'help|?' => \$help,
'man' => \$man,
'verbose' => sub { $loglevel = 2; $cpargs .= "v" },
'debug' => sub { $loglevel = 3; $cpargs .= "v" },
'snapshot_dir=s' => \$snapshot_dir,
);
switch($ARGV[0])
{
case "save"
{
$operation = shift @ARGV;
$params{'message|m=s'} = \$message;
}
case "restore"
{
$operation = shift @ARGV;
$params{'time|t=s'} = \$restore_time;
}
case "view"
{
$operation = shift @ARGV;
$params{'time|t=s'} = \$restore_time;
}
case "list"
{
$operation = shift @ARGV;
}
case "grep"
{
$operation = shift @ARGV;
$grep_args = join(" ", map {qq('$_')} splice @ARGV, 0, -1);
}
else
{
}
}
GetOptions(%params) or pod2usage(2);
pod2usage(-exitstatus => 1, -verbose => 2) if $man;
pod2usage(-verbose => 99, -sections => "NAME|SYNOPSIS|OPERATION|GLOBAL OPTIONS") if ($help || $operation eq undef);
}
sub epoch2date()
{
my $datestr = `date --date="\@$_[0]"`;
chomp $datestr;
return $datestr;
}
sub mod_timestamp()
{
my $file = $_[0];
my @info = stat($file);
return(int $info[9]);
}
sub get_comment()
{
my $patch = $_[0];
open(my $fd, "${snapshot_dir}/${patch}");
my $first = <$fd>;
close($fd);
chomp $first;
return undef unless ($first =~ /^\@\@\s/);
$first =~ s/^\@\@\s(.*)\@\@$/$1/;
return($first);
}
sub error($)
{
my $message = $_[0];
print STDERR "$message\n";
}
sub info($)
{
my $message = $_[0];
print "$message\n";
}
sub verbose($)
{
my $message = $_[0];
if ($loglevel >= 2)
{
print "$message\n";
}
}
sub debug($)
{
my $message = $_[0];
if ($loglevel >= 3)
{
print "$message\n";
}
}
# remove characters from the filename that might make
# the snapshot directory name confusing
sub sanitize_filename()
{
my $f = $_[0];
$f =~ s/^\.+//;
return($f);
}
#################### Perl POD documentation ########################
__END__
=head1 NAME
snapshot
Simple utility which uses diff/patch to snapshot
a single text file without touching the original file.
=head1 SYNOPSIS
snapshot <OPERATION> [OPTIONS] <FILE>
=head1 DESCRIPTION
When a revision history of a single file in a home directory is desired,
all of the other version control systems are difficult to use in
such a simple use case. RCS, CVS, and git are suited for multi-user
collaborations on entire directory trees. Tracking one file is a pain.
Most of these use a "black box" data storage. Common
operations like check-ins can also delete and then recreate the source
file, which freaks out most text editors.
I wanted something that used common GNU diff and patch tools and stored
patches in a hidden directory for a single file. You can even view
or edit the individual patch revisions if you want. And it supports
a simple comment in each patch if you desire. All without ever modifying
the original source file.
This is meant to be run from a cron job to keep track of text files like
a I<.bashrc>, I<.bash_history> or a scratchpad of notes or to-do lists.
=head1 REQUIREMENTS
This script requires perl packages:
=over 5
=item * Getopt::Long (perl-Getopt-Long)
=item * Pod::Usage (perl-Pod-Usage)
=item * Switch (libswitch-perl or perl-Switch)
=item * File::Spec
=back
Requires GNU utilities I<diff>, I<patch>, I<mktemp> and I<date>
=head1 OPERATION
=over 5
=item B<save>
Save a diff of the file
=over 5
=item B<--message or -m> <string>
Optionally add a message to the diff file. Keep it only one line.
=back
=item B<restore>
Roll through the diffs and create a temp file at
a snapshotted point in time. Does B<NOT> modify
the original file.
=over 5
=item B<--time or -t> <string>
By default, restore will patch up to the most recent
patch file stored in the snapshot directory. Specify
a time string to be parsed by your local
GNU I<date --date> utility. Examples like "last Thursday",
"2021-12-08 13:27:00" or "2 weeks ago + 5 hours"
=back
=item B<view>
Restore a snapshot to a temp file and view it with whatever
your $EDITOR is set to.
Also accepts the I<--time> parameter like the I<restore> operation.
After your editor exits, the temp file will be deleted.
=item B<list>
List the snapshots for this file
=item B<grep> [OPTIONS]
Grep through the contents of all snapshots. I<OPTIONS> are passed
directly to your system's I<grep> utility.
=back
=head1 GLOBAL OPTIONS
=over 5
=item B<--help>
Show usage information
=item B<--man>
Show the full manual page. Includes more content than the --help display.
=item B<--snapshot_dir> </path/to/directory>
By default, I<snapshot> creates a new subdirectory within the absolute path
of the given I<FILE>. The directory name is I<.FILE-snapshot>
Override this if you want something special.
=item B<--verbose> B<--debug>
By default, this script runs fairly quiet for use with scripts and crontabs.
Add verbose or debug for extra noise
=back
=head1 EXAMPLES
=over 5
=item B<Start or save a new snapshot>
$ snapshot save myfile.txt
$ snapshot save --verbose --message "Updates to TODO list" myfile.txt
=item B<View a list of snapshots>
$ snapshot list myfile.txt
Patch Time Comment
Wed Dec 8 13:10:13 CST 2021 Original Snapshot
Wed Dec 8 13:25:07 CST 2021 Updates to TODO list
=item B<Restore a temp snapshot>
$ snapshot restore --time "15 minutes ago" myfile.txt
File /tmp/tmp.gN8bAHpsRE is restored to time Wed Dec 8 13:10:13 CST 2021
$ snapshot restore --time "Wed Dec 8 13:25:07" myfile.txt
File /tmp/tmp.qrAayDnLQI is restored to time Wed Dec 8 13:25:07 CST 2021
=item B<View a temp snapshot>
$ snapshot view --time "last Thursday" myfile.txt
=item B<Files are plain text patches>
$ ls -l .myfile.txt-snapshot/
-rw-rw-r-- 13 Dec 8 13:10 original
-rw-rw-r-- 174 Dec 8 13:25 1638991507.patch
=item B<Grep your .bash_history snapshots for a command>
$ snapshot grep 'aws ecs create-service' .bash_history
$ snapshot grep -i apigateway .bash_history
=back