|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/* Copyright (c) 2019 The Brave Software Team. Distributed under the MPL2 |
| 4 | + * license. This Source Code Form is subject to the terms of the Mozilla Public |
| 5 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 6 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 7 | + |
| 8 | +/** |
| 9 | + * This code parses the public suffix rule list into a header file of |
| 10 | + * rules that gets build into the ad-block library. |
| 11 | + */ |
| 12 | + |
| 13 | +const fsLib = require("fs"); |
| 14 | +const pathLib = require("path"); |
| 15 | + |
| 16 | +const ruleTextPath = pathLib.join(__dirname, "public_suffix_list.dat"); |
| 17 | +const ruleText = fsLib.readFileSync(ruleTextPath, "utf8"); |
| 18 | + |
| 19 | +const templatePath = pathLib.join(__dirname, "public_suffix_list.h.template"); |
| 20 | +const templateText = fsLib.readFileSync(templatePath, "utf8"); |
| 21 | +const rules = []; |
| 22 | + |
| 23 | +const toPublicSuffixRuleSerializedString = (isWildcard, isException, labels) => { |
| 24 | + const constructorArgs = []; |
| 25 | + constructorArgs.push(isWildcard ? "true" : "false"); |
| 26 | + constructorArgs.push(isException ? "true" : "false"); |
| 27 | + |
| 28 | + const wrappedLabels = labels.map(JSON.stringify); |
| 29 | + constructorArgs.push("{" + wrappedLabels.join(", ") + "}"); |
| 30 | + return "{" + constructorArgs.join(", ") + "}"; |
| 31 | +} |
| 32 | + |
| 33 | +for (const line of ruleText.split("\n")) { |
| 34 | + let isWildcard = false; |
| 35 | + let isException = false; |
| 36 | + let trimmedLine = line.trim(); |
| 37 | + if (trimmedLine.length === 0) { |
| 38 | + continue; |
| 39 | + } |
| 40 | + |
| 41 | + // Check to see if this is a comment line. If so, process no further. |
| 42 | + if (trimmedLine.indexOf("//") == 0) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + const firstChar = trimmedLine[0]; |
| 47 | + switch (firstChar) { |
| 48 | + case "!": |
| 49 | + trimmedLine = trimmedLine.slice(1); |
| 50 | + isException = true; |
| 51 | + break; |
| 52 | + |
| 53 | + case "*": |
| 54 | + isWildcard = true; |
| 55 | + break; |
| 56 | + |
| 57 | + default: |
| 58 | + break; |
| 59 | + } |
| 60 | + |
| 61 | + const lineUntilWhiteSpace = trimmedLine.split(" ")[0]; |
| 62 | + const ruleLabels = lineUntilWhiteSpace.split("."); |
| 63 | + |
| 64 | + const ruleAsString = toPublicSuffixRuleSerializedString(isWildcard, isException, ruleLabels); |
| 65 | + rules.push(ruleAsString); |
| 66 | +} |
| 67 | + |
| 68 | +const serializedString = rules.join(",\n"); |
| 69 | +const replaceArg = "{" + serializedString + "}"; |
| 70 | +const finalCodeText = templateText.replace("{contents}", replaceArg); |
| 71 | + |
| 72 | +const generatedFilePath = pathLib.join(__dirname, "public_suffix_list.h"); |
| 73 | +fsLib.writeFileSync(generatedFilePath, finalCodeText, "utf8"); |
0 commit comments