1 | const fs = require('fs-extra')
|
2 | const path = require('path')
|
3 | const { promisify } = require('util')
|
4 | const xml2js = require('xml2js')
|
5 | const parseXML = promisify(xml2js.parseString)
|
6 | const buildXML = new xml2js.Builder({ cdata: true })
|
7 | const fsOpts = { encoding: 'utf8' }
|
8 | const snippetsFileName = 'CodeSnippets.xml'
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | module.exports = async ({ downloadPath, destPath, removeDownload, newVersion }) => {
|
22 | removeDownload = !!removeDownload
|
23 | const downloadFile = path.join(downloadPath, snippetsFileName)
|
24 | const destFile = path.join(destPath, snippetsFileName)
|
25 | const newXmlObject = await readXml({ xmlFile: downloadFile })
|
26 | const blinkSnippets = filterBlinkSnippets({ xmlObject: newXmlObject, filterOut: false })
|
27 | const xmlObject = await readXml({ xmlFile: destFile })
|
28 | removeDownload && await fs.remove(downloadPath)
|
29 | const nonBlinkSnippets = filterBlinkSnippets({ xmlObject, filterOut: true })
|
30 | const mergedCategories = nonBlinkSnippets.concat(blinkSnippets)
|
31 | xmlObject.CodeSnippets.snippets[0].category = mergedCategories
|
32 | await writeXml({ xmlObject, xmlFileName: destFile, newVersion })
|
33 | }
|
34 |
|
35 | const readXml = async ({ xmlFile }) => {
|
36 | let xmlObject = null
|
37 | try {
|
38 | const xmlText = await fs.readFile(xmlFile, fsOpts)
|
39 | xmlObject = await parseXML(xmlText)
|
40 | } catch (err) {
|
41 | console.log('Error parsing existing CodeSnippets.xml')
|
42 | return Promise.reject(err)
|
43 | }
|
44 | return xmlObject
|
45 | }
|
46 |
|
47 | const filterBlinkSnippets = ({ xmlObject, filterOut }) => {
|
48 | filterOut = !!filterOut
|
49 | let categories = []
|
50 | let re
|
51 | if (filterOut) {
|
52 | re = /^(?!Blink Snippets).*/
|
53 | } else {
|
54 | re = /^Blink Snippets/
|
55 | }
|
56 | categories = xmlObject.CodeSnippets.snippets[0].category
|
57 | .filter((category) => {
|
58 | |
59 |
|
60 |
|
61 |
|
62 | if (typeof category !== 'object') return false
|
63 | return !category.$ || !category.$.title || re.test(category.$.title)
|
64 | })
|
65 | return categories
|
66 | }
|
67 |
|
68 | const writeXml = async ({ xmlObject, xmlFileName, newVersion }) => {
|
69 | let newXml = buildXML.buildObject(xmlObject)
|
70 |
|
71 | const searchString = '<CodeSnippets>'
|
72 | const commentString = '\n<!-- -->'
|
73 | newXml = newXml.replace(searchString, searchString + commentString)
|
74 | if (newVersion) {
|
75 | newXml = newXml.replace(/BLINK_SNIPPETS_VERSION/, `${newVersion}`)
|
76 | }
|
77 | return fs.writeFile(xmlFileName, newXml, fsOpts)
|
78 | }
|