Adding content in file in specific place with node js (Like Angular Cli Modify app.module file) - node.js

I got the idea that node js its not just for web application for example I can create a console application with node (cli) .
and already I have an interest in how I can make a cli app that create files and modify existing files for example something like angular cli with one command "ng generate component" its :-
1- create a set of files
2- modify app.module file
a. add import statement for generated component
b. add generated component in declarations array
and after a lot of search I got that first step can be handled in some way with node file system module.
but i don't know how they modify "app.module" file by just adding some syntax in its right place for instance adding new import statement after all exists import statements also adding the component name in declarations array as a last item
I'm really appreciate any help maybe with some code example if possible and thanks in advance

After some searches i found this answer:
There a couple of ways of editing a file, the most reliable is perhaps
the most complex one which can be done by parsing the file (Generating
an abstract syntax tree) update the new ast and pass it to a code
generator which will output the new string (code) of the modified ast.
Another option is to use regular expressions to know where add to
certain statements. For example there would be a regex to match import
statements to lines, you will map the lines of the file to this regex
where you'll get an array of booleans denoting whether the line is an
import stmt. Or not, once the import stmts are finished you can insert
a new line with the new import statement in the original lines array.
A third option is to regenerate the file all at once everytime, but
this means that you'll have to a ctx of the project (ctx = object
contains some details.
and as reference i found that AST (Abstract Syntax Tree) is more reliable way also it's not that hard this is some links that helped me a lot to know what is AST in simple way and how to deal with it
1- What is AST and how to understand it and how to use it https://www.youtube.com/watch?v=tM_S-pa4xDk
2- and this is an amazing article about "Write Code to Rewrite Your Code with jscodeshift" https://www.toptal.com/javascript/write-code-to-rewrite-your-code
https://www.youtube.com/watch?v=tM_S-pa4xDk

Related

Is there a better/more pythonic way to load an arbitrary set of functions from modules in another folder?

