Adding a line in a method block of java code using python










3















I have a lot of java files wherein I have to search for a method, if present I have to add a line inside this method "If this line does not already exist". This line has to be added before the closing brace of the method.



So far I have the following code:



import os
import ntpath
extensions = set(['.java','.kt'])
for subdir, dirs, files in os.walk("/src/main"):
for file in files:
filepath = subdir + os.sep + file
extension = os.path.splitext(filepath)[1]
if extension in extensions:
if 'onCreate(' in open(filepath).read():
print (ntpath.basename(filepath))
if 'onPause' in open (filepath).read():
print ("is Activity and contains onPausen")
#Check if Config.pauseCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }
if 'onResume' in open (filepath).read():
print ("is Activity and contains onResumen")
#Check if Config.resumeCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }


But I am not sure where to go from here, Python not being my first language. Could I request to be guided in the right direction.



Example:
I am looking for a method with the following signature:



public void onPause()
super.onPause();
// Add my line here


public void onPause()
super.onPause();
Config.pauseCollectingLifecycleData(); // Line exists do nothing










share|improve this question



















  • 1





    Don't read the file multiple times. After if extension in extensions, read the file content into a variable and use in on that variable: sourcecode = open(filepath).read() and then if "onPause" in sourcecode. Much faster, much cleaner.

    – digitalarbeiter
    Nov 18 '18 at 16:11















3















I have a lot of java files wherein I have to search for a method, if present I have to add a line inside this method "If this line does not already exist". This line has to be added before the closing brace of the method.



So far I have the following code:



import os
import ntpath
extensions = set(['.java','.kt'])
for subdir, dirs, files in os.walk("/src/main"):
for file in files:
filepath = subdir + os.sep + file
extension = os.path.splitext(filepath)[1]
if extension in extensions:
if 'onCreate(' in open(filepath).read():
print (ntpath.basename(filepath))
if 'onPause' in open (filepath).read():
print ("is Activity and contains onPausen")
#Check if Config.pauseCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }
if 'onResume' in open (filepath).read():
print ("is Activity and contains onResumen")
#Check if Config.resumeCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }


But I am not sure where to go from here, Python not being my first language. Could I request to be guided in the right direction.



Example:
I am looking for a method with the following signature:



public void onPause()
super.onPause();
// Add my line here


public void onPause()
super.onPause();
Config.pauseCollectingLifecycleData(); // Line exists do nothing










share|improve this question



















  • 1





    Don't read the file multiple times. After if extension in extensions, read the file content into a variable and use in on that variable: sourcecode = open(filepath).read() and then if "onPause" in sourcecode. Much faster, much cleaner.

    – digitalarbeiter
    Nov 18 '18 at 16:11













3












3








3








I have a lot of java files wherein I have to search for a method, if present I have to add a line inside this method "If this line does not already exist". This line has to be added before the closing brace of the method.



So far I have the following code:



import os
import ntpath
extensions = set(['.java','.kt'])
for subdir, dirs, files in os.walk("/src/main"):
for file in files:
filepath = subdir + os.sep + file
extension = os.path.splitext(filepath)[1]
if extension in extensions:
if 'onCreate(' in open(filepath).read():
print (ntpath.basename(filepath))
if 'onPause' in open (filepath).read():
print ("is Activity and contains onPausen")
#Check if Config.pauseCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }
if 'onResume' in open (filepath).read():
print ("is Activity and contains onResumen")
#Check if Config.resumeCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }


But I am not sure where to go from here, Python not being my first language. Could I request to be guided in the right direction.



Example:
I am looking for a method with the following signature:



public void onPause()
super.onPause();
// Add my line here


public void onPause()
super.onPause();
Config.pauseCollectingLifecycleData(); // Line exists do nothing










share|improve this question
















I have a lot of java files wherein I have to search for a method, if present I have to add a line inside this method "If this line does not already exist". This line has to be added before the closing brace of the method.



So far I have the following code:



import os
import ntpath
extensions = set(['.java','.kt'])
for subdir, dirs, files in os.walk("/src/main"):
for file in files:
filepath = subdir + os.sep + file
extension = os.path.splitext(filepath)[1]
if extension in extensions:
if 'onCreate(' in open(filepath).read():
print (ntpath.basename(filepath))
if 'onPause' in open (filepath).read():
print ("is Activity and contains onPausen")
#Check if Config.pauseCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }
if 'onResume' in open (filepath).read():
print ("is Activity and contains onResumen")
#Check if Config.resumeCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }


But I am not sure where to go from here, Python not being my first language. Could I request to be guided in the right direction.



Example:
I am looking for a method with the following signature:



public void onPause()
super.onPause();
// Add my line here


