PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/pip/_vendor/distro.py

http://github.com/pypa/pip
Python | 1040 lines | 985 code | 6 blank | 49 comment | 6 complexity | 5a12c0f6b5100b567c19a6d5aca930dc MD5 | raw file
Possible License(s): 0BSD, MIT, BSD-3-Clause, MPL-2.0, LGPL-2.1, Apache-2.0
  1. # Copyright 2015,2016 Nir Cohen
  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. """
  15. The ``distro`` package (``distro`` stands for Linux Distribution) provides
  16. information about the Linux distribution it runs on, such as a reliable
  17. machine-readable distro ID, or version information.
  18. It is a renewed alternative implementation for Python's original
  19. :py:func:`platform.linux_distribution` function, but it provides much more
  20. functionality. An alternative implementation became necessary because Python
  21. 3.5 deprecated this function, and Python 3.7 is expected to remove it
  22. altogether. Its predecessor function :py:func:`platform.dist` was already
  23. deprecated since Python 2.6 and is also expected to be removed in Python 3.7.
  24. Still, there are many cases in which access to Linux distribution information
  25. is needed. See `Python issue 1322 <https://bugs.python.org/issue1322>`_ for
  26. more information.
  27. """
  28. import os
  29. import re
  30. import sys
  31. import shlex
  32. import subprocess
  33. from pip._vendor import six
  34. _UNIXCONFDIR = '/etc'
  35. _OS_RELEASE_BASENAME = 'os-release'
  36. #: Translation table for normalizing the "ID" attribute defined in os-release
  37. #: files, for use by the :func:`distro.id` method.
  38. #:
  39. #: * Key: Value as defined in the os-release file, translated to lower case,
  40. #: with blanks translated to underscores.
  41. #:
  42. #: * Value: Normalized value.
  43. NORMALIZED_OS_ID = {
  44. }
  45. #: Translation table for normalizing the "Distributor ID" attribute returned by
  46. #: the lsb_release command, for use by the :func:`distro.id` method.
  47. #:
  48. #: * Key: Value as returned by the lsb_release command, translated to lower
  49. #: case, with blanks translated to underscores.
  50. #:
  51. #: * Value: Normalized value.
  52. NORMALIZED_LSB_ID = {
  53. 'enterpriseenterprise': 'oracle', # Oracle Enterprise Linux
  54. 'redhatenterpriseworkstation': 'rhel', # RHEL 6.7
  55. }
  56. #: Translation table for normalizing the distro ID derived from the file name
  57. #: of distro release files, for use by the :func:`distro.id` method.
  58. #:
  59. #: * Key: Value as derived from the file name of a distro release file,
  60. #: translated to lower case, with blanks translated to underscores.
  61. #:
  62. #: * Value: Normalized value.
  63. NORMALIZED_DISTRO_ID = {
  64. 'redhat': 'rhel', # RHEL 6.x, 7.x
  65. }
  66. # Pattern for content of distro release file (reversed)
  67. _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
  68. r'(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)')
  69. # Pattern for base file name of distro release file
  70. _DISTRO_RELEASE_BASENAME_PATTERN = re.compile(
  71. r'(\w+)[-_](release|version)')
  72. # Base file names to be ignored when searching for distro release file
  73. _DISTRO_RELEASE_IGNORE_BASENAMES = [
  74. 'debian_version',
  75. 'system-release',
  76. _OS_RELEASE_BASENAME
  77. ]
  78. def linux_distribution(full_distribution_name=True):
  79. """
  80. Return information about the current Linux distribution as a tuple
  81. ``(id_name, version, codename)`` with items as follows:
  82. * ``id_name``: If *full_distribution_name* is false, the result of
  83. :func:`distro.id`. Otherwise, the result of :func:`distro.name`.
  84. * ``version``: The result of :func:`distro.version`.
  85. * ``codename``: The result of :func:`distro.codename`.
  86. The interface of this function is compatible with the original
  87. :py:func:`platform.linux_distribution` function, supporting a subset of
  88. its parameters.
  89. The data it returns may not exactly be the same, because it uses more data
  90. sources than the original function, and that may lead to different data if
  91. the Linux distribution is not consistent across multiple data sources it
  92. provides (there are indeed such distributions ...).
  93. Another reason for differences is the fact that the :func:`distro.id`
  94. method normalizes the distro ID string to a reliable machine-readable value
  95. for a number of popular Linux distributions.
  96. """
  97. return _distroi.linux_distribution(full_distribution_name)
  98. def id():
  99. """
  100. Return the distro ID of the current Linux distribution, as a
  101. machine-readable string.
  102. For a number of Linux distributions, the returned distro ID value is
  103. *reliable*, in the sense that it is documented and that it does not change
  104. across releases of the distribution.
  105. This package maintains the following reliable distro ID values:
  106. ============== =========================================
  107. Distro ID Distribution
  108. ============== =========================================
  109. "ubuntu" Ubuntu
  110. "debian" Debian
  111. "rhel" RedHat Enterprise Linux
  112. "centos" CentOS
  113. "fedora" Fedora
  114. "sles" SUSE Linux Enterprise Server
  115. "opensuse" openSUSE
  116. "amazon" Amazon Linux
  117. "arch" Arch Linux
  118. "cloudlinux" CloudLinux OS
  119. "exherbo" Exherbo Linux
  120. "gentoo" GenToo Linux
  121. "ibm_powerkvm" IBM PowerKVM
  122. "kvmibm" KVM for IBM z Systems
  123. "linuxmint" Linux Mint
  124. "mageia" Mageia
  125. "mandriva" Mandriva Linux
  126. "parallels" Parallels
  127. "pidora" Pidora
  128. "raspbian" Raspbian
  129. "oracle" Oracle Linux (and Oracle Enterprise Linux)
  130. "scientific" Scientific Linux
  131. "slackware" Slackware
  132. "xenserver" XenServer
  133. ============== =========================================
  134. If you have a need to get distros for reliable IDs added into this set,
  135. or if you find that the :func:`distro.id` function returns a different
  136. distro ID for one of the listed distros, please create an issue in the
  137. `distro issue tracker`_.
  138. **Lookup hierarchy and transformations:**
  139. First, the ID is obtained from the following sources, in the specified
  140. order. The first available and non-empty value is used:
  141. * the value of the "ID" attribute of the os-release file,
  142. * the value of the "Distributor ID" attribute returned by the lsb_release
  143. command,
  144. * the first part of the file name of the distro release file,
  145. The so determined ID value then passes the following transformations,
  146. before it is returned by this method:
  147. * it is translated to lower case,
  148. * blanks (which should not be there anyway) are translated to underscores,
  149. * a normalization of the ID is performed, based upon
  150. `normalization tables`_. The purpose of this normalization is to ensure
  151. that the ID is as reliable as possible, even across incompatible changes
  152. in the Linux distributions. A common reason for an incompatible change is
  153. the addition of an os-release file, or the addition of the lsb_release
  154. command, with ID values that differ from what was previously determined
  155. from the distro release file name.
  156. """
  157. return _distroi.id()
  158. def name(pretty=False):
  159. """
  160. Return the name of the current Linux distribution, as a human-readable
  161. string.
  162. If *pretty* is false, the name is returned without version or codename.
  163. (e.g. "CentOS Linux")
  164. If *pretty* is true, the version and codename are appended.
  165. (e.g. "CentOS Linux 7.1.1503 (Core)")
  166. **Lookup hierarchy:**
  167. The name is obtained from the following sources, in the specified order.
  168. The first available and non-empty value is used:
  169. * If *pretty* is false:
  170. - the value of the "NAME" attribute of the os-release file,
  171. - the value of the "Distributor ID" attribute returned by the lsb_release
  172. command,
  173. - the value of the "<name>" field of the distro release file.
  174. * If *pretty* is true:
  175. - the value of the "PRETTY_NAME" attribute of the os-release file,
  176. - the value of the "Description" attribute returned by the lsb_release
  177. command,
  178. - the value of the "<name>" field of the distro release file, appended
  179. with the value of the pretty version ("<version_id>" and "<codename>"
  180. fields) of the distro release file, if available.
  181. """
  182. return _distroi.name(pretty)
  183. def version(pretty=False, best=False):
  184. """
  185. Return the version of the current Linux distribution, as a human-readable
  186. string.
  187. If *pretty* is false, the version is returned without codename (e.g.
  188. "7.0").
  189. If *pretty* is true, the codename in parenthesis is appended, if the
  190. codename is non-empty (e.g. "7.0 (Maipo)").
  191. Some distributions provide version numbers with different precisions in
  192. the different sources of distribution information. Examining the different
  193. sources in a fixed priority order does not always yield the most precise
  194. version (e.g. for Debian 8.2, or CentOS 7.1).
  195. The *best* parameter can be used to control the approach for the returned
  196. version:
  197. If *best* is false, the first non-empty version number in priority order of
  198. the examined sources is returned.
  199. If *best* is true, the most precise version number out of all examined
  200. sources is returned.
  201. **Lookup hierarchy:**
  202. In all cases, the version number is obtained from the following sources.
  203. If *best* is false, this order represents the priority order:
  204. * the value of the "VERSION_ID" attribute of the os-release file,
  205. * the value of the "Release" attribute returned by the lsb_release
  206. command,
  207. * the version number parsed from the "<version_id>" field of the first line
  208. of the distro release file,
  209. * the version number parsed from the "PRETTY_NAME" attribute of the
  210. os-release file, if it follows the format of the distro release files.
  211. * the version number parsed from the "Description" attribute returned by
  212. the lsb_release command, if it follows the format of the distro release
  213. files.
  214. """
  215. return _distroi.version(pretty, best)
  216. def version_parts(best=False):
  217. """
  218. Return the version of the current Linux distribution as a tuple
  219. ``(major, minor, build_number)`` with items as follows:
  220. * ``major``: The result of :func:`distro.major_version`.
  221. * ``minor``: The result of :func:`distro.minor_version`.
  222. * ``build_number``: The result of :func:`distro.build_number`.
  223. For a description of the *best* parameter, see the :func:`distro.version`
  224. method.
  225. """
  226. return _distroi.version_parts(best)
  227. def major_version(best=False):
  228. """
  229. Return the major version of the current Linux distribution, as a string,
  230. if provided.
  231. Otherwise, the empty string is returned. The major version is the first
  232. part of the dot-separated version string.
  233. For a description of the *best* parameter, see the :func:`distro.version`
  234. method.
  235. """
  236. return _distroi.major_version(best)
  237. def minor_version(best=False):
  238. """
  239. Return the minor version of the current Linux distribution, as a string,
  240. if provided.
  241. Otherwise, the empty string is returned. The minor version is the second
  242. part of the dot-separated version string.
  243. For a description of the *best* parameter, see the :func:`distro.version`
  244. method.
  245. """
  246. return _distroi.minor_version(best)
  247. def build_number(best=False):
  248. """
  249. Return the build number of the current Linux distribution, as a string,
  250. if provided.
  251. Otherwise, the empty string is returned. The build number is the third part
  252. of the dot-separated version string.
  253. For a description of the *best* parameter, see the :func:`distro.version`
  254. method.
  255. """
  256. return _distroi.build_number(best)
  257. def like():
  258. """
  259. Return a space-separated list of distro IDs of distributions that are
  260. closely related to the current Linux distribution in regards to packaging
  261. and programming interfaces, for example distributions the current
  262. distribution is a derivative from.
  263. **Lookup hierarchy:**
  264. This information item is only provided by the os-release file.
  265. For details, see the description of the "ID_LIKE" attribute in the
  266. `os-release man page
  267. <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.
  268. """
  269. return _distroi.like()
  270. def codename():
  271. """
  272. Return the codename for the release of the current Linux distribution,
  273. as a string.
  274. If the distribution does not have a codename, an empty string is returned.
  275. Note that the returned codename is not always really a codename. For
  276. example, openSUSE returns "x86_64". This function does not handle such
  277. cases in any special way and just returns the string it finds, if any.
  278. **Lookup hierarchy:**
  279. * the codename within the "VERSION" attribute of the os-release file, if
  280. provided,
  281. * the value of the "Codename" attribute returned by the lsb_release
  282. command,
  283. * the value of the "<codename>" field of the distro release file.
  284. """
  285. return _distroi.codename()
  286. def info(pretty=False, best=False):
  287. """
  288. Return certain machine-readable information items about the current Linux
  289. distribution in a dictionary, as shown in the following example:
  290. .. sourcecode:: python
  291. {
  292. 'id': 'rhel',
  293. 'version': '7.0',
  294. 'version_parts': {
  295. 'major': '7',
  296. 'minor': '0',
  297. 'build_number': ''
  298. },
  299. 'like': 'fedora',
  300. 'codename': 'Maipo'
  301. }
  302. The dictionary structure and keys are always the same, regardless of which
  303. information items are available in the underlying data sources. The values
  304. for the various keys are as follows:
  305. * ``id``: The result of :func:`distro.id`.
  306. * ``version``: The result of :func:`distro.version`.
  307. * ``version_parts -> major``: The result of :func:`distro.major_version`.
  308. * ``version_parts -> minor``: The result of :func:`distro.minor_version`.
  309. * ``version_parts -> build_number``: The result of
  310. :func:`distro.build_number`.
  311. * ``like``: The result of :func:`distro.like`.
  312. * ``codename``: The result of :func:`distro.codename`.
  313. For a description of the *pretty* and *best* parameters, see the
  314. :func:`distro.version` method.
  315. """
  316. return _distroi.info(pretty, best)
  317. def os_release_info():
  318. """
  319. Return a dictionary containing key-value pairs for the information items
  320. from the os-release file data source of the current Linux distribution.
  321. See `os-release file`_ for details about these information items.
  322. """
  323. return _distroi.os_release_info()
  324. def lsb_release_info():
  325. """
  326. Return a dictionary containing key-value pairs for the information items
  327. from the lsb_release command data source of the current Linux distribution.
  328. See `lsb_release command output`_ for details about these information
  329. items.
  330. """
  331. return _distroi.lsb_release_info()
  332. def distro_release_info():
  333. """
  334. Return a dictionary containing key-value pairs for the information items
  335. from the distro release file data source of the current Linux distribution.
  336. See `distro release file`_ for details about these information items.
  337. """
  338. return _distroi.distro_release_info()
  339. def os_release_attr(attribute):
  340. """
  341. Return a single named information item from the os-release file data source
  342. of the current Linux distribution.
  343. Parameters:
  344. * ``attribute`` (string): Key of the information item.
  345. Returns:
  346. * (string): Value of the information item, if the item exists.
  347. The empty string, if the item does not exist.
  348. See `os-release file`_ for details about these information items.
  349. """
  350. return _distroi.os_release_attr(attribute)
  351. def lsb_release_attr(attribute):
  352. """
  353. Return a single named information item from the lsb_release command output
  354. data source of the current Linux distribution.
  355. Parameters:
  356. * ``attribute`` (string): Key of the information item.
  357. Returns:
  358. * (string): Value of the information item, if the item exists.
  359. The empty string, if the item does not exist.
  360. See `lsb_release command output`_ for details about these information
  361. items.
  362. """
  363. return _distroi.lsb_release_attr(attribute)
  364. def distro_release_attr(attribute):
  365. """
  366. Return a single named information item from the distro release file
  367. data source of the current Linux distribution.
  368. Parameters:
  369. * ``attribute`` (string): Key of the information item.
  370. Returns:
  371. * (string): Value of the information item, if the item exists.
  372. The empty string, if the item does not exist.
  373. See `distro release file`_ for details about these information items.
  374. """
  375. return _distroi.distro_release_attr(attribute)
  376. class LinuxDistribution(object):
  377. """
  378. Provides information about a Linux distribution.
  379. This package creates a private module-global instance of this class with
  380. default initialization arguments, that is used by the
  381. `consolidated accessor functions`_ and `single source accessor functions`_.
  382. By using default initialization arguments, that module-global instance
  383. returns data about the current Linux distribution (i.e. the distro this
  384. package runs on).
  385. Normally, it is not necessary to create additional instances of this class.
  386. However, in situations where control is needed over the exact data sources
  387. that are used, instances of this class can be created with a specific
  388. distro release file, or a specific os-release file, or without invoking the
  389. lsb_release command.
  390. """
  391. def __init__(self,
  392. include_lsb=True,
  393. os_release_file='',
  394. distro_release_file=''):
  395. """
  396. The initialization method of this class gathers information from the
  397. available data sources, and stores that in private instance attributes.
  398. Subsequent access to the information items uses these private instance
  399. attributes, so that the data sources are read only once.
  400. Parameters:
  401. * ``include_lsb`` (bool): Controls whether the
  402. `lsb_release command output`_ is included as a data source.
  403. If the lsb_release command is not available in the program execution
  404. path, the data source for the lsb_release command will be empty.
  405. * ``os_release_file`` (string): The path name of the
  406. `os-release file`_ that is to be used as a data source.
  407. An empty string (the default) will cause the default path name to
  408. be used (see `os-release file`_ for details).
  409. If the specified or defaulted os-release file does not exist, the
  410. data source for the os-release file will be empty.
  411. * ``distro_release_file`` (string): The path name of the
  412. `distro release file`_ that is to be used as a data source.
  413. An empty string (the default) will cause a default search algorithm
  414. to be used (see `distro release file`_ for details).
  415. If the specified distro release file does not exist, or if no default
  416. distro release file can be found, the data source for the distro
  417. release file will be empty.
  418. Public instance attributes:
  419. * ``os_release_file`` (string): The path name of the
  420. `os-release file`_ that is actually used as a data source. The
  421. empty string if no distro release file is used as a data source.
  422. * ``distro_release_file`` (string): The path name of the
  423. `distro release file`_ that is actually used as a data source. The
  424. empty string if no distro release file is used as a data source.
  425. Raises:
  426. * :py:exc:`IOError`: Some I/O issue with an os-release file or distro
  427. release file.
  428. * :py:exc:`subprocess.CalledProcessError`: The lsb_release command had
  429. some issue (other than not being available in the program execution
  430. path).
  431. * :py:exc:`UnicodeError`: A data source has unexpected characters or
  432. uses an unexpected encoding.
  433. """
  434. self.os_release_file = os_release_file or \
  435. os.path.join(_UNIXCONFDIR, _OS_RELEASE_BASENAME)
  436. self.distro_release_file = distro_release_file or '' # updated later
  437. self._os_release_info = self._os_release_info()
  438. self._lsb_release_info = self._lsb_release_info() \
  439. if include_lsb else {}
  440. self._distro_release_info = self._distro_release_info()
  441. def __repr__(self):
  442. return \
  443. "LinuxDistribution(" \
  444. "os_release_file={0!r}, " \
  445. "distro_release_file={1!r}, " \
  446. "_os_release_info={2!r}, " \
  447. "_lsb_release_info={3!r}, " \
  448. "_distro_release_info={4!r})".format(
  449. self.os_release_file,
  450. self.distro_release_file,
  451. self._os_release_info,
  452. self._lsb_release_info,
  453. self._distro_release_info)
  454. def linux_distribution(self, full_distribution_name=True):
  455. """
  456. Return information about the Linux distribution that is compatible
  457. with Python's :func:`platform.linux_distribution`, supporting a subset
  458. of its parameters.
  459. For details, see :func:`distro.linux_distribution`.
  460. """
  461. return (
  462. self.name() if full_distribution_name else self.id(),
  463. self.version(),
  464. self.codename()
  465. )
  466. def id(self):
  467. """
  468. Return the distro ID of the Linux distribution, as a string.
  469. For details, see :func:`distro.id`.
  470. """
  471. distro_id = self.os_release_attr('id')
  472. if distro_id:
  473. distro_id = distro_id.lower().replace(' ', '_')
  474. return NORMALIZED_OS_ID.get(distro_id, distro_id)
  475. distro_id = self.lsb_release_attr('distributor_id')
  476. if distro_id:
  477. distro_id = distro_id.lower().replace(' ', '_')
  478. return NORMALIZED_LSB_ID.get(distro_id, distro_id)
  479. distro_id = self.distro_release_attr('id')
  480. if distro_id:
  481. distro_id = distro_id.lower().replace(' ', '_')
  482. return NORMALIZED_DISTRO_ID.get(distro_id, distro_id)
  483. return ''
  484. def name(self, pretty=False):
  485. """
  486. Return the name of the Linux distribution, as a string.
  487. For details, see :func:`distro.name`.
  488. """
  489. name = self.os_release_attr('name') \
  490. or self.lsb_release_attr('distributor_id') \
  491. or self.distro_release_attr('name')
  492. if pretty:
  493. name = self.os_release_attr('pretty_name') \
  494. or self.lsb_release_attr('description')
  495. if not name:
  496. name = self.distro_release_attr('name')
  497. version = self.version(pretty=True)
  498. if version:
  499. name = name + ' ' + version
  500. return name or ''
  501. def version(self, pretty=False, best=False):
  502. """
  503. Return the version of the Linux distribution, as a string.
  504. For details, see :func:`distro.version`.
  505. """
  506. versions = [
  507. self.os_release_attr('version_id'),
  508. self.lsb_release_attr('release'),
  509. self.distro_release_attr('version_id'),
  510. self._parse_distro_release_content(
  511. self.os_release_attr('pretty_name')).get('version_id', ''),
  512. self._parse_distro_release_content(
  513. self.lsb_release_attr('description')).get('version_id', '')
  514. ]
  515. version = ''
  516. if best:
  517. # This algorithm uses the last version in priority order that has
  518. # the best precision. If the versions are not in conflict, that
  519. # does not matter; otherwise, using the last one instead of the
  520. # first one might be considered a surprise.
  521. for v in versions:
  522. if v.count(".") > version.count(".") or version == '':
  523. version = v
  524. else:
  525. for v in versions:
  526. if v != '':
  527. version = v
  528. break
  529. if pretty and version and self.codename():
  530. version = u'{0} ({1})'.format(version, self.codename())
  531. return version
  532. def version_parts(self, best=False):
  533. """
  534. Return the version of the Linux distribution, as a tuple of version
  535. numbers.
  536. For details, see :func:`distro.version_parts`.
  537. """
  538. version_str = self.version(best=best)
  539. if version_str:
  540. g = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?')
  541. m = g.match(version_str)
  542. if m:
  543. major, minor, build_number = m.groups()
  544. return (major, minor or '', build_number or '')
  545. return ('', '', '')
  546. def major_version(self, best=False):
  547. """
  548. Return the major version number of the current distribution.
  549. For details, see :func:`distro.major_version`.
  550. """
  551. return self.version_parts(best)[0]
  552. def minor_version(self, best=False):
  553. """
  554. Return the minor version number of the Linux distribution.
  555. For details, see :func:`distro.minor_version`.
  556. """
  557. return self.version_parts(best)[1]
  558. def build_number(self, best=False):
  559. """
  560. Return the build number of the Linux distribution.
  561. For details, see :func:`distro.build_number`.
  562. """
  563. return self.version_parts(best)[2]
  564. def like(self):
  565. """
  566. Return the IDs of distributions that are like the Linux distribution.
  567. For details, see :func:`distro.like`.
  568. """
  569. return self.os_release_attr('id_like') or ''
  570. def codename(self):
  571. """
  572. Return the codename of the Linux distribution.
  573. For details, see :func:`distro.codename`.
  574. """
  575. return self.os_release_attr('codename') \
  576. or self.lsb_release_attr('codename') \
  577. or self.distro_release_attr('codename') \
  578. or ''
  579. def info(self, pretty=False, best=False):
  580. """
  581. Return certain machine-readable information about the Linux
  582. distribution.
  583. For details, see :func:`distro.info`.
  584. """
  585. return dict(
  586. id=self.id(),
  587. version=self.version(pretty, best),
  588. version_parts=dict(
  589. major=self.major_version(best),
  590. minor=self.minor_version(best),
  591. build_number=self.build_number(best)
  592. ),
  593. like=self.like(),
  594. codename=self.codename(),
  595. )
  596. def os_release_info(self):
  597. """
  598. Return a dictionary containing key-value pairs for the information
  599. items from the os-release file data source of the Linux distribution.
  600. For details, see :func:`distro.os_release_info`.
  601. """
  602. return self._os_release_info
  603. def lsb_release_info(self):
  604. """
  605. Return a dictionary containing key-value pairs for the information
  606. items from the lsb_release command data source of the Linux
  607. distribution.
  608. For details, see :func:`distro.lsb_release_info`.
  609. """
  610. return self._lsb_release_info
  611. def distro_release_info(self):
  612. """
  613. Return a dictionary containing key-value pairs for the information
  614. items from the distro release file data source of the Linux
  615. distribution.
  616. For details, see :func:`distro.distro_release_info`.
  617. """
  618. return self._distro_release_info
  619. def os_release_attr(self, attribute):
  620. """
  621. Return a single named information item from the os-release file data
  622. source of the Linux distribution.
  623. For details, see :func:`distro.os_release_attr`.
  624. """
  625. return self._os_release_info.get(attribute, '')
  626. def lsb_release_attr(self, attribute):
  627. """
  628. Return a single named information item from the lsb_release command
  629. output data source of the Linux distribution.
  630. For details, see :func:`distro.lsb_release_attr`.
  631. """
  632. return self._lsb_release_info.get(attribute, '')
  633. def distro_release_attr(self, attribute):
  634. """
  635. Return a single named information item from the distro release file
  636. data source of the Linux distribution.
  637. For details, see :func:`distro.distro_release_attr`.
  638. """
  639. return self._distro_release_info.get(attribute, '')
  640. def _os_release_info(self):
  641. """
  642. Get the information items from the specified os-release file.
  643. Returns:
  644. A dictionary containing all information items.
  645. """
  646. if os.path.isfile(self.os_release_file):
  647. with open(self.os_release_file, 'r') as f:
  648. return self._parse_os_release_content(f)
  649. return {}
  650. @staticmethod
  651. def _parse_os_release_content(lines):
  652. """
  653. Parse the lines of an os-release file.
  654. Parameters:
  655. * lines: Iterable through the lines in the os-release file.
  656. Each line must be a unicode string or a UTF-8 encoded byte
  657. string.
  658. Returns:
  659. A dictionary containing all information items.
  660. """
  661. props = {}
  662. lexer = shlex.shlex(lines, posix=True)
  663. lexer.whitespace_split = True
  664. # The shlex module defines its `wordchars` variable using literals,
  665. # making it dependent on the encoding of the Python source file.
  666. # In Python 2.6 and 2.7, the shlex source file is encoded in
  667. # 'iso-8859-1', and the `wordchars` variable is defined as a byte
  668. # string. This causes a UnicodeDecodeError to be raised when the
  669. # parsed content is a unicode object. The following fix resolves that
  670. # (... but it should be fixed in shlex...):
  671. if sys.version_info[0] == 2 and isinstance(lexer.wordchars, str):
  672. lexer.wordchars = lexer.wordchars.decode('iso-8859-1')
  673. tokens = list(lexer)
  674. for token in tokens:
  675. # At this point, all shell-like parsing has been done (i.e.
  676. # comments processed, quotes and backslash escape sequences
  677. # processed, multi-line values assembled, trailing newlines
  678. # stripped, etc.), so the tokens are now either:
  679. # * variable assignments: var=value
  680. # * commands or their arguments (not allowed in os-release)
  681. if '=' in token:
  682. k, v = token.split('=', 1)
  683. if isinstance(v, six.binary_type):
  684. v = v.decode('utf-8')
  685. props[k.lower()] = v
  686. if k == 'VERSION':
  687. # this handles cases in which the codename is in
  688. # the `(CODENAME)` (rhel, centos, fedora) format
  689. # or in the `, CODENAME` format (Ubuntu).
  690. codename = re.search(r'(\(\D+\))|,(\s+)?\D+', v)
  691. if codename:
  692. codename = codename.group()
  693. codename = codename.strip('()')
  694. codename = codename.strip(',')
  695. codename = codename.strip()
  696. # codename appears within paranthese.
  697. props['codename'] = codename
  698. else:
  699. props['codename'] = ''
  700. else:
  701. # Ignore any tokens that are not variable assignments
  702. pass
  703. return props
  704. def _lsb_release_info(self):
  705. """
  706. Get the information items from the lsb_release command output.
  707. Returns:
  708. A dictionary containing all information items.
  709. """
  710. cmd = 'lsb_release -a'
  711. p = subprocess.Popen(
  712. cmd,
  713. shell=True,
  714. stdout=subprocess.PIPE,
  715. stderr=subprocess.PIPE)
  716. out, err = p.communicate()
  717. rc = p.returncode
  718. if rc == 0:
  719. content = out.decode('ascii').splitlines()
  720. return self._parse_lsb_release_content(content)
  721. elif rc == 127: # Command not found
  722. return {}
  723. else:
  724. if sys.version_info[0:2] >= (2, 7):
  725. raise subprocess.CalledProcessError(rc, cmd, err)
  726. else:
  727. raise subprocess.CalledProcessError(rc, cmd)
  728. @staticmethod
  729. def _parse_lsb_release_content(lines):
  730. """
  731. Parse the output of the lsb_release command.
  732. Parameters:
  733. * lines: Iterable through the lines of the lsb_release output.
  734. Each line must be a unicode string or a UTF-8 encoded byte
  735. string.
  736. Returns:
  737. A dictionary containing all information items.
  738. """
  739. props = {}
  740. for line in lines:
  741. if isinstance(line, six.binary_type):
  742. line = line.decode('utf-8')
  743. kv = line.strip('\n').split(':', 1)
  744. if len(kv) != 2:
  745. # Ignore lines without colon.
  746. continue
  747. k, v = kv
  748. props.update({k.replace(' ', '_').lower(): v.strip()})
  749. return props
  750. def _distro_release_info(self):
  751. """
  752. Get the information items from the specified distro release file.
  753. Returns:
  754. A dictionary containing all information items.
  755. """
  756. if self.distro_release_file:
  757. # If it was specified, we use it and parse what we can, even if
  758. # its file name or content does not match the expected pattern.
  759. distro_info = self._parse_distro_release_file(
  760. self.distro_release_file)
  761. basename = os.path.basename(self.distro_release_file)
  762. # The file name pattern for user-specified distro release files
  763. # is somewhat more tolerant (compared to when searching for the
  764. # file), because we want to use what was specified as best as
  765. # possible.
  766. match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
  767. if match:
  768. distro_info['id'] = match.group(1)
  769. return distro_info
  770. else:
  771. basenames = os.listdir(_UNIXCONFDIR)
  772. # We sort for repeatability in cases where there are multiple
  773. # distro specific files; e.g. CentOS, Oracle, Enterprise all
  774. # containing `redhat-release` on top of their own.
  775. basenames.sort()
  776. for basename in basenames:
  777. if basename in _DISTRO_RELEASE_IGNORE_BASENAMES:
  778. continue
  779. match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
  780. if match:
  781. filepath = os.path.join(_UNIXCONFDIR, basename)
  782. distro_info = self._parse_distro_release_file(filepath)
  783. if 'name' in distro_info:
  784. # The name is always present if the pattern matches
  785. self.distro_release_file = filepath
  786. distro_info['id'] = match.group(1)
  787. return distro_info
  788. return {}
  789. def _parse_distro_release_file(self, filepath):
  790. """
  791. Parse a distro release file.
  792. Parameters:
  793. * filepath: Path name of the distro release file.
  794. Returns:
  795. A dictionary containing all information items.
  796. """
  797. if os.path.isfile(filepath):
  798. with open(filepath, 'r') as fp:
  799. # Only parse the first line. For instance, on SLES there
  800. # are multiple lines. We don't want them...
  801. return self._parse_distro_release_content(fp.readline())
  802. return {}
  803. @staticmethod
  804. def _parse_distro_release_content(line):
  805. """
  806. Parse a line from a distro release file.
  807. Parameters:
  808. * line: Line from the distro release file. Must be a unicode string
  809. or a UTF-8 encoded byte string.
  810. Returns:
  811. A dictionary containing all information items.
  812. """
  813. if isinstance(line, six.binary_type):
  814. line = line.decode('utf-8')
  815. m = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(
  816. line.strip()[::-1])
  817. distro_info = {}
  818. if m:
  819. distro_info['name'] = m.group(3)[::-1] # regexp ensures non-None
  820. if m.group(2):
  821. distro_info['version_id'] = m.group(2)[::-1]
  822. if m.group(1):
  823. distro_info['codename'] = m.group(1)[::-1]
  824. return distro_info
  825. _distroi = LinuxDistribution()