私はこの方法を検索するために有しており、私は「この行が存在しない場合は、」このメソッド内の行を追加する必要が存在する場合、私は、javaファイルがたくさんあります。この行は、メソッドの閉じ括弧の前に追加する必要があります。
これまでのところ私は、次のコードを持っています:
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 onPause\n")
#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 onResume\n")
#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 }
しかし、私はここから行くことがどこかわからない、Pythonは私の第一言語でありません。私は正しい方向に案内されるように要求することができます。
例:私は、次のシグネチャを持つメソッドを探しています:
public void onPause(){
super.onPause();
// Add my line here
}
public void onPause(){
super.onPause();
Config.pauseCollectingLifecycleData(); // Line exists do nothing
}
これは実際には非常に困難です。まず第一に、あなたのif "onPause" in sourcecode
アプローチは、現在を区別しません定義 onPause()
と呼び出し、それを。そして第二に、すべての正しい閉鎖を見つけることは}
容易ではありません。単純に、あなただけ(開閉カーリー数えるかもしれない{
、刻みblocklevelを}
、それをデクリメント)、および仮定}
blocklevelをゼロにすることがカーリー方法の閉鎖があります。しかし、これは間違っているかもしれません!方法はいくつか含まれている場合がありますので、文字列 リテラル(おそらくアンバランス)カーリーを含むを。またはコメントカーリーと。これはblocklevel、カウントアップ混乱だろう。
これを適切に行うには、実際のJavaパーサを構築する必要があります。それは、次のようなライブラリを使用する場合でも、多くの仕事だ達を。
あなたはむしろ揮発性としている罰金場合はその場しのぎの、あなたがしようとblocklevel数が手がかりとして、インデントと一緒に、上記使用することができます(ソースコードがきちんとインデントされると仮定した場合)。ここで私は開始点として、最大ハッキングきた何かがあります:
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\")"))
これは、(のようなすべてのエッジケースの種類に対して脆弱であることに注意してください{
、おそらく文字列やコメントの中に、またはその代わりに空白のタブインデント、または千の他のもの)。これはあなたのためだけの開始点です。