public void onPause()
super.onPause();
Config.pauseCollectingLifecycleData(); // Line exists do nothing







java python python-3.x python-2.7 code-editor






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 7:58







User3

















asked Nov 14 '18 at 6:22









User3User3

67242061




67242061







  • 1





    Don't read the file multiple times. After if extension in extensions, read the file content into a variable and use in on that variable: sourcecode = open(filepath).read() and then if "onPause" in sourcecode. Much faster, much cleaner.

    – digitalarbeiter
    Nov 18 '18 at 16:11












  • 1





    Don't read the file multiple times. After if extension in extensions, read the file content into a variable and use in on that variable: sourcecode = open(filepath).read() and then if "onPause" in sourcecode. Much faster, much cleaner.

    – digitalarbeiter
    Nov 18 '18 at 16:11







1




1





Don't read the file multiple times. After if extension in extensions, read the file content into a variable and use in on that variable: sourcecode = open(filepath).read() and then if "onPause" in sourcecode. Much faster, much cleaner.

– digitalarbeiter
Nov 18 '18 at 16:11





Don't read the file multiple times. After if extension in extensions, read the file content into a variable and use in on that variable: sourcecode = open(filepath).read() and then if "onPause" in sourcecode. Much faster, much cleaner.

– digitalarbeiter
Nov 18 '18 at 16:11












1 Answer
1






active

oldest

votes


















2














This is actually quite difficult. First of all, your if "onPause" in sourcecode approach currently doesn't distinguish between defining onPause() and calling it. And second of all, finding the correct closing } isn't trivial. Naively, you might just count opening and closing curlies ( increments the blocklevel, decrements it), and assume that the } that makes the blocklevel zero is the closing curly of the method. However, this might be wrong! Because the method might contain some string literal containing (possibly unbalanced) curlies. Or comments with curlies. This would mess up the blocklevel count.



To do this properly, you would have to build an actual Java parser. That's a lot of work, even when using libraries such as tatsu.



If you're fine with a rather volatile kludge, you can try and use the blocklevel count mentioned above together with the indentation as a clue (assuming your source code is decently indented). Here's something I've hacked up as a starting point:



def augment_function(sourcecode, function, line_to_insert):
in_function = False
blocklevel = 0
insert_before = None
source = sourcecode.split("n")
for line_no, line in enumerate(source):
if in_function:
if "" in line:
blocklevel += 1
if "" in line:
blocklevel -= 1
if blocklevel == 0:
insert_before = line_no
indent = len(line) - len(line.lstrip(" ")) + 4 #4=your indent level
break
elif function in line and "public " in line:
in_function = True
if "" in line:
blocklevel += 1
if insert_before:
source.insert(insert_before, " "*indent + line_to_insert)
return "n".join(source)

# test code:
java_code = """class Foo
private int foo;
public void main(String args)
foo = 1;

public void setFoo(int f)

foo = f;

public int getFoo(int f)
return foo;


"""
print(augment_function(java_code, "setFoo", "log.debug("setFoo")"))


