-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
78 lines (64 loc) · 2.15 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const assert = require('assert')
const fs = require('fs')
const {post} = require('got')
const FormData = require('form-data')
const tmp = require('tmp')
const open = require('open')
const {stringify: csvify} = require('csv-string')
module.exports = function (opts = {}) {
return new Glossary(opts)
}
class Glossary {
constructor (opts) {
const defaults = {
openAfterUpload: true
}
Object.assign(this, defaults, opts)
if (!this.crowdinKey) this.crowdinKey = process.env.CROWDIN_KEY
assert(this.project, 'project is required')
assert(this.crowdinKey, 'crowdinKey or process.env.CROWDIN_KEY is required')
this._entries = {}
return this
}
add (term, description) {
assert(term && term.length, 'term is required')
assert(description && description.length, 'description is required')
assert(!(Object.keys(this.entries).includes(term)), `term ${term} has already been added`)
this._entries[term] = description
}
get entries () {
return this._entries
}
get csv () {
return Object.keys(this.entries).reduce((acc, term) => {
const description = this.entries[term]
return acc.concat(csvify([term, description]))
}, '')
}
get webpage () {
return `https://crowdin.com/project/${this.project}/settings#glossary`
}
async upload () {
const url = `https://api.crowdin.com/api/project/${this.project}/upload-glossary?key=${this.crowdinKey}`
const glossaryFile = tmp.fileSync({postfix: '.csv'}).name
fs.writeFileSync(glossaryFile, this.csv)
const form = new FormData()
form.append('scheme', 'term_en,description_en')
form.append('file', fs.createReadStream(glossaryFile))
form.append('json', 'true')
const result = await post(url, {body: form})
.then(() => {
if (this.openAfterUpload && !process.env.CI) {
console.log(`Uploaded glossary! Opening ${this.webpage} in your browser`)
open(this.webpage)
} else {
console.log(`Uploaded glossary! See ${this.webpage}`)
}
})
.catch(err => {
console.error('Problem uploading glossary')
console.error(err)
})
return result
}
}