|
| 1 | +#!/usr/bin/env node |
| 2 | +const path = require('path'); |
| 3 | +const fs = require('fs'); |
| 4 | + |
| 5 | + |
| 6 | +const topDir = path.join(__dirname, '..', '..'); |
| 7 | + |
| 8 | +const jsDir = path.join(topDir, 'src/assets/js'); |
| 9 | +console.log('jsDir ' + jsDir); |
| 10 | +for(const file of fs.readdirSync(jsDir)) { |
| 11 | + if (!file.endsWith('.js')) { |
| 12 | + continue; |
| 13 | + } |
| 14 | + const origFile = fs.readFileSync(path.join(jsDir, file), 'utf8'); |
| 15 | + |
| 16 | + let newFile = ''; |
| 17 | + for(let line of origFile.split(/\n/)) { |
| 18 | + const gtagIndex = line.indexOf('gtag('); |
| 19 | + if (gtagIndex >= 0) { |
| 20 | + const linePrefix = line.substring(0, gtagIndex); |
| 21 | + |
| 22 | + const paramStartIndex = gtagIndex + 5; |
| 23 | + const paramEndIndex = line.lastIndexOf(')'); |
| 24 | + if (paramEndIndex >= paramStartIndex) { |
| 25 | + |
| 26 | + const paramStr = line.substring(paramStartIndex, paramEndIndex); |
| 27 | + |
| 28 | + const linePrefix = line.substring(0, gtagIndex); |
| 29 | + const lineSuffix = line.substring(paramEndIndex + 1); |
| 30 | + |
| 31 | + const params = paramStr.split(','); |
| 32 | + for(let ii = 0; ii < params.length; ii++) { |
| 33 | + params[ii] = params[ii].trim(); |
| 34 | + } |
| 35 | + if (params.length >= 4) { |
| 36 | + if (params[0] == "'send'" && params[1] == "'event'") { |
| 37 | + // console.log('params', params); |
| 38 | + |
| 39 | + // ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]); |
| 40 | + // 2 eventCategory -> event_category |
| 41 | + // 3 eventAction -> event_action |
| 42 | + // 4 eventLabel -> event_label |
| 43 | + // 5 eventValue -> event_value |
| 44 | + |
| 45 | + switch(params.length) { |
| 46 | + case 4: |
| 47 | + line = linePrefix + "gtag('event', " + params[3] + ", {'event_category':" + params[2] + "})" + lineSuffix; |
| 48 | + break; |
| 49 | + |
| 50 | + case 5: |
| 51 | + line = linePrefix + "gtag('event', " + params[3] + ", {'event_category':" + params[2] + ", 'event_label':" + params[4] + "})" + lineSuffix; |
| 52 | + break; |
| 53 | + |
| 54 | + default: |
| 55 | + console.log('too many parameters', params); |
| 56 | + break; |
| 57 | + } |
| 58 | + |
| 59 | + console.log('updated line: ' + line); |
| 60 | + } |
| 61 | + else { |
| 62 | + console.log('not send event params', params); |
| 63 | + } |
| 64 | + } |
| 65 | + else { |
| 66 | + console.log('not enough parameters', params); |
| 67 | + } |
| 68 | + } |
| 69 | + else { |
| 70 | + console.log('missing end )'); |
| 71 | + } |
| 72 | + } |
| 73 | + newFile += line + '\n'; |
| 74 | + } |
| 75 | + |
| 76 | + if (newFile.trim() != origFile.trim()) { |
| 77 | + console.log('changed ' + file); |
| 78 | + fs.writeFileSync(path.join(jsDir, file), newFile); |
| 79 | + } |
| 80 | +} |
0 commit comments