vscode findFiles returns nothing but npm glob returns correct results - file

I'm writing and vscode extension in which I need a list of the test files inside workspace.
To find the test files I'm using the default testMatch from the jest.config.js which is:
[
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)'
]
My problem is that vscode.workspace.findFiles returns empty array and I cannot set it up to get correct results, but using Glob package the output is correct.
protected async findTestFiles(
matchTestsGlobPatterns: string[]
): Promise<vscode.Uri[]> {
const testFilesUris: vscode.Uri[] = [];
const glob_testFilesUris: vscode.Uri[] = [];
const { name: workspaceName, workspaceFolders } = vscode.workspace;
if (workspaceName === undefined || workspaceFolders === undefined) {
throw new Error(`No active workspace${!workspaceFolders ? ' folders' : ''}.`);
}
for (let folderIdx = 0; folderIdx < workspaceFolders.length; folderIdx++) {
const folder = workspaceFolders[folderIdx];
// - by vscode.workspace.findFiles
for (let patternIdx = 0; patternIdx < matchTestsGlobPatterns.length; patternIdx++) {
const currentPattern = matchTestsGlobPatterns[patternIdx];
const pattern = new vscode.RelativePattern(
folder.uri.fsPath,
currentPattern
);
const files = await vscode.workspace.findFiles(
pattern,
'**/node_modules/**'
);
testFilesUris.push(...files);
}
console.log('by [vscode.workspace.findFiles]', testFilesUris.length);
// - by npm Glob
var glob = require('glob');
for (let patternIdx = 0; patternIdx < matchTestsGlobPatterns.length; patternIdx++) {
const currentPattern = matchTestsGlobPatterns[patternIdx];
const files: any[] = await new Promise((resolve, reject) => {
glob(
currentPattern,
{
absolute: true,
cwd: folder.uri.fsPath,
ignore: ['**/node_modules/**']
},
function (err: Error, files: any[]) {
if (err) {
return reject(err);
}
resolve(files);
}
);
});
glob_testFilesUris.push(...files);
}
console.log('by [npm Glob]', glob_testFilesUris.length);
}
// #todo: remove duplicates.
return testFilesUris;
}
The example console output of this function for some project is:
by [vscode.workspace.findFiles] 0
by [npm Glob] 45
Project structure:
rootFolder
src
__tests__
files.test.ts
...
utils
array.test.ts
...
So my question is how do I call vscode.workspace.findFiles to get correct results, or is there known problem with this function?
I have found some kind of answer to the question.
The problem is ?(x) in patterns. The vscode.workspace.findFiles does not work with this pattern as other packages do. If remove it from mentioned glob patterns they work except the .jsx | .tsx files are ommited.

After deep dive into vscode github's issues I have learned (here) that vscode.workspace.findFiles does not support extended patterns like ?(patterLike)

Related

npm exceljs is unable to read any existing file

// read from a file
const workbook = new Excel.Workbook();
await workbook.xlsx.readFile(filename);
// ... use workbook
As per the exceljs documentation, it should load the already existing file 'filename', but when I tried reading it,
const sheet = workbook.addWorksheet('My Sheet');
sheet was actually undefined.
My concern is, is it possible to do read from and write to a file operations in ReactJS, also I came across another article
https://stackoverflow.com/questions/49491710/can-reactjs-write-into-file#:~:text=React%20runs%20in%20browser%20so,gets%20served%20to%20the%20browser
that suggest it is not possible
My project did read and write on the same file template using exceljs in node js. Hope can help you.
workbook.xlsx.readFile(template)
.then(function () {
// machines
var wsMachine = workbook.getWorksheet('No');
wsTemplate = _.cloneDeep(wsMachine);
for (var index = 1; index <= 10; index++) {
var copySheet = workbook.addWorksheet('No' + index, { state: 'visible' });
copySheet.pageSetup.printArea = 'A1:FE219';
var ws = _.cloneDeep(wsTemplate);
copySheet.model = Object.assign(ws.model, {
mergeCells: ws.model.merges
});
copySheet.name = 'No' + index;
}
wsMachine.state = 'hidden';
wsTemplate.state = 'hidden';
return workbook.xlsx.writeFile(urlOutput);
})
.then(function () {
return true
})
.catch(function () {
return false;
});
Happy code

How to NOT delete existing translations with "react-intl-translations-manager"?

