这与 Python 和 Golang 代码库都相关,但我想知道找到一个函数的所有调用点的最简单方法是什么,包括最终调用该函数的所有函数,无论是直接调用,还是通过另一个函数/辅助方法调用。
所以假设我们有:
file1.go
func SomeFunction() bool {
return false
}
一些/目录/file2.go
func HelperFunction() bool {
return SomeFunction()
}
some_other_file.go
func OtherFunc() bool {
return HelperFunction()
}
现在显然我可以使用 IDE 找到对 SomeFunction 的所有引用,但我还想知道 OtherFunc() 最终也会调用 SomeFunction。
有没有一种工具可以从根本上帮助做到这一点?
递归解析代码库中的所有源文件并构建某种树是否是一种选择?等等
在 Python 代码库中,如果您能够执行代码,您可以为这样的函数创建一个 decorator 并使用模块 tracebak 来获取函数被调用的确切位置。
import traceback
def extract_execution_points(func):
def wrapper(*args, **kwargs):
frames = traceback.extract_stack()
# Last stack frame is for the decorator, we are interested in frames[-2]
# wich is the actual function call.
target_frame = frames[-2]
print(f"File: {target_frame.filename}, lineno: {target_frame.lineno}")
return func(*args, **kwargs)
return wrapper
@extract_execution_points
def target_func():
pass
if __name__ == '__main__':
target_func()
# With other name
foo = target_func
foo()
打印:
File: /tmp/example/test_foo.py, lineno: 23
File: /tmp/example/test_foo.py, lineno: 26