Note that this is vulnerable to all sorts of edge cases (such as  






Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53294223%2fadding-a-line-in-a-method-block-of-java-code-using-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














This is actually quite difficult. First of all, your if "onPause" in sourcecode approach currently doesn't distinguish between defining onPause() and calling it. And second of all, finding the correct closing isn't trivial. Naively, you might just count opening and closing curlies ( increments the blocklevel, decrements it), and assume that the that makes the blocklevel zero is the closing curly of the method. However, this might be wrong! Because the method might contain some string literal containing (possibly unbalanced) curlies. Or comments with curlies. This would mess up the blocklevel count.



To do this properly, you would have to build an actual Java parser. That's a lot of work, even when using libraries such as tatsu.



If you're fine with a rather volatile kludge, you can try and use the blocklevel count mentioned above together with the indentation as a clue (assuming your source code is decently indented). Here's something I've hacked up as a starting point:



def augment_function(sourcecode, function, line_to_insert):
in_function = False
blocklevel = 0
insert_before = None
source = sourcecode.split("n")
for line_no, line in enumerate(source):
if in_function:
if "" in line:
blocklevel += 1
if "" in line:
blocklevel -= 1
if blocklevel == 0:
insert_before = line_no
indent = len(line) - len(line.lstrip(" ")) + 4 #4=your indent level
break
elif function in line and "public " in line:
in_function = True
if "" in line:
blocklevel += 1
if insert_before:
source.insert(insert_before, " "*indent + line_to_insert)
return "n".join(source)

# test code:
java_code = """class Foo
private int foo;
public void main(String args)
foo = 1;

public void setFoo(int f)

foo = f;

public int getFoo(int f)
return foo;


"""
print(augment_function(java_code, "setFoo", "log.debug("setFoo")"))


Note that this is vulnerable to all sorts of edge cases (such as in a string or in a comment, or tab indent instead of space, or possibly a thousand other things). This is just a starting point for you.






share isn't trivial. Naively, you might just count opening and closing curlies ( increments the blocklevel, decrements it), and assume that the that makes the blocklevel zero is the closing curly of the method. However, this might be wrong! Because the method might contain some string literal containing (possibly unbalanced) curlies. Or comments with curlies. This would mess up the blocklevel count.

To do this properly, you would have to build an actual Java parser. That's a lot of work, even when using libraries such as tatsu.



If you're fine with a rather volatile kludge, you can try and use the blocklevel count mentioned above together with the indentation as a clue (assuming your source code is decently indented). Here's something I've hacked up as a starting point:



def augment_function(sourcecode, function, line_to_insert):
in_function = False
blocklevel = 0
insert_before = None
source = sourcecode.split("n")
for line_no, line in enumerate(source):
if in_function:
if "" in line:
blocklevel += 1
if "" in line:
blocklevel -= 1
if blocklevel == 0:
insert_before = line_no
indent = len(line) - len(line.lstrip(" ")) + 4 #4=your indent level
break
elif function in line and "public " in line:
in_function = True
if "" in line:
blocklevel += 1
if insert_before:
source.insert(insert_before, " "*indent + line_to_insert)
return "n".join(source)

# test code:
java_code = """class Foo
private int foo;
public void main(String args)
foo = 1;

public void setFoo(int f)

foo = f;

public int getFoo(int f)
return foo;


"""
print(augment_function(java_code, "setFoo", "log.debug("setFoo")"))


Note that this is vulnerable to all sorts of edge cases (such as

improve this answer

























  • Thanks man, Been long -- I ended up using the IDE's search and regex facilities :) nevertheless that is a beauty you've written!

    – User3
    Jan 26 at 4:33




















This is actually quite difficult. First of all, your if "onPause" in sourcecode approach currently doesn't distinguish between defining onPause() and calling it. And second of all, finding the correct closing isn't trivial. Naively, you might just count opening and closing curlies ( increments the blocklevel, decrements it), and assume that the that makes the blocklevel zero is the closing curly of the method. However, this might be wrong! Because the method might contain some string literal containing (possibly unbalanced) curlies. Or comments with curlies. This would mess up the blocklevel count.



To do this properly, you would have to build an actual Java parser. That's a lot of work, even when using libraries such as tatsu.



If you're fine with a rather volatile kludge, you can try and use the blocklevel count mentioned above together with the indentation as a clue (assuming your source code is decently indented). Here's something I've hacked up as a starting point:



def augment_function(sourcecode, function, line_to_insert):
in_function = False
blocklevel = 0
insert_before = None
source = sourcecode.split("n")
for line_no, line in enumerate(source):
if in_function:
if "" in line:
blocklevel += 1
if "" in line:
blocklevel -= 1
if blocklevel == 0:
insert_before = line_no
indent = len(line) - len(line.lstrip(" ")) + 4 #4=your indent level
break
elif function in line and "public " in line:
in_function = True
if "{" in line:
blocklevel += 1
if insert_before:
source.insert(insert_before, " "*indent + line_to_insert)
return "n".join(source)

# test code:
java_code = """class Foo
private int foo;
public void main(String args)
foo = 1;

public void setFoo(int f)

foo = f;

public int getFoo(int f)
return foo;


"""
print(augment_function(java_code, "setFoo", "log.debug("setFoo")"))


Note that this is vulnerable to all sorts of edge cases (such as { in a string or in a comment, or tab indent instead of space, or possibly a thousand other things). This is just a starting point for you.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 18 '18 at 20:41

























answered Nov 18 '18 at 16:27









digitalarbeiterdigitalarbeiter

1,6901112




1,6901112












  • Thanks man, Been long -- I ended up using the IDE's search and regex facilities :) nevertheless that is a beauty you've written!

    – User3
    Jan 26 at 4:33

















  • Thanks man, Been long -- I ended up using the IDE's search and regex facilities :) nevertheless that is a beauty you've written!

    – User3
    Jan 26 at 4:33
















Thanks man, Been long -- I ended up using the IDE's search and regex facilities :) nevertheless that is a beauty you've written!

– User3
Jan 26 at 4:33





Thanks man, Been long -- I ended up using the IDE's search and regex facilities :) nevertheless that is a beauty you've written!

– User3
Jan 26 at 4:33



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53294223%2fadding-a-line-in-a-method-block-of-java-code-using-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

How to read a connectionString WITH PROVIDER in .NET Core?

In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

Museum of Modern and Contemporary Art of Trento and Rovereto