-
Notifications
You must be signed in to change notification settings - Fork 0
/
cb-content-populate-translations
executable file
·98 lines (87 loc) · 2.66 KB
/
cb-content-populate-translations
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
97
98
#!/usr/bin/env node
const csvtojson = require('csvtojson');
const contentful = require('contentful-management');
const axios = require('axios');
const Papa = require('papaparse');
const { Command } = require('commander');
const { findOrCreateEntry } = require('./utils');
const fs = require('fs');
const main = async ({
source,
sheet = '',
environmentId = 'master',
spaceId,
languages,
accessToken,
}) => {
const getSource = async (source, sheet) => {
// If source starts with ./ or / expect file
if (source.match(/^(.\/|\/)/)) {
const res = fs.readFileSync(source, 'utf8');
return res;
} else {
if (sheet) sheet = `&sheet=${sheet}`;
var url = `https://docs.google.com/spreadsheets/d/${source}/gviz/tq?tqx=out:csv${sheet}`;
var res = await axios.get(url);
return res.data;
}
};
const contentfulClient = await contentful.createClient({ accessToken });
const client = await contentfulClient
.getSpace(spaceId)
.then(s => s.getEnvironment(environmentId))
.catch(e => console.log(e));
// Better logic here. Check total from response
const [entries1, entries2] = await Promise.all([
client.getEntries({
limit: 1000,
content_type: 'translation',
}),
client.getEntries({
limit: 1000,
skip: 1000,
content_type: 'translation',
}),
]);
const entries = [...entries1.items, ...entries2.items];
var res = await getSource(source, sheet);
var input = await csvtojson().fromString(res);
const headers = ['identifier', ...languages];
const csv = [];
input.forEach(item => {
const row = [item.identifier];
const entry = entries.find(
e =>
e.fields &&
e.fields.identifier &&
e.fields.identifier['en-US'] === item.identifier
);
if (entry) {
languages.forEach(l => {
row.push(
entry.fields.translation && entry.fields.translation[l]
? entry.fields.translation[l].trim() // Replace new line if it's the last char...
: ''
);
});
}
csv.push(row);
});
console.log(Papa.unparse(csv));
};
const program = new Command();
program
.requiredOption('-t, --accessToken <accessToken>', 'Content Management Token')
.requiredOption('-s, --spaceId <spaceId>', 'Space Id')
.requiredOption('--source <source>', 'Google Sheet Id or file')
.option('-e, --environmentId <environmentId>', 'Environment Id')
.option('--tab <tab>', 'Google Sheet Tab');
program.parseAsync(process.argv);
main({
accessToken: program.accessToken,
spaceId: program.spaceId,
environmentId: program.environmentId,
source: program.source,
sheet: program.tab,
languages: program.args,
});