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