重构代码 --- 计算长函数工具的实现(附源代码)

长函数代表着腐化的代码,难以修改和扩展。在网上搜了竞没找到相关工具,于是就自己手动写了一个。

计算函数行数,找出长函数,这样就可以开始重构代码了。

 

工具:fl.py

说明:计算函数长度,目前只支持.c文件和.cpp文件,支持其他文件类型,只需将代码中.cpp改为对应的文件类型即可

环境要求:安装Python 2.7

使用方法: ./fl.py max_lengthrelative_dir

Max_length:大于该长度的函数则输出

Relative_dir:目录相对路径

 

使用例子:./fl.py 300101_StarZoneServer/

@IED_40_125_sles10sp1:~> ./fl.py 300 101_ZoneServer/
Lines > 300 , Search in dir: 101_StarZoneServer/
101_ZoneServer/DropEngine/DropFramework.cpp : line 295 total : 563 namespace DroppedThingPrivateFunction
101_ZoneServer/GameMaster/PetAttributeCommand.cpp : line 41 total : 341 int CPetAttributeCommand::SecurityCheck()
101_ZoneServer/GameMaster/RoleAttributeCommand.cpp : line 186 total : 320 int CRoleAttributeCommand::SecurityCheck()
101_ZoneServer/GameMaster/PetEnhanceCommand.cpp : line 36 total : 403 int CPetEnhanceCommand::SecurityCheck()

输出第一行为参数,函数长度大于300,搜索目录名。

后面输出为:

文件名 函数起始行号 函数总长度函数名称

 

如果有什么不足或BUG,欢迎交流反馈和完善。

#!/usr/bin/python
# Create by douglaschen, 2011.12.12. All right Reserved.
import os
import string
import sys
import linecache

__DEBUG = 0
def fl(FILENAME, LENGTH):
	sysSed="sed -e '/^{\|^}/=' -n "
	sysSed += str(FILENAME)

	result = os.popen(sysSed).read()

	resultlist = result.split('\n')

	# print len(resultlist)
	for i in range(0, len(resultlist)-1, 2):
		start = int(resultlist[i])
		end   = int(resultlist[i+1])
		if ((end - start) < LENGTH):
			continue

		print FILENAME, ": line", start - 1, "total :", (end - start), 
		print linecache.getline(FILENAME, start - 1), 


def walkdir(directory):
	if __DEBUG != 0:
		import pdb 
		pdb.set_trace()
	# print directory
	for root, dirs, files in os.walk(directory):
		# print "root : ", root
		# print "dirs : ", dirs
		# print "files :", files
		for file in files:
			# print file
			string = str(file)
			if not (string.endswith(".cpp") or string.endswith(".c")):
				continue
		
			file = os.path.join(root, file)
			# print "file is : ", file
			fl(file, LENGTH)
	
		for dir in dirs:
			# print dir
			walkdir(dir)

if __name__ == '__main__':
	# fl("UseThing.cpp", 50)
	LENGTH=150
	DIR=os.path.abspath('CandyAT/Bin/Server_proj/')
	
	argc = len(sys.argv)
	if 3 != argc:
		print "argc :", argc
		print "Usage : ./fl.py max_length relative_dir"
		sys.exit(0)
	if (argc > 1):
		LENGTH = int(sys.argv[1])
	if (argc > 2):
		DIR = sys.argv[2]
	print "Lines >", LENGTH, ", Search in dir:", DIR
	walkdir(DIR)

如果有什么不足或BUG,欢迎交流反馈和完善。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值