Don't write .bak file, write only if there were changes

This commit is contained in:
Austen Adler 2016-08-19 11:23:25 -04:00
parent b00004f73e
commit 9c691994d0
No known key found for this signature in database
GPG Key ID: 7ECEE590CCDFE3F1

View File

@ -10,21 +10,17 @@ foreach my $file (@ARGV) {
# If it exists
if (-e $file) {
# Load the autoformatted data into $data
my $data = process_file($file);
open(MYOUTPUTFILE, "+>$file.bak") or die "Error opening output file $!";
# Write the data to $file.bak
#TODO: This could be done with no .bak
my ($data, $old_data) = process_file($file);
# Check if original data matches new data, if it doesn't, write it
# If it matches (there were no changes made), do nothing
if (not $data eq $old_data) {
# Write out the data
open(MYOUTPUTFILE, "+>$file") or die "Error opening output file $!";
print MYOUTPUTFILE $data;
close(MYOUTPUTFILE);
if (compare($file, "$file.bak") != 0) {
# If there were changes, then tell the user
# Tell the user that we changed the file
print "Processed $file\n";
}
# Replace the original file with this file
# Delete it
unlink $file;
# Overwrite the old one
rename "$file.bak", $file;
}
}
# Creates the automatically formatted file
@ -33,8 +29,12 @@ sub process_file {
open(MYINPUTFILE, "<$filename") or die "x $!";
# The formatted file
my($data) = "";
# The original file (used for comparison to see if changes were made)
my($old_data) = "";
# Loop through every line in the file
while(<MYINPUTFILE>) {
# Add data to $old_data
$old_data .= $_;
# Get rid of trailing whitespace
s/\s*$//;
my($line) = $_;
@ -54,5 +54,5 @@ sub process_file {
my $basename = basename($filename);
$data = "/**\n * \@file $basename\n * \@author Austen Adler (agadler)\n * TODO: Description\n */\n$data";
}
return $data;
return ($data, $old_data);
}