addChecksum.pl 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env perl
  2. # Copyright 2011 Wladimir Palant
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. use strict;
  16. use warnings;
  17. use Path::Tiny;
  18. use Digest::MD5 qw(md5_base64);
  19. use Encode qw(encode_utf8);
  20. use POSIX qw(strftime);
  21. use feature 'unicode_strings';
  22. die "Usage: $^X $0 subscription.txt\n" unless @ARGV;
  23. my $file = shift;
  24. die "Specified file: $file doesn't exist!\n" unless (-e $file);
  25. my $data = path($file)->slurp_utf8;
  26. # Get existing checksum
  27. $data =~ /^.*!\s*checksum[\s\-:]+([\w\+\/=]+).*\n/gmi;
  28. my $oldchecksum = $1;
  29. # Remove already existing checksum
  30. $data =~ s/^.*!\s*checksum[\s\-:]+([\w\+\/=]+).*\n//gmi;
  31. # Calculate new checksum: remove all CR symbols and empty
  32. # lines and get an MD5 checksum of the result (base64-encoded,
  33. # without the trailing = characters)
  34. my $checksumData = $data;
  35. $checksumData =~ s/\r//g;
  36. $checksumData =~ s/\n+/\n/g;
  37. # Calculate new checksum
  38. my $checksum = md5_base64(encode_utf8($checksumData));
  39. # If the old checksum matches the new one die
  40. die "List has not changed.\n" if (($oldchecksum) and ($checksum eq $oldchecksum));
  41. # Update the date and time.
  42. my $updated = strftime("%Y-%m-%d %H:%M UTC", gmtime);
  43. $data =~ s/(^.*!.*(Last modified|Updated):\s*)(.*)\s*$/$1$updated/gmi if ($data =~ m/^.*!.*(Last modified|Updated)/gmi);
  44. # Update version
  45. my $version = strftime("%Y%m%d%H%M" ,gmtime);
  46. $data =~ s/^.*!\s*Version:.*/! Version: $version/gmi;
  47. # Recalculate the checksum as we've altered the date
  48. $checksumData = $data;
  49. $checksumData =~ s/\r//g;
  50. $checksumData =~ s/\n+/\n/g;
  51. $checksum = md5_base64(encode_utf8($checksumData));
  52. # Insert checksum into the file
  53. $data =~ s/(\r?\n)/$1! Checksum: $checksum$1/;
  54. path($file)->spew_utf8($data);