2
0

cs.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/python
  2. #
  3. # Copyright (c) 2013-2021 Winlin
  4. #
  5. # SPDX-License-Identifier: MIT
  6. #
  7. #################################################################################
  8. # to stat the code and comments lines
  9. #################################################################################
  10. import sys
  11. def trace(msg):
  12. print msg
  13. pass
  14. def info(msg):
  15. print msg
  16. pass
  17. def verbose(msg):
  18. #print msg
  19. pass
  20. def process(f, code_file):
  21. info("process file success")
  22. (stat_code, stat_block_comments, stat_line_comments) = (0, 0, 0)
  23. is_block_comments = False
  24. is_line_comments = False
  25. for line in f.readlines():
  26. line = line.strip()
  27. if is_block_comments:
  28. if "*/" in line:
  29. verbose("[block][end] %s"%line)
  30. is_block_comments = False
  31. is_line_comments = False
  32. else:
  33. verbose("[block][cont] %s"%line)
  34. stat_block_comments += 1
  35. continue
  36. if line.startswith("/*"):
  37. verbose("[block][start] %s"%line)
  38. is_block_comments = True
  39. is_line_comments = False
  40. stat_block_comments += 1
  41. # inline block comments
  42. if is_block_comments:
  43. if "*/" in line:
  44. verbose("[block][end] %s"%line)
  45. is_block_comments = False
  46. is_line_comments = False
  47. continue
  48. if line.startswith("//"):
  49. verbose("[line] %s"%line)
  50. is_block_comments = False
  51. is_line_comments = True
  52. stat_line_comments += 1
  53. continue
  54. verbose("[code] %s"%line)
  55. is_block_comments = False
  56. is_line_comments = False
  57. stat_code += 1
  58. total = stat_code + stat_block_comments + stat_line_comments
  59. comments = stat_block_comments + stat_line_comments
  60. trace("total:%s code:%s comments:%s block:%s line:%s file:%s"%(total, stat_code, comments, stat_block_comments, stat_line_comments, code_file))
  61. return (0, total, stat_code, comments, stat_block_comments, stat_line_comments, code_file)
  62. def do_stat(code_file):
  63. f = None
  64. try:
  65. f = open(code_file, "r")
  66. info("open file success");
  67. return process(f, code_file)
  68. finally:
  69. if f is not None:
  70. f.close()
  71. info("close file success")
  72. return (-1, 0, 0, 0, 0, 0, None)
  73. code_file = None
  74. if __name__ == "__main__":
  75. if len(sys.argv) <= 1:
  76. print "to stat the code and comments lines"
  77. print "Usage: python %s <code_file>"%(sys.argv[0])
  78. print " code_file: the code(header or source) file to stat"
  79. print "Example:"
  80. print " python %s src/core/srs_core.hpp"%(sys.argv[0])
  81. sys.exit(-1)
  82. code_file = sys.argv[1]
  83. info("stat %s"%(code_file))
  84. do_stat(code_file)