I'm just basically asking:
if it's considered OK to use exec() in this context
if there's a better/more pythonic solution
for any input or comments on how my code could be improved
First, some context. I have main.py which basically takes input and checks to see if I've written a command. Let's say I type '/help'. The slash just tells it my input was supposed to be a command, so then it checks if a function called 'help' exists, and if so, that function will be run.
To keep things tidy in main.py, and to allow myself to add more commands easily, I have a 'commands' directory, with individual command files in it, such as help.py. help.py would look like this for example:
def help():
print("You've been helped")
So then of course, I need to import help() from help.py, which was trivial.
As I added more commands, I decided to add an init.py file where I'd keep all the command import lines of code, and then just do 'from init import *' in main.py. At first, each time I added a command, I'd add another line in init.py to import it. But that wasn't as flexible as I wanted, so I thought, there's got to be a way to just loop through all the .py files in my commands directory and import them. I struggled with this for a while but came up with a solution that works.
In the init.py snippet below, I loop through the commands directory (and a couple others, but they're irrelevant to the question), and you'll see I use the dreaded exec() function to actually import the commands.
loaded, failed = '', ''
for directory in command_directories:
command_list = os.listdir(directory)
command_list.sort()
for command_file in command_list:
if command_file.endswith(".py"):
command_name = command_file.split(".")[0]
try:
# Evil exec() hack to use variable-name directories/modules
# Haven't found a more... pythonic... way to do this
exec(f"from {directory}.{command_name} import {command_name}")
loaded = loaded + f" - Loaded: {command_name}\n"
except:
failed = failed + f" - Failed to load: {command_name}\n"
if debug == True:
for init_debug in [loaded, failed]: print(init_debug)
I use exec() because I don't know a better way to make a variable with the name of the function being loaded, so I use {command_name} in my exec string to arbitrarily evaluate the variable name that will store the function I'm importing. And... well, it works. The functions work perfectly when called from main.py, so I believe they are being imported in the correct namespace.
Obviously, exec() can be dangerous, but I'm not taking any user input into it, just file names. Filenames that I only I am creating. This program isn't being distributed, but if it was, then I believe using exec() would be bad since there's potential someone could exploit it.
If I'm wrong about something, I'd love to hear about it and get suggestions for a better implementation. Python has been very easy to pick up for me, but I'm probably missing some of the fundamentals.
I should note, I'm running python 3.10 on replit (until I move this project to another host).

Skip Empty Modules - Sphinx Autodoc

I am using Sphinx to build documentation for a package. I can't find a way to skip (remove) empty submodules when building doc. Example in Section 2 there is a subsection named Submodule which is blank I want to skip such subsections. I tried using the following code.
def skip_util_classes(app, what, name, obj, skip, options):
if what == "Submodules":
skip = True
return skip
def setup(sphinx):
sphinx.connect("autodoc-skip-member", skip_util_classes)
The above code is not eliminating section Submodules.
I want to know how can I define a section or subsection that needs to be skipped? And how can I define empty section or subsection that I want to skip in skip_util_classes?
Something like the skip_util_classes function (a handler for the autodoc-skip-member event) is used when you want Sphinx to ignore certain members of Python modules or classes. See Connect Sphinx autodoc-skip-member to my function.
This technique cannot be used to skip or remove sections in generated .rst files. Here are two suggestions that might help with that problem:
Create a custom sphinx-apidoc template. See Remove the word "module" from Sphinx documentation.
Don't run sphinx-apidoc over and over again. Run the tool once, tweak the output and add it to source control. See Keeping the API updated in Sphinx.

How to share a variable between 2 pyRevit scripts?

I am using the latest version of pyRevit, v45.
I'm writing some info in temporary files with
myTempFile = script.get_instance_data_file("id")
This creates a file named pyRevit_2018_xxxx_id.tmp in which I store useful info. If I'm not mistaken, the "xxxx" part is changing every time I reload Revit. Now, I need to get access to this information from another pyRevit script.
How can I retrieve the name of the temp file I need to read? In other words, how do I access "myTempFile" from within the second script, which has no idea of the name of "myTempFile"?
I guess I can share somehow that variable between my script, but what's the proper way to do this? I know this must be a very basic programming question, but I'm indeed not a programmer ;)
Thanks a lot,
Arnaud.
Ok, I realise now that my variables in the 1st script cease to exist after its execution.
So for now I wrote the file name in another file, of which I know the name.. That works.
But if there's a cleaner way to do this, I'd be glad to learn ;)
Arnaud
pyrevit.script module provides 4 different methods for creating temporary files based on their use case:
get_instance_data_file:
for data files marked with Revit instance pid. This means that scripts running on another instance will not see this temp file.
http://pyrevit.readthedocs.io/en/latest/pyrevit/script.html#pyrevit.script.get_instance_data_file
get_universal_data_file:
for temp files accessible to all Revit instances and versions
http://pyrevit.readthedocs.io/en/latest/pyrevit/script.html#pyrevit.script.get_universal_data_file
get_data_file:
Base method to get a standard temp file for current revit version
http://pyrevit.readthedocs.io/en/latest/pyrevit/script.html#pyrevit.script.get_data_file
get_document_data_file:
temp file marked with active document (so scripts working on another document will not see this)
http://pyrevit.readthedocs.io/en/latest/pyrevit/script.html#pyrevit.script.get_document_data_file
Each method uses a pattern to create the temp file name. So as long as the call to the method is the same of different scripts, the method generates the same file name.
Example:
Script 1:
from pyrevit import script
tfile = script.get_data_file('mydata')
Script 2:
from pyrevit import script
tempfile = script.get_data_file('mydata')
In this example tempfile = tfile since the file id is the same.
There is documentation on each so make sure you take a look at those and pick the flavor that serves your purpose.

minko / lua issue : premake5.lua:3: attempt to index global 'minko' (a nil value)

