utils.py 11 KB

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