免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
123
最近访问板块 发新帖
楼主: abcfy2
打印 上一主题 下一主题

请教python分析groovy代码文件的写法 [复制链接]

论坛徽章:
0
21 [报告]
发表于 2013-05-27 17:24 |只看该作者
回复 20# GhostFromHeaven


    我按照你说的把if not line:语句全删了,改后的代码如下:
  1. #!/usr/bin/python
  2. #-*- coding:utf-8 -*-
  3. import os
  4. import re
  5. import string
  6. import sys
  7. pattern_func_def = re.compile('''(?<!\S)def\s+.*?\{\s*''')
  8. pattern_save = re.compile('''\.save\s*\(.*?\)|\.delete\s*\(.*?\)''')  #同时筛选save方法和delete方法
  9. pattern_left_brace = re.compile('''.*?\{.*?''')
  10. pattern_right_brace = re.compile('''.*?\}.*?''')
  11. pattern_switch = re.compile('''(?<!\S)switch\s*\(.*?\)\s*{''')
  12. pattern_case = re.compile('''(?<!\S)(case\s+\S+)|(default)\s*:''')
  13. pattern_break = re.compile('''(?<!\S)break(?!\S)''')
  14. pattern_if = re.compile('''(?<!\S)if\s*\(.*\.save\(\s*\).*\)\s*''')
  15. pattern_save_without_arg = re.compile('''\.save\s*\(\s*\)''')
  16. class GroovyParser(object):
  17.     def __init__(self):
  18.         self.current_file_name = ""
  19.         self.current_file_handler = None
  20.         self.current_line = ""
  21.         self.current_line_index = 0
  22.         
  23.     def _get_line(self):
  24.         for self.current_line in open(self.current_file_name, "r"):
  25.             self.current_line_index += 1
  26.             self.current_line = self.current_line.strip('\n')
  27.             yield "%s" % self.current_line
  28.    
  29.     def print_line(self):
  30.         print "%s:%d:%s" % (self.current_file_name,
  31.                                 self.current_line_index,
  32.                                 self.current_line)
  33.    
  34.     # 处理{}
  35.     def _handle_brace(self, line):
  36.         # 假设每行可以有多个{
  37.         _brace_count = 0
  38.         groups = pattern_left_brace.findall(line)
  39.         if groups:
  40.             _brace_count -= len(groups)
  41.         # 假设每行可以有多个}
  42.         groups = pattern_right_brace.findall(line)
  43.         if groups:
  44.             _brace_count += len(groups)
  45.         return _brace_count
  46.    
  47.     # 处理xx.save(yy)
  48.     def _handle_save(self, line, save_count):
  49.         _save_count_in_1_function = save_count
  50.         # 假设每行可以有多个.save()
  51.         new_save_count = 0
  52.         groups = pattern_save.findall(line)
  53.         if groups:
  54.             # 检测是否为if()
  55.             new_save_count = len(groups)
  56.             if pattern_if.search(line):
  57.                 # 搜索.save()
  58.                 groups = pattern_save_without_arg.findall(line)
  59.                 new_save_count -= len(groups)
  60.             
  61.             _save_count_in_1_function += new_save_count
  62.             # 如果有多个save,则打印出来
  63.             if new_save_count > 0 and _save_count_in_1_function > 1:
  64.                 self.print_line()
  65.             return 1
  66.         return 0
  67.         
  68.     def parse_func_def(self):
  69.         _brace_count = -1
  70.         _save_count_in_1_function = 0
  71.         for line in self.line_reader:
  72.             # function
  73.             if pattern_func_def.search(line):
  74.                 self.parse_func_def()
  75.             
  76.             # switch
  77.             if pattern_switch.search(line):
  78.                _save_count_in_1_function = self.parse_switch_def(_save_count_in_1_function)
  79.             
  80.             # {}
  81.             _brace_count += self._handle_brace(line)
  82.             
  83.             # xx.save(yy)
  84.             _save_count_in_1_function += self._handle_save(line, _save_count_in_1_function)
  85.             
  86.             # 定义结束
  87.             if _brace_count >= 0:
  88.                 return
  89.     def parse_switch_def(self, save_count):
  90.         _brace_count = -1
  91.         _save_count_in_1_function = save_count
  92.         _max_save_count = save_count
  93.         _all_save_count = save_count
  94.         for line in self.line_reader:
  95.             # switch
  96.             if pattern_switch.search(line):
  97.                 _all_save_count = self.parse_switch_def(_save_count_in_1_function)
  98.             
  99.             if pattern_case.search(line):
  100.                 _get_brace_count, _all_save_count = self.parse_case_def(_save_count_in_1_function)
  101.                 _brace_count += _get_brace_count
  102.             
  103.             if _max_save_count < _all_save_count:
  104.                _max_save_count = _all_save_count
  105.             
  106.             # {}
  107.             _brace_count += self._handle_brace(line)
  108.             
  109.             # 定义结束
  110.             if _brace_count >= 0:
  111.                 break
  112.         return _max_save_count
  113.    
  114.     def parse_case_def(self, save_count):
  115.         _brace_count = 0
  116.         _save_count_in_1_function = save_count
  117.         for line in self.line_reader:
  118.             
  119.             # xx.save(yy)
  120.             _save_count_in_1_function += self._handle_save(line, _save_count_in_1_function)
  121.             
  122.             # break
  123.             if pattern_break.search(line):
  124.                 break
  125.             # {}
  126.             _brace_count = self._handle_brace(line)
  127.             if _brace_count == -1:
  128.                 break
  129.         return (_brace_count, _save_count_in_1_function)
  130.     def parse(self, file_list):
  131.         for self.current_file_name in file_list:
  132.             self.line_reader = self._get_line()
  133.             self.current_line_index = 0
  134.             for line in self.line_reader:
  135.                 if pattern_func_def.search(line):
  136.                     self.parse_func_def()
  137. def help():
  138.     print """用法:
  139.     sys.argv[0] dir1 [dir2] [dir3] ..."""
  140.         
  141. if __name__ == "__main__":
  142.     if len(sys.argv) <= 1:
  143.         help()
  144.         exit(1)
  145.     else:
  146.         for dir in sys.argv[1:]:
  147.             file_list = os.popen('find '+ dir + ' -type f -name *Controller.groovy').read().rstrip('\n').split('\n')
  148.             if file_list != ['']:
  149.                 gp = GroovyParser()
  150.                 gp.parse(file_list)
