Created
May 25, 2021 20:24
-
-
Save Hakky54/b92c9b08a4c6033c416b70d3e801f820 to your computer and use it in GitHub Desktop.
Adding Google Analytics script to html files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.nio.charset.StandardCharsets; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.nio.file.StandardOpenOption; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class App { | |
public static void main(String[] args) throws IOException { | |
if (args.length != 2) { | |
throw new IllegalArgumentException(); | |
} | |
String googleAnalyticsTagId = args[0]; | |
String startLocation = args[1]; | |
String googleAnalytics = | |
""" | |
<!-- Global site tag (gtag.js) - Google Analytics --> | |
<script async src="https://www.googletagmanager.com/gtag/js?id=%s"> | |
</script> | |
<script> | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', '%s'); | |
</script> | |
""".formatted(googleAnalyticsTagId, googleAnalyticsTagId); | |
List<Path> paths = Files.find( | |
Paths.get(startLocation), | |
Integer.MAX_VALUE, | |
(p, basicFileAttributes) -> p.getFileName().toString().endsWith(".html")) | |
.collect(Collectors.toList()); | |
for (Path path : paths) { | |
List<String> contents = Files.readAllLines(path, StandardCharsets.UTF_8); | |
List<String> newContents = new ArrayList<>(); | |
for (String content : contents) { | |
if (content.contains("</head>")) { | |
newContents.add(googleAnalytics + content); | |
} else { | |
newContents.add(content); | |
} | |
} | |
Files.write(path, newContents, StandardCharsets.UTF_8, StandardOpenOption.WRITE); | |
} | |
System.out.println("done"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment