feature: server: columns: get rid of mock-require

This commit is contained in:
coderaiser 2024-03-20 12:13:17 +02:00
parent 46c8accd84
commit 98d3a4cc56
41 changed files with 233 additions and 215 deletions

View file

@ -10,6 +10,7 @@ module.exports = {
],
rules: {
'key-spacing': 'off',
'n/prefer-node-protocol': 'error',
},
overrides: [{
files: ['bin/release.js'],

View file

@ -1,11 +1,11 @@
'use strict';
const fs = require('fs');
const fs = require('node:fs');
const {
basename,
extname,
join,
} = require('path');
} = require('node:path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

View file

@ -4,7 +4,7 @@ const {
resolve,
sep,
join,
} = require('path');
} = require('node:path');
const {EnvironmentPlugin} = require('webpack');
const WebpackBar = require('webpackbar');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
/* global DOM */
const Emitify = require('emitify');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
require('../css/main.css');
require('../css/nojs.css');
require('../css/columns/name-size-date.css');

View file

@ -1,6 +1,6 @@
'use strict';
const {join} = require('path');
const {join} = require('node:path');
const {test, stub} = require('supertape');
const mockRequire = require('mock-require');

View file

@ -1,6 +1,6 @@
'use strict';
const {extname} = require('path');
const {extname} = require('node:path');
const currify = require('currify');
const testRegExp = currify((name, reg) => reg.test(name));
const getRegExp = (ext) => RegExp(`\\.${ext}$`, 'i');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const codegen = require('codegen.macro');
const tryToCatch = require('try-to-catch');
const currify = require('currify');

View file

@ -1,7 +1,7 @@
'use strict';
const {join} = require('path');
const {readFileSync} = require('fs');
const {join} = require('node:path');
const {readFileSync} = require('node:fs');
const test = require('supertape');
const montag = require('montag');

View file

@ -121,6 +121,7 @@
"just-snake-case": "^1.1.0",
"markdown-it": "^14.0.0",
"mellow": "^3.0.0",
"nano-memoize": "^3.0.16",
"nomine": "^4.0.0",
"object.omit": "^3.0.0",
"once": "^1.4.0",
@ -171,7 +172,7 @@
"domtokenlist-shim": "^1.2.0",
"emitify": "^4.0.1",
"eslint": "^8.0.1",
"eslint-plugin-n": "^16.0.1",
"eslint-plugin-n": "^17.0.0-4",
"eslint-plugin-putout": "^22.0.0",
"extract-text-webpack-plugin": "^4.0.0-alpha.0",
"gritty": "^8.0.0",

View file

@ -1,6 +1,6 @@
'use strict';
const path = require('path');
const path = require('node:path');
const {test, stub} = require('supertape');
const cloudcmd = require('./cloudcmd.js');

View file

@ -1,9 +1,13 @@
'use strict';
const fullstore = require('fullstore');
const process = require('process');
const path = require('path');
const fs = require('fs');
const {nanomemoize} = require('nano-memoize');
const readFilesSync = require('@cloudcmd/read-files-sync');
const isMap = (a) => /\.map$/.test(a);
const not = (fn) => (a) => !fn(a);
@ -12,19 +16,26 @@ const defaultColumns = {
'name-size-date-owner-mode': '',
};
const isDev = process.env.NODE_ENV === 'development';
const _isDev = fullstore(process.env.NODE_ENV === 'development');
const getDist = (isDev) => isDev ? 'dist-dev' : 'dist';
const dist = getDist(isDev);
const columnsDir = path.join(__dirname, '..', dist, 'columns');
module.exports.isDev = _isDev;
const names = fs
.readdirSync(columnsDir)
.filter(not(isMap));
module.exports.getColumns = ({isDev = _isDev()} = {}) => {
const columns = readFilesSyncMemo(isDev);
const columns = readFilesSync(columnsDir, names, 'utf8');
module.exports = {
...columns,
...defaultColumns,
return {
...columns,
...defaultColumns,
};
};
const readFilesSyncMemo = nanomemoize((isDev) => {
const dist = getDist(isDev);
const columnsDir = path.join(__dirname, '..', dist, 'columns');
const names = fs
.readdirSync(columnsDir)
.filter(not(isMap));
return readFilesSync(columnsDir, names, 'utf8');
});

37
server/columns.spec.js Normal file
View file

@ -0,0 +1,37 @@
'use strict';
const test = require('supertape');
const fs = require('fs');
const {getColumns, isDev} = require('./columns');
test('columns: prod', (t) => {
const columns = getColumns({
isDev: false,
});
t.equal(columns[''], '');
t.end();
});
test('columns: dev', (t) => {
const columns = getColumns({
isDev: true,
});
const css = fs.readFileSync(`${__dirname}/../css/columns/name-size-date.css`, 'utf8');
t.equal(columns['name-size-date'], css);
t.end();
});
test('columns: no args', (t) => {
const currentIsDev = isDev();
isDev(true);
const columns = getColumns();
const css = fs.readFileSync(`${__dirname}/../css/columns/name-size-date.css`, 'utf8');
isDev(currentIsDev);
t.equal(columns['name-size-date'], css);
t.end();
});

View file

@ -2,11 +2,11 @@
const DIR_SERVER = `${__dirname}/`;
const DIR_COMMON = '../common/';
const path = require('path');
const path = require('node:path');
const fs = require('fs');
const Emitter = require('events');
const {homedir} = require('os');
const fs = require('node:fs');
const Emitter = require('node:events');
const {homedir} = require('node:os');
const exit = require(`${DIR_SERVER}exit`);
const CloudFunc = require(`${DIR_COMMON}cloudfunc`);

View file

@ -1,6 +1,6 @@
'use strict';
const {once} = require('events');
const {once} = require('node:events');
const test = require('supertape');
const io = require('socket.io-client');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const test = require('supertape');
const {promisify} = require('util');
const tryToCatch = require('try-to-catch');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const test = require('supertape');
const env = require('./env');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const getMessage = (a) => a?.message || a;
module.exports = (...args) => {

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const {test, stub} = require('supertape');
const exit = require('./exit');

View file

@ -1,7 +1,7 @@
'use strict';
const {join} = require('path');
const {callbackify} = require('util');
const {join} = require('node:path');
const {callbackify} = require('node:util');
const pullout = require('pullout');
const ponse = require('ponse');

View file

@ -1,8 +1,8 @@
'use strict';
const fs = require('fs');
const {join} = require('path');
const {promisify} = require('util');
const fs = require('node:fs');
const {join} = require('node:path');
const {promisify} = require('node:util');
const tryToCatch = require('try-to-catch');
const serveOnce = require('serve-once');

View file

@ -1,8 +1,8 @@
'use strict';
const process = require('process');
const net = require('net');
const repl = require('repl');
const process = require('node:process');
const net = require('node:net');
const repl = require('node:repl');
module.exports = net
.createServer((socket) => {

View file

@ -1,11 +1,11 @@
'use strict';
const process = require('process');
const process = require('node:process');
const DIR = '../';
const DIR_COMMON = `${DIR}../common/`;
const path = require('path');
const fs = require('fs');
const path = require('node:path');
const fs = require('node:fs');
const root = require(`${DIR}root`);
const CloudFunc = require(`${DIR_COMMON}cloudfunc`);

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const format = require('format-io');
const {version} = require('../../package');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const {test, stub} = require('supertape');
const info = require('./info');

View file

@ -1,9 +1,6 @@
'use strict';
const DIR_SERVER = './';
const DIR_COMMON = '../common/';
const {extname} = require('path');
const {extname} = require('node:path');
const {read} = require('win32');
const ponse = require('ponse');
@ -16,12 +13,13 @@ const once = require('once');
const pipe = require('pipe-io');
const {contentType} = require('mime-types');
const root = require(`${DIR_SERVER}root`);
const prefixer = require(`${DIR_SERVER}prefixer`);
const CloudFunc = require(`${DIR_COMMON}cloudfunc`);
const Columns = require(`${DIR_SERVER}/columns`);
const Template = require(`${DIR_SERVER}/template`);
const root = require(`./root`);
const prefixer = require(`./prefixer`);
const CloudFunc = require(`../common/cloudfunc`);
const {getColumns} = require(`./columns`);
const Template = require(`./template`);
const {stringify} = JSON;
const {FS} = CloudFunc;
const sendIndex = (params, data) => {
@ -29,7 +27,7 @@ const sendIndex = (params, data) => {
...params,
name: 'index.html',
};
ponse.send(data, ponseParams);
};
@ -39,9 +37,9 @@ const getPrefix = (config) => prefixer(config('prefix'));
const getReadDir = (config) => {
if (!config('dropbox'))
return read;
const {readDir} = onceRequire('@cloudcmd/dropbox');
return wraptile(readDir, config('dropboxToken'));
};
@ -51,10 +49,10 @@ const getReadDir = (config) => {
module.exports = currify((config, options, request, response, next) => {
const name = ponse.getPathName(request);
const isFS = RegExp(`^/$|^${FS}`).test(name);
if (!isFS)
return next();
route({
config,
options,
@ -74,36 +72,36 @@ async function route({config, options, request, response}) {
gzip,
name,
};
config('prefix', prefixer(request.baseUrl));
const rootName = name.replace(CloudFunc.FS, '') || '/';
const fullPath = root(rootName, config('root'));
const read = getReadDir(config);
const [error, stream] = await tryToCatch(read, fullPath, {
root: config('root'),
});
const {html} = options;
if (error)
return ponse.sendError(error, p);
if (stream.type === 'directory') {
const {files} = stream;
return sendIndex(p, buildIndex(config, html, {
files,
path: format.addSlashToEnd(rootName),
}));
}
const {contentLength} = stream;
response.setHeader('Content-Length', contentLength);
response.setHeader('Content-Type', contentType(extname(fullPath)));
await pipe([stream, response]);
}
@ -118,56 +116,56 @@ function indexProcessing(config, options) {
const noConsole = !config('console');
const noTerminal = !config('terminal');
const {panel} = options;
let {data} = options;
if (noKeysPanel)
data = hideKeysPanel(data);
if (oneFilePanel)
data = data
.replace('icon-move', 'icon-move none')
.replace('icon-copy', 'icon-copy none');
if (noContact)
data = data.replace('icon-contact', 'icon-contact none');
if (noConfig)
data = data.replace('icon-config', 'icon-config none');
if (noConsole)
data = data.replace('icon-console', 'icon-console none');
if (noTerminal)
data = data.replace('icon-terminal', 'icon-terminal none');
const left = rendy(Template.panel, {
side: 'left',
content: panel,
className: !oneFilePanel ? '' : 'panel-single',
});
let right = '';
if (!oneFilePanel)
right = rendy(Template.panel, {
side: 'right',
content: panel,
className: '',
});
const name = config('name');
data = rendy(data, {
title: CloudFunc.getTitle({
name,
}),
fm: left + right,
prefix: getPrefix(config),
config: JSON.stringify(config('*')),
columns: Columns[config('columns')],
config: stringify(config('*')),
columns: getColumns()[config('columns')],
});
return data;
}
@ -177,7 +175,7 @@ function buildIndex(config, html, data) {
prefix: getPrefix(config),
template: Template,
});
return indexProcessing(config, {
panel,
data: html,
@ -188,14 +186,14 @@ module.exports._hideKeysPanel = hideKeysPanel;
function hideKeysPanel(html) {
const keysPanel = '<div id="js-keyspanel" class="{{ className }}"';
const keysPanelRegExp = '<div id="?js-keyspanel"? class="?{{ className }}"?';
const from = rendy(keysPanelRegExp, {
className: 'keyspanel',
});
const to = rendy(keysPanel, {
className: 'keyspanel hidden',
});
return html.replace(RegExp(from), to);
}

View file

@ -1,9 +1,9 @@
'use strict';
const {Readable} = require('stream');
const {Readable} = require('node:stream');
const path = require('path');
const fs = require('fs');
const path = require('node:path');
const fs = require('node:fs');
const tryToCatch = require('try-to-catch');
const {test, stub} = require('supertape');

View file

@ -1,6 +1,6 @@
'use strict';
const path = require('path');
const path = require('node:path');
const readFilesSync = require('@cloudcmd/read-files-sync');
const templatePath = path.join(__dirname, '..', 'tmpl/fs');

View file

@ -1,7 +1,7 @@
'use strict';
const fs = require('fs');
const {join} = require('path');
const fs = require('node:fs');
const {join} = require('node:path');
const {test, stub} = require('supertape');

View file

@ -3,36 +3,36 @@
const tryCatch = require('try-catch');
const exit = require('./exit');
const columns = require('./columns');
const {getColumns} = require('./columns');
const isString = (a) => typeof a === 'string';
module.exports.root = (dir, config) => {
if (!isString(dir))
throw Error('dir should be a string');
if (dir === '/')
return;
if (config('dropbox'))
return;
const {statSync} = require('fs');
const [error] = tryCatch(statSync, dir);
if (error)
return exit('cloudcmd --root: %s', error.message);
};
module.exports.editor = (name) => {
const reg = /^(dword|edward|deepword)$/;
if (!reg.test(name))
exit('cloudcmd --editor: could be "dword", "edward" or "deepword" only');
};
module.exports.packer = (name) => {
const reg = /^(tar|zip)$/;
if (!reg.test(name))
exit('cloudcmd --packer: could be "tar" or "zip" only');
};
@ -40,14 +40,14 @@ module.exports.packer = (name) => {
module.exports.columns = (type) => {
const addQuotes = (a) => `"${a}"`;
const all = Object
.keys(columns)
.keys(getColumns())
.concat('');
const names = all
.filter(Boolean)
.map(addQuotes)
.join(', ');
if (!all.includes(type))
exit(`cloudcmd --columns: can be only one of: ${names}`);
};

View file

@ -1,6 +1,6 @@
'use strict';
const fs = require('fs');
const fs = require('node:fs');
const {test, stub} = require('supertape');
@ -22,20 +22,20 @@ test('validate: root: bad', (t) => {
const config = {
root: Math.random(),
};
const [e] = tryCatch(cloudcmd, {
config,
});
t.equal(e.message, 'dir should be a string', 'should throw');
t.end();
});
test('validate: root: config', (t) => {
const config = stub().returns(true);
validate.root('/hello', config);
t.calledWith(config, ['dropbox'], 'should call config');
t.end();
});
@ -43,7 +43,7 @@ test('validate: root: config', (t) => {
test('validate: root: /', (t) => {
const fn = stub();
validate.root('/', fn);
t.notCalled(fn, 'should not call fn');
t.end();
});
@ -51,57 +51,57 @@ test('validate: root: /', (t) => {
test('validate: root: stat', (t) => {
const fn = stub();
const {statSync} = fs;
const error = 'ENOENT';
fs.statSync = () => {
throw Error(error);
};
mockRequire(exitPath, fn);
const {root} = reRequire(validatePath);
root('hello', fn);
const msg = 'cloudcmd --root: %s';
fs.statSync = statSync;
stopAll();
t.calledWith(fn, [msg, error], 'should call fn');
t.end();
});
test('validate: packer: not valid', (t) => {
const fn = stub();
mockRequire(exitPath, fn);
const {packer} = reRequire(validatePath);
const msg = 'cloudcmd --packer: could be "tar" or "zip" only';
packer('hello');
stopAll();
t.calledWith(fn, [msg], 'should call fn');
t.end();
});
test('validate: editor: not valid', (t) => {
const fn = stub();
mockRequire(exitPath, fn);
const {editor} = reRequire(validatePath);
const msg = 'cloudcmd --editor: could be "dword", "edward" or "deepword" only';
editor('hello');
stopAll();
t.calledWith(fn, [msg], 'should call fn');
t.end();
});
@ -109,33 +109,36 @@ test('validate: editor: not valid', (t) => {
test('validate: columns', (t) => {
const fn = stub();
mockRequire(exitPath, fn);
const {columns} = require(validatePath);
columns('name-size-date');
stopAll();
t.notCalled(fn, 'should not call exit');
t.end();
});
test('validate: columns: wrong', (t) => {
const fn = stub();
mockRequire(exitPath, fn);
mockRequire(columnsPath, {
const getColumns = stub().returns({
'name-size-date': '',
'name-size': '',
});
mockRequire(exitPath, fn);
mockRequire(columnsPath, {
getColumns,
});
const {columns} = reRequire(validatePath);
const msg = 'cloudcmd --columns: can be only one of: "name-size-date", "name-size"';
columns('hello');
stopAll();
t.calledWith(fn, [msg], 'should call exit');
t.end();
});

View file

@ -1,8 +1,8 @@
'use strict';
const process = require('process');
const http = require('http');
const os = require('os');
const process = require('node:process');
const http = require('node:http');
const os = require('node:os');
const express = require('express');
const io = require('socket.io');

View file

@ -1,6 +1,6 @@
'use strict';
const fs = require('fs');
const fs = require('node:fs');
const tryCatch = require('try-catch');
const DIR = `${__dirname}/../../`;

View file

@ -1,7 +1,7 @@
'use strict';
const {mkdirSync} = require('fs');
const {join} = require('path');
const {mkdirSync} = require('node:fs');
const {join} = require('node:path');
const test = require('supertape');
const rimraf = require('rimraf');

View file

@ -1,6 +1,6 @@
'use strict';
const fs = require('fs');
const fs = require('node:fs');
const test = require('supertape');
const {Volume} = require('memfs');

View file

@ -1,8 +1,8 @@
'use strict';
const fs = require('fs');
const {join} = require('path');
const {promisify} = require('util');
const fs = require('node:fs');
const {join} = require('node:path');
const {promisify} = require('node:util');
const {reRequire} = require('mock-require');
const test = require('supertape');

View file

@ -1,6 +1,6 @@
'use strict';
const fs = require('fs');
const fs = require('node:fs');
const test = require('supertape');
const {Volume} = require('memfs');
@ -19,45 +19,45 @@ test('cloudcmd: rest: rename', async (t) => {
'/fixture/mv.txt': 'hello',
'/fixture/tmp/a.txt': 'a',
};
const vol = Volume.fromJSON(volume, '/');
const unionFS = ufs
.use(vol)
.use(fs);
mockRequire('fs', unionFS);
mockRequire('node:fs', unionFS);
reRequire('@cloudcmd/rename-files');
reRequire('@cloudcmd/move-files');
reRequire(restPath);
const cloudcmd = reRequire(cloudcmdPath);
const {createConfigManager} = cloudcmd;
const configManager = createConfigManager();
configManager('auth', false);
configManager('root', '/');
const {request} = serveOnce(cloudcmd, {
configManager,
});
const files = {
from: '/fixture/mv.txt',
to: '/fixture/tmp/mv.txt',
};
const {body} = await request.put(`/api/v1/rename`, {
body: files,
});
mockRequire.stop('fs');
mockRequire.stopAll();
const expected = 'rename: ok("{"from":"/fixture/mv.txt","to":"/fixture/tmp/mv.txt"}")';
stopAll();
t.equal(body, expected, 'should move');
t.end();
});
@ -65,23 +65,23 @@ test('cloudcmd: rest: rename', async (t) => {
test('cloudcmd: rest: rename: no from', async (t) => {
const cloudcmd = reRequire(cloudcmdPath);
const {createConfigManager} = cloudcmd;
const configManager = createConfigManager();
configManager('auth', false);
configManager('root', '/');
const {request} = serveOnce(cloudcmd, {
configManager,
});
const files = {};
const {body} = await request.put(`/api/v1/rename`, {
body: files,
});
const expected = '"from" should be filled';
t.equal(body, expected);
t.end();
});
@ -89,25 +89,25 @@ test('cloudcmd: rest: rename: no from', async (t) => {
test('cloudcmd: rest: rename: no to', async (t) => {
const cloudcmd = reRequire(cloudcmdPath);
const {createConfigManager} = cloudcmd;
const configManager = createConfigManager();
configManager('auth', false);
configManager('root', '/');
const {request} = serveOnce(cloudcmd, {
configManager,
});
const files = {
from: '/',
};
const {body} = await request.put(`/api/v1/rename`, {
body: files,
});
const expected = '"to" should be filled';
t.equal(body, expected);
t.end();
});

View file

@ -1,33 +0,0 @@
'use strict';
const process = require('process');
const test = require('supertape');
const fs = require('fs');
const {reRequire} = require('mock-require');
const columnsPath = '../../server/columns';
test('columns: prod', (t) => {
const {NODE_ENV} = process.env;
process.env.NODE_ENV = '';
const columns = reRequire(columnsPath);
process.env.NODE_ENV = NODE_ENV;
t.equal(columns[''], '');
t.end();
});
test('columns: dev', (t) => {
const {NODE_ENV} = process.env;
process.env.NODE_ENV = 'development';
const columns = reRequire(columnsPath);
const css = fs.readFileSync(`${__dirname}/../../css/columns/name-size-date.css`, 'utf8');
process.env.NODE_ENV = NODE_ENV;
t.equal(columns['name-size-date'], css);
t.end();
});

View file

@ -1,7 +1,7 @@
'use strict';
const path = require('path');
const {once} = require('events');
const path = require('node:path');
const {once} = require('node:events');
const test = require('supertape');
const io = require('socket.io-client');

View file

@ -1,6 +1,6 @@
'use strict';
const process = require('process');
const process = require('node:process');
const test = require('supertape');
const env = require('../../server/env');

View file

@ -1,6 +1,6 @@
'use strict';
const {join} = require('path');
const {join} = require('node:path');
const {test, stub} = require('supertape');
const cloudcmdPath = join(__dirname, '..', '..');