Editing source of a file via name with my extension - visual-studio-code

I am writing a VSC extension. What I wanna do is be able to edit a file by using the name of said file to find it?
I just don't know how I would edit the source of said file. I also don't know how to find that file.
EX:
I pass in a name to a function that finds and returns the file needed to edit.
function -> (name: string) -> File
function -> ("script.py") -> ./src/script.py
I hope this makes sense???

Do you not know the filePath?
// note escaped backslashes below
const file = await vscode.workspace.openTextDocument("C:\\Users\\Mark\\jump-and-select\\command-alias\\jsconfig.json");
// or use showTextDocument() instead if you want to open and see the document and changes
console.log(file);
// file.getText() has all your file text
// then look at edit(callback: (editBuilder: TextEditorEdit) => functionality

Related

FileManager: Attribute for when a file was last opened

I need a way of checking when a file was last opened. I tried by creating a custom FileAttributeKey and setting that to the current Date, but when I go to open the file again the attribute does not exist:
private let key = FileAttributeKey(rawValue: "lastOpenedAt")
do {
try FileManager.default.setAttributes(
[key: Date()],
ofItemAtPath: videoNameDirectoryPath
)
} catch {
Log.error(error.localizedDescription)
}
So now I am resorting to using the modification date key to say when I last opened the file, it is not ideal so I am wondering if there is a better way to do this
setAttributes doesn't support custom attributes, you can only use the documented ones.
To set your own attributes, you may use xattr as described in this question:
Write extend file attributes swift example
If you're lucky, you may use kMDItemLastUsedDate from Spotlight aka MDItem as described in the documentation archive of File Metadata Attributes.

Accept a specific type of file Matlab

I have a GUI using a Browe Button to search a file :
function Browse(app, event)
FileName,FilePath ]= uigetfile();
ExPath = fullfile(FilePath, FileName);
app.FileTextArea.Value = ExPath;
end
And i save the file Path in a Text Area.
I have another button that start a matlab script with the file path as parameter and so i would like to accept only a certain type of file (.ctm which is my own type of file) if possible like this :
if file is .ctm
do something
else
print('a .ctm file is needed')
Thanks for helping
There are two things you can do:
Display only the files with a certain extension with uigetfile()
[fileName, dataDir] = uigetfile('*.ctm', 'Select a *.ctm file', yourDefaultPth);
Verify that selected file has a .ctm extension
[data.dir,data.fileName,data.ext] = fileparts(fullfile(dataDir, fileName)); % dataDir and fileName from pt. 1
if strcmp(data.ext, '.ctm')
% do something
else
print('a .ctm file is needed')
end
Keep in mind that neither of the two will verify that the content of the file is the one you're expecting and if someone will manually modify extension of the file, your program will most likely crash. It's good for a start but if you want to do a more reliable check, you should verify that the content of the file is correct, not its extension.

VSCode create unsaved file and add content

In VS Code I would like to create a new document in a new editor (same window), but it need to remain unsaved. I cannot find a way to programmatically set the content of this document while it is in a unsaved state.
I have used:
commands.executeCommand("workbench.action.files.newUntitledFile")
but there seems to be no way to then add content to the file.
When I create a new temporary file and open it with:
workspace.openTextDocument(path)
The file is already saved.
Any thoughts?
Try using openTextDocument with an untitled document to create a unsaved file at a given path, and then use WorkspaceEdit to add some text:
import * as vscode from 'vscode';
import * as path from 'path';
const newFile = vscode.Uri.parse('untitled:' + path.join(vscode.workspace.rootPath, 'safsa.txt'));
vscode.workspace.openTextDocument(newFile).then(document => {
const edit = new vscode.WorkspaceEdit();
edit.insert(newFile, new vscode.Position(0, 0), "Hello world!");
return vscode.workspace.applyEdit(edit).then(success => {
if (success) {
vscode.window.showTextDocument(document);
} else {
vscode.window.showInformationMessage('Error!');
}
});
});
The new file will be unsaved when first opened, but saved to the given path when a user saves it.
Hope that provides a good starting point.
I don't know how to open it in the editor, but you can create an unsaved file with content like the following:
vscode.workspace.openTextDocument({
content: "your content",
language: "text"
});
That should be supported in VSCode 1.54 (Feb. 2021), meaning the vscode.workspace.openTextDocument script from Matt is implemented by default:
Open Editors New Untitled File action
We have introduced a New Untitled File action in the Open Editors view title area.
I was having some issues when the document was eventually saved using this solution from Matt, but I was able to use it in combination with DarkTrick's response.
By using the default behavior of creating an empty document and making it active in the then clause.
vscode.workspace.openTextDocument({
content: newXmlContent,
language: "xml"
}).then(newDocument => {
vscode.window.showTextDocument(newDocument);
});
This allows me to create an untitled document with any content I want and show it in the editor. I was not able to give it a specific name though. This might be a limitation of creating an untitled document.

Replace strings and save file in Scala

I have the following code where I am reading a file and replacing any occurences of "*.tar.gz" file with the new file name provided. Everything works fine and I can see the replaced changes in the console however I am not being able to write a new file with all the changes.
def modifyFile(newFileName: String, filename: String) = {
Source.fromFile(filename).getLines.foreach { line =>
println(line.replaceAll(".+\\.tar\\.gz", newFileName.concat(".tar.gz")))
}
}
}
You forgot to write your modified lines into the new file:
def modifyFile(newFileName: String, sourceFilePath: String, targetFilePath:String) {
scala.tools.nsc.io.File(targetFilePath).printlnAll(
Source.fromFile(sourceFilePath).getLines().map {
_.replaceAll(".+\\.tar\\.gz", newFileName.concat(".tar.gz"))
}.toSeq:_*)
}
Please note that this approach is not the most efficient in terms of performance, as the content of source file is read fully to memory, processed and then written back. More efficient approach will be more verbose and will include java's FileReader/FileWriter.
Upd
As rightfully pointed in comments you have to chose suitable way to write result to file depending on what tools and dependencies you have.

Which file contains function of core/session in magento?

I need to customize other's code,
so I found they used
Mage::getSingleton('core/session')->getMyCustomBlockInfo();
in Order.php file for custom order email
so I can't find this function getMyCustomBlockInfo();
Can anyone tell me where this function reside?
Thanks
those are magic functions get() and set() and you are asking a session variable there that is set as
Mage::getSingleton('core/session')->setMyCustomBlockInfo();
somewhere in your code. If you use terminal you can easily find by making a following grep:
grep '>setMyCustomBlockInfo(' . -rsni
and it will list the files where your variable is set to session.
example :
Mage::getModel('catalog/product'); //or
Mage::getSingleton('catalog/product');
the code must be in '../app/core/Mage/Catalog/Model/Product.php' file
then
Mage::getSingleton('core/session');
the code must be in '../app/core/Mage/Core/Model/Session.php' file
because the class Mage_Core_Model_Session's parent::parent is Varien_Object, then you can do all magic functions and you can ->getData() to see the Data inside.
Mage::getSingleton('core/session')->getData();
on your problem when go call ->getData() you can see data : [my_custom_block_info]
you can set it with call
Mage::getSingleton('core/session')->setMyCustomBlockInfo('what');
Mage::getSingleton('core/session')->getMyCustomBlockInfo();
// will return 'what'