Skip to content

Commit

Permalink
Merge pull request #3 from vardario/sahin/utils
Browse files Browse the repository at this point in the history
chore: structure clean-up
  • Loading branch information
sahinvardar authored May 31, 2023
2 parents f26043c + ac4ec94 commit 04415a5
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 81 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@vardario/svelte-i18next",
"version": "0.1.2",
"version": "0.1.3",
"description": "",
"license": "MIT",
"author": "Sahin Vardar",
Expand Down
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import fs from 'node:fs';
import path from 'node:path';

import { extractI18NextKeys } from './extract-i18n-keys.js';
import { parseCsv, recordsToCsv } from './utils.js';
import { parseCsv, recordsToCsv } from './csv-utils.js';

export const TODO_STRING = 'xxxTODOxxx';

Expand Down
51 changes: 51 additions & 0 deletions src/csv-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { parse } from 'csv-parse/sync';
import { stringify } from 'csv-stringify/sync';
import _ from 'lodash';

const CSV_OPTIONS = {
delimiter: ';',
trim: true,
bom: true
};

export function parseCsv(csv: string): Record<string, string> {
const items = parse(csv, {
delimiter: ';',
trim: true,
bom: true
}) as string[][];

return items.reduce((acc, item) => {
if (item.length === 2) {
acc[item[0]] = item[1];
}

return acc;
}, {} as Record<string, string>);
}

export function recordsToCsv(items: Record<string, string>) {
const keys = _.keys(items);
const values = _.values(items);
const csv = keys.reduce((acc, key, index) => {
acc.push([key, values[index]]);
return acc;
}, [] as string[][]);

return stringify(
csv.sort((a, b) => a[0].localeCompare(b[0])),
CSV_OPTIONS
);
}

export function csvToI18Next(csv: string) {
const object = {};

const items = parse(csv, CSV_OPTIONS) as string[];

for (const item of items) {
const [path, value] = item;
_.set(object, path, value);
}
return object;
}
3 changes: 2 additions & 1 deletion src/extract-i18n-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import fs from 'node:fs/promises';
import path from 'node:path';
import * as compiler from 'svelte/compiler';
import { Ast } from 'svelte/types/compiler/interfaces.js';
import { extractKeyPathFromFile, scanDir, stripScriptTag } from './utils.js';
import { extractKeyPathFromFile, stripScriptTag } from './string-utils.js';
import { scanDir } from './utils.js';

function extractKeysFromComponent(ast: Ast, callIdentifier: string): string[] {
const result: string[] = [];
Expand Down
2 changes: 1 addition & 1 deletion src/i18n-preprocessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { CallExpression, Node } from 'estree';
import * as compiler from 'svelte/compiler';
import { Ast, TemplateNode } from 'svelte/types/compiler/interfaces';
import type { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
import { extractKeyPathFromFile, stripScriptTag } from './utils.js';
import { extractKeyPathFromFile, stripScriptTag } from './string-utils.js';

export function create18nCallLabelAttribute(callIdentifier: string, i18nKey: string) {
const expression = parse(`${callIdentifier}("${i18nKey}")`, { ecmaVersion: 'latest' });
Expand Down
4 changes: 2 additions & 2 deletions src/utils.test.ts → src/string-utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'vitest';
import { extractKeyPathFromFile, stripScriptTag } from './utils.js';
import { extractKeyPathFromFile, stripScriptTag } from './string-utils.js';

describe('utils', () => {
describe('string-utils', () => {
test('extractPrefixFromFile', () => {
expect(extractKeyPathFromFile('example/components/auth.svelte')).toBe('components.auth');
expect(extractKeyPathFromFile('example/components/sub-component/auth.svelte')).toBe(
Expand Down
27 changes: 27 additions & 0 deletions src/string-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import path from 'node:path';

export function stripScriptTag(code: string) {
const scriptTagRegEx = /(<script[\s\S]*?[\s\S\]*?>[\s\S]*?<\/script>)/gi;
const scriptTags: string[] = [];

for (const match of code.matchAll(scriptTagRegEx)) {
scriptTags.push(match[0]);
}

return { code: code.replace(scriptTagRegEx, ''), scriptTags };
}

export function extractKeyPathFromFile(filename: string) {
filename = filename.split('.').slice(0, -1).join('.');
const regEx = /(components|routes)/;
const match = regEx.exec(filename);
if (match === null) {
throw new Error(`${filename} is not valid.`);
}

const pathParts = filename.split(path.sep);
const index = pathParts.findIndex(pathPart => regEx.exec(pathPart));

const result = pathParts.slice(index).join('.');
return result.replace('.svelte', '').replace('+', '');
}
75 changes: 0 additions & 75 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
import { parse } from 'csv-parse/sync';
import { stringify } from 'csv-stringify/sync';

import _ from 'lodash';
import fs from 'node:fs/promises';
import path from 'node:path';
import url from 'node:url';

const CSV_OPTIONS = {
delimiter: ';',
trim: true,
bom: true
};

export async function scanDir(dir: string, filter?: (file: string) => boolean) {
const result: string[] = [];

Expand All @@ -35,75 +25,10 @@ export async function scanDir(dir: string, filter?: (file: string) => boolean) {
return result.sort();
}

export function stripScriptTag(code: string) {
const scriptTagRegEx = /(<script[\s\S]*?[\s\S\]*?>[\s\S]*?<\/script>)/gi;
const scriptTags: string[] = [];

for (const match of code.matchAll(scriptTagRegEx)) {
scriptTags.push(match[0]);
}

return { code: code.replace(scriptTagRegEx, ''), scriptTags };
}

export function __dirname(meta: ImportMeta) {
const __filename = url.fileURLToPath(import.meta.url);
return path.dirname(__filename);
}

export function extractKeyPathFromFile(filename: string) {
filename = filename.split('.').slice(0, -1).join('.');
const regEx = /(components|routes)/;
const match = regEx.exec(filename);
if (match === null) {
throw new Error(`${filename} is not valid.`);
}

const pathParts = filename.split(path.sep);
const index = pathParts.findIndex(pathPart => regEx.exec(pathPart));

const result = pathParts.slice(index).join('.');
return result.replace('.svelte', '').replace('+', '');
}

export function parseCsv(csv: string): Record<string, string> {
const items = parse(csv, {
delimiter: ';',
trim: true,
bom: true
}) as string[][];

return items.reduce((acc, item) => {
if (item.length === 2) {
acc[item[0]] = item[1];
}

return acc;
}, {} as Record<string, string>);
}

export function recordsToCsv(items: Record<string, string>) {
const keys = _.keys(items);
const values = _.values(items);
const csv = keys.reduce((acc, key, index) => {
acc.push([key, values[index]]);
return acc;
}, [] as string[][]);

return stringify(
csv.sort((a, b) => a[0].localeCompare(b[0])),
CSV_OPTIONS
);
}

export function csvToI18Next(csv: string) {
const object = {};

const items = parse(csv, CSV_OPTIONS) as string[];

for (const item of items) {
const [path, value] = item;
_.set(object, path, value);
}
return object;
}

0 comments on commit 04415a5

Please sign in to comment.