diff --git a/index.js b/index.js index b28bd6e..71a7a56 100644 --- a/index.js +++ b/index.js @@ -19,10 +19,36 @@ module.exports = function getOs (cb) { var osName = os.platform() // Linux is a special case. if (osName === 'linux') return getLinuxDistro(cb) + if (osName === 'darwin') return getDarwinVersion(cb) // Else, node's builtin is acceptable. return cb(null, { os: osName }) } +function getDarwinVersion (cb) { + if (cachedDistro) return cb(null, cachedDistro) + var productVersionRegex = /^ProductVersion:\s+(.*)/m + var productNameRegex = /^ProductName:\s+(.*)/m + var exec = require('child_process').exec + + var distro = { os: 'darwin' } + + exec('sw_vers', function (error, stdout, stderr) { + if (error) { + return cb(error, { os: os.platform() }) + } + var productVersion = stdout.match(productVersionRegex) + if (productVersion && productVersion.length === 2) { + distro.release = productVersion[1] + } + var name = stdout.match(productNameRegex) + if (name && name.length === 2) { + distro.name = name[1] + } + cachedDistro = distro + return cb(null, distro) + }) +} + /** * Identify the actual distribution name on a linux box. */ diff --git a/tests/mockdata.json b/tests/mockdata.json index c2c2d66..f731e91 100644 --- a/tests/mockdata.json +++ b/tests/mockdata.json @@ -1,5 +1,5 @@ [ - { "desc": "OS X", "platform": "darwin", "expected": { "os": "darwin" } } + { "desc": "OS X", "platform": "darwin", "exec": { "sw_vers": "ProductName:\tmacOS\nProductVersion:\t11.4\nBuildVersion:\t20F71\n"}, "expected": { "os": "darwin", "release": "11.4", "name": "macOS" } } , { "desc": "Windows", "platform": "win32", "expected": { "os": "win32" } } , { "desc": "Ubuntu 14.10", "platform": "linux", "file": { "/etc/lsb-release": "DISTRIB_ID=Ubuntu\nDISTRIB_RELEASE=14.10\nDISTRIB_CODENAME=utopic\nDISTRIB_DESCRIPTION=\"Ubuntu 14.10\"\n" }, "expected": { "codename": "utopic", "dist": "Ubuntu", "os": "linux", "release": "14.10" } } , { "desc": "Ubuntu 14.04", "platform": "linux", "file": { "/etc/lsb-release": "DISTRIB_ID=Ubuntu\nDISTRIB_RELEASE=14.04\nDISTRIB_CODENAME=trusty\nDISTRIB_DESCRIPTION=\"Ubuntu 14.04.2 LTS\"\n" }, "expected": { "codename": "trusty", "dist": "Ubuntu", "os": "linux", "release": "14.04" } } diff --git a/tests/mocktests.js b/tests/mocktests.js index aa152d7..64806e6 100644 --- a/tests/mocktests.js +++ b/tests/mocktests.js @@ -1,6 +1,7 @@ var test = require('tape') var fs = require('fs') var os = require('os') +var cp = require('child_process') var mockdata = require('./mockdata') var currentData @@ -23,6 +24,13 @@ fs.readFile = function (file, enc, callback) { }) } +cp.exec = function (command, callback) { + process.nextTick(function () { + if (!currentData.exec[command]) { return callback(new Error()) } + callback(null, currentData.exec[command]) + }) +} + mockdata.forEach(function (data) { test('test ' + data.desc, function (t) { // reload each time to avoid internal caching