import os
import sys
import json
import time




'''

2024.8.26
  kunlun项目生成vscode配置
  在Mainline文件夹中运行

'''

# 定义配置文件路径
_vscode_cfg_path=os.path.normpath(os.path.abspath('.')+'/../../../.vscode/c_cpp_properties.json')

# 定义编译日志路径
_build_log_path='build_log.log'

# 定义编译器关键字
_complier_list = [
  "riscv64-unknown-elf-gcc",
  "gcc",
  "g++"
]

# 读取编译日志，提取需要的编译项
def read_build_log():
  current_path=''
  def_list=[]
  inc_list=[]
  with open(_build_log_path,encoding='utf-8') as f:
    lines=f.readlines()
  for line in lines:
    if(line.find("进入目录")>0):
      start_str="“"
      end_str="”"
      start=line.find(start_str)
      end=line.find(end_str)
      current_path=line[start+len(start_str):end]
    else:
      sp_list=line.split()
      if(len(sp_list)==0):
        continue
      if(sp_list[0] in _complier_list):
        for item in sp_list:
          if(item.startswith('-D')):
            define=item[2:]
            if(define not in def_list):
              def_list.append(define)
          elif(item.startswith('-I')):
            path=item[2:]
            if(path[0]!='/'):
              path=os.path.join(current_path,path)
            path=os.path.normpath(path)
            # if(os.path.exists(path)) and (path not in inc_list):
            if(path not in inc_list):
              inc_list.append(path)
  return def_list,inc_list


def setting(defs:list,incs:list):
  with open(_vscode_cfg_path) as f:
    cfgs=json.loads(f.read())
  predef_info=cfgs["configurations"][0]
  predef_info["includePath"]=incs
  predef_info["defines"]=defs
  with open(_vscode_cfg_path,mode='w+', encoding='utf-8') as f:
    f.write(json.dumps(cfgs,sort_keys=True, indent=2, separators=(',', ': ')))


if __name__ == "__main__":
  defs,incs=read_build_log()
  setting(defs,incs)


