Debian Codegraph @

node/gettext-parser/lib/shared.js

raw
1 // see https://www.gnu.org/software/gettext/manual/html_node/Header-Entry.html
2 const PLURAL_FORMS = 'Plural-Forms';
3 export const HEADERS = new Map([
4 ['project-id-version', 'Project-Id-Version'],
5 ['report-msgid-bugs-to', 'Report-Msgid-Bugs-To'],
6 ['pot-creation-date', 'POT-Creation-Date'],
7 ['po-revision-date', 'PO-Revision-Date'],
8 ['last-translator', 'Last-Translator'],
9 ['language-team', 'Language-Team'],
10 ['language', 'Language'],
11 ['content-type', 'Content-Type'],
12 ['content-transfer-encoding', 'Content-Transfer-Encoding'],
13 ['plural-forms', PLURAL_FORMS]
14 ]);
15
16 const PLURAL_FORM_HEADER_NPLURALS_REGEX = /nplurals\s*=\s*(?<nplurals>\d+)/;
17
18 /**
19 * Parses a header string into an object of key-value pairs
20 *
21 * @param {String} str Header string
22 * @return {Object} An object of key-value pairs
23 */
24 export function parseHeader (str = '') {
25 return str.split('\n')
26 .reduce((headers, line) => {
27 const parts = line.split(':');
28 let key = (parts.shift() || '').trim();
29
30 if (key) {
31 const value = parts.join(':').trim();
32
33 key = HEADERS.get(key.toLowerCase()) || key;
34
35 Object.defineProperty(headers, key, { value, writable: true, enumerable: true, configurable: true });
36 }
37
38 return headers;
39 }, {});
40 }
41
42 /**
43 * Attempts to safely parse 'nplurals" value from "Plural-Forms" header
44 *
45 * @param {Object} [headers = {}] An object with parsed headers
46 * @returns {number} Parsed result
47 */
48 export function parseNPluralFromHeadersSafely (headers = {}, fallback = 1) {
49 const pluralForms = headers[PLURAL_FORMS];
50
51 if (!pluralForms) {
52 return fallback;
53 }
54
55 const {
56 groups: { nplurals } = { nplurals: '' + fallback }
57 } = pluralForms.match(PLURAL_FORM_HEADER_NPLURALS_REGEX) || {};
58
59 return parseInt(nplurals, 10) || fallback;
60 }
61
62 /**
63 * Joins a header object of key value pairs into a header string
64 *
65 * @param {Object} header Object of key value pairs
66 * @return {String} Header string
67 */
68 export function generateHeader (header = {}) {
69 const keys = Object.keys(header)
70 .filter(key => !!key);
71
72 if (!keys.length) {
73 return '';
74 }
75
76 return keys.map(key =>
77 `${key}: ${(header[key] || '').trim()}`
78 )
79 .join('\n') + '\n';
80 }
81
82 /**
83 * Normalizes charset name. Converts utf8 to utf-8, WIN1257 to windows-1257 etc.
84 *
85 * @param {String} charset Charset name
86 * @return {String} Normalized charset name
87 */
88 export function formatCharset (charset = 'iso-8859-1', defaultCharset = 'iso-8859-1') {
89 return charset.toString()
90 .toLowerCase()
91 .replace(/^utf[-_]?(\d+)$/, 'utf-$1')
92 .replace(/^win(?:dows)?[-_]?(\d+)$/, 'windows-$1')
93 .replace(/^latin[-_]?(\d+)$/, 'iso-8859-$1')
94 .replace(/^(us[-_]?)?ascii$/, 'ascii')
95 .replace(/^charset$/, defaultCharset)
96 .trim();
97 }
98
99 /**
100 * Folds long lines according to PO format
101 *
102 * @param {String} str PO formatted string to be folded
103 * @param {Number} [maxLen=76] Maximum allowed length for folded lines
104 * @return {Array} An array of lines
105 */
106 export function foldLine (str, maxLen = 76) {
107 const lines = [];
108 const len = str.length;
109 let curLine = '';
110 let pos = 0;
111 let match;
112
113 while (pos < len) {
114 curLine = str.substr(pos, maxLen);
115
116 // ensure that the line never ends with a partial escaping
117 // make longer lines if needed
118 while (curLine.substr(-1) === '\\' && pos + curLine.length < len) {
119 curLine += str.charAt(pos + curLine.length);
120 }
121
122 // ensure that if possible, line breaks are done at reasonable places
123 if ((match = /.*?\\n/.exec(curLine))) {
124 // use everything before and including the first line break
125 curLine = match[0];
126 } else if (pos + curLine.length < len) {
127 // if we're not at the end
128 if ((match = /.*\s+/.exec(curLine)) && /[^\s]/.test(match[0])) {
129 // use everything before and including the last white space character (if anything)
130 curLine = match[0];
131 } else if ((match = /.*[\x21-\x2f0-9\x5b-\x60\x7b-\x7e]+/.exec(curLine)) && /[^\x21-\x2f0-9\x5b-\x60\x7b-\x7e]/.test(match[0])) {
132 // use everything before and including the last "special" character (if anything)
133 curLine = match[0];
134 }
135 }
136
137 lines.push(curLine);
138 pos += curLine.length;
139 }
140
141 return lines;
142 }
143
144 /**
145 * Comparator function for comparing msgid
146 *
147 * @param {Object} object with msgid prev
148 * @param {Object} object with msgid next
149 * @returns {number} comparator index
150 */
151 export function compareMsgid ({ msgid: left }, { msgid: right }) {
152 if (left < right) {
153 return -1;
154 }
155
156 if (left > right) {
157 return 1;
158 }
159
160 return 0;
161 }