-
Notifications
You must be signed in to change notification settings - Fork 0
/
export_requirements.py
71 lines (56 loc) · 2.27 KB
/
export_requirements.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import os
from datetime import datetime
import subprocess
import re
def export_requirements(fpath="/Users/macjianfeng/Dropbox/github/python/py2ls/", exclude=["py2ls","jaraco"]):
"""
Main function to generate a timestamped requirements file and convert it to Poetry dependencies.
"""
if not fpath.endswith('/'):
fpath+='/'
with open(os.path.join(fpath,'pyproject.toml'),'r') as f:
txt=f.read()
txt_list = re.split('\n',txt)
idx_start=[i for i,item in enumerate(txt_list) if item.startswith('[tool.poetry.dependencies]')][0]+2
idx_stop=[i for i,item in enumerate(txt_list) if item.startswith('[build-system]')][0]
# keep the head info
txt_list_head=txt_list[:idx_start]
txt_list_tail=txt_list[idx_stop:]
# keep the tail info
txt_list_head=[i+"\n" for i in txt_list_head]
txt_list_tail=[i+"\n" for i in txt_list_tail]
# filename
current_time = datetime.now().strftime("%Y-%m-%d")
fpath_requirements = f"{fpath}requirements_{current_time}.txt"
os.makedirs(os.path.dirname(fpath_requirements), exist_ok=True)
# get the updated requirements.txt
try:
with open(fpath_requirements, 'w') as requirements_file:
subprocess.run(['pip', 'freeze'], stdout=requirements_file, check=True)
print(f"Requirements have been saved to {fpath_requirements}")
except subprocess.CalledProcessError as e:
print(f"An error occurred while creating the requirements file: {e}")
# open the orgi toml file
try:
with open(fpath_requirements, 'r') as file:
txt = file.read()
except Exception as e:
print(f"An error occurred while reading the requirements file: {e}")
# convert to poetry
txt_corr=[]
for txt_ in re.split('\n', txt):
if len(txt_) <=40 and not txt_=='':
txt_corr.append(txt_.replace("==",' = ">=')+'"\n')
# add a newline
txt_corr.append('\n')
# merge
txt_corr_=[*txt_list_head, *txt_corr, *txt_list_tail]
# rm .txt
# os.remove(fpath_requirements)
# fsave
with open(f"{fpath}pyproject_{current_time}.toml", 'w') as f:
f.writelines(txt_corr_)
def main():
export_requirements(fpath="/Users/macjianfeng/Dropbox/github/python/py2ls/")
if __name__ == "__main__":
main()