utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import sys
  16. import json
  17. import platform
  18. import subprocess
  19. import contextlib
  20. from parsley import makeGrammar
  21. PLATFORM = platform.system()
  22. def _check_call(*args, **kwargs):
  23. return subprocess.check_call(*args, **kwargs)
  24. def _check_output(*args, **kwargs):
  25. return subprocess.check_output(*args, **kwargs)
  26. def check_installation_using_pip(pkg):
  27. """check_installation_using_pip"""
  28. out = _check_output(["pip", "list", "--format", "json"])
  29. out = out.rstrip()
  30. lst = json.loads(out)
  31. return any(ele["name"] == pkg for ele in lst)
  32. def uninstall_package_using_pip(pkg):
  33. """uninstall_package_using_pip"""
  34. return _check_call([sys.executable, "-m", "pip", "uninstall", "-y", pkg])
  35. def install_packages_using_pip(
  36. pkgs, editable=False, req_files=None, cons_files=None, no_deps=False, pip_flags=None
  37. ):
  38. """install_packages_using_pip"""
  39. args = [sys.executable, "-m", "pip", "install"]
  40. if editable:
  41. args.append("-e")
  42. if req_files is not None:
  43. for req_file in req_files:
  44. args.append("-r")
  45. args.append(req_file)
  46. if cons_files is not None:
  47. for cons_file in cons_files:
  48. args.append("-c")
  49. args.append(cons_file)
  50. if isinstance(pkgs, str):
  51. pkgs = [pkgs]
  52. args.extend(pkgs)
  53. if pip_flags is not None:
  54. args.extend(pip_flags)
  55. return _check_call(args)
  56. def install_deps_using_pip():
  57. """install requirements"""
  58. current_file_path = os.path.dirname(os.path.abspath(__file__))
  59. deps_path = os.path.join(current_file_path, "requirements.txt")
  60. args = [sys.executable, "-m", "pip", "install", "-r", deps_path]
  61. return _check_call(args)
  62. def clone_repo_using_git(url, branch=None):
  63. """clone_repo_using_git"""
  64. args = ["git", "clone", "--depth", "1"]
  65. if isinstance(url, str):
  66. url = [url]
  67. args.extend(url)
  68. if branch is not None:
  69. args.extend(["-b", branch])
  70. return _check_call(args)
  71. def fetch_repo_using_git(branch, url, depth=1):
  72. """fetch_repo_using_git"""
  73. args = ["git", "fetch", url, branch, "--depth", str(depth)]
  74. _check_call(args)
  75. def reset_repo_using_git(pointer, hard=True):
  76. """reset_repo_using_git"""
  77. args = ["git", "reset", "--hard", pointer]
  78. return _check_call(args)
  79. def remove_repo_using_rm(name):
  80. """remove_repo_using_rm"""
  81. if os.path.exists(name):
  82. if PLATFORM == "Windows":
  83. return _check_call(["rmdir", "/S", "/Q", name], shell=True)
  84. else:
  85. return _check_call(["rm", "-rf", name])
  86. def build_wheel_using_pip(pkg, dst_dir="./", with_deps=False, pip_flags=None):
  87. """build_wheel_using_pip"""
  88. args = [sys.executable, "-m", "pip", "wheel", "--wheel-dir", dst_dir]
  89. if not with_deps:
  90. args.append("--no-deps")
  91. if pip_flags is not None:
  92. args.extend(pip_flags)
  93. args.append(pkg)
  94. return _check_call(args)
  95. @contextlib.contextmanager
  96. def mute():
  97. """mute"""
  98. with open(os.devnull, "w") as f:
  99. with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
  100. yield
  101. @contextlib.contextmanager
  102. def switch_working_dir(new_wd):
  103. """switch_working_dir"""
  104. cwd = os.getcwd()
  105. os.chdir(new_wd)
  106. try:
  107. yield
  108. finally:
  109. os.chdir(cwd)
  110. def _build_dep_spec_pep508_grammar():
  111. # Refer to https://peps.python.org/pep-0508/
  112. grammar = """
  113. wsp = ' ' | '\t'
  114. version_cmp = wsp* <'<=' | '<' | '!=' | '==' | '>=' | '>' | '~=' | '==='>
  115. version = wsp* <(letterOrDigit | '-' | '_' | '.' | '*' | '+' | '!')+>
  116. version_one = version_cmp:op version:v wsp* -> (op, v)
  117. version_many = version_one:v1 (wsp* ',' version_one)*:v2 -> [v1] + v2
  118. versionspec = ('(' version_many:v ')' ->v) | version_many
  119. urlspec = '@' wsp* <uri_reference>
  120. marker_op = version_cmp | (wsp* 'in') | (wsp* 'not' wsp+ 'in')
  121. python_str_c = (wsp | letter | digit | '(' | ')' | '.' | '{' | '}' |
  122. '-' | '_' | '*' | '#' | ':' | ';' | ',' | '/' | '?' |
  123. '[' | ']' | '!' | '~' | '`' | '@' | '$' | '%' | '^' |
  124. '&' | '=' | '+' | '|' | '<' | '>' )
  125. dquote = '"'
  126. squote = '\\''
  127. comment = '#' <anything*>:s end -> s
  128. python_str = (squote <(python_str_c | dquote)*>:s squote |
  129. dquote <(python_str_c | squote)*>:s dquote) -> s
  130. env_var = ('python_version' | 'python_full_version' |
  131. 'os_name' | 'sys_platform' | 'platform_release' |
  132. 'platform_system' | 'platform_version' |
  133. 'platform_machine' | 'platform_python_implementation' |
  134. 'implementation_name' | 'implementation_version' |
  135. 'extra' # ONLY when defined by a containing layer
  136. )
  137. marker_var = wsp* (env_var | python_str)
  138. marker_expr = marker_var:l marker_op:o marker_var:r -> (o, l, r)
  139. | wsp* '(' marker:m wsp* ')' -> m
  140. marker_and = marker_expr:l wsp* 'and' marker_expr:r -> ('and', l, r)
  141. | marker_expr:m -> m
  142. marker_or = marker_and:l wsp* 'or' marker_and:r -> ('or', l, r)
  143. | marker_and:m -> m
  144. marker = marker_or
  145. quoted_marker = ';' wsp* marker
  146. identifier_end = letterOrDigit | (('-' | '_' | '.' )* letterOrDigit)
  147. identifier = <letterOrDigit identifier_end* >
  148. name = identifier
  149. extras_list = identifier:i (wsp* ',' wsp* identifier)*:ids -> [i] + ids
  150. extras = '[' wsp* extras_list?:e wsp* ']' -> e
  151. name_req = (name:n wsp* extras?:e wsp* versionspec?:v wsp* quoted_marker?:m
  152. -> (n, e or [], v or [], m))
  153. url_req = (name:n wsp* extras?:e wsp* urlspec:v (wsp+ | end) quoted_marker?:m
  154. -> (n, e or [], v, m))
  155. specification = wsp* (url_req | name_req):s wsp* comment? -> s
  156. # The result is a tuple - name, list-of-extras,
  157. # list-of-version-constraints-or-a-url, marker-ast or None
  158. uri_reference = <uri | relative_ref>
  159. uri = scheme ':' hier_part ('?' query )? ('#' fragment)?
  160. hier_part = ('//' authority path_abempty) | path_absolute | path_rootless | path_empty
  161. absolute_uri = scheme ':' hier_part ('?' query )?
  162. relative_ref = relative_part ('?' query )? ('#' fragment )?
  163. relative_part = '//' authority path_abempty | path_absolute | path_noscheme | path_empty
  164. scheme = letter (letter | digit | '+' | '-' | '.')*
  165. authority = (userinfo '@' )? host (':' port )?
  166. userinfo = (unreserved | pct_encoded | sub_delims | ':')*
  167. host = ip_literal | ipv4_address | reg_name
  168. port = digit*
  169. ip_literal = '[' (ipv6_address | ipvfuture) ']'
  170. ipvfuture = 'v' hexdig+ '.' (unreserved | sub_delims | ':')+
  171. ipv6_address = (
  172. (h16 ':'){6} ls32
  173. | '::' (h16 ':'){5} ls32
  174. | (h16 )? '::' (h16 ':'){4} ls32
  175. | ((h16 ':')? h16 )? '::' (h16 ':'){3} ls32
  176. | ((h16 ':'){0,2} h16 )? '::' (h16 ':'){2} ls32
  177. | ((h16 ':'){0,3} h16 )? '::' h16 ':' ls32
  178. | ((h16 ':'){0,4} h16 )? '::' ls32
  179. | ((h16 ':'){0,5} h16 )? '::' h16
  180. | ((h16 ':'){0,6} h16 )? '::' )
  181. h16 = hexdig{1,4}
  182. ls32 = (h16 ':' h16) | ipv4_address
  183. ipv4_address = dec_octet '.' dec_octet '.' dec_octet '.' dec_octet
  184. nz = ~'0' digit
  185. dec_octet = (
  186. digit # 0-9
  187. | nz digit # 10-99
  188. | '1' digit{2} # 100-199
  189. | '2' ('0' | '1' | '2' | '3' | '4') digit # 200-249
  190. | '25' ('0' | '1' | '2' | '3' | '4' | '5') )# %250-255
  191. reg_name = (unreserved | pct_encoded | sub_delims)*
  192. path = (
  193. path_abempty # begins with '/' or is empty
  194. | path_absolute # begins with '/' but not '//'
  195. | path_noscheme # begins with a non-colon segment
  196. | path_rootless # begins with a segment
  197. | path_empty ) # zero characters
  198. path_abempty = ('/' segment)*
  199. path_absolute = '/' (segment_nz ('/' segment)* )?
  200. path_noscheme = segment_nz_nc ('/' segment)*
  201. path_rootless = segment_nz ('/' segment)*
  202. path_empty = pchar{0}
  203. segment = pchar*
  204. segment_nz = pchar+
  205. segment_nz_nc = (unreserved | pct_encoded | sub_delims | '@')+
  206. # non-zero-length segment without any colon ':'
  207. pchar = unreserved | pct_encoded | sub_delims | ':' | '@'
  208. query = (pchar | '/' | '?')*
  209. fragment = (pchar | '/' | '?')*
  210. pct_encoded = '%' hexdig
  211. unreserved = letter | digit | '-' | '.' | '_' | '~'
  212. reserved = gen_delims | sub_delims
  213. gen_delims = ':' | '/' | '?' | '#' | '(' | ')?' | '@'
  214. sub_delims = '!' | '$' | '&' | '\\'' | '(' | ')' | '*' | '+' | ',' | ';' | '='
  215. hexdig = digit | 'a' | 'A' | 'b' | 'B' | 'c' | 'C' | 'd' | 'D' | 'e' | 'E' | 'f' | 'F'
  216. """
  217. compiled = makeGrammar(grammar, {})
  218. return compiled
  219. _pep508_grammar = None
  220. def to_dep_spec_pep508(s):
  221. """to_dep_spec_pep508"""
  222. global _pep508_grammar
  223. if _pep508_grammar is None:
  224. _pep508_grammar = _build_dep_spec_pep508_grammar()
  225. parsed = _pep508_grammar(s)
  226. return parsed.specification()
  227. def env_marker_ast2expr(marker_ast):
  228. """env_marker_ast2expr"""
  229. MARKER_VARS = (
  230. "python_version",
  231. "python_full_version",
  232. "os_name",
  233. "sys_platform",
  234. "platform_release",
  235. "platform_system",
  236. "platform_version",
  237. "platform_machine",
  238. "platform_python_implementation",
  239. "implementation_name",
  240. "implementation_version",
  241. "extra", # ONLY when defined by a containing layer
  242. )
  243. o, l, r = marker_ast
  244. if isinstance(l, tuple):
  245. l = env_marker_ast2expr(l)
  246. else:
  247. assert isinstance(l, str)
  248. if l not in MARKER_VARS:
  249. l = repr(l)
  250. if isinstance(r, tuple):
  251. r = env_marker_ast2expr(r)
  252. else:
  253. assert isinstance(r, str)
  254. if r not in MARKER_VARS:
  255. r = repr(r)
  256. return f"{l} {o} {r}"