How to exclude folder from Typewriter code generation - typewriter

I'm using the settings below to include project "Soft.Data" in my Typewriter code generation.
But how do I exclude a specific folder (e.g. "ViewModels") from the code generation?
Template(Settings settings)
{
settings.IncludeProject("Soft.Data");
settings.OutputFilenameFactory = file =>
{
return $"{file.Name.Replace("ViewModel", "GenViewModel").Replace(".cs", ".ts")}";
};
}

You can use a lambda filter in your template to exclude a namespace.
${
Template(Settings settings)
{
settings.IncludeProject("Soft.Data");
settings.OutputFilenameFactory = file =>
{
return $"{file.Name.Replace("ViewModel", "GenViewModel").Replace(".cs", ".ts")}";
};
}
}
$Classes(c => c.Namespace != "Soft.Data.ViewModels")[
...
]

Related

vscode findFiles returns nothing but npm glob returns correct results

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)

Delete file from file system in ionic 4

I am working with one application in which I am creating offline PDF and save them in file system.
Now the problem is when I delete the particular record I need to delete the PDF from file system I go through the file plugin but couldn't find any method related to that. I am using ionic 4 here are some peace of code.
if (this.plt.is('cordova')) {
this.pdfObj.getBuffer((buffer) => {
const blob = new Blob([buffer], { type: 'application/pdf' });
// Save the PDF to the data Directory of our App
this.file.writeFile(this.file.externalRootDirectory + '/Downloads/', 'ACCSYS-' +
this.randomString(4) + '-' + encodeURI(this.headerData.title) + '.pdf', blob, { replace: true }).then(fileEntry => {
// Open the PDf with the correct OS tools
setTimeout(() => {
this.hideLoader();
this.fileOpener.open(fileEntry.nativeURL, 'application/pdf');
this.pdfObj = null;
}, 1000);
});
});
} else {
setTimeout(() => {
this.hideLoader();
this.pdfObj.download();
this.pdfObj = null;
}, 500);
}
Assume I store the nativeURL in localstorage.
any idea how to delete the file ??
If you already have a fileEntry object you can use the remove() method to delete the file like this:
fileEntry.remove(function() {
// if the file has been successfully removed
}, function(error) {
// if there was an error removing the file
}, function() {
// if the file does not exist
});
See these links for more documentation and examples.
here is the perfect way to do it ( define window on the top of ts file )
delete() {
// this.fileHelper.removeFile();
const fileToRemove = this.remoteURL; // Change this with your file path
window.resolveLocalFileSystemURL( fileToRemove, (dirEntry) => {
dirEntry.remove(this.successHandler, this.errorHandler);
});
}
successHandler() {
console.log('Directory deleted successfully');
}
errorHandler() {
console.log('There is some error while deleting directory')
}

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)
);
}
}
}
}
});

When i run my script nothing happens

So i recently found this google drive script and tried to use it.
The script should normally get file names and url on my google drive folder and copy them in a spreadsheet.
When i click Run, I get no error and nothing happens in my drive.
Is there variables i should change to make it work ?
PS : I'm very new to coding and can't seem to find what is wrong with this code
Thanks in advance for your help !
Here is the code :
function myFunction() {
function listFilesInFolder(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
niceFileType( file.getMimeType() )
];
sheet.appendRow(data);
}
}
}
Two issues. This needs to be ran in a script attached to a spreadsheet and you have a nested function.
Your code:
function myFunction() {
function listFilesInFolder(foldername) {
...
}
}
remove the outer function decleration and its matching closing bracket. The code will run.
It should look like:
function listFilesInFolder(foldername) {
...
}
Try this modified code in spreadsheet instead:
function myfunction(){
//Declaring the function listFolders to temp
var temp = function listFolders(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
file.getMimeType()
];
sheet.appendRow(data);
}
}
// calls the function listFolders below
temp()
}

Function Download in Yii2

public function actionUnduh($id) {
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('../web/bukti/') . $download->bukti;
if (file_exists($path)) {
//return \Yii::$app->response->sendFile($download->pre_paper,#file_get_contents($path));
return Yii::$app->response->sendFile($path);
}
}
I need to download file from folder web/bukti, the code not error but the code doesn't work, Anyone can help me :(
public function actionUnduh($id)
{
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('#webroot').'/bukti/'.$download->bukti;
if (file_exists($path)) {
return Yii::$app->response->sendFile($path, 'File name here');
}
}
Refer below:
Yii2 Aliases
Yii2 sendFile()
Firstly you can write an action in SiteController.php like this:
public function actionDownload()
{
$file=Yii::$app->request->get('file');
$path=Yii::$app->request->get('path');
$root=Yii::getAlias('#webroot').$path.$file;
if (file_exists($root)) {
return Yii::$app->response->sendFile($root);
} else {
throw new \yii\web\NotFoundHttpException("{$file} is not found!");
}
}
then you can call this function anywhere:
Yii::$app->urlManager->createUrl(['site/download','path'=>'/upload/files/','file'=>'filename.pdf'])
Be careful your files must be in this directory:
"backend/web/upload/files/filename.pdf"
or
"frontend/web/upload/files/filename.pdf"

Resources