utils.py 11 KB

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