I use React-Intl in my app and it works great, but to be easier to manage new keys to translate I started using "react-intl-translations-manager".
My problem is that some of my translations are used through a notification system and the babel extractor don't recognize them because it's outside of his scan scope.
So when I run "react-intl-translations-manager" it deletes all the keys relatives to notifications and other non-scanned translations.
Here is my question: is there any method to "say" to "react-intl-translations-manager" that it's forbidden to delete those keys ?
I tried multiple solutions including whitelists and other but nothing is working.
Here is my translationRunner.js (the configuration file)
const manageTranslations = require('react-intl-translations-manager').default;
manageTranslations({
messagesDirectory: 'src/messages/',
translationsDirectory: 'src/locales/',
languages: ['en_GB', 'fr_FR']
});
There are two ways to do this. One is to use hooks and another way is to override the module where deletion of the actual code happens.
To do the same we can override the getLanguageReport module from react-intl-translations-manager/dist/getLanguageReport
getLanguageReport = require('react-intl-translations-manager/dist/getLanguageReport');
getLanguageReport.original = getLanguageReport.default
getLanguageReport.default = function(defaultMessages, languageMessages, languageWhitelist) {
data = getLanguageReport.original(defaultMessages, languageMessages, languageWhitelist)
// this whitelist ids can be read through a config file as well
whitelisted_id = ['helloworld2', 'helloworld']
deleted = data.deleted;
re_add = []
for (var i=0; i < deleted.length; ) {
if (whitelisted_id.indexOf(deleted[i].key)>=0) {
// we are removing a record so lets not increment i
removed_element = deleted.splice(i,1)[0];
data.fileOutput[removed_element.key] = removed_element.message;
} else {
i++;
}
}
return data;
}
const manageTranslations = require('react-intl-translations-manager').default;
manageTranslations({
messagesDirectory: 'build/messages/src/extracted/',
translationsDirectory: 'src/translations/locales/',
languages: ['de'] // Any translation --- don't include the default language
}
);
This method works fine and will keep the helloworld2 message even if it is not there in new code.
Hooks approach
In this we use the hook reportLanguage and override it to change the data
const manageTranslations = require('react-intl-translations-manager').default;
const writeFileSync = require('fs').writeFileSync
const stringify = require('react-intl-translations-manager/dist/stringify').default;
stringifyOpts = {
sortKeys: true,
space: 2,
trailingNewline: false,
};
manageTranslations({
messagesDirectory: 'build/messages/src/extracted/',
translationsDirectory: 'src/translations/locales/',
languages: ['de'], // Any translation --- don't include the default language
overrideCoreMethods: {
reportLanguage: function(langResults) {
data = langResults.report;
// this whitelist ids can be read through a config file as well
whitelisted_id = ['helloworld2', 'helloworld']
deleted = data.deleted;
re_add = []
for (var i=0; i < deleted.length; ) {
if (whitelisted_id.indexOf(deleted[i].key)>=0) {
// we are removing a record so lets not increment i
removed_element = deleted.splice(i,1)[0];
data.fileOutput[removed_element.key] = removed_element.message;
} else {
i++;
}
}
// original definition of reportLanguage from manageTranslations.js
// unfortunately the original core method is not exposed for us to re-use
// so we need to copy the code again
if (
!langResults.report.noTranslationFile &&
!langResults.report.noWhitelistFile
) {
// printers.printLanguageReport(langResults);
writeFileSync(
langResults.languageFilepath,
stringify(langResults.report.fileOutput, stringifyOpts)
);
writeFileSync(
langResults.whitelistFilepath,
stringify(langResults.report.whitelistOutput, stringifyOpts)
);
} else {
if (langResults.report.noTranslationFile) {
printers.printNoLanguageFile(langResults);
writeFileSync(
langResults,
stringify(langResults.report.fileOutput, stringifyOpts)
);
}
if (langResults.report.noWhitelistFile) {
printers.printNoLanguageWhitelistFile(langResults);
writeFileSync(
langResults.whitelistFilepath,
stringify([], stringifyOpts)
);
}
}
}
}
});

Gulp-eslint throws errors on dynamically loaded JSs

I have a project structure like
There are approx 10 JS files in com. lab1 and lab2 has a config.json file which tells, out of 10 files which files to be concatenated and placed as app-min.js in dist/lab1 or dist/lab2.
In the gulp file I've created something like this.
var filesArr = [];
var labName;
// Player Task
gulp.task('player', function () {
return gulp.src(filesArr)
.pipe(eslint())
.pipe(babel())
.pipe(concat('app-min.js'))
.pipe(uglify({
compress: {
drop_console: true
}
}).on('error', gutil.log))
.pipe(gulp.dest('dist/' + labName));
});
// Clean
gulp.task('clean', function () {
if (readJson()) {
return del([
'dist/' + labName
]);
}
return null;
});
// Watch
gulp.task('watch', function () {
gulp.watch(filesArr, gulp.series('player'));
});
// Read Json and create JS Array
function readJson() {
// LAB STRUCTURE
var _n = prompt('Specify the LAB name. ');
labName = _n;
var _path = path.resolve('./src/' + _n);
var _exists = fs.existsSync(_path);
if (_exists) {
var _json = fs.readFileSync(path.resolve(_path + '/labstructure.json'), 'utf-8');
var _jObj = JSON.parse(_json).labObj.components;
for (var i = 0; i < _jObj.length; i++) {
var _jsName = 'src/com/component/' + _jObj[i].ref + '.js';
if (filesArr.indexOf(_jsName) === -1) {
filesArr.push(_jsName);
}
}
}
return _exists;
}
gulp.task('default', gulp.series('clean', 'player', 'watch'));
Here the filesArr looks like:
[ 'src/com/component/ColorActClass.js',
'src/com/component/PanelCompClass.js',
'src/com/component/ToggleCompClass.js',
'src/com/component/SliderCompClass.js',
'src/com/component/CheckBoxCompClass.js',
'src/com/component/ButtonCompClass.js',
'src/com/component/LabelCompClass.js',
'src/com/component/InputBoxClass.js',
'src/com/component/ColorMonitorClass.js',
'src/com/component/MsgBoxClass.js',
'src/com/component/ConfBoxClass.js',
'src/com/component/NumberPadClass.js',
'src/com/main/lib/webfontloader.js',
'src/com/main/lib/howler.core.min.js',
'src/com/main/PlayerClass.js',
'src/kl1001_color/BrainClass.js' ]
This works perfectly fine at the first place. But when any JS is modified then in watch player task throws eslint error on some files which are untouched. This doesn't happen always rather if watch is running for 10-20 mins then it throws error. Like this:
In this case CheckBoxCompClass.js is not the file which is modified, but still got the issue. On top of that, the semicolon is in place. If this file has issue then eslint should have thrown the error at the first place.
Please help.
Accidentally, my NVM was set to an older version. Solved the issue after updating the NVM and by setting the current NVM version to the latest one.