复制代码
测试样本:
  1. def fuction4 = {
  2.     dosomething
  3.     something.save(abc1).save(dxy)
  4.     something.save(def2)
  5.     if (xx.save() && yy.save())
  6.     {
  7.         xxa.save()
  8.     }
  9.    
  10.     if(xx.save() && yy.save())
  11.     {
  12.         xxa.save()
  13.     }
  14.    
  15.     if(xx.save(xx) && yy.save())
  16.     {
  17.         xxa.save()
  18.     }
  19.    
  20.     if(xx.save(xx) && yy.save(yy))
  21.     {
  22.         xxa.save()
  23.     }
  24. }

  25.     def giveUpBentAxle(){
  26.         withPersonalProject{projectInstance->
  27.             try {
  28.                 def bentAxleList=projectInstance.bentAxle
  29.                 projectInstance.bentAxle=null
  30.                 bentAxleList.each {BentAxle bentAxle->
  31.                     bentAxle.delete()
  32.                 }   
  33.                 projectInstance.bentAxleStep=0
  34.                 !projectInstance.save(flush: true)?renderMsg('放弃曲轴校验,请联系管理员!'):renderSuccess()
  35.             }catch (VulcanCustomeException e) {
  36.                 renderMsg('放弃设计失败,请联系管理员!')
  37.             }   
  38.         }   
  39.     }

  40.     def giveUpConnectingRod(){
  41.         withPersonalProject{projectInstance->
  42.             try {
  43.                 ConnectingRod rod=projectInstance.connectingRod
  44.                 if (rod) {
  45.                     projectInstance.connectingRod=null
  46.                     rod.delete()
  47.                 }
  48.                 projectInstance.rodStep=0
  49.                 !projectInstance.save(flush: true)?renderMsg('放弃连杆校验,请联系管理员!'):renderSuccess()
  50.             }catch (VulcanCustomeException e) {
  51.                 renderMsg('放弃连杆失败,请联系管理员!')
  52.             }
  53.         }
  54.     }
复制代码
筛选结果如下:
  1. ./to_parse_2Controller.groovy:0003:    something.save(abc1).save(dxy)
  2. ./to_parse_2Controller.groovy:0004:    something.save(def2)
  3. ./to_parse_2Controller.groovy:0007:        xxa.save()
  4. ./to_parse_2Controller.groovy:0012:        xxa.save()
  5. ./to_parse_2Controller.groovy:0015:    if(xx.save(xx) && yy.save())
  6. ./to_parse_2Controller.groovy:0017:        xxa.save()
  7. ./to_parse_2Controller.groovy:0020:    if(xx.save(xx) && yy.save(yy))
  8. ./to_parse_2Controller.groovy:0022:        xxa.save()
  9. ./to_parse_2Controller.groovy:0035:                !projectInstance.save(flush: true)?renderMsg('放弃曲轴校验,请联系管理员!'):renderSuccess()
  10. ./to_parse_2Controller.groovy:0051:                !projectInstance.save(flush: true)?renderMsg('放弃连杆校验,请联系管理员!'):renderSuccess()
复制代码
最后两行的确是给筛选出来了

论坛徽章:
0
22 [报告]
发表于 2013-05-27 18:48 |只看该作者
本帖最后由 GhostFromHeaven 于 2013-05-27 18:51 编辑

回复 21# abcfy2

1、
pattern_save = re.compile('''\.save\s*\(.*?\)|\.delete\s*\(.*?\)''')  #同时筛选save方法和delete方法

这句有问题,这样的话save和delete的数量就加在一起了。

前面有:rod.delete(),这个计算变为1了,后面的save自然就变为2,就会筛选出来。所以不能加delete。

2、
要想处理用同样的办法处理delete可以再增加处理函数。
   

论坛徽章:
0
23 [报告]
发表于 2013-05-27 20:37 |只看该作者
回复 22# GhostFromHeaven


    明白了,多谢指导,我自己加一个方法吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP