-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclear_trailing_ws.pl
More file actions
executable file
·92 lines (75 loc) · 1.91 KB
/
clear_trailing_ws.pl
File metadata and controls
executable file
·92 lines (75 loc) · 1.91 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
#!/usr/bin/perl -w
#
# clear_trailing_ws.pl - revision 4 (2019/8/21)
# Copyright(C) 2019 by Richard Bradley
#
# Removes trailing white space (end of line and trailing blank lines) and
# only overwrites original file with processed version if changes are made.
#
use strict;
use File::Copy;
use File::Temp qw(tempfile);
use LWP::MediaTypes qw(guess_media_type);
#### GLOBALS ####
# mime file types to be processed - all other file types are ignored
my %allowed =
("application/x-perl" => 1,
"application/x-sh" => 1,
"text/html" => 1,
"text/plain" => 1,
"text/x-c" => 1,
"text/markdown" => 1);
#### FUNCTIONS ####
sub FixFile {
my $fileName = shift;
# Save fixed file to temp file
my $fhIn;
open($fhIn, "<", $fileName) || die "Can't read file '$fileName'\n";
my ($fhOut, $tmpFile) = tempfile();
my $changed = 0;
my $blankLines = "";
while (my $line = <$fhIn>) {
# strip trailing white space from line
my $originalLine = $line;
$line =~ s/\s*\n$/\n/;
if ($line ne $originalLine) {
$changed = 1;
}
if ($line eq "\n") {
# collect blank lines to remove extra at end of file
$blankLines .= "\n";
} else {
print { $fhOut } $blankLines;
$blankLines = "";
print { $fhOut } "$line";
}
}
close $fhOut;
close $fhIn;
if ($blankLines ne "") {
# blank lines removed from end of file
$changed = 1;
}
if ($changed) {
# overwrite original file with temp version
print "$fileName\n";
move $tmpFile, $fileName;
} else {
# nothing changed, just kill the temp file
unlink $tmpFile;
}
}
#### MAIN ####
if (@ARGV <= 0) {
print "Usage: $0 <file list>\n";
print "Only files found to have trailing white space will be cleansed.\n";
exit 0;
}
foreach my $i (@ARGV) {
my $mt = guess_media_type($i);
if (defined $allowed{$mt}) {
FixFile $i;
} else {
print STDERR "$i: file type '$mt' not allowed\n";
}
}