-
-
Notifications
You must be signed in to change notification settings - Fork 436
/
Copy pathtransifex-push.js
96 lines (86 loc) · 3.15 KB
/
transifex-push.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// @ts-check
const transifex = require('./transifex');
const fetch = require('node-fetch');
const fs = require('fs');
const shell = require('shelljs');
const util = require('util');
const uploadSourceFile = async (organization, project, resource, filePath) => {
const url = transifex.url('resource_strings_async_uploads');
const data = {
data: {
attributes: {
callback_url: null,
content: fs.readFileSync(filePath).toString('base64'),
content_encoding: 'base64'
},
relationships: {
resource: {
data: {
id: util.format('o:%s:p:%s:r:%s', organization, project, resource),
type: 'resources'
}
}
},
type: 'resource_strings_async_uploads'
}
};
const headers = transifex.authHeader();
headers['Content-Type'] = 'application/vnd.api+json';
const json = await fetch(url, { method: 'POST', headers, body: JSON.stringify(data) })
.catch(err => {
shell.echo(err);
shell.exit(1);
})
.then(res => res.json());
return json['data']['id'];
};
const getSourceUploadStatus = async (uploadId) => {
const url = transifex.url(util.format('resource_strings_async_uploads/%s', uploadId));
// The download request status must be asked from time to time, if it's
// still pending we try again using exponentional backoff starting from 2.5 seconds.
let backoffMs = 2500;
const headers = transifex.authHeader();
while (true) {
const json = await fetch(url, { headers })
.catch(err => {
shell.echo(err);
shell.exit(1);
})
.then(res => res.json());
const status = json['data']['attributes']['status'];
if (status === 'succeeded') {
return
} else if (status === 'pending' || status === 'processing') {
await new Promise(r => setTimeout(r, backoffMs));
backoffMs = backoffMs * 2;
// Retry the upload request status again
continue
} else if (status === 'failed') {
const errors = [];
json['data']['attributes']['errors'].forEach(err => {
errors.push(util.format('%s: %s', err.code, err.details));
});
throw util.format('Download request failed: %s', errors.join(', '));
}
throw 'Download request failed in an unforeseen way';
}
}
(async () => {
const { organization, project, resource } = await transifex.credentials();
const sourceFile = process.argv[2];
if (!sourceFile) {
shell.echo('Translation source file not specified');
shell.exit(1);
}
const uploadId = await uploadSourceFile(organization, project, resource, sourceFile)
.catch(err => {
shell.echo(err);
shell.exit(1);
});
await getSourceUploadStatus(uploadId)
.catch(err => {
shell.echo(err);
shell.exit(1);
});
shell.echo("Translation source file uploaded");
})()