I am working with minko and managed to compile MINKO SDK properly for 3 platforms (Linux, Android, HTML5) and build all tutorials / examples. Moving on to create my own project, I followed the instructions on how to use the existing skeleton project, then using an existing example project.
(I believe there is an error in the skeleton code at this line :
auto sceneManager = SceneManager::create(canvas->context()); //does not compile
where as the example file look like this :
auto sceneManager = SceneManager::create(canvas); //compile and generate binary
I was able to do so by modifying premake5.lua (to include more plugins) and calling script/solution_gmake_gcc.sh
to generate the make solution a week ago. Today, I tried to make a new project in a new folder but calling
script/solution_gmake_gcc.sh and script/clean failed with this error:
minko-master/skel_tut/mycode/premake5.lua:3: attempt to index global 'minko' (a nil value)
Now at premake5.lua line 3 there is this line : minko.project.solution(PROJECT_NAME),
however sine i am not familiar with lua at all, can anyone shed any light on the issue ?
What is supposed to be declared here, why is it failing suddenly... ?
(I can still modify,compile and run the code but i can't for example add more plug-ins)
PS: weirdly enough, the previously 'working' project is also failing at this point.
Thanks.
PROJECT_NAME = path.getname(os.getcwd())
minko.project.application("minko-tutorial-" .. PROJECT_NAME)
files { "src/**.cpp", "src/**.hpp", "asset/**" }
includedirs { "src" }
-- plugins
minko.plugin.enable("sdl")
minko.plugin.enable("assimp")
minko.plugin.enable("jpeg")
minko.plugin.enable("bullet")
minko.plugin.enable("png")
--html overlay
minko.plugin.enable("html-overlay")
Assuming that's indeed your project premake5.lua file (please us the code tags next time), you should have include "script" at the beginning of the file:
https://github.com/aerys/minko/blob/master/skeleton/premake5.lua#L1
If you don't have this line, it will not include script/premake5.lua which is in charge of including the SDK build system files that defines everything inside the minko Lua namespace/table. That's why you get that error.
I think you copy pasted one of the examples/tutorials premake5.lua file instead of modifying the one provided by the skeleton. The premake conf file of the examples/tutorials are different since they are included from the SDK premake files. But your app premake5.lua does the "opposite": it includes the SDK conf files rather than being included by them.
The best practice is to edit your app's copy of the skeleton's premake5.lua (instead of copy/pasting one from the examples/tutorials).
(I believe there is an error in the skeleton code at this line :
That's possible. Our build server doesn't test the skeleton code. That's a mistake we will fix ASAP to make sure it works properly.
script/solution_gmake_gcc.sh and script/clean failed with this error:
minko-master/skel_tut/mycode/premake5.lua:3: attempt to index global 'minko' (a nil value)
Could you copy/paste your premake5.lua file?
Also, what's the value you set for the MINKO_HOME env var? Maybe you've moved the SDK...
Note that instead of setting a global MINKO_HOME env var, you can also set the corresponding LUA constant at the very begining of your premake5.lua file.

Adding a new lexer to scintilla/scite (...and eventually wxPython StyledTextCtrl)

Has anyone of you successfully added a lexer to scintilla?
I have been following the short instructions at http://www.scintilla.org/SciTELexer.html - and even discovered the secret extra instructions at http://www.scintilla.org/ScintillaDoc.html#BuildingScintilla (Changing Set of Lexers)
Everything compiles, and I can add the lexer to SciTE just fine, but my ColouriseMapfileDoc method just does not get called (a printf does not produce output). If I add the same code to e.g. the ColouriseLuaDoc lexer, everything is fine (a printf does produce output).
Specifically I have
In scintilla/include/Scintilla.iface, added val SCLEX_MAPFILE=99
And any lexical class IDs
In the scintilla/include directory run HFacer.py and confirmed that the SciLexer.h file has changed.
Created LexMapfile.cxx with a ColouriseMapfileDoc function
At the end of the file associated the lexer ID and name with the function:
LexerModule lmMapfile(SCLEX_MAPFILE, ColouriseMapfileDoc, "mapfile");
Run LexGen.py to generate all the makefiles (as per the secret instructions)
Created a new SciTE properties file by cloning scite/src/others.properties
Set up some styles
In scite/src/SciTEGlobal.properties added $(filter.conf) to the definition of open.filter.
Added this language to the Language menu of SciTE,
Built both Scintilla and SciTE.
Grumbled and cursed.
What am I doing wrong, except maybe step 12?
In case someone reads this question in the future - you will also have to add a line
import yourformat in SciTEGlobal.properties. That's the undocumented step 9b.
In case someone reads this question in the future - you will also have to add a line import
yourformat in SciTEGlobal.properties. That's the undocumented step 9b.
This step is no longer required. I compiled 3.2.2 and this was done with import *. The rest of the steps are still complete and relevant though.
I'm wring one lexer directly in scintilla/lexer/LexOthers.cxx as described in http://www.scintilla.org/SciTELexer.html.
For scite 3.2.3 the lacking step 5b is that you need to add LINK_LEXER(lmYouLexerMod); in scintilla/src/Catalogue.cxx.

Resources