summaryrefslogtreecommitdiffstats
path: root/pkg/lib/html2po.js
blob: 634ffc4c7167c308c64c03c1efa6c3817434284d (plain)
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/env node

/*
 * Extracts translatable strings from HTML files in the following forms:
 *
 * <tag translate>String</tag>
 * <tag translate context="value">String</tag>
 * <tag translate="...">String</tag>
 * <tag translate-attr attr="String"></tag>
 *
 * Supports the following angular-gettext compatible forms:
 *
 * <translate>String</translate>
 * <tag translate-plural="Plural">Singular</tag>
 *
 * Note that some of the use of the translated may not support all the strings
 * depending on the code actually using these strings to translate the HTML.
 */

import fs from 'fs';
import path from 'path';
import htmlparser from 'htmlparser';
import { ArgumentParser } from 'argparse';

function fatal(message, code) {
    console.log((filename || "html2po") + ": " + message);
    process.exit(code || 1);
}

const parser = new ArgumentParser();
parser.add_argument('-d', '--directory', { help: "Base directory for input files" });
parser.add_argument('-o', '--output', { help: 'Output file', required: true });
parser.add_argument('files', { nargs: '+', help: "One or more input files", metavar: "FILE" });
const args = parser.parse_args();

const input = args.files;
const entries = { };

/* Filename being parsed and offset of line number */
let filename = null;
let offsets = 0;

/* The HTML parser we're using */
const handler = new htmlparser.DefaultHandler(function(error, dom) {
    if (error)
        fatal(error);
    else
        walk(dom);
});

/* Now process each file in turn */
step();

function step() {
    filename = input.shift();
    if (filename === undefined) {
        finish();
        return;
    }

    /* Qualify the filename if necessary */
    let full = filename;
    if (args.directory)
        full = path.join(args.directory, filename);

    fs.readFile(full, { encoding: "utf-8" }, function(err, data) {
        if (err)
            fatal(err.message);

        const parser = new htmlparser.Parser(handler, { includeLocation: true });
        parser.parseComplete(data);
        step();
    });
}

/* Process an array of nodes */
function walk(children) {
    if (!children)
        return;

    children.forEach(function(child) {
        const line = (child.location || { }).line || 0;
        const offset = line - 1;

        /* Scripts get their text processed as HTML */
        if (child.type == 'script' && child.children) {
            const parser = new htmlparser.Parser(handler, { includeLocation: true });

            /* Make note of how far into the outer HTML file we are */
            offsets += offset;

            child.children.forEach(function(node) {
                parser.parseChunk(node.raw);
            });
            parser.done();

            offsets -= offset;

        /* Tags get extracted as usual */
        } else if (child.type == 'tag') {
            tag(child);
        }
    });
}

/* Process a single loaded tag */
function tag(node) {
    let tasks, line, entry;
    const attrs = node.attribs || { };
    let nest = true;

    /* Extract translate strings */
    if ("translate" in attrs || "translatable" in attrs) {
        tasks = (attrs.translate || attrs.translatable || "yes").split(" ");

        /* Calculate the line location taking into account nested parsing */
        line = (node.location || { }).line || 0;
        line += offsets;

        entry = {
            msgctxt: attrs['translate-context'] || attrs.context,
            msgid_plural: attrs['translate-plural'],
            locations: [filename + ":" + line]
        };

        /* For each thing listed */
        tasks.forEach(function(task) {
            const copy = Object.assign({}, entry);

            /* The element text itself */
            if (task == "yes" || task == "translate") {
                copy.msgid = extract(node.children);
                nest = false;

            /* An attribute */
            } else if (task) {
                copy.msgid = attrs[task];
            }

            if (copy.msgid)
                push(copy);
        });
    }

    /* Walk through all the children */
    if (nest)
        walk(node.children);
}

/* Push an entry onto the list */
function push(entry) {
    const key = entry.msgid + "\0" + entry.msgid_plural + "\0" + entry.msgctxt;
    const prev = entries[key];
    if (prev) {
        prev.locations = prev.locations.concat(entry.locations);
    } else {
        entries[key] = entry;
    }
}

/* Extract the given text */
function extract(children) {
    if (!children)
        return null;

    const str = [];
    children.forEach(function(node) {
        if (node.type == 'tag' && node.children)
            str.push(extract(node.children));
        else if (node.type == 'text' && node.data)
            str.push(node.data);
    });

    const msgid = str.join("");

    if (msgid != msgid.trim()) {
        console.error("FATAL: string contains leading or trailing whitespace:", msgid);
        process.exit(1);
    }

    return msgid;
}

/* Escape a string for inclusion in po file */
function escape(string) {
    const bs = string.split('\\')
            .join('\\\\')
            .split('"')
            .join('\\"');
    return bs.split("\n").map(function(line) {
        return '"' + line + '"';
    }).join("\n");
}

/* Finish by writing out the strings */
function finish() {
    const result = [
        'msgid ""',
        'msgstr ""',
        '"Project-Id-Version: PACKAGE_VERSION\\n"',
        '"MIME-Version: 1.0\\n"',
        '"Content-Type: text/plain; charset=UTF-8\\n"',
        '"Content-Transfer-Encoding: 8bit\\n"',
        '"X-Generator: Cockpit html2po\\n"',
        '',
    ];

    for (const msgid in entries) {
        const entry = entries[msgid];
        result.push('#: ' + entry.locations.join(" "));
        if (entry.msgctxt)
            result.push('msgctxt ' + escape(entry.msgctxt));
        result.push('msgid ' + escape(entry.msgid));
        if (entry.msgid_plural) {
            result.push('msgid_plural ' + escape(entry.msgid_plural));
            result.push('msgstr[0] ""');
            result.push('msgstr[1] ""');
        } else {
            result.push('msgstr ""');
        }
        result.push('');
    }

    const data = result.join('\n');
    if (!args.output) {
        process.stdout.write(data);
        process.exit(0);
    } else {
        fs.writeFile(args.output, data, function(err) {
            if (err)
                fatal(err.message);
            process.exit(0);
        });
    }
}