You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1480 lines
51 KiB

  1. """Miscellaneous utility functions."""
  2. import os
  3. import re
  4. import csv
  5. import imp
  6. import sys
  7. import errno
  8. import codecs
  9. import shutil
  10. import string
  11. import hashlib
  12. import posixpath
  13. import subprocess
  14. import sysconfig
  15. from glob import iglob as std_iglob
  16. from fnmatch import fnmatchcase
  17. from inspect import getsource
  18. from configparser import RawConfigParser
  19. from packaging import logger
  20. from packaging.errors import (PackagingPlatformError, PackagingFileError,
  21. PackagingExecError, InstallationException,
  22. PackagingInternalError)
  23. __all__ = [
  24. # file dependencies
  25. 'newer', 'newer_group',
  26. # helpers for commands (dry-run system)
  27. 'execute', 'write_file',
  28. # spawning programs
  29. 'find_executable', 'spawn',
  30. # path manipulation
  31. 'convert_path', 'change_root',
  32. # 2to3 conversion
  33. 'Mixin2to3', 'run_2to3',
  34. # packaging compatibility helpers
  35. 'cfg_to_args', 'generate_setup_py',
  36. 'egginfo_to_distinfo',
  37. 'get_install_method',
  38. # misc
  39. 'ask', 'check_environ', 'encode_multipart', 'resolve_name',
  40. # querying for information TODO move to sysconfig
  41. 'get_compiler_versions', 'get_platform', 'set_platform',
  42. # configuration TODO move to packaging.config
  43. 'get_pypirc_path', 'read_pypirc', 'generate_pypirc',
  44. 'strtobool', 'split_multiline',
  45. ]
  46. _PLATFORM = None
  47. _DEFAULT_INSTALLER = 'packaging'
  48. def newer(source, target):
  49. """Tell if the target is newer than the source.
  50. Returns true if 'source' exists and is more recently modified than
  51. 'target', or if 'source' exists and 'target' doesn't.
  52. Returns false if both exist and 'target' is the same age or younger
  53. than 'source'. Raise PackagingFileError if 'source' does not exist.
  54. Note that this test is not very accurate: files created in the same second
  55. will have the same "age".
  56. """
  57. if not os.path.exists(source):
  58. raise PackagingFileError("file '%s' does not exist" %
  59. os.path.abspath(source))
  60. if not os.path.exists(target):
  61. return True
  62. return os.stat(source).st_mtime > os.stat(target).st_mtime
  63. def get_platform():
  64. """Return a string that identifies the current platform.
  65. By default, will return the value returned by sysconfig.get_platform(),
  66. but it can be changed by calling set_platform().
  67. """
  68. global _PLATFORM
  69. if _PLATFORM is None:
  70. _PLATFORM = sysconfig.get_platform()
  71. return _PLATFORM
  72. def set_platform(identifier):
  73. """Set the platform string identifier returned by get_platform().
  74. Note that this change doesn't impact the value returned by
  75. sysconfig.get_platform(); it is local to packaging.
  76. """
  77. global _PLATFORM
  78. _PLATFORM = identifier
  79. def convert_path(pathname):
  80. """Return 'pathname' as a name that will work on the native filesystem.
  81. The path is split on '/' and put back together again using the current
  82. directory separator. Needed because filenames in the setup script are
  83. always supplied in Unix style, and have to be converted to the local
  84. convention before we can actually use them in the filesystem. Raises
  85. ValueError on non-Unix-ish systems if 'pathname' either starts or
  86. ends with a slash.
  87. """
  88. if os.sep == '/':
  89. return pathname
  90. if not pathname:
  91. return pathname
  92. if pathname[0] == '/':
  93. raise ValueError("path '%s' cannot be absolute" % pathname)
  94. if pathname[-1] == '/':
  95. raise ValueError("path '%s' cannot end with '/'" % pathname)
  96. paths = pathname.split('/')
  97. while os.curdir in paths:
  98. paths.remove(os.curdir)
  99. if not paths:
  100. return os.curdir
  101. return os.path.join(*paths)
  102. def change_root(new_root, pathname):
  103. """Return 'pathname' with 'new_root' prepended.
  104. If 'pathname' is relative, this is equivalent to
  105. os.path.join(new_root,pathname). Otherwise, it requires making 'pathname'
  106. relative and then joining the two, which is tricky on DOS/Windows.
  107. """
  108. if os.name == 'posix':
  109. if not os.path.isabs(pathname):
  110. return os.path.join(new_root, pathname)
  111. else:
  112. return os.path.join(new_root, pathname[1:])
  113. elif os.name == 'nt':
  114. drive, path = os.path.splitdrive(pathname)
  115. if path[0] == '\\':
  116. path = path[1:]
  117. return os.path.join(new_root, path)
  118. elif os.name == 'os2':
  119. drive, path = os.path.splitdrive(pathname)
  120. if path[0] == os.sep:
  121. path = path[1:]
  122. return os.path.join(new_root, path)
  123. else:
  124. raise PackagingPlatformError("nothing known about "
  125. "platform '%s'" % os.name)
  126. _environ_checked = False
  127. def check_environ():
  128. """Ensure that 'os.environ' has all the environment variables needed.
  129. We guarantee that users can use in config files, command-line options,
  130. etc. Currently this includes:
  131. HOME - user's home directory (Unix only)
  132. PLAT - description of the current platform, including hardware
  133. and OS (see 'get_platform()')
  134. """
  135. global _environ_checked
  136. if _environ_checked:
  137. return
  138. if os.name == 'posix' and 'HOME' not in os.environ:
  139. import pwd
  140. os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  141. if 'PLAT' not in os.environ:
  142. os.environ['PLAT'] = sysconfig.get_platform()
  143. _environ_checked = True
  144. # Needed by 'split_quoted()'
  145. _wordchars_re = _squote_re = _dquote_re = None
  146. def _init_regex():
  147. global _wordchars_re, _squote_re, _dquote_re
  148. _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
  149. _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
  150. _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
  151. # TODO replace with shlex.split after testing
  152. def split_quoted(s):
  153. """Split a string up according to Unix shell-like rules for quotes and
  154. backslashes.
  155. In short: words are delimited by spaces, as long as those
  156. spaces are not escaped by a backslash, or inside a quoted string.
  157. Single and double quotes are equivalent, and the quote characters can
  158. be backslash-escaped. The backslash is stripped from any two-character
  159. escape sequence, leaving only the escaped character. The quote
  160. characters are stripped from any quoted string. Returns a list of
  161. words.
  162. """
  163. # This is a nice algorithm for splitting up a single string, since it
  164. # doesn't require character-by-character examination. It was a little
  165. # bit of a brain-bender to get it working right, though...
  166. if _wordchars_re is None:
  167. _init_regex()
  168. s = s.strip()
  169. words = []
  170. pos = 0
  171. while s:
  172. m = _wordchars_re.match(s, pos)
  173. end = m.end()
  174. if end == len(s):
  175. words.append(s[:end])
  176. break
  177. if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
  178. words.append(s[:end]) # we definitely have a word delimiter
  179. s = s[end:].lstrip()
  180. pos = 0
  181. elif s[end] == '\\': # preserve whatever is being escaped;
  182. # will become part of the current word
  183. s = s[:end] + s[end + 1:]
  184. pos = end + 1
  185. else:
  186. if s[end] == "'": # slurp singly-quoted string
  187. m = _squote_re.match(s, end)
  188. elif s[end] == '"': # slurp doubly-quoted string
  189. m = _dquote_re.match(s, end)
  190. else:
  191. raise RuntimeError("this can't happen "
  192. "(bad char '%c')" % s[end])
  193. if m is None:
  194. raise ValueError("bad string (mismatched %s quotes?)" % s[end])
  195. beg, end = m.span()
  196. s = s[:beg] + s[beg + 1:end - 1] + s[end:]
  197. pos = m.end() - 2
  198. if pos >= len(s):
  199. words.append(s)
  200. break
  201. return words
  202. def split_multiline(value):
  203. """Split a multiline string into a list, excluding blank lines."""
  204. return [element for element in
  205. (line.strip() for line in value.split('\n'))
  206. if element]
  207. def execute(func, args, msg=None, dry_run=False):
  208. """Perform some action that affects the outside world.
  209. Some actions (e.g. writing to the filesystem) are special because
  210. they are disabled by the 'dry_run' flag. This method takes care of all
  211. that bureaucracy for you; all you have to do is supply the
  212. function to call and an argument tuple for it (to embody the
  213. "external action" being performed), and an optional message to
  214. print.
  215. """
  216. if msg is None:
  217. msg = "%s%r" % (func.__name__, args)
  218. if msg[-2:] == ',)': # correct for singleton tuple
  219. msg = msg[0:-2] + ')'
  220. logger.info(msg)
  221. if not dry_run:
  222. func(*args)
  223. def strtobool(val):
  224. """Convert a string representation of truth to a boolean.
  225. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  226. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  227. 'val' is anything else.
  228. """
  229. val = val.lower()
  230. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  231. return True
  232. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  233. return False
  234. else:
  235. raise ValueError("invalid truth value %r" % (val,))
  236. def byte_compile(py_files, optimize=0, force=False, prefix=None,
  237. base_dir=None, dry_run=False, direct=None):
  238. """Byte-compile a collection of Python source files to either .pyc
  239. or .pyo files in a __pycache__ subdirectory.
  240. 'py_files' is a list of files to compile; any files that don't end in
  241. ".py" are silently skipped. 'optimize' must be one of the following:
  242. 0 - don't optimize (generate .pyc)
  243. 1 - normal optimization (like "python -O")
  244. 2 - extra optimization (like "python -OO")
  245. This function is independent from the running Python's -O or -B options;
  246. it is fully controlled by the parameters passed in.
  247. If 'force' is true, all files are recompiled regardless of
  248. timestamps.
  249. The source filename encoded in each bytecode file defaults to the
  250. filenames listed in 'py_files'; you can modify these with 'prefix' and
  251. 'basedir'. 'prefix' is a string that will be stripped off of each
  252. source filename, and 'base_dir' is a directory name that will be
  253. prepended (after 'prefix' is stripped). You can supply either or both
  254. (or neither) of 'prefix' and 'base_dir', as you wish.
  255. If 'dry_run' is true, doesn't actually do anything that would
  256. affect the filesystem.
  257. Byte-compilation is either done directly in this interpreter process
  258. with the standard py_compile module, or indirectly by writing a
  259. temporary script and executing it. Normally, you should let
  260. 'byte_compile()' figure out to use direct compilation or not (see
  261. the source for details). The 'direct' flag is used by the script
  262. generated in indirect mode; unless you know what you're doing, leave
  263. it set to None.
  264. """
  265. # FIXME use compileall + remove direct/indirect shenanigans
  266. # First, if the caller didn't force us into direct or indirect mode,
  267. # figure out which mode we should be in. We take a conservative
  268. # approach: choose direct mode *only* if the current interpreter is
  269. # in debug mode and optimize is 0. If we're not in debug mode (-O
  270. # or -OO), we don't know which level of optimization this
  271. # interpreter is running with, so we can't do direct
  272. # byte-compilation and be certain that it's the right thing. Thus,
  273. # always compile indirectly if the current interpreter is in either
  274. # optimize mode, or if either optimization level was requested by
  275. # the caller.
  276. if direct is None:
  277. direct = (__debug__ and optimize == 0)
  278. # "Indirect" byte-compilation: write a temporary script and then
  279. # run it with the appropriate flags.
  280. if not direct:
  281. from tempfile import mkstemp
  282. # XXX use something better than mkstemp
  283. script_fd, script_name = mkstemp(".py")
  284. os.close(script_fd)
  285. script_fd = None
  286. logger.info("writing byte-compilation script '%s'", script_name)
  287. if not dry_run:
  288. if script_fd is not None:
  289. script = os.fdopen(script_fd, "w", encoding='utf-8')
  290. else:
  291. script = open(script_name, "w", encoding='utf-8')
  292. with script:
  293. script.write("""\
  294. from packaging.util import byte_compile
  295. files = [
  296. """)
  297. # XXX would be nice to write absolute filenames, just for
  298. # safety's sake (script should be more robust in the face of
  299. # chdir'ing before running it). But this requires abspath'ing
  300. # 'prefix' as well, and that breaks the hack in build_lib's
  301. # 'byte_compile()' method that carefully tacks on a trailing
  302. # slash (os.sep really) to make sure the prefix here is "just
  303. # right". This whole prefix business is rather delicate -- the
  304. # problem is that it's really a directory, but I'm treating it
  305. # as a dumb string, so trailing slashes and so forth matter.
  306. #py_files = map(os.path.abspath, py_files)
  307. #if prefix:
  308. # prefix = os.path.abspath(prefix)
  309. script.write(",\n".join(map(repr, py_files)) + "]\n")
  310. script.write("""
  311. byte_compile(files, optimize=%r, force=%r,
  312. prefix=%r, base_dir=%r,
  313. dry_run=False,
  314. direct=True)
  315. """ % (optimize, force, prefix, base_dir))
  316. cmd = [sys.executable, script_name]
  317. env = os.environ.copy()
  318. env['PYTHONPATH'] = os.path.pathsep.join(sys.path)
  319. try:
  320. spawn(cmd, env=env)
  321. finally:
  322. execute(os.remove, (script_name,), "removing %s" % script_name,
  323. dry_run=dry_run)
  324. # "Direct" byte-compilation: use the py_compile module to compile
  325. # right here, right now. Note that the script generated in indirect
  326. # mode simply calls 'byte_compile()' in direct mode, a weird sort of
  327. # cross-process recursion. Hey, it works!
  328. else:
  329. from py_compile import compile
  330. for file in py_files:
  331. if file[-3:] != ".py":
  332. # This lets us be lazy and not filter filenames in
  333. # the "install_lib" command.
  334. continue
  335. # Terminology from the py_compile module:
  336. # cfile - byte-compiled file
  337. # dfile - purported source filename (same as 'file' by default)
  338. # The second argument to cache_from_source forces the extension to
  339. # be .pyc (if true) or .pyo (if false); without it, the extension
  340. # would depend on the calling Python's -O option
  341. cfile = imp.cache_from_source(file, not optimize)
  342. dfile = file
  343. if prefix:
  344. if file[:len(prefix)] != prefix:
  345. raise ValueError("invalid prefix: filename %r doesn't "
  346. "start with %r" % (file, prefix))
  347. dfile = dfile[len(prefix):]
  348. if base_dir:
  349. dfile = os.path.join(base_dir, dfile)
  350. cfile_base = os.path.basename(cfile)
  351. if direct:
  352. if force or newer(file, cfile):
  353. logger.info("byte-compiling %s to %s", file, cfile_base)
  354. if not dry_run:
  355. compile(file, cfile, dfile)
  356. else:
  357. logger.debug("skipping byte-compilation of %s to %s",
  358. file, cfile_base)
  359. _RE_VERSION = re.compile('(\d+\.\d+(\.\d+)*)')
  360. _MAC_OS_X_LD_VERSION = re.compile('^@\(#\)PROGRAM:ld '
  361. 'PROJECT:ld64-((\d+)(\.\d+)*)')
  362. def _find_ld_version():
  363. """Find the ld version. The version scheme differs under Mac OS X."""
  364. if sys.platform == 'darwin':
  365. return _find_exe_version('ld -v', _MAC_OS_X_LD_VERSION)
  366. else:
  367. return _find_exe_version('ld -v')
  368. def _find_exe_version(cmd, pattern=_RE_VERSION):
  369. """Find the version of an executable by running `cmd` in the shell.
  370. `pattern` is a compiled regular expression. If not provided, defaults
  371. to _RE_VERSION. If the command is not found, or the output does not
  372. match the mattern, returns None.
  373. """
  374. from subprocess import Popen, PIPE
  375. executable = cmd.split()[0]
  376. if find_executable(executable) is None:
  377. return None
  378. pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
  379. try:
  380. stdout, stderr = pipe.communicate()
  381. finally:
  382. pipe.stdout.close()
  383. pipe.stderr.close()
  384. # some commands like ld under MacOS X, will give the
  385. # output in the stderr, rather than stdout.
  386. if stdout != '':
  387. out_string = stdout
  388. else:
  389. out_string = stderr
  390. result = pattern.search(out_string)
  391. if result is None:
  392. return None
  393. return result.group(1)
  394. def get_compiler_versions():
  395. """Return a tuple providing the versions of gcc, ld and dllwrap
  396. For each command, if a command is not found, None is returned.
  397. Otherwise a string with the version is returned.
  398. """
  399. gcc = _find_exe_version('gcc -dumpversion')
  400. ld = _find_ld_version()
  401. dllwrap = _find_exe_version('dllwrap --version')
  402. return gcc, ld, dllwrap
  403. def newer_group(sources, target, missing='error'):
  404. """Return true if 'target' is out-of-date with respect to any file
  405. listed in 'sources'.
  406. In other words, if 'target' exists and is newer
  407. than every file in 'sources', return false; otherwise return true.
  408. 'missing' controls what we do when a source file is missing; the
  409. default ("error") is to blow up with an OSError from inside 'stat()';
  410. if it is "ignore", we silently drop any missing source files; if it is
  411. "newer", any missing source files make us assume that 'target' is
  412. out-of-date (this is handy in "dry-run" mode: it'll make you pretend to
  413. carry out commands that wouldn't work because inputs are missing, but
  414. that doesn't matter because you're not actually going to run the
  415. commands).
  416. """
  417. # If the target doesn't even exist, then it's definitely out-of-date.
  418. if not os.path.exists(target):
  419. return True
  420. # Otherwise we have to find out the hard way: if *any* source file
  421. # is more recent than 'target', then 'target' is out-of-date and
  422. # we can immediately return true. If we fall through to the end
  423. # of the loop, then 'target' is up-to-date and we return false.
  424. target_mtime = os.stat(target).st_mtime
  425. for source in sources:
  426. if not os.path.exists(source):
  427. if missing == 'error': # blow up when we stat() the file
  428. pass
  429. elif missing == 'ignore': # missing source dropped from
  430. continue # target's dependency list
  431. elif missing == 'newer': # missing source means target is
  432. return True # out-of-date
  433. if os.stat(source).st_mtime > target_mtime:
  434. return True
  435. return False
  436. def write_file(filename, contents):
  437. """Create *filename* and write *contents* to it.
  438. *contents* is a sequence of strings without line terminators.
  439. This functions is not intended to replace the usual with open + write
  440. idiom in all cases, only with Command.execute, which runs depending on
  441. the dry_run argument and also logs its arguments).
  442. """
  443. with open(filename, "w") as f:
  444. for line in contents:
  445. f.write(line + "\n")
  446. def _is_package(path):
  447. return os.path.isdir(path) and os.path.isfile(
  448. os.path.join(path, '__init__.py'))
  449. # Code taken from the pip project
  450. def _is_archive_file(name):
  451. archives = ('.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar')
  452. ext = splitext(name)[1].lower()
  453. return ext in archives
  454. def _under(path, root):
  455. # XXX use os.path
  456. path = path.split(os.sep)
  457. root = root.split(os.sep)
  458. if len(root) > len(path):
  459. return False
  460. for pos, part in enumerate(root):
  461. if path[pos] != part:
  462. return False
  463. return True
  464. def _package_name(root_path, path):
  465. # Return a dotted package name, given a subpath
  466. if not _under(path, root_path):
  467. raise ValueError('"%s" is not a subpath of "%s"' % (path, root_path))
  468. return path[len(root_path) + 1:].replace(os.sep, '.')
  469. def find_packages(paths=(os.curdir,), exclude=()):
  470. """Return a list all Python packages found recursively within
  471. directories 'paths'
  472. 'paths' should be supplied as a sequence of "cross-platform"
  473. (i.e. URL-style) path; it will be converted to the appropriate local
  474. path syntax.
  475. 'exclude' is a sequence of package names to exclude; '*' can be used as
  476. a wildcard in the names, such that 'foo.*' will exclude all subpackages
  477. of 'foo' (but not 'foo' itself).
  478. """
  479. packages = []
  480. discarded = []
  481. def _discarded(path):
  482. for discard in discarded:
  483. if _under(path, discard):
  484. return True
  485. return False
  486. for path in paths:
  487. path = convert_path(path)
  488. for root, dirs, files in os.walk(path):
  489. for dir_ in dirs:
  490. fullpath = os.path.join(root, dir_)
  491. if _discarded(fullpath):
  492. continue
  493. # we work only with Python packages
  494. if not _is_package(fullpath):
  495. discarded.append(fullpath)
  496. continue
  497. # see if it's excluded
  498. excluded = False
  499. package_name = _package_name(path, fullpath)
  500. for pattern in exclude:
  501. if fnmatchcase(package_name, pattern):
  502. excluded = True
  503. break
  504. if excluded:
  505. continue
  506. # adding it to the list
  507. packages.append(package_name)
  508. return packages
  509. def resolve_name(name):
  510. """Resolve a name like ``module.object`` to an object and return it.
  511. This functions supports packages and attributes without depth limitation:
  512. ``package.package.module.class.class.function.attr`` is valid input.
  513. However, looking up builtins is not directly supported: use
  514. ``builtins.name``.
  515. Raises ImportError if importing the module fails or if one requested
  516. attribute is not found.
  517. """
  518. if '.' not in name:
  519. # shortcut
  520. __import__(name)
  521. return sys.modules[name]
  522. # FIXME clean up this code!
  523. parts = name.split('.')
  524. cursor = len(parts)
  525. module_name = parts[:cursor]
  526. ret = ''
  527. while cursor > 0:
  528. try:
  529. ret = __import__('.'.join(module_name))
  530. break
  531. except ImportError:
  532. cursor -= 1
  533. module_name = parts[:cursor]
  534. if ret == '':
  535. raise ImportError(parts[0])
  536. for part in parts[1:]:
  537. try:
  538. ret = getattr(ret, part)
  539. except AttributeError as exc:
  540. raise ImportError(exc)
  541. return ret
  542. def splitext(path):
  543. """Like os.path.splitext, but take off .tar too"""
  544. base, ext = posixpath.splitext(path)
  545. if base.lower().endswith('.tar'):
  546. ext = base[-4:] + ext
  547. base = base[:-4]
  548. return base, ext
  549. if sys.platform == 'darwin':
  550. _cfg_target = None
  551. _cfg_target_split = None
  552. def spawn(cmd, search_path=True, dry_run=False, env=None):
  553. """Run another program specified as a command list 'cmd' in a new process.
  554. 'cmd' is just the argument list for the new process, ie.
  555. cmd[0] is the program to run and cmd[1:] are the rest of its arguments.
  556. There is no way to run a program with a name different from that of its
  557. executable.
  558. If 'search_path' is true (the default), the system's executable
  559. search path will be used to find the program; otherwise, cmd[0]
  560. must be the exact path to the executable. If 'dry_run' is true,
  561. the command will not actually be run.
  562. If 'env' is given, it's a environment dictionary used for the execution
  563. environment.
  564. Raise PackagingExecError if running the program fails in any way; just
  565. return on success.
  566. """
  567. logger.debug('spawn: running %r', cmd)
  568. if dry_run:
  569. logger.debug('dry run, no process actually spawned')
  570. return
  571. if sys.platform == 'darwin':
  572. global _cfg_target, _cfg_target_split
  573. if _cfg_target is None:
  574. _cfg_target = sysconfig.get_config_var(
  575. 'MACOSX_DEPLOYMENT_TARGET') or ''
  576. if _cfg_target:
  577. _cfg_target_split = [int(x) for x in _cfg_target.split('.')]
  578. if _cfg_target:
  579. # ensure that the deployment target of build process is not less
  580. # than that used when the interpreter was built. This ensures
  581. # extension modules are built with correct compatibility values
  582. env = env or os.environ
  583. cur_target = env.get('MACOSX_DEPLOYMENT_TARGET', _cfg_target)
  584. if _cfg_target_split > [int(x) for x in cur_target.split('.')]:
  585. my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: '
  586. 'now "%s" but "%s" during configure'
  587. % (cur_target, _cfg_target))
  588. raise PackagingPlatformError(my_msg)
  589. env = dict(env, MACOSX_DEPLOYMENT_TARGET=cur_target)
  590. exit_status = subprocess.call(cmd, env=env)
  591. if exit_status != 0:
  592. msg = "command %r failed with exit status %d"
  593. raise PackagingExecError(msg % (cmd, exit_status))
  594. def find_executable(executable, path=None):
  595. """Try to find 'executable' in the directories listed in 'path'.
  596. *path* is a string listing directories separated by 'os.pathsep' and
  597. defaults to os.environ['PATH']. Returns the complete filename or None
  598. if not found.
  599. """
  600. if path is None:
  601. path = os.environ['PATH']
  602. paths = path.split(os.pathsep)
  603. base, ext = os.path.splitext(executable)
  604. if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'):
  605. executable = executable + '.exe'
  606. if not os.path.isfile(executable):
  607. for p in paths:
  608. f = os.path.join(p, executable)
  609. if os.path.isfile(f):
  610. # the file exists, we have a shot at spawn working
  611. return f
  612. return None
  613. else:
  614. return executable
  615. DEFAULT_REPOSITORY = 'http://pypi.python.org/pypi'
  616. DEFAULT_REALM = 'pypi'
  617. DEFAULT_PYPIRC = """\
  618. [distutils]
  619. index-servers =
  620. pypi
  621. [pypi]
  622. username:%s
  623. password:%s
  624. """
  625. def get_pypirc_path():
  626. """Return path to pypirc config file."""
  627. return os.path.join(os.path.expanduser('~'), '.pypirc')
  628. def generate_pypirc(username, password):
  629. """Create a default .pypirc file."""
  630. rc = get_pypirc_path()
  631. with open(rc, 'w') as f:
  632. f.write(DEFAULT_PYPIRC % (username, password))
  633. try:
  634. os.chmod(rc, 0o600)
  635. except OSError:
  636. # should do something better here
  637. pass
  638. def read_pypirc(repository=DEFAULT_REPOSITORY, realm=DEFAULT_REALM):
  639. """Read the .pypirc file."""
  640. rc = get_pypirc_path()
  641. if os.path.exists(rc):
  642. config = RawConfigParser()
  643. config.read(rc)
  644. sections = config.sections()
  645. if 'distutils' in sections:
  646. # let's get the list of servers
  647. index_servers = config.get('distutils', 'index-servers')
  648. _servers = [server.strip() for server in
  649. index_servers.split('\n')
  650. if server.strip() != '']
  651. if _servers == []:
  652. # nothing set, let's try to get the default pypi
  653. if 'pypi' in sections:
  654. _servers = ['pypi']
  655. else:
  656. # the file is not properly defined, returning
  657. # an empty dict
  658. return {}
  659. for server in _servers:
  660. current = {'server': server}
  661. current['username'] = config.get(server, 'username')
  662. # optional params
  663. for key, default in (('repository', DEFAULT_REPOSITORY),
  664. ('realm', DEFAULT_REALM),
  665. ('password', None)):
  666. if config.has_option(server, key):
  667. current[key] = config.get(server, key)
  668. else:
  669. current[key] = default
  670. if (current['server'] == repository or
  671. current['repository'] == repository):
  672. return current
  673. elif 'server-login' in sections:
  674. # old format
  675. server = 'server-login'
  676. if config.has_option(server, 'repository'):
  677. repository = config.get(server, 'repository')
  678. else:
  679. repository = DEFAULT_REPOSITORY
  680. return {'username': config.get(server, 'username'),
  681. 'password': config.get(server, 'password'),
  682. 'repository': repository,
  683. 'server': server,
  684. 'realm': DEFAULT_REALM}
  685. return {}
  686. # utility functions for 2to3 support
  687. def run_2to3(files, doctests_only=False, fixer_names=None,
  688. options=None, explicit=None):
  689. """ Wrapper function around the refactor() class which
  690. performs the conversions on a list of python files.
  691. Invoke 2to3 on a list of Python files. The files should all come
  692. from the build area, as the modification is done in-place."""
  693. #if not files:
  694. # return
  695. # Make this class local, to delay import of 2to3
  696. from lib2to3.refactor import get_fixers_from_package, RefactoringTool
  697. fixers = []
  698. fixers = get_fixers_from_package('lib2to3.fixes')
  699. if fixer_names:
  700. for fixername in fixer_names:
  701. fixers.extend(fixer for fixer in
  702. get_fixers_from_package(fixername))
  703. r = RefactoringTool(fixers, options=options)
  704. r.refactor(files, write=True, doctests_only=doctests_only)
  705. class Mixin2to3:
  706. """ Wrapper class for commands that run 2to3.
  707. To configure 2to3, setup scripts may either change
  708. the class variables, or inherit from this class
  709. to override how 2to3 is invoked.
  710. """
  711. # provide list of fixers to run.
  712. # defaults to all from lib2to3.fixers
  713. fixer_names = None
  714. # options dictionary
  715. options = None
  716. # list of fixers to invoke even though they are marked as explicit
  717. explicit = None
  718. def run_2to3(self, files, doctests_only=False):
  719. """ Issues a call to util.run_2to3. """
  720. return run_2to3(files, doctests_only, self.fixer_names,
  721. self.options, self.explicit)
  722. RICH_GLOB = re.compile(r'\{([^}]*)\}')
  723. _CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
  724. _CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
  725. def iglob(path_glob):
  726. """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
  727. if _CHECK_RECURSIVE_GLOB.search(path_glob):
  728. msg = """invalid glob %r: recursive glob "**" must be used alone"""
  729. raise ValueError(msg % path_glob)
  730. if _CHECK_MISMATCH_SET.search(path_glob):
  731. msg = """invalid glob %r: mismatching set marker '{' or '}'"""
  732. raise ValueError(msg % path_glob)
  733. return _iglob(path_glob)
  734. def _iglob(path_glob):
  735. rich_path_glob = RICH_GLOB.split(path_glob, 1)
  736. if len(rich_path_glob) > 1:
  737. assert len(rich_path_glob) == 3, rich_path_glob
  738. prefix, set, suffix = rich_path_glob
  739. for item in set.split(','):
  740. for path in _iglob(''.join((prefix, item, suffix))):
  741. yield path
  742. else:
  743. if '**' not in path_glob:
  744. for item in std_iglob(path_glob):
  745. yield item
  746. else:
  747. prefix, radical = path_glob.split('**', 1)
  748. if prefix == '':
  749. prefix = '.'
  750. if radical == '':
  751. radical = '*'
  752. else:
  753. # we support both
  754. radical = radical.lstrip('/')
  755. radical = radical.lstrip('\\')
  756. for path, dir, files in os.walk(prefix):
  757. path = os.path.normpath(path)
  758. for file in _iglob(os.path.join(path, radical)):
  759. yield file
  760. # HOWTO change cfg_to_args
  761. #
  762. # This function has two major constraints: It is copied by inspect.getsource
  763. # in generate_setup_py; it is used in generated setup.py which may be run by
  764. # any Python version supported by distutils2 (2.4-3.3).
  765. #
  766. # * Keep objects like D1_D2_SETUP_ARGS static, i.e. in the function body
  767. # instead of global.
  768. # * If you use a function from another module, update the imports in
  769. # SETUP_TEMPLATE. Use only modules, classes and functions compatible with
  770. # all versions: codecs.open instead of open, RawConfigParser.readfp instead
  771. # of read, standard exceptions instead of Packaging*Error, etc.
  772. # * If you use a function from this module, update the template and
  773. # generate_setup_py.
  774. #
  775. # test_util tests this function and the generated setup.py, but does not test
  776. # that it's compatible with all Python versions.
  777. def cfg_to_args(path='setup.cfg'):
  778. """Compatibility helper to use setup.cfg in setup.py.
  779. This functions uses an existing setup.cfg to generate a dictionnary of
  780. keywords that can be used by distutils.core.setup(**kwargs). It is used
  781. by generate_setup_py.
  782. *file* is the path to the setup.cfg file. If it doesn't exist,
  783. PackagingFileError is raised.
  784. """
  785. # XXX ** == needs testing
  786. D1_D2_SETUP_ARGS = {"name": ("metadata",),
  787. "version": ("metadata",),
  788. "author": ("metadata",),
  789. "author_email": ("metadata",),
  790. "maintainer": ("metadata",),
  791. "maintainer_email": ("metadata",),
  792. "url": ("metadata", "home_page"),
  793. "description": ("metadata", "summary"),
  794. "long_description": ("metadata", "description"),
  795. "download-url": ("metadata",),
  796. "classifiers": ("metadata", "classifier"),
  797. "platforms": ("metadata", "platform"), # **
  798. "license": ("metadata",),
  799. "requires": ("metadata", "requires_dist"),
  800. "provides": ("metadata", "provides_dist"), # **
  801. "obsoletes": ("metadata", "obsoletes_dist"), # **
  802. "package_dir": ("files", 'packages_root'),
  803. "packages": ("files",),
  804. "scripts": ("files",),
  805. "py_modules": ("files", "modules"), # **
  806. }
  807. MULTI_FIELDS = ("classifiers",
  808. "platforms",
  809. "requires",
  810. "provides",
  811. "obsoletes",
  812. "packages",
  813. "scripts",
  814. "py_modules")
  815. def has_get_option(config, section, option):
  816. if config.has_option(section, option):
  817. return config.get(section, option)
  818. elif config.has_option(section, option.replace('_', '-')):
  819. return config.get(section, option.replace('_', '-'))
  820. else:
  821. return False
  822. # The real code starts here
  823. config = RawConfigParser()
  824. f = codecs.open(path, encoding='utf-8')
  825. try:
  826. config.readfp(f)
  827. finally:
  828. f.close()
  829. kwargs = {}
  830. for arg in D1_D2_SETUP_ARGS:
  831. if len(D1_D2_SETUP_ARGS[arg]) == 2:
  832. # The distutils field name is different than packaging's
  833. section, option = D1_D2_SETUP_ARGS[arg]
  834. else:
  835. # The distutils field name is the same thant packaging's
  836. section = D1_D2_SETUP_ARGS[arg][0]
  837. option = arg
  838. in_cfg_value = has_get_option(config, section, option)
  839. if not in_cfg_value:
  840. # There is no such option in the setup.cfg
  841. if arg == 'long_description':
  842. filenames = has_get_option(config, section, 'description-file')
  843. if filenames:
  844. filenames = split_multiline(filenames)
  845. in_cfg_value = []
  846. for filename in filenames:
  847. fp = codecs.open(filename, encoding='utf-8')
  848. try:
  849. in_cfg_value.append(fp.read())
  850. finally:
  851. fp.close()
  852. in_cfg_value = '\n\n'.join(in_cfg_value)
  853. else:
  854. continue
  855. if arg == 'package_dir' and in_cfg_value:
  856. in_cfg_value = {'': in_cfg_value}
  857. if arg in MULTI_FIELDS:
  858. # support multiline options
  859. in_cfg_value = split_multiline(in_cfg_value)
  860. kwargs[arg] = in_cfg_value
  861. return kwargs
  862. SETUP_TEMPLATE = """\
  863. # This script was automatically generated by packaging
  864. import os
  865. import codecs
  866. from distutils.core import setup
  867. try:
  868. from ConfigParser import RawConfigParser
  869. except ImportError:
  870. from configparser import RawConfigParser
  871. %(split_multiline)s
  872. %(cfg_to_args)s
  873. setup(**cfg_to_args())
  874. """
  875. def generate_setup_py():
  876. """Generate a distutils compatible setup.py using an existing setup.cfg.
  877. Raises a PackagingFileError when a setup.py already exists.
  878. """
  879. if os.path.exists("setup.py"):
  880. raise PackagingFileError("a setup.py file already exists")
  881. source = SETUP_TEMPLATE % {'split_multiline': getsource(split_multiline),
  882. 'cfg_to_args': getsource(cfg_to_args)}
  883. with open("setup.py", "w", encoding='utf-8') as fp:
  884. fp.write(source)
  885. # Taken from the pip project
  886. # https://github.com/pypa/pip/blob/master/pip/util.py
  887. def ask(message, options):
  888. """Prompt the user with *message*; *options* contains allowed responses."""
  889. while True:
  890. response = input(message)
  891. response = response.strip().lower()
  892. if response not in options:
  893. print('invalid response:', repr(response))
  894. print('choose one of', ', '.join(repr(o) for o in options))
  895. else:
  896. return response
  897. def _parse_record_file(record_file):
  898. distinfo, extra_metadata, installed = ({}, [], [])
  899. with open(record_file, 'r') as rfile:
  900. for path in rfile:
  901. path = path.strip()
  902. if path.endswith('egg-info') and os.path.isfile(path):
  903. distinfo_dir = path.replace('egg-info', 'dist-info')
  904. metadata = path
  905. egginfo = path
  906. elif path.endswith('egg-info') and os.path.isdir(path):
  907. distinfo_dir = path.replace('egg-info', 'dist-info')
  908. egginfo = path
  909. for metadata_file in os.listdir(path):
  910. metadata_fpath = os.path.join(path, metadata_file)
  911. if metadata_file == 'PKG-INFO':
  912. metadata = metadata_fpath
  913. else:
  914. extra_metadata.append(metadata_fpath)
  915. elif 'egg-info' in path and os.path.isfile(path):
  916. # skip extra metadata files
  917. continue
  918. else:
  919. installed.append(path)
  920. distinfo['egginfo'] = egginfo
  921. distinfo['metadata'] = metadata
  922. distinfo['distinfo_dir'] = distinfo_dir
  923. distinfo['installer_path'] = os.path.join(distinfo_dir, 'INSTALLER')
  924. distinfo['metadata_path'] = os.path.join(distinfo_dir, 'METADATA')
  925. distinfo['record_path'] = os.path.join(distinfo_dir, 'RECORD')
  926. distinfo['requested_path'] = os.path.join(distinfo_dir, 'REQUESTED')
  927. installed.extend([distinfo['installer_path'], distinfo['metadata_path']])
  928. distinfo['installed'] = installed
  929. distinfo['extra_metadata'] = extra_metadata
  930. return distinfo
  931. def _write_record_file(record_path, installed_files):
  932. with open(record_path, 'w', encoding='utf-8') as f:
  933. writer = csv.writer(f, delimiter=',', lineterminator=os.linesep,
  934. quotechar='"')
  935. for fpath in installed_files:
  936. if fpath.endswith('.pyc') or fpath.endswith('.pyo'):
  937. # do not put size and md5 hash, as in PEP-376
  938. writer.writerow((fpath, '', ''))
  939. else:
  940. hash = hashlib.md5()
  941. with open(fpath, 'rb') as fp:
  942. hash.update(fp.read())
  943. md5sum = hash.hexdigest()
  944. size = os.path.getsize(fpath)
  945. writer.writerow((fpath, md5sum, size))
  946. # add the RECORD file itself
  947. writer.writerow((record_path, '', ''))
  948. return record_path
  949. def egginfo_to_distinfo(record_file, installer=_DEFAULT_INSTALLER,
  950. requested=False, remove_egginfo=False):
  951. """Create files and directories required for PEP 376
  952. :param record_file: path to RECORD file as produced by setup.py --record
  953. :param installer: installer name
  954. :param requested: True if not installed as a dependency
  955. :param remove_egginfo: delete egginfo dir?
  956. """
  957. distinfo = _parse_record_file(record_file)
  958. distinfo_dir = distinfo['distinfo_dir']
  959. if os.path.isdir(distinfo_dir) and not os.path.islink(distinfo_dir):
  960. shutil.rmtree(distinfo_dir)
  961. elif os.path.exists(distinfo_dir):
  962. os.unlink(distinfo_dir)
  963. os.makedirs(distinfo_dir)
  964. # copy setuptools extra metadata files
  965. if distinfo['extra_metadata']:
  966. for path in distinfo['extra_metadata']:
  967. shutil.copy2(path, distinfo_dir)
  968. new_path = path.replace('egg-info', 'dist-info')
  969. distinfo['installed'].append(new_path)
  970. metadata_path = distinfo['metadata_path']
  971. logger.info('creating %s', metadata_path)
  972. shutil.copy2(distinfo['metadata'], metadata_path)
  973. installer_path = distinfo['installer_path']
  974. logger.info('creating %s', installer_path)
  975. with open(installer_path, 'w') as f:
  976. f.write(installer)
  977. if requested:
  978. requested_path = distinfo['requested_path']
  979. logger.info('creating %s', requested_path)
  980. open(requested_path, 'wb').close()
  981. distinfo['installed'].append(requested_path)
  982. record_path = distinfo['record_path']
  983. logger.info('creating %s', record_path)
  984. _write_record_file(record_path, distinfo['installed'])
  985. if remove_egginfo:
  986. egginfo = distinfo['egginfo']
  987. logger.info('removing %s', egginfo)
  988. if os.path.isfile(egginfo):
  989. os.remove(egginfo)
  990. else:
  991. shutil.rmtree(egginfo)
  992. def _has_egg_info(srcdir):
  993. if os.path.isdir(srcdir):
  994. for item in os.listdir(srcdir):
  995. full_path = os.path.join(srcdir, item)
  996. if item.endswith('.egg-info') and os.path.isdir(full_path):
  997. logger.debug("Found egg-info directory.")
  998. return True
  999. logger.debug("No egg-info directory found.")
  1000. return False
  1001. def _has_setuptools_text(setup_py):
  1002. return _has_text(setup_py, 'setuptools')
  1003. def _has_distutils_text(setup_py):
  1004. return _has_text(setup_py, 'distutils')
  1005. def _has_text(setup_py, installer):
  1006. installer_pattern = re.compile('import {0}|from {0}'.format(installer))
  1007. with open(setup_py, 'r', encoding='utf-8') as setup:
  1008. for line in setup:
  1009. if re.search(installer_pattern, line):
  1010. logger.debug("Found %s text in setup.py.", installer)
  1011. return True
  1012. logger.debug("No %s text found in setup.py.", installer)
  1013. return False
  1014. def _has_required_metadata(setup_cfg):
  1015. config = RawConfigParser()
  1016. config.read([setup_cfg], encoding='utf8')
  1017. return (config.has_section('metadata') and
  1018. 'name' in config.options('metadata') and
  1019. 'version' in config.options('metadata'))
  1020. def _has_pkg_info(srcdir):
  1021. pkg_info = os.path.join(srcdir, 'PKG-INFO')
  1022. has_pkg_info = os.path.isfile(pkg_info)
  1023. if has_pkg_info:
  1024. logger.debug("PKG-INFO file found.")
  1025. else:
  1026. logger.debug("No PKG-INFO file found.")
  1027. return has_pkg_info
  1028. def _has_setup_py(srcdir):
  1029. setup_py = os.path.join(srcdir, 'setup.py')
  1030. if os.path.isfile(setup_py):
  1031. logger.debug('setup.py file found.')
  1032. return True
  1033. return False
  1034. def _has_setup_cfg(srcdir):
  1035. setup_cfg = os.path.join(srcdir, 'setup.cfg')
  1036. if os.path.isfile(setup_cfg):
  1037. logger.debug('setup.cfg file found.')
  1038. return True
  1039. logger.debug("No setup.cfg file found.")
  1040. return False
  1041. def is_setuptools(path):
  1042. """Check if the project is based on setuptools.
  1043. :param path: path to source directory containing a setup.py script.
  1044. Return True if the project requires setuptools to install, else False.
  1045. """
  1046. srcdir = os.path.abspath(path)
  1047. setup_py = os.path.join(srcdir, 'setup.py')
  1048. return _has_setup_py(srcdir) and (_has_egg_info(srcdir) or
  1049. _has_setuptools_text(setup_py))
  1050. def is_distutils(path):
  1051. """Check if the project is based on distutils.
  1052. :param path: path to source directory containing a setup.py script.
  1053. Return True if the project requires distutils to install, else False.
  1054. """
  1055. srcdir = os.path.abspath(path)
  1056. setup_py = os.path.join(srcdir, 'setup.py')
  1057. return _has_setup_py(srcdir) and (_has_pkg_info(srcdir) or
  1058. _has_distutils_text(setup_py))
  1059. def is_packaging(path):
  1060. """Check if the project is based on packaging
  1061. :param path: path to source directory containing a setup.cfg file.
  1062. Return True if the project has a valid setup.cfg, else False.
  1063. """
  1064. srcdir = os.path.abspath(path)
  1065. setup_cfg = os.path.join(srcdir, 'setup.cfg')
  1066. return _has_setup_cfg(srcdir) and _has_required_metadata(setup_cfg)
  1067. def get_install_method(path):
  1068. """Check if the project is based on packaging, setuptools, or distutils
  1069. :param path: path to source directory containing a setup.cfg file,
  1070. or setup.py.
  1071. Returns a string representing the best install method to use.
  1072. """
  1073. if is_packaging(path):
  1074. return "packaging"
  1075. elif is_setuptools(path):
  1076. return "setuptools"
  1077. elif is_distutils(path):
  1078. return "distutils"
  1079. else:
  1080. raise InstallationException('Cannot detect install method')
  1081. # XXX to be replaced by shutil.copytree
  1082. def copy_tree(src, dst, preserve_mode=True, preserve_times=True,
  1083. preserve_symlinks=False, update=False, dry_run=False):
  1084. # FIXME use of this function is why we get spurious logging message on
  1085. # stdout when tests run; kill and replace by shutil!
  1086. from distutils.file_util import copy_file
  1087. if not dry_run and not os.path.isdir(src):
  1088. raise PackagingFileError(
  1089. "cannot copy tree '%s': not a directory" % src)
  1090. try:
  1091. names = os.listdir(src)
  1092. except os.error as e:
  1093. errstr = e[1]
  1094. if dry_run:
  1095. names = []
  1096. else:
  1097. raise PackagingFileError(
  1098. "error listing files in '%s': %s" % (src, errstr))
  1099. if not dry_run:
  1100. _mkpath(dst)
  1101. outputs = []
  1102. for n in names:
  1103. src_name = os.path.join(src, n)
  1104. dst_name = os.path.join(dst, n)
  1105. if preserve_symlinks and os.path.islink(src_name):
  1106. link_dest = os.readlink(src_name)
  1107. logger.info("linking %s -> %s", dst_name, link_dest)
  1108. if not dry_run:
  1109. os.symlink(link_dest, dst_name)
  1110. outputs.append(dst_name)
  1111. elif os.path.isdir(src_name):
  1112. outputs.extend(
  1113. copy_tree(src_name, dst_name, preserve_mode,
  1114. preserve_times, preserve_symlinks, update,
  1115. dry_run=dry_run))
  1116. else:
  1117. copy_file(src_name, dst_name, preserve_mode,
  1118. preserve_times, update, dry_run=dry_run)
  1119. outputs.append(dst_name)
  1120. return outputs
  1121. # cache for by mkpath() -- in addition to cheapening redundant calls,
  1122. # eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
  1123. _path_created = set()
  1124. # I don't use os.makedirs because a) it's new to Python 1.5.2, and
  1125. # b) it blows up if the directory already exists (I want to silently
  1126. # succeed in that case).
  1127. def _mkpath(name, mode=0o777, dry_run=False):
  1128. # Detect a common bug -- name is None
  1129. if not isinstance(name, str):
  1130. raise PackagingInternalError(
  1131. "mkpath: 'name' must be a string (got %r)" % (name,))
  1132. # XXX what's the better way to handle verbosity? print as we create
  1133. # each directory in the path (the current behaviour), or only announce
  1134. # the creation of the whole path? (quite easy to do the latter since
  1135. # we're not using a recursive algorithm)
  1136. name = os.path.normpath(name)
  1137. created_dirs = []
  1138. if os.path.isdir(name) or name == '':
  1139. return created_dirs
  1140. if os.path.abspath(name) in _path_created:
  1141. return created_dirs
  1142. head, tail = os.path.split(name)
  1143. tails = [tail] # stack of lone dirs to create
  1144. while head and tail and not os.path.isdir(head):
  1145. head, tail = os.path.split(head)
  1146. tails.insert(0, tail) # push next higher dir onto stack
  1147. # now 'head' contains the deepest directory that already exists
  1148. # (that is, the child of 'head' in 'name' is the highest directory
  1149. # that does *not* exist)
  1150. for d in tails:
  1151. head = os.path.join(head, d)
  1152. abs_head = os.path.abspath(head)
  1153. if abs_head in _path_created:
  1154. continue
  1155. logger.info("creating %s", head)
  1156. if not dry_run:
  1157. try:
  1158. os.mkdir(head, mode)
  1159. except OSError as exc:
  1160. if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
  1161. raise PackagingFileError(
  1162. "could not create '%s': %s" % (head, exc.args[-1]))
  1163. created_dirs.append(head)
  1164. _path_created.add(abs_head)
  1165. return created_dirs
  1166. def encode_multipart(fields, files, boundary=None):
  1167. """Prepare a multipart HTTP request.
  1168. *fields* is a sequence of (name: str, value: str) elements for regular
  1169. form fields, *files* is a sequence of (name: str, filename: str, value:
  1170. bytes) elements for data to be uploaded as files.
  1171. Returns (content_type: bytes, body: bytes) ready for http.client.HTTP.
  1172. """
  1173. # Taken from http://code.activestate.com/recipes/146306
  1174. if boundary is None:
  1175. boundary = b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
  1176. elif not isinstance(boundary, bytes):
  1177. raise TypeError('boundary must be bytes, not %r' % type(boundary))
  1178. l = []
  1179. for key, values in fields:
  1180. # handle multiple entries for the same name
  1181. if not isinstance(values, (tuple, list)):
  1182. values = [values]
  1183. for value in values:
  1184. l.extend((
  1185. b'--' + boundary,
  1186. ('Content-Disposition: form-data; name="%s"' %
  1187. key).encode('utf-8'),
  1188. b'',
  1189. value.encode('utf-8')))
  1190. for key, filename, value in files:
  1191. l.extend((
  1192. b'--' + boundary,
  1193. ('Content-Disposition: form-data; name="%s"; filename="%s"' %
  1194. (key, filename)).encode('utf-8'),
  1195. b'',
  1196. value))
  1197. l.append(b'--' + boundary + b'--')
  1198. l.append(b'')
  1199. body = b'\r\n'.join(l)
  1200. content_type = b'multipart/form-data; boundary=' + boundary
  1201. return content_type, body