Skip to content

Instantly share code, notes, and snippets.

@sbeitzel
Created June 24, 2021 22:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbeitzel/44bf71e05a595ae29ec9b4ac2ddb9d67 to your computer and use it in GitHub Desktop.
Save sbeitzel/44bf71e05a595ae29ec9b4ac2ddb9d67 to your computer and use it in GitHub Desktop.
Perl script to rename a flutter web app with a unique name.
#!/usr/bin/perl
use strict;
use warnings;
sub hash_file {
my $fileName = shift(@_);
my $sumString = `md5sum $fileName`;
if ($sumString =~ /([a-f0-9]{32})/) {
return $1;
}
return '';
}
# We're going to stamp the build with the current time. A build takes well over a minute, so
# that's all the granularity we need.
my ($sec, $min, $hour, $mday, $month, $year, $wday, $yday, $isdst) = localtime(time);
my $stamp = "-$year$month$mday$hour$min";
my $hostDir = "firebase/hosting";
my $main = "main.dart.js";
my $stamped = "main$stamp.dart.js";
# rename `main.dart.js` to main-yyyymmddhhmm.dart.js
rename "$hostDir/$main", "$hostDir/$stamped";
rename "$hostDir/$main.map", "$hostDir/$stamped.map";
print "Renamed main.dart.js\n";
my $service_worker = "$hostDir/flutter_service_worker.js";
my $service_worker_tmp = "$hostDir/flutter_service_worker.js.tmp";
# change `main` to `main-yyyymmddhhmm` in the service worker
open(SWIN, "<$service_worker") or die("Unable to read service worker");
open(SWOUT, ">$service_worker_tmp") or die("Unable to write service worker");
while(<SWIN>) {
if (/(.*)(main\.dart\.js)(.*)/) {
print(SWOUT "$1$stamped$3\n");
} else {
print(SWOUT $_);
}
}
close(SWIN);
close(SWOUT);
unlink $service_worker;
rename $service_worker_tmp, $service_worker;
print "Updated main.dart.js in flutter_service_worker.js\n";
# change 'main' in index.html
my $index = "$hostDir/index.html";
my $index_tmp = "$hostDir/index.html.tmp";
open(IXIN, "<$index") or die("Unable to read index.html");
open(IXOUT, ">$index_tmp") or die("Unable to write index.html.tmp");
while(<IXIN>) {
if (/(.*)(main\.dart\.js)(.*)/) {
print(IXOUT "$1$stamped$3\n");
} else {
print(IXOUT $_);
}
}
close(IXIN);
close(IXOUT);
unlink $index;
rename $index_tmp, $index;
print "Updated main.dart.js in index.html\n";
# update the md5 sum for index.html in the service worker
my $index_hash = hash_file($index);
open(SWIN, "<$service_worker") or die("Unable to read service worker");
open(SWOUT, ">$service_worker_tmp") or die("Unable to write service worker");
while(<SWIN>) {
if (/^\"index.html\": \"[a-f0-9]{32}\",$/) {
print(SWOUT "\"index.html\": \"$index_hash\",\n");
} else {
print(SWOUT $_);
}
}
close(SWIN);
close(SWOUT);
unlink $service_worker;
rename $service_worker_tmp, $service_worker;
print "Updated MD5 of index.html in flutter_service_worker.js\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment