bashlex icon indicating copy to clipboard operation
bashlex copied to clipboard

Traversing the BashLex AST Node.

Open shivamgupta01 opened this issue 8 years ago • 5 comments

Hey,

I am trying to traverse through the bashlex.ast.node to find something specific, such as if the bash command is writing something to temp or deleting any file.

Till now I was trying manual check if (tree[0].tree[i].word) == 'rm' : return command But I assume its not the right way to traverse the Bashlex AST tree, what if I need to find the files with are writing to Temp directory.

Can you shed some light on how I can efficiently traverse through the AST and fulfill the above requirement.

shivamgupta01 avatar Apr 30 '18 18:04 shivamgupta01

I think you want to look for a CommandNode and see if its first WordNode is 'rm'. Then traverse the subsequent WordNodes (which are the arguments to rm) and do the rest of the checks. Does that answer your question?

idank avatar Apr 30 '18 19:04 idank

Sounds Good to me, can you also explain to check if the file is updating something in /temp?

For Example:

import bashlex parts = parser.parse("echo "hello world" >/tmp/foo") print(parts[0]) ''' CommandNode(parts=[WordNode(parts=[] pos=(0, 4) word='echo'), WordNode(parts=[] pos=(5, 18) word='hello world'), RedirectNode(heredoc=None input=None output=WordNode(parts=[] pos=(20, 28) word='/tmp/foo') pos=(19, 28) type='>')] pos=(0, 28)) ''' if parts[0].parts[2] == 'RedirectNode': print("DoSomething") This Code is not working.

I want to check if a particular Node is a redirect node or any other particular type of node., I can Manually write up an split function for that, but I am assuming that there is better a way to access this data.

shivamgupta01 avatar Apr 30 '18 20:04 shivamgupta01

Late to the party, I just discovered this library the other day. So, first of all, great work, also on explainshell!

I'd like to go back to the traversal question. I know that I can implement it myself because everything is basically just lists but is there maybe code already that makes it more convenient, like for @shivamgupta01's use case when I only want to hook into visited redirect nodes?

dAnjou avatar Jan 23 '20 11:01 dAnjou

I think the nodevisitor should get you there. See https://github.com/idank/bashlex/blob/master/examples/commandsubstitution-remover.py for a similar program that utilizes it to visit command substitutions only.

idank avatar Jan 23 '20 16:01 idank

Hey, just wanted to shamelessly plug my package here. I wrote a ton of code that easily allows for bash AST manipulation in this way if anyone is interested in the future: https://github.com/BlankCanvasStudio/bashparser

BlankCanvasStudio avatar Mar 12 '23 03:03 BlankCanvasStudio