How to create a gulp file with reusable functions - Multiple Watch points & Multiple Output destinations

Goal is to use this Gulp file to execute 'n' number of different source & destinations.
How can we pass the arguments(source, destination) so that the CSS-Generator task is accepting those source & destinations and giving out the separate output files.
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
var paths = {
styles: {
src1: "scss/slider-one/index.scss",
src2: "scss/slider-two/index.scss"
dest1: "slider-one",
dest2: "slider-two"
}
};
function style1() {
return (
gulp
.src(paths.styles.src1)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest1))
);
}
exports.style1 = style1;
function style2() {
return (
gulp
.src(paths.styles.src2)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest2))
);
}
exports.style2 = style2;
function watch() {
style1();
style2();
gulp.watch("scss/slider-one/*.scss", style1);
gulp.watch("scss/slider-two/*.scss", style2);
}
exports.watch = watch
Your source is scss/slider-one/index.scss & destination is slider-one and watch is scss/slider-one/*.scss.
slider-one is common in source, destination & watch.
So you can define the paths array as ["slider-one","slider-two"]
And you are calling the style1 & style2 as the callback of watch function. So you can club that and define that in one function.
And call that function inside for loop with parameters (source,destination,watch).
Full Code:
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
function runGulpSass(src,dest,watch) {
gulp.watch(watch, function() {
return gulp.src(src)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(dest))
});
}
exports.runGulpSass = runGulpSass;
function startGulp() {
var paths = ["slider-one","slider-two"];
for(var i=0;i<paths.length;i++) {
runGulpSass("scss/"+paths[i]+"/index.scss",paths[i],"scss/"+paths[i]+"/*.scss")
}
}
exports.watch = startGulp
[Edit] If there is no common value in source, destination & watch :
Define the paths array like this :
var paths = [
["scss/slider-one/index.scss","css/slider-one","slider-one/*.scss"],
["scss/slider-two/index.scss","css/slider-two","slider-two/*.scss"]
];
And set the runGulpSass function parameter like this :
runGulpSass(paths[i][0],paths[i][1],paths[i][2])

Dynamic import in different folder

I have some trouble to import dynamicaly a class.
I use alias for this projet :
config.resolve.alias = {
App: path.resolve('./src/'),
Reactive: path.resolve('./app/')
}
I want to import a list of class :
const classes = {
foo: 'App/Foo',
bar: 'App/Bar'
};
let list = {};
for(var c in classes) {
(async (k, v, list) => {
const m = await import(`${v}`);
list[k] = new m.default();
})(c, classes[c], list);
}
This script is called in app, and all imported classes in src.
The error is simple : Cannot find module 'App/Foo'.
When I check the last entry of error's log :
var map = {
"./OtherClass1": [
"./app/OtherClass1.js"
],
"./OtherClass1.js": [
"./app/OtherClass1.js"
],
"./OtherClass2": [
"./app/OtherClass2.js"
],
"./OtherClass2.js": [
"./app/OtherClass2.js"
]
};
function webpackAsyncContext(req) {
var ids = map[req];
if(!ids)
return Promise.reject(new Error("Cannot find module '" + req + "'."));
return Promise.all(ids.slice(1).map(__webpack_require__.e)).then(function() {
return __webpack_require__(ids[0]);
});
};
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
return Object.keys(map);
};
webpackAsyncContext.id = "./app lazy recursive ^.*$";
module.exports = webpackAsyncContext;
So, the error is legit, because the map does not contain Foo and Bar classes in src, only those in app.
How can I specify to Webpack to check in both folders, recursively?
But, when I test this, it's work fine :
for(var c in classes) {
(async (k, v, list) => {
const m = await import(`${"App/Foo"}`);
list[k] = new m.default();
})(c, classes[c], list);
}
use react import to import your file and use file.classname to call them
eg import claases from '/src';
and use it link
app = classes.myfile

Resources