1 // https://github.com/nir0s/distro - Copyright 2015,2016,2017 Nir Cohen
2 // Copyright 2019 Victor Porton
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 /**
17 The ``distro`` package (``distro`` stands for Linux Distribution) provides
18 information about the Linux distribution it runs on, such as a reliable
19 machine-readable distro ID, or version information.
20 Still, there are many cases in which access to OS distribution information
21 is needed. See `Python issue 1322 <https://bugs.python.org/issue1322>`_ for
22 more information.
23 */
24 module distro;
25 
26 import std.typecons;
27 import std.exception;
28 import std.conv;
29 import std.range;
30 import std.algorithm.iteration;
31 import std.algorithm.searching;
32 import std.algorithm.sorting;
33 import std.array;
34 import std..string;
35 import std.process : environment;
36 import std.path;
37 import std.regex;
38 import std.stdio;
39 import std.file;
40 import std.process;
41 import shlex;
42 
43 private immutable string _UNIXCONFDIR = "/etc"; //environment.get("UNIXCONFDIR", "/etc"); // FIXME
44 private immutable dstring _OS_RELEASE_BASENAME = "os-release"d;
45 
46 // Translation table for normalizing the "ID" attribute defined in os-release
47 // files, for use by the :func:`distro.id` method.
48 //
49 // * Key: Value as defined in the os-release file, translated to lower case,
50 //   with blanks translated to underscores.
51 //
52 // * Value: Normalized value.
53 private dstring[dstring] NORMALIZED_OS_ID;
54 
55 // Pattern for content of distro release file (reversed)
56 private immutable _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = regex(
57     r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"d);
58 
59 // Pattern for base file name of distro release file
60 private immutable _DISTRO_RELEASE_BASENAME_PATTERN = regex(
61     r"(\w+)[-_](release|version)$"d);
62 
63 // Base file names to be ignored when searching for distro release file
64 private immutable _DISTRO_RELEASE_IGNORE_BASENAMES = [
65     "debian_version"d,
66     "lsb-release"d,
67     "oem-release"d,
68     _OS_RELEASE_BASENAME,
69     "system-released"
70 ];
71 
72 
73 /**
74 Return information about the current OS distribution as a tuple
75 ``(id_name, version, codename)`` with items as follows:
76 * ``id_name``:  If *full_distribution_name* is false, the result of
77   :func:`distro.id`. Otherwise, the result of :func:`distro.name`.
78 * ``version``:  The result of :func:`distro.version`.
79 * ``codename``:  The result of :func:`distro.codename`.
80 The interface of this function is compatible with the original
81 :py:func:`platform.linux_distribution` function, supporting a subset of
82 its parameters.
83 The data it returns may not exactly be the same, because it uses more data
84 sources than the original function, and that may lead to different data if
85 the OS distribution is not consistent across multiple data sources it
86 provides (there are indeed such distributions ...).
87 Another reason for differences is the fact that the :func:`distro.id`
88 method normalizes the distro ID string to a reliable machine-readable value
89 for a number of popular OS distributions.
90 */
91 auto linux_distribution(bool full_distribution_name=true) {
92     return _distro.linux_distribution(full_distribution_name);
93 }
94 
95 
96 /**
97 Return the distro ID of the current distribution, as a
98 machine-readable string.
99 For a number of OS distributions, the returned distro ID value is
100 *reliable*, in the sense that it is documented and that it does not change
101 across releases of the distribution.
102 This package maintains the following reliable distro ID values:
103 ==============  =========================================
104 Distro ID       Distribution
105 ==============  =========================================
106 "ubuntu"        Ubuntu
107 "debian"        Debian
108 "rhel"          RedHat Enterprise Linux
109 "centos"        CentOS
110 "fedora"        Fedora
111 "sles"          SUSE Linux Enterprise Server
112 "opensuse"      openSUSE
113 "amazon"        Amazon Linux
114 "arch"          Arch Linux
115 "cloudlinux"    CloudLinux OS
116 "exherbo"       Exherbo Linux
117 "gentoo"        GenToo Linux
118 "ibm_powerkvm"  IBM PowerKVM
119 "kvmibm"        KVM for IBM z Systems
120 "linuxmint"     Linux Mint
121 "mageia"        Mageia
122 "mandriva"      Mandriva Linux
123 "parallels"     Parallels
124 "pidora"        Pidora
125 "raspbian"      Raspbian
126 "oracle"        Oracle Linux (and Oracle Enterprise Linux)
127 "scientific"    Scientific Linux
128 "slackware"     Slackware
129 "xenserver"     XenServer
130 "openbsd"       OpenBSD
131 "netbsd"        NetBSD
132 "freebsd"       FreeBSD
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 OS 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 dstring id() {
158     return _distro.id();
159 }
160 
161 
162 /**
163 Return the name of the current OS distribution, as a human-readable
164 string.
165 If *pretty* is false, the name is returned without version or codename.
166 (e.g. "CentOS Linux")
167 If *pretty* is true, the version and codename are appended.
168 (e.g. "CentOS Linux 7.1.1503 (Core)")
169 **Lookup hierarchy:**
170 The name is obtained from the following sources, in the specified order.
171 The first available and non-empty value is used:
172 * If *pretty* is false:
173   - the value of the "NAME" attribute of the os-release file,
174   - the value of the "Distributor ID" attribute returned by the lsb_release
175     command,
176   - the value of the "<name>" field of the distro release file.
177 * If *pretty* is true:
178   - the value of the "PRETTY_NAME" attribute of the os-release file,
179   - the value of the "Description" attribute returned by the lsb_release
180     command,
181   - the value of the "<name>" field of the distro release file, appended
182     with the value of the pretty version ("<version_id>" and "<codename>"
183     fields) of the distro release file, if available.
184 */
185 dstring name(bool pretty=false) {
186     return _distro.name(pretty);
187 }
188 
189 
190 /**
191 Return the version of the current OS distribution, as a human-readable
192 dstring.
193 If *pretty* is false, the version is returned without codename (e.g.
194 "7.0").
195 If *pretty* is true, the codename in parenthesis is appended, if the
196 codename is non-empty (e.g. "7.0 (Maipo)").
197 Some distributions provide version numbers with different precisions in
198 the different sources of distribution information. Examining the different
199 sources in a fixed priority order does not always yield the most precise
200 version (e.g. for Debian 8.2, or CentOS 7.1).
201 The *best* parameter can be used to control the approach for the returned
202 version:
203 If *best* is false, the first non-empty version number in priority order of
204 the examined sources is returned.
205 If *best* is true, the most precise version number out of all examined
206 sources is returned.
207 **Lookup hierarchy:**
208 In all cases, the version number is obtained from the following sources.
209 If *best* is false, this order represents the priority order:
210 * the value of the "VERSION_ID" attribute of the os-release file,
211 * the value of the "Release" attribute returned by the lsb_release
212   command,
213 * the version number parsed from the "<version_id>" field of the first line
214   of the distro release file,
215 * the version number parsed from the "PRETTY_NAME" attribute of the
216   os-release file, if it follows the format of the distro release files.
217 * the version number parsed from the "Description" attribute returned by
218   the lsb_release command, if it follows the format of the distro release
219   files.
220 */
221 dstring version_(bool pretty=false, bool best=false) {
222     return _distro.version_(pretty, best);
223 }
224 
225 /**
226 Return the version of the current OS distribution as a tuple
227 ``(major, minor, build_number)`` with items as follows:
228 * ``major``:  The result of :func:`distro.major_version`.
229 * ``minor``:  The result of :func:`distro.minor_version`.
230 * ``build_number``:  The result of :func:`distro.build_number`.
231 For a description of the *best* parameter, see the :func:`distro.version`
232 method.
233 */
234 auto version_parts(bool best=false) {
235     return _distro.version_parts(best);
236 }
237 
238 
239 /**
240 Return the major version of the current OS distribution, as a string,
241 if provided.
242 Otherwise, the empty string is returned. The major version is the first
243 part of the dot-separated version string.
244 For a description of the *best* parameter, see the :func:`distro.version`
245 method.
246 */
247 dstring major_version(bool best=false) {
248     return _distro.major_version(best);
249 }
250 
251 /**
252 Return the minor version of the current OS distribution, as a string,
253 if provided.
254 Otherwise, the empty string is returned. The minor version is the second
255 part of the dot-separated version string.
256 For a description of the *best* parameter, see the :func:`distro.version`
257 method.
258 */
259 dstring minor_version(bool best=false) {
260     return _distro.minor_version(best);
261 }
262 
263 /**
264 Return the build number of the current OS distribution, as a string,
265 if provided.
266 Otherwise, the empty string is returned. The build number is the third part
267 of the dot-separated version string.
268 For a description of the *best* parameter, see the :func:`distro.version`
269 method.
270 */
271 dstring build_number(bool best=false) {
272     return _distro.build_number(best);
273 }
274 
275 /**
276 Return a space-separated list of distro IDs of distributions that are
277 closely related to the current OS distribution in regards to packaging
278 and programming interfaces, for example distributions the current
279 distribution is a derivative from.
280 **Lookup hierarchy:**
281 This information item is only provided by the os-release file.
282 For details, see the description of the "ID_LIKE" attribute in the
283 `os-release man page
284 <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.
285 */
286 dstring like() {
287     return _distro.like();
288 }
289 
290 /**
291 Return the codename for the release of the current OS distribution,
292 as a string.
293 If the distribution does not have a codename, an empty string is returned.
294 Note that the returned codename is not always really a codename. For
295 example, openSUSE returns "x86_64". This function does not handle such
296 cases in any special way and just returns the string it finds, if any.
297 **Lookup hierarchy:**
298 * the codename within the "VERSION" attribute of the os-release file, if
299   provided,
300 * the value of the "Codename" attribute returned by the lsb_release
301   command,
302 * the value of the "<codename>" field of the distro release file.
303 */
304 dstring codename() {
305     return _distro.codename();
306 }
307 
308 /**
309 Return certain machine-readable information items about the current OS
310 distribution in a dictionary, as shown in the following example:
311 .. sourcecode:: python
312     {
313         'id': 'rhel',
314         'version': '7.0',
315         'version_parts': {
316             'major': '7',
317             'minor': '0',
318             'build_number': ''
319         },
320         'like': 'fedora',
321         'codename': 'Maipo'
322     }
323 The dictionary structure and keys are always the same, regardless of which
324 information items are available in the underlying data sources. The values
325 for the various keys are as follows:
326 * ``id``:  The result of :func:`distro.id`.
327 * ``version``:  The result of :func:`distro.version`.
328 * ``version_parts -> major``:  The result of :func:`distro.major_version`.
329 * ``version_parts -> minor``:  The result of :func:`distro.minor_version`.
330 * ``version_parts -> build_number``:  The result of
331   :func:`distro.build_number`.
332 * ``like``:  The result of :func:`distro.like`.
333 * ``codename``:  The result of :func:`distro.codename`.
334 For a description of the *pretty* and *best* parameters, see the
335 :func:`distro.version` method.
336 */
337 auto info(bool pretty=false, bool best=false) {
338     return _distro.info(pretty, best);
339 }
340 
341 /**
342 Return a dictionary containing key-value pairs for the information items
343 from the os-release file data source of the current OS distribution.
344 See `os-release file`_ for details about these information items.
345 */
346 dstring[dstring] os_release_info() {
347     return _distro.os_release_info();
348 }
349 
350 /**
351 Return a dictionary containing key-value pairs for the information items
352 from the lsb_release command data source of the current OS distribution.
353 See `lsb_release command output`_ for details about these information
354 items.
355 */
356 dstring[dstring] lsb_release_info() {
357     return _distro.lsb_release_info();
358 }
359 
360 /**
361 Return a dictionary containing key-value pairs for the information items
362 from the distro release file data source of the current OS distribution.
363 See `distro release file`_ for details about these information items.
364 */
365 dstring[dstring] distro_release_info() {
366     return _distro.distro_release_info();
367 }
368 
369 /**
370 Return a dictionary containing key-value pairs for the information items
371 from the distro release file data source of the current OS distribution.
372 */
373 dstring[dstring] uname_info() {
374     return _distro.uname_info();
375 }
376 
377 /**
378 Return a single named information item from the os-release file data source
379 of the current OS distribution.
380 Parameters:
381 * ``attribute`` (string): Key of the information item.
382 Returns:
383 * (string): Value of the information item, if the item exists.
384   The empty string, if the item does not exist.
385 See `os-release file`_ for details about these information items.
386 */
387 dstring os_release_attr(dstring attribute) {
388     return _distro.os_release_attr(attribute);
389 }
390 
391 /**
392 Return a single named information item from the lsb_release command output
393 data source of the current OS distribution.
394 Parameters:
395 * ``attribute`` (string): Key of the information item.
396 Returns:
397 * (string): Value of the information item, if the item exists.
398   The empty string, if the item does not exist.
399 See `lsb_release command output`_ for details about these information
400 items.
401 */
402 dstring lsb_release_attr(dstring attribute) {
403     return _distro.lsb_release_attr(attribute);
404 }
405 
406 /**
407 Return a single named information item from the distro release file
408 data source of the current OS distribution.
409 Parameters:
410 * ``attribute`` (string): Key of the information item.
411 Returns:
412 * (string): Value of the information item, if the item exists.
413   The empty string, if the item does not exist.
414 See `distro release file`_ for details about these information items.
415 */
416 dstring distro_release_attr(dstring attribute) {
417     return _distro.distro_release_attr(attribute);
418 }
419 
420 /**
421 Return a single named information item from the distro release file
422 data source of the current OS distribution.
423 Parameters:
424 * ``attribute`` (string): Key of the information item.
425 Returns:
426 * (string): Value of the information item, if the item exists.
427             The empty string, if the item does not exist.
428 */
429 dstring uname_attr(dstring attribute) {
430     return _distro.uname_attr(attribute);
431 }
432 
433 /**
434 The following code makes cached (memoized) property `f`
435 ```
436 class {
437     @property string _f() { ... }
438     mixin mixin Cached!"f";
439 }
440 ```
441 */
442 mixin template Cached(string name, string baseName = '_' ~ name) {
443     mixin("private typeof(" ~ baseName ~ ") " ~ name ~ "Cache;");
444     mixin("private bool " ~ name ~ "IsCached = false;");
445     mixin("@property typeof(" ~ baseName ~ ") " ~ name ~ "() {\n" ~
446           "if (" ~ name ~ "IsCached" ~ ") return " ~ name ~ "Cache;\n" ~
447           name ~ "IsCached = true;\n" ~
448           "return " ~ name ~ "Cache = " ~ baseName ~ ";\n" ~
449           '}');
450 }
451 
452 /**
453 Provides information about a OS distribution.
454 This package creates a private module-global instance of this class with
455 default initialization arguments, that is used by the
456 `consolidated accessor functions`_ and `single source accessor functions`_.
457 By using default initialization arguments, that module-global instance
458 returns data about the current OS distribution (i.e. the distro this
459 package runs on).
460 Normally, it is not necessary to create additional instances of this class.
461 However, in situations where control is needed over the exact data sources
462 that are used, instances of this class can be created with a specific
463 distro release file, or a specific os-release file, or without invoking the
464 lsb_release command.
465 */
466 struct LinuxDistribution {
467 private:
468         string os_release_file;
469         string distro_release_file; // updated later
470         bool include_lsb;
471         bool include_uname;
472 
473 public:
474     /**
475     The initialization method of this class gathers information from the
476     available data sources, and stores that in private instance attributes.
477     Subsequent access to the information items uses these private instance
478     attributes, so that the data sources are read only once.
479     Parameters:
480     * ``include_lsb`` (bool): Controls whether the
481       `lsb_release command output`_ is included as a data source.
482       If the lsb_release command is not available in the program execution
483       path, the data source for the lsb_release command will be empty.
484     * ``os_release_file`` (string): The path name of the
485       `os-release file`_ that is to be used as a data source.
486       An empty string (the default) will cause the default path name to
487       be used (see `os-release file`_ for details).
488       If the specified or defaulted os-release file does not exist, the
489       data source for the os-release file will be empty.
490     * ``distro_release_file`` (string): The path name of the
491       `distro release file`_ that is to be used as a data source.
492       An empty string (the default) will cause a default search algorithm
493       to be used (see `distro release file`_ for details).
494       If the specified distro release file does not exist, or if no default
495       distro release file can be found, the data source for the distro
496       release file will be empty.
497     * ``include_name`` (bool): Controls whether uname command output is
498       included as a data source. If the uname command is not available in
499       the program execution path the data source for the uname command will
500       be empty.
501     Public instance attributes:
502     * ``os_release_file`` (string): The path name of the
503       `os-release file`_ that is actually used as a data source. The
504       empty string if no distro release file is used as a data source.
505     * ``distro_release_file`` (string): The path name of the
506       `distro release file`_ that is actually used as a data source. The
507       empty string if no distro release file is used as a data source.
508     * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.
509       This controls whether the lsb information will be loaded.
510     * ``include_uname`` (bool): The result of the ``include_uname``
511       parameter. This controls whether the uname information will
512       be loaded.
513     Raises:
514     * :py:exc:`IOError`: Some I/O issue with an os-release file or distro
515       release file.
516     * :py:exc:`subprocess.CalledProcessError`: The lsb_release command had
517       some issue (other than not being available in the program execution
518       path).
519     * :py:exc:`UnicodeError`: A data source has unexpected characters or
520       uses an unexpected encoding.
521     */
522     static LinuxDistribution create(bool include_lsb=true,
523                                     string os_release_file="",
524                                     string distro_release_file="",
525                                     bool include_uname=true)
526     {
527         LinuxDistribution d;
528 
529         d.os_release_file = os_release_file != "" ? os_release_file :
530             buildPath(_UNIXCONFDIR, _OS_RELEASE_BASENAME.text); // TODO
531         d.distro_release_file = distro_release_file; // updated later
532         d.include_lsb = include_lsb;
533         d.include_uname = include_uname;
534 
535         return d;
536     }
537 
538     /**
539     Return repr of all info
540     */
541     dstring toString() {
542         return
543             format!(
544                 "LinuxDistribution("d ~
545                 "os_release_file=%s, "d ~
546                 "distro_release_file=%s, "d ~
547                 "include_lsb=%s, "d ~
548                 "include_uname=%s, "d ~
549                 "_os_release_info=%s, "d ~
550                 "_lsb_release_info=%s, "d ~
551                 "_distro_release_info=%s, "d ~
552                 "_uname_info=%s)"d)(
553                 os_release_file,
554                 distro_release_file,
555                 include_lsb,
556                 include_uname,
557                 _os_release_info,
558                 _lsb_release_info,
559                 _distro_release_info,
560                 _uname_info);
561     }
562 
563     /**
564     Return information about the OS distribution that is compatible
565     with Python's :func:`platform.linux_distribution`, supporting a subset
566     of its parameters.
567     For details, see :func:`distro.linux_distribution`.
568     */
569     auto linux_distribution(bool full_distribution_name=true) {
570         return tuple(
571             full_distribution_name ? name : id,
572             version_,
573             codename
574         );
575     }
576 
577     /**
578     Return the distro ID of the OS distribution, as a string.
579     For details, see :func:`distro.id`.
580     */
581     dstring id() {
582         dstring normalize(const dstring distro_id, const dstring[dstring] table) {
583             immutable dstring distro_id2 = distro_id.toLower.replace(" "d, "_"d);
584             return table.get(distro_id2, distro_id2);
585         }
586 
587         // Translation table for normalizing the "Distributor ID" attribute returned by
588         // the lsb_release command, for use by the :func:`distro.id` method.
589         //
590         // * Key: Value as returned by the lsb_release command, translated to lower
591         //   case, with blanks translated to underscores.
592         //
593         // * Value: Normalized value.
594         immutable NORMALIZED_LSB_ID = [
595             "enterpriseenterprise"d: "oracle"d,  // Oracle Enterprise Linux
596             "redhatenterpriseworkstation"d: "rhel"d,  // RHEL 6, 7 Workstation
597             "redhatenterpriseserver"d: "rhel"d,  // RHEL 6, 7 Server
598         ];
599 
600         // Translation table for normalizing the distro ID derived from the file name
601         // of distro release files, for use by the :func:`distro.id` method.
602         //
603         // * Key: Value as derived from the file name of a distro release file,
604         //   translated to lower case, with blanks translated to underscores.
605         //
606         // * Value: Normalized value.
607         dstring[dstring] NORMALIZED_DISTRO_ID = [
608             "redhat"d: "rhel"d,  // RHEL 6.x, 7.x
609         ];
610 
611         dstring distro_id;
612 
613         distro_id = os_release_attr("id");
614         if (distro_id)
615             return normalize(distro_id, NORMALIZED_OS_ID);
616 
617         distro_id = lsb_release_attr("distributor_id");
618         if (distro_id)
619             return normalize(distro_id, NORMALIZED_LSB_ID);
620 
621         distro_id = distro_release_attr("id");
622         if (distro_id)
623             return normalize(distro_id, NORMALIZED_DISTRO_ID);
624 
625         distro_id = uname_attr("id");
626         if (distro_id)
627             return normalize(distro_id, NORMALIZED_DISTRO_ID);
628 
629         return "";
630     }
631 
632     /**
633     Return the name of the OS distribution, as a string.
634     For details, see :func:`distro.name`.
635     */
636     dstring name(bool pretty=false) {
637         dstring name;
638         name = os_release_attr("name");
639         if (name.empty) {
640             name = lsb_release_attr("distributor_id");
641             if (name.empty) {
642                 name = distro_release_attr("name");
643                 if (name.empty) {
644                     name = uname_attr("name");
645                 }
646             }
647         }
648         if (pretty) {
649             name = os_release_attr("pretty_name");
650             if (name.empty) {
651                 name = lsb_release_attr("description");
652             }
653             if (name.empty) {
654                 name = distro_release_attr("name");
655                 if (name.empty) {
656                     name = uname_attr("name");
657                 }
658                 immutable version_ = this.version_(true);
659                 if (version_)
660                     name = name ~ ' ' ~ version_;
661             }
662         }
663         return name;
664     }
665 
666     /**
667     Return the version of the OS distribution, as a string.
668     For details, see :func:`distro.version`.
669     */
670     dstring version_(bool pretty=false, bool best=false) {
671         auto versions = [
672             os_release_attr("version_id"),
673             lsb_release_attr("release"),
674             distro_release_attr("version_id"),
675             _parse_distro_release_content(
676                 os_release_attr("pretty_name")).get("version_id", ""),
677             _parse_distro_release_content(
678                 lsb_release_attr("description")).get("version_id", ""),
679             uname_attr("release"),
680         ];
681         dstring version_;
682         if (best) {
683             // This algorithm uses the last version in priority order that has
684             // the best precision. If the versions are not in conflict, that
685             // does not matter; otherwise, using the last one instead of the
686             // first one might be considered a surprise.
687             foreach (v; versions) {
688                 if (v.count('.') > version_.count('.') || version_.empty)
689                     version_ = v;
690             }
691         } else {
692             foreach (v; versions) {
693                 if (!v.empty) {
694                     version_ = v;
695                     break;
696                 }
697             }
698         }
699         if (pretty && !version_.empty && !codename.empty)
700             version_ = "%s (%s)"d.format(version_, codename);
701         return version_;
702     }
703 
704     /**
705     Return the version of the OS distribution, as a tuple of version
706     numbers.
707     For details, see :func:`distro.version_parts`.
708     */
709     auto version_parts(bool best=false) {
710         immutable dstring version_str = version_(false, best);
711         if (!version_str.empty) {
712             auto version_regex = regex(r"(\d+)\.?(\d+)?\.?(\d+)?"d);
713             auto matches = version_str.matchAll(version_regex);
714             if (matches) {
715                 // can be simplified using https://bitbucket.org/infognition/dstuff/src or https://code.dlang.org/packages/vest
716                 dstring major = matches.front.hit;
717                 matches.popFront();
718                 dstring minor = matches.front.hit;
719                 matches.popFront();
720                 dstring build_number = matches.front.hit;
721                 //matches.popFront();
722                 return tuple(major, minor, build_number);
723             }
724         }
725         return tuple(""d, ""d, ""d);
726     }
727 
728     /**
729     Return the major version number of the current distribution.
730     For details, see :func:`distro.major_version`.
731     */
732     dstring major_version(bool best=false) {
733         return version_parts(best)[0];
734     }
735 
736     /**
737     Return the minor version number of the current distribution.
738     For details, see :func:`distro.minor_version`.
739     */
740     dstring minor_version(bool best=false) {
741         return version_parts(best)[1];
742     }
743 
744     /**
745     Return the build number of the current distribution.
746     For details, see :func:`distro.build_number`.
747     */
748     dstring build_number(bool best=false) {
749         return version_parts(best)[2];
750     }
751 
752     /**
753     Return the IDs of distributions that are like the OS distribution.
754     For details, see :func:`distro.like`.
755     */
756     dstring like() {
757         return os_release_attr("id_like");
758     }
759 
760     /**
761     Return the codename of the OS distribution.
762     For details, see :func:`distro.codename`.
763     */
764     dstring codename() {
765         dstring codename;
766         codename = os_release_attr("codename");
767         if (!codename.empty) return codename;
768         codename = lsb_release_attr("codename");
769         if (!codename.empty) return codename;
770         codename = distro_release_attr("codename");
771         if (!codename.empty) return codename;
772         return "";
773     }
774 
775     struct VersionInfo {
776         dstring id, version_, like, codename;
777         Tuple!(dstring, "major", dstring, "minor", dstring, "build_number") version_parts;
778     }
779 
780     /**
781     Return certain machine-readable information about the OS
782     distribution.
783     For details, see :func:`distro.info`.
784     */
785     VersionInfo info(bool pretty=false, bool best=false) {
786         Tuple!(dstring, "major", dstring, "minor", dstring, "build_number") version_parts = tuple(
787             /*major:*/ major_version(best),
788             /*minor:*/ minor_version(best),
789             /*build_number:*/ build_number(best)
790         );
791         return VersionInfo(
792             /*id:*/ id(),
793             /*version_:*/ version_(pretty, best),
794             /*like:*/ like(),
795             /*codename:*/ codename(),
796             /*version_parts:*/ version_parts,
797         );
798     }
799 
800     /**
801     Return a dictionary containing key-value pairs for the information
802     items from the os-release file data source of the OS distribution.
803     For details, see :func:`distro.os_release_info`.
804     */
805     dstring[dstring] os_release_info() {
806         return _os_release_info;
807     }
808 
809     /**
810     Return a dictionary containing key-value pairs for the information
811     items from the lsb_release command data source of the OS
812     distribution.
813     For details, see :func:`distro.lsb_release_info`.
814     */
815     dstring[dstring] lsb_release_info() {
816         return _lsb_release_info;
817     }
818 
819     /**
820     Return a dictionary containing key-value pairs for the information
821     items from the distro release file data source of the OS
822     distribution.
823     For details, see :func:`distro.distro_release_info`.
824     */
825     dstring[dstring] distro_release_info() {
826         return _distro_release_info;
827     }
828 
829     /**
830     Return a dictionary containing key-value pairs for the information
831     items from the uname command data source of the OS distribution.
832     For details, see :func:`distro.uname_info`.
833     */
834     auto uname_info() {
835         return _uname_info;
836     }
837 
838     /**
839     Return a single named information item from the os-release file data
840     source of the OS distribution.
841     For details, see :func:`distro.os_release_attr`.
842     */
843     dstring os_release_attr(dstring attribute) {
844         return _os_release_info.get(attribute, "");
845     }
846 
847     /**
848     Return a single named information item from the lsb_release command
849     output data source of the OS distribution.
850     For details, see :func:`distro.lsb_release_attr`.
851     */
852     dstring lsb_release_attr(dstring attribute) {
853         return _lsb_release_info.get(attribute, "");
854     }
855 
856     /**
857     Return a single named information item from the distro release file
858     data source of the OS distribution.
859     For details, see :func:`distro.distro_release_attr`.
860     */
861     dstring distro_release_attr(dstring attribute) {
862         return _distro_release_info.get(attribute, "");
863     }
864 
865     /**
866     Return a single named information item from the uname command
867     output data source of the OS distribution.
868     For details, see :func:`distro.uname_release_attr`.
869     */
870     dstring uname_attr(dstring attribute) {
871         return _uname_info.get(attribute, "");
872     }
873 
874     /**
875     Get the information items from the specified os-release file.
876     Returns:
877         A dictionary containing all information items.
878     */
879     @property dstring[dstring] _os_release_info_impl() {
880         if (std.file.isFile(os_release_file)) {
881             scope auto release_file = File(os_release_file);
882             return _parse_os_release_content(map!dtext(release_file.byLine).array); // TODO: efficiency
883         }
884         return null;
885     }
886     mixin Cached!("_os_release_info", "_os_release_info_impl");
887 
888     /**
889     Parse the lines of an os-release file.
890     Parameters:
891     * lines: Iterable through the lines in the os-release file.
892     Returns:
893         A dictionary containing all information items.
894     */
895     static dstring[dstring] _parse_os_release_content(const dstring[] lines) {
896         dstring[dstring] props;
897 
898         auto provider = new ShlexProviderStream!(dchar[]).ShlexProvider;
899         auto stream = lines.join('\n').dup; // TODO: Deal with lines correctly
900         ShlexProviderStream!(dchar[]).ShlexParams.WithDefaults params = {
901             instream: stream, posix: Shlex.Posix.yes, whitespaceSplit: true};
902         Shlex *lexer = provider.callWithDefaults(params);
903 
904         foreach(ctoken; *lexer) {
905             // At this point, all shell-like parsing has been done (i.e.
906             // comments processed, quotes and backslash escape sequences
907             // processed, multi-line values assembled, trailing newlines
908             // stripped, etc.), so the tokens are now either:
909             // * variable assignments: var=value
910             // * commands or their arguments (not allowed in os-release)
911             immutable token = ctoken.dtext;
912             if(token.canFind('=')) {
913                 immutable eqPosition = token.countUntil("=");
914                 immutable k = token[0..eqPosition];
915                 immutable v = token[eqPosition+1..$];
916                 props[k.toLower()] = v;
917                 if(k == "VERSION") {
918                     // this handles cases in which the codename is in
919                     // the `(CODENAME)` (rhel, centos, fedora) format
920                     // or in the `, CODENAME` format (Ubuntu).
921                     static immutable ourRegex = regex(r"(\(\D+\))|,(\s+)?\D+"d);
922                     auto codenameMatch = matchFirst(v, ourRegex);
923                     if(!codenameMatch.empty) {
924                         auto codename = codenameMatch[0];
925                         codename = codename.strip("()"d);
926                         codename = codename.strip(","d);
927                         codename = codename.strip();
928                         // codename appears within paranthese.
929                         props["codename"] = codename;
930                     } else {
931                         props["codename"] = "";
932                     }
933                 }
934             } else {
935                 // Ignore any tokens that are not variable assignments
936             }
937         }
938         return props;
939     }
940 
941     /**
942     Get the information items from the lsb_release command output.
943     Returns:
944         A dictionary containing all information items.
945     */
946     @property dstring[dstring] _lsb_release_info_impl() {
947         if(!include_lsb) return null;
948         immutable response = execute(["lsb_release", "-a"]);
949         if(response.status != 0) return null;
950         immutable stdout = response.output;
951         return _parse_lsb_release_content(map!dtext(stdout.splitLines).array); // TODO: in Python stdout.decode(sys.getfilesystemencoding()) // TODO: efficiency
952     }
953     mixin Cached!("_lsb_release_info", "_lsb_release_info_impl");
954 
955     /**
956     Parse the output of the lsb_release command.
957     Parameters:
958     * lines: Iterable through the lines of the lsb_release output.
959                 Each line must be a unicode string or a UTF-8 encoded byte
960                 string.
961     Returns:
962         A dictionary containing all information items.
963     */
964     static dstring[dstring] _parse_lsb_release_content(const dstring[] lines) {
965         dstring[dstring] props;
966         foreach(immutable line; lines) {
967             immutable line2 = line.strip("\n"d);
968             if(!line2.canFind(':')) continue;
969             immutable colonPosition = line2.countUntil(":");
970             immutable k = line2[0..colonPosition];
971             immutable v = line2[colonPosition+1..$];
972             props[k.replace(" "d, "_"d).toLower()] = v.strip();
973         }
974         return props;
975     }
976 
977     @property dstring[dstring] _uname_info_impl() {
978         immutable response = execute(["uname", "-rs"]);
979         if(response.status != 0) return null;
980         immutable stdout = response.output;
981         return _parse_uname_content(map!dtext(stdout.splitLines).array); // TODO: stdout.decode(sys.getfilesystemencoding()) in Python // TODO: efficiency
982     }
983     mixin Cached!("_uname_info", "_uname_info_impl");
984 
985     static dstring[dstring] _parse_uname_content(dstring[] lines) {
986         dstring[dstring] props;
987         static immutable r = regex(r"^([^\s]+)\s+([\d\.]+)"d);
988         auto match = matchFirst(lines[0].strip(), r); // FIXME: What if there is zero lines? (Also submit bug to Python?)
989         if(!match.empty) {
990             immutable name = match[1];
991             immutable version_ = match[2];
992 
993             // This is to prevent the Linux kernel version from
994             // appearing as the 'best' version on otherwise
995             // identifiable distributions.
996             if(name == "Linux") return null;
997             props["id"] = name.toLower();
998             props["name"] = name;
999             props["release"] = version_;
1000         }
1001         return props;
1002     }
1003 
1004     /**
1005     Get the information items from the specified distro release file.
1006     Returns:
1007         A dictionary containing all information items.
1008     */
1009     @property dstring[dstring] _distro_release_info_impl() {
1010         if(!distro_release_file.empty) {
1011             // If it was specified, we use it and parse what we can, even if
1012             // its file name or content does not match the expected pattern.
1013             auto distro_info = _parse_distro_release_file(distro_release_file);
1014             immutable basename = baseName(distro_release_file).dtext;
1015             // The file name pattern for user-specified distro release files
1016             // is somewhat more tolerant (compared to when searching for the
1017             // file), because we want to use what was specified as best as
1018             // possible.
1019             auto match = basename.matchFirst(_DISTRO_RELEASE_BASENAME_PATTERN);
1020             if(!match.empty) distro_info["id"] = match[1];
1021             return distro_info;
1022         } else {
1023             dstring[] basenames;
1024             try {
1025                 basenames = map!"a.name.dtext"(dirEntries(_UNIXCONFDIR, SpanMode.shallow)).array; // TODO: Is it path or full path?
1026                 // We sort for repeatability in cases where there are multiple
1027                 // distro specific files; e.g. CentOS, Oracle, Enterprise all
1028                 // containing `redhat-release` on top of their own.
1029                 basenames.sort();
1030             }
1031             catch(FileException) {
1032                 // This may occur when /etc is not readable but we can't be
1033                 // sure about the *-release files. Check common entries of
1034                 // /etc for information. If they turn out to not be there the
1035                 // error is handled in `_parse_distro_release_file()`.
1036                 basenames = ["SuSE-release"d,
1037                              "arch-release"d,
1038                              "base-release"d,
1039                              "centos-release"d,
1040                              "fedora-release"d,
1041                              "gentoo-release"d,
1042                              "mageia-release"d,
1043                              "mandrake-release"d,
1044                              "mandriva-release"d,
1045                              "mandrivalinux-release"d,
1046                              "manjaro-release"d,
1047                              "oracle-release"d,
1048                              "redhat-release"d,
1049                              "sl-release"d,
1050                              "slackware-version"d];
1051             }
1052             foreach(immutable basename; basenames) {
1053                 if(_DISTRO_RELEASE_IGNORE_BASENAMES.canFind(basename)) continue;
1054                 auto match = basename.matchFirst(_DISTRO_RELEASE_BASENAME_PATTERN);
1055                 if(!match.empty) {
1056                     immutable filepath = chainPath(_UNIXCONFDIR, basename);
1057                     auto distro_info = _parse_distro_release_file(filepath.text);
1058                     if("name" in distro_info) {
1059                         // The name is always present if the pattern matches
1060                         distro_release_file = filepath.text;
1061                         distro_info["id"] = match[1];
1062                         return distro_info;
1063                     }
1064                 }
1065             }
1066             return null;
1067         }
1068     }
1069     mixin Cached!("_distro_release_info", "_distro_release_info_impl");
1070 
1071     /**
1072     Parse a distro release file.
1073     Parameters:
1074     * filepath: Path name of the distro release file.
1075     Returns:
1076         A dictionary containing all information items.
1077     */
1078     dstring[dstring] _parse_distro_release_file(string filepath) {
1079         try {
1080             scope fp = File(filepath);
1081             // Only parse the first line. For instance, on SLES there
1082             // are multiple lines. We don't want them...
1083             return _parse_distro_release_content(fp.readln().dtext);
1084         }
1085         // Ignore not being able to read a specific, seemingly version
1086         // related file.
1087         // See https://github.com/nir0s/distro/issues/162
1088         catch(ErrnoException) {
1089             return null;
1090         }
1091         catch(StdioException) {
1092             return null;
1093         }
1094     }
1095 
1096     /**
1097     Parse a line from a distro release file.
1098     Parameters:
1099     * line: Line from the distro release file. Must be a unicode string
1100             or a UTF-8 encoded byte string.
1101     Returns:
1102         A dictionary containing all information items.
1103     */
1104     static dstring[dstring] _parse_distro_release_content(const dstring line) {
1105         auto matches = line.strip.retro.dtext.matchFirst(_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN);
1106         dstring[dstring] distro_info;
1107         if(!matches.empty) {
1108             // regexp ensures non-None
1109             distro_info["name"] = matches[3].retro.array;
1110             if(matches[2])
1111                 distro_info["version_id"] = matches[2].retro.array;
1112             if(matches[1])
1113                 distro_info["codename"] = matches[1].retro.array;
1114         } else if(!line.empty)
1115             distro_info["name"] = line.strip;
1116         return distro_info;
1117     }
1118 }
1119 
1120 /** TODO: Remove this as a global initilization? */
1121 auto _distro = LinuxDistribution.create(); // TODO: Can we make it immutable?