-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatchDir
More file actions
executable file
·282 lines (208 loc) · 7.48 KB
/
watchDir
File metadata and controls
executable file
·282 lines (208 loc) · 7.48 KB
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
#!/usr/bin/env perl -w
#
# watchDir: See when files in a directory change.
# 2006-10-16: Written by Steven J. DeRose.
#
use strict;
use Getopt::Long;
use sigtrap qw(die INT QUIT); # give user a way out
our %metadata = (
'title' => "watchDir",
'description' => "Do something when files in a directory change.",
'rightsHolder' => "Steven J. DeRose",
'creator' => "http://viaf.org/viaf/50334488",
'type' => "http://purl.org/dc/dcmitype/Software",
'language' => "Perl 5.18",
'created' => "2006-10-16",
'modified' => "2021-09-23",
'publisher' => "http://github.com/sderose",
'license' => "https://creativecommons.org/licenses/by-sa/3.0/"
);
our $VERSION_DATE = $metadata{'modified'};
=pod
=head1 Usage
watchDir [path]
Reports when files are added, deleted, or modified in the directory.
This is done in a really simplistic way, and tied to a single directory.
Use ^C (control-C) to exit.
You can use C<--exec [cmd]> to run a command on each file each time it changes.
For example, you can open an editor on each file as it changes, with:
watchDir --exec "$EDITOR" ~/myDir
Or re-lint a program each time you save a change to it:
watchDir --exec "pylint" ~/myPythonStuff
Some other handy commands to use with C<--exec> include C<ls -l>, C<diff> vs. a backup,
C<backup>, C<lint>, and many others.
There is not yet a way to watch a single file in isolation.
Just watch the parent directory, which includes catching changes to all files
directly within that directory. If you're only editing one, it's the same effect.
=head1 Options
=over
=item * B<--exec> I<cmd>
When a file changes, run I<cmd> on it. If I<cmd> contains "{}" one or more times,
replace it with the file's path; otherwise, append the file's path to I<cmd> after a space.
If the system command fails, a message and the return code are printed.
To change the "{}" string, set I<--repstring>.
=item * B<-p>
Check for permission changes, too (not implemented).
=item * B<--quiet> OR B<-q>
Suppress most messages.
=item * B<-repstring> I<s>
Change the string which will be replaced by the relevant filename, from "{}" to I<s>.
=item * B<--sleep> I<n> OR B<-n> I<n>
Sleep I<n> seconds between checks (default 1; 0 is ok).
=item * B<--spinner>
Show a cheesy spinning progress indicator. Default: on (use I<--no-spinner>
to turn off).
=item * B<--verbose>
Add more messages (repeatable).
=item * B<--version>
Display version info and exit.
=back
=head1 Related commands
There are many similar commands, such as:
C<opensnoop> -- seems great, but I couldn't get it to work on MacOSX Catalina.
C<instruments>
C<watch> -- C<watchDir> is a lot like C<watch -d -n 2 ls -lt --full-time> (which
is available in Linux, but apparently not on BSD/MacOSX except via C<brew>).
However, C<watchDir> has at least these differences:
=over
=item * distinguishes changes, additions, and deletions as such
=item * outputs a log of changes, rather than highlighting in one list
=item * is better if you're watching a big listing as a whole
=item * counts changed files
=back
L<https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes>
has several additional solutions for similar problems.
=head1 To Do
* Support single-file watching.
* Option to find the first changed line and display it, or edit at it.
* Option to do a special command (maybe scp) on the most-recently-changed
file, when a certain trigger occurs. For example, this would let people
drop things into a watchDir'd dropbox, then poll to re-fetch the file.
Would rsync mirroring be enough?
=head1 History
2006-10-16: Written by Steven J. DeRose.
2012-09-04: Clean up, update.
2020-11-20: New layout. Mention related commands.
2020-12-21: Switch from ls to stat. Add --exec.
2021-01-22: Add --spinner.
2021-07-23: Refactor --exec, report if it fails, support {} substitution.
2021-09-23: Add I<--repstring>..
=head1 Rights
Copyright 2006-10-16 by Steven J. DeRose. This work is licensed under a
Creative Commons Attribution-Share Alike 3.0 Unported License.
For further information on this license, see
L<https://creativecommons.org/licenses/by-sa/3.0>.
For the most recent version, see L<http://www.derose.net/steve/utilities> or
L<https://github.com/sderose>.
=cut
###############################################################################
# Options
#
my $color = 0;
my $exec = "";
my $quiet = 0;
my $repstring = "{}";
my $sleep = 1;
my $spinner = 1;
my $verbose = 0;
my %getoptHash = (
"color!" => \$color,
"exec=s" => \$exec,
"h|help" => sub { system "perldoc $0"; exit; },
"n|sleep=o" => \$sleep,
"q|quiet!" => \$quiet,
"repstring=s" => \$repstring,
"spinner!" => \$spinner,
"v|verbose+" => \$verbose,
"version" => sub {
die "Version of $VERSION_DATE, by Steven J. DeRose.\n";
},
);
Getopt::Long::Configure ("ignore_case");
GetOptions(%getoptHash) || die "Bad options.\n";
###############################################################################
# Main
#
my $dir = $ARGV[0] || ".";
(-d $dir) || die "Couldn't find directory '$dir'.\n";
($exec) && print("Running '$exec' on each changed file...\n");
print "(^C to exit)\n";
my $prevTimesRef = getModTimes($dir);
my $repCount = 0;
while (1) {
$repCount++;
my $nextTimesRef = getModTimes($dir);
my $nchanged = 0;
my @pfiles = sort keys %{$prevTimesRef};
foreach my $x (@pfiles) {
if (!defined $nextTimesRef->{$x}) {
print "\n$x \tDISAPPEARED\n";
$nchanged++;
}
}
my @nfiles = sort keys %{$nextTimesRef};
foreach my $x (@nfiles) {
if (!defined $prevTimesRef->{$x}) {
print "\n$x \tAPPEARED\n";
$nchanged++;
}
}
foreach my $x (@pfiles) {
if (defined $nextTimesRef->{$x} &&
$prevTimesRef->{$x} ne $nextTimesRef->{$x}) {
print "\n$x \tUPDATED\n";
if ($exec) { runExec($x); }
$nchanged++;
}
}
if ($spinner) {
my $spinChar = substr("/-\\|", $repCount % 4, 1);
print " ($spinChar $nchanged CHANGED)\r";
}
$prevTimesRef = $nextTimesRef;
if ($sleep > 0) {
if (`sleep $sleep`) { exit; }
}
}
print "Done.\n";
exit;
###############################################################################
# Return a hash of file -> modtime.
#
sub getModTimes {
my $theCmd = "stat -f \"%N\t%Sm\" $dir/*";
($verbose) && warn "Cmd: $theCmd\n";
my %rc = ();
my @raw = `$theCmd`;
for (my $i=0; $i<scalar @raw; $i++) {
chomp($raw[$i]);
my @fields = split(/\t/, $raw[$i]);
if (scalar @fields != 2) {
warn sprintf("Got %d fields (expected 2) in:\n \"%s\"\n",
scalar @fields, $raw[$i]);
for (my $i=0; $i<scalar @fields; $i++) {
warn sprintf(" %2d: \"%s\"\n", $i, $fields[$i]);
}
exit;
}
my ($name, $mtime) = @fields;
$rc{$name} = $mtime;
}
#($verbose) && print join("\n",@raw) . "\n\n";
return(\%rc);
}
sub runExec {
my ($path) = @_;
my $cmd = $exec;
if (index($cmd, $repstring) > -1) {
$cmd =~ s/$repstring/$path/g;
}
else {
$cmd .= " " . $path;
}
system($cmd);
if ($? != 0) {
print("******* Command failed, rc $?: $cmd\n");
}
}