raphinesse commented on a change in pull request #1130:
URL: https://github.com/apache/cordova-android/pull/1130#discussion_r528391145



##########
File path: bin/templates/cordova/lib/Java.js
##########
@@ -0,0 +1,157 @@
+/*
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+*/
+
+const execa = require('execa');
+const fs = require('fs-extra');
+const path = require('path');
+const glob = require('fast-glob');
+const { CordovaError, events } = require('cordova-common');
+const utils = require('./utils');
+
+let javaIsEnsured = false;
+
+module.exports = class Java {
+    /**
+     * Gets the version from the javac executable.
+     * @returns {Object}
+     * {
+     *      major: number
+     *      minor: number
+     *      patch: number
+     *      build: number
+     * }
+     */
+    static async getVersion () {
+        await Java._ensure();
+
+        // Java <= 8 writes version info to stderr, Java >= 9 to stdout
+        let version = null;
+        try {
+            version = (await execa('javac', ['-version'], { all: true })).all;
+        } catch (ex) {
+            events.emit('verbose', ex.shortMessage);
+
+            let msg =
+            'Failed to run "javac -version", make sure that you have a JDK 
version 8 installed.\n' +
+            'You can get it from the following location:\n' +
+            
'https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html';
+            if (process.env.JAVA_HOME) {
+                msg += '\n\n';
+                msg += 'Your JAVA_HOME is invalid: ' + process.env.JAVA_HOME;
+            }
+            throw new CordovaError(msg);
+        }
+
+        return Java._parseVersion(version);
+    }
+
+    /**
+     * Parses a java version output, ie: "javac 1.8.0_275"
+     *
+     * @param {String} version
+     * @returns {Object}
+     * {
+     *      major: number
+     *      minor: number
+     *      patch: number
+     *      build: number
+     * }
+     */
+    static _parseVersion (version) {
+        version = version.replace('javac ', '');
+
+        const mainParts = version.split('.');
+
+        const output = {
+            major: parseInt(mainParts[0]),
+            minor: parseInt(mainParts[1]),
+            patch: null,
+            build: null,
+            string: version
+        };
+
+        const buildParts = mainParts[2].split('_');
+        output.patch = parseInt(buildParts[0]);
+        output.build = parseInt(buildParts[1]);
+
+        return output;
+    }
+
+    /**
+     * Ensures that Java is installed. Will throw exception if not.
+     * Will set JAVA_HOME and PATH environment variables.
+     *
+     * This function becomes a no-op if already ran previously.
+     */
+    static async _ensure () {
+        if (javaIsEnsured) {
+            return;
+        }
+
+        const javacPath = utils.forgivingWhichSync('javac');
+        const hasJavaHome = !!process.env.JAVA_HOME;
+        if (hasJavaHome) {
+            // Windows java installer doesn't add javac to PATH, nor set 
JAVA_HOME (ugh).
+            if (!javacPath) {
+                process.env.PATH += path.delimiter + 
path.join(process.env.JAVA_HOME, 'bin');
+            }
+        } else {
+            if (javacPath) {
+                // OS X has a command for finding JAVA_HOME.
+                const find_java = '/usr/libexec/java_home';
+                const default_java_error_msg = 'Failed to find \'JAVA_HOME\' 
environment variable. Try setting it manually.';
+                if (fs.existsSync(find_java)) {
+                    try {
+                        process.env.JAVA_HOME = (await 
execa(find_java)).stdout;
+                        console.log('JAVA HOME', process.env.JAVA_HOME);

Review comment:
       This looks like leftover debug output to me
   ```suggestion
   ```

##########
File path: spec/unit/Java.spec.js
##########
@@ -0,0 +1,158 @@
+/**
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+*/
+
+const path = require('path');
+const rewire = require('rewire');
+const { CordovaError } = require('cordova-common');
+const utils = require('../../bin/templates/cordova/lib/utils');
+
+describe('Java', () => {
+    const Java = rewire('../../bin/templates/cordova/lib/Java');
+    let originalEnv = null;
+
+    beforeAll(() => {
+        originalEnv = Object.assign({}, process.env);
+    });
+
+    afterAll(() => {
+        process.env = Object.assign({}, originalEnv);
+    });
+
+    describe('getVersion', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+        });
+
+        it('runs', async () => {
+            Java.__set__('execa', () => Promise.resolve({
+                all: 'javac 1.8.0_275'
+            }));
+
+            const versionObj = {
+                major: 1,
+                minor: 8,
+                patch: 0,
+                build: 275,
+                string: '1.8.0_275'
+            };
+
+            await expectAsync(Java.getVersion()).toBeResolvedTo(versionObj);
+        });
+
+        it('produces a CordovaError on error', async () => {
+            Java.__set__('execa', () => Promise.reject({
+                shortMessage: 'test error'
+            }));
+            const emitSpy = jasmine.createSpy('events.emit');
+            Java.__set__('events', {
+                emit: emitSpy
+            });
+
+            await 
expectAsync(Java.getVersion()).toBeRejectedWithError(CordovaError, /Failed to 
run "javac -version"/);
+            expect(emitSpy).toHaveBeenCalledWith('verbose', 'test error');
+        });
+    });
+
+    describe('_ensure', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+            Java.__set__('javaIsEnsured', false);
+        });
+
+        it('with JAVA_HOME / without javac', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('');
+            process.env.JAVA_HOME = '/tmp/jdk';
+
+            await Java._ensure();
+
+            expect(process.env.PATH.split(path.delimiter))
+                .toContain(path.join(process.env.JAVA_HOME, 'bin'));
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - success', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            const fsSpy = jasmine.createSpy('fs').and.returnValue(true);
+            Java.__set__('fs', {
+                existsSync: fsSpy
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.resolve({
+                stdout: '/tmp/jdk'
+            })));

Review comment:
       If we do not use the features of Jasmine spies, I would prefer using 
plain JS function as test-fakes. It makes for far less verbose code IMHO.
   ```suggestion
               Java.__set__('execa', async () => ({ stdout: '/tmp/jdk' }));
   ```
   
   This might be a matter of taste of course.

##########
File path: spec/unit/Java.spec.js
##########
@@ -0,0 +1,158 @@
+/**
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+*/
+
+const path = require('path');
+const rewire = require('rewire');
+const { CordovaError } = require('cordova-common');
+const utils = require('../../bin/templates/cordova/lib/utils');
+
+describe('Java', () => {
+    const Java = rewire('../../bin/templates/cordova/lib/Java');
+    let originalEnv = null;
+
+    beforeAll(() => {
+        originalEnv = Object.assign({}, process.env);
+    });
+
+    afterAll(() => {
+        process.env = Object.assign({}, originalEnv);
+    });
+
+    describe('getVersion', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+        });
+
+        it('runs', async () => {
+            Java.__set__('execa', () => Promise.resolve({
+                all: 'javac 1.8.0_275'
+            }));
+
+            const versionObj = {
+                major: 1,
+                minor: 8,
+                patch: 0,
+                build: 275,
+                string: '1.8.0_275'
+            };
+
+            await expectAsync(Java.getVersion()).toBeResolvedTo(versionObj);
+        });
+
+        it('produces a CordovaError on error', async () => {
+            Java.__set__('execa', () => Promise.reject({
+                shortMessage: 'test error'
+            }));
+            const emitSpy = jasmine.createSpy('events.emit');
+            Java.__set__('events', {
+                emit: emitSpy
+            });
+
+            await 
expectAsync(Java.getVersion()).toBeRejectedWithError(CordovaError, /Failed to 
run "javac -version"/);
+            expect(emitSpy).toHaveBeenCalledWith('verbose', 'test error');
+        });
+    });
+
+    describe('_ensure', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+            Java.__set__('javaIsEnsured', false);
+        });
+
+        it('with JAVA_HOME / without javac', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('');
+            process.env.JAVA_HOME = '/tmp/jdk';
+
+            await Java._ensure();
+
+            expect(process.env.PATH.split(path.delimiter))
+                .toContain(path.join(process.env.JAVA_HOME, 'bin'));
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - success', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            const fsSpy = jasmine.createSpy('fs').and.returnValue(true);
+            Java.__set__('fs', {
+                existsSync: fsSpy
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.resolve({
+                stdout: '/tmp/jdk'
+            })));
+
+            await Java._ensure();
+
+            expect(fsSpy).toHaveBeenCalledWith('/usr/libexec/java_home');
+            expect(process.env.JAVA_HOME).toBe('/tmp/jdk');
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - error', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            Java.__set__('fs', {
+                existsSync: jasmine.createSpy('fs').and.returnValue(true)
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.reject({
+                shortMessage: 'test error'
+            })));

Review comment:
       Latest jasmine also has special promise strategies:
   ```suggestion
               Java.__set__('execa', jasmine.createSpy('execa').and.rejectWith({
                   shortMessage: 'test error'
               }));
   ```

##########
File path: bin/templates/cordova/lib/Java.js
##########
@@ -0,0 +1,157 @@
+/*
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+*/
+
+const execa = require('execa');
+const fs = require('fs-extra');
+const path = require('path');
+const glob = require('fast-glob');
+const { CordovaError, events } = require('cordova-common');
+const utils = require('./utils');
+
+let javaIsEnsured = false;
+
+module.exports = class Java {
+    /**
+     * Gets the version from the javac executable.
+     * @returns {Object}
+     * {
+     *      major: number
+     *      minor: number
+     *      patch: number
+     *      build: number
+     * }
+     */
+    static async getVersion () {
+        await Java._ensure();
+
+        // Java <= 8 writes version info to stderr, Java >= 9 to stdout
+        let version = null;
+        try {
+            version = (await execa('javac', ['-version'], { all: true })).all;
+        } catch (ex) {
+            events.emit('verbose', ex.shortMessage);
+
+            let msg =
+            'Failed to run "javac -version", make sure that you have a JDK 
version 8 installed.\n' +
+            'You can get it from the following location:\n' +
+            
'https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html';
+            if (process.env.JAVA_HOME) {
+                msg += '\n\n';
+                msg += 'Your JAVA_HOME is invalid: ' + process.env.JAVA_HOME;
+            }
+            throw new CordovaError(msg);
+        }
+
+        return Java._parseVersion(version);
+    }
+
+    /**
+     * Parses a java version output, ie: "javac 1.8.0_275"
+     *
+     * @param {String} version
+     * @returns {Object}
+     * {
+     *      major: number
+     *      minor: number
+     *      patch: number
+     *      build: number
+     * }
+     */
+    static _parseVersion (version) {
+        version = version.replace('javac ', '');
+
+        const mainParts = version.split('.');
+
+        const output = {
+            major: parseInt(mainParts[0]),
+            minor: parseInt(mainParts[1]),
+            patch: null,
+            build: null,
+            string: version
+        };
+
+        const buildParts = mainParts[2].split('_');
+        output.patch = parseInt(buildParts[0]);
+        output.build = parseInt(buildParts[1]);
+
+        return output;
+    }
+
+    /**
+     * Ensures that Java is installed. Will throw exception if not.
+     * Will set JAVA_HOME and PATH environment variables.
+     *
+     * This function becomes a no-op if already ran previously.
+     */
+    static async _ensure () {
+        if (javaIsEnsured) {
+            return;
+        }
+
+        const javacPath = utils.forgivingWhichSync('javac');
+        const hasJavaHome = !!process.env.JAVA_HOME;
+        if (hasJavaHome) {
+            // Windows java installer doesn't add javac to PATH, nor set 
JAVA_HOME (ugh).
+            if (!javacPath) {
+                process.env.PATH += path.delimiter + 
path.join(process.env.JAVA_HOME, 'bin');
+            }
+        } else {
+            if (javacPath) {
+                // OS X has a command for finding JAVA_HOME.
+                const find_java = '/usr/libexec/java_home';
+                const default_java_error_msg = 'Failed to find \'JAVA_HOME\' 
environment variable. Try setting it manually.';
+                if (fs.existsSync(find_java)) {
+                    try {
+                        process.env.JAVA_HOME = (await 
execa(find_java)).stdout;
+                        console.log('JAVA HOME', process.env.JAVA_HOME);
+                    } catch (ex) {
+                        if (ex) {
+                            events.emit('verbose', ex.shortMessage);
+                        }

Review comment:
       I know that the original version had this if-clause too, but according 
to the `execa` docs, `ex` should always be a `childProcessResult` and thus 
truthy. So I would suggest to use 
   ```suggestion
                           events.emit('verbose', ex.shortMessage);
   ```

##########
File path: spec/unit/Java.spec.js
##########
@@ -0,0 +1,158 @@
+/**
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+*/
+
+const path = require('path');
+const rewire = require('rewire');
+const { CordovaError } = require('cordova-common');
+const utils = require('../../bin/templates/cordova/lib/utils');
+
+describe('Java', () => {
+    const Java = rewire('../../bin/templates/cordova/lib/Java');
+    let originalEnv = null;
+
+    beforeAll(() => {
+        originalEnv = Object.assign({}, process.env);
+    });
+
+    afterAll(() => {
+        process.env = Object.assign({}, originalEnv);
+    });
+
+    describe('getVersion', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+        });
+
+        it('runs', async () => {
+            Java.__set__('execa', () => Promise.resolve({
+                all: 'javac 1.8.0_275'
+            }));
+
+            const versionObj = {
+                major: 1,
+                minor: 8,
+                patch: 0,
+                build: 275,
+                string: '1.8.0_275'
+            };
+
+            await expectAsync(Java.getVersion()).toBeResolvedTo(versionObj);
+        });
+
+        it('produces a CordovaError on error', async () => {
+            Java.__set__('execa', () => Promise.reject({
+                shortMessage: 'test error'
+            }));
+            const emitSpy = jasmine.createSpy('events.emit');
+            Java.__set__('events', {
+                emit: emitSpy
+            });
+
+            await 
expectAsync(Java.getVersion()).toBeRejectedWithError(CordovaError, /Failed to 
run "javac -version"/);
+            expect(emitSpy).toHaveBeenCalledWith('verbose', 'test error');
+        });
+    });
+
+    describe('_ensure', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+            Java.__set__('javaIsEnsured', false);
+        });
+
+        it('with JAVA_HOME / without javac', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('');
+            process.env.JAVA_HOME = '/tmp/jdk';
+
+            await Java._ensure();
+
+            expect(process.env.PATH.split(path.delimiter))
+                .toContain(path.join(process.env.JAVA_HOME, 'bin'));
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - success', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            const fsSpy = jasmine.createSpy('fs').and.returnValue(true);
+            Java.__set__('fs', {
+                existsSync: fsSpy
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.resolve({
+                stdout: '/tmp/jdk'
+            })));
+
+            await Java._ensure();
+
+            expect(fsSpy).toHaveBeenCalledWith('/usr/libexec/java_home');
+            expect(process.env.JAVA_HOME).toBe('/tmp/jdk');
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - error', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            Java.__set__('fs', {
+                existsSync: jasmine.createSpy('fs').and.returnValue(true)
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.reject({
+                shortMessage: 'test error'
+            })));
+            const emitSpy = jasmine.createSpy('events.emit');
+            Java.__set__('events', {
+                emit: emitSpy
+            });
+
+            await 
expectAsync(Java._ensure()).toBeRejectedWithError(CordovaError, /Failed to find 
'JAVA_HOME' environment variable/);
+
+            expect(emitSpy).toHaveBeenCalledWith('verbose', 'test error');
+        });
+
+        it('derive from javac location - success', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            Java.__set__('fs', {
+                existsSync: jasmine.createSpy('fs').and.callFake((path) => {
+                    if (/java_home$/.test(path)) {
+                        return false;
+                    } else {
+                        return true;
+                    }
+                })
+            });

Review comment:
       I would much prefer something a little less verbose here:
   ```suggestion
               Java.__set__('fs', { existsSync: path => 
!/java_home$/.test(path) });
   ```

##########
File path: spec/unit/Java.spec.js
##########
@@ -0,0 +1,158 @@
+/**
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+*/
+
+const path = require('path');
+const rewire = require('rewire');
+const { CordovaError } = require('cordova-common');
+const utils = require('../../bin/templates/cordova/lib/utils');
+
+describe('Java', () => {
+    const Java = rewire('../../bin/templates/cordova/lib/Java');
+    let originalEnv = null;
+
+    beforeAll(() => {
+        originalEnv = Object.assign({}, process.env);
+    });
+
+    afterAll(() => {
+        process.env = Object.assign({}, originalEnv);
+    });
+
+    describe('getVersion', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+        });
+
+        it('runs', async () => {
+            Java.__set__('execa', () => Promise.resolve({
+                all: 'javac 1.8.0_275'
+            }));
+
+            const versionObj = {
+                major: 1,
+                minor: 8,
+                patch: 0,
+                build: 275,
+                string: '1.8.0_275'
+            };
+
+            await expectAsync(Java.getVersion()).toBeResolvedTo(versionObj);
+        });
+
+        it('produces a CordovaError on error', async () => {
+            Java.__set__('execa', () => Promise.reject({
+                shortMessage: 'test error'
+            }));
+            const emitSpy = jasmine.createSpy('events.emit');
+            Java.__set__('events', {
+                emit: emitSpy
+            });
+
+            await 
expectAsync(Java.getVersion()).toBeRejectedWithError(CordovaError, /Failed to 
run "javac -version"/);
+            expect(emitSpy).toHaveBeenCalledWith('verbose', 'test error');
+        });
+    });
+
+    describe('_ensure', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+            Java.__set__('javaIsEnsured', false);
+        });
+
+        it('with JAVA_HOME / without javac', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('');
+            process.env.JAVA_HOME = '/tmp/jdk';
+
+            await Java._ensure();
+
+            expect(process.env.PATH.split(path.delimiter))
+                .toContain(path.join(process.env.JAVA_HOME, 'bin'));
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - success', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            const fsSpy = jasmine.createSpy('fs').and.returnValue(true);
+            Java.__set__('fs', {
+                existsSync: fsSpy
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.resolve({
+                stdout: '/tmp/jdk'
+            })));
+
+            await Java._ensure();
+
+            expect(fsSpy).toHaveBeenCalledWith('/usr/libexec/java_home');
+            expect(process.env.JAVA_HOME).toBe('/tmp/jdk');
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - error', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            Java.__set__('fs', {
+                existsSync: jasmine.createSpy('fs').and.returnValue(true)
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.reject({
+                shortMessage: 'test error'
+            })));
+            const emitSpy = jasmine.createSpy('events.emit');
+            Java.__set__('events', {
+                emit: emitSpy
+            });
+
+            await 
expectAsync(Java._ensure()).toBeRejectedWithError(CordovaError, /Failed to find 
'JAVA_HOME' environment variable/);
+
+            expect(emitSpy).toHaveBeenCalledWith('verbose', 'test error');
+        });
+
+        it('derive from javac location - success', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            Java.__set__('fs', {
+                existsSync: jasmine.createSpy('fs').and.callFake((path) => {
+                    if (/java_home$/.test(path)) {
+                        return false;
+                    } else {
+                        return true;
+                    }
+                })
+            });
+
+            await Java._ensure();
+
+            expect(process.env.JAVA_HOME).toBe('/tmp');
+        });
+
+        it('derive from javac location - error', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            Java.__set__('fs', {
+                existsSync: jasmine.createSpy('fs').and.callFake((path) => {
+                    if (/java_home$/.test(path)) {
+                        return false;
+                    } else {
+                        return false;
+                    }
+                })
+            });

Review comment:
       AFAICT this should be the same fake implementation as above
   ```suggestion
               Java.__set__('fs', { existsSync: path => 
!/java_home$/.test(path) });
   ```

##########
File path: spec/unit/Java.spec.js
##########
@@ -0,0 +1,158 @@
+/**
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+*/
+
+const path = require('path');
+const rewire = require('rewire');
+const { CordovaError } = require('cordova-common');
+const utils = require('../../bin/templates/cordova/lib/utils');
+
+describe('Java', () => {
+    const Java = rewire('../../bin/templates/cordova/lib/Java');
+    let originalEnv = null;
+
+    beforeAll(() => {
+        originalEnv = Object.assign({}, process.env);
+    });
+
+    afterAll(() => {
+        process.env = Object.assign({}, originalEnv);
+    });
+
+    describe('getVersion', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+        });
+
+        it('runs', async () => {
+            Java.__set__('execa', () => Promise.resolve({
+                all: 'javac 1.8.0_275'
+            }));
+
+            const versionObj = {
+                major: 1,
+                minor: 8,
+                patch: 0,
+                build: 275,
+                string: '1.8.0_275'
+            };
+
+            await expectAsync(Java.getVersion()).toBeResolvedTo(versionObj);
+        });
+
+        it('produces a CordovaError on error', async () => {
+            Java.__set__('execa', () => Promise.reject({
+                shortMessage: 'test error'
+            }));
+            const emitSpy = jasmine.createSpy('events.emit');
+            Java.__set__('events', {
+                emit: emitSpy
+            });
+
+            await 
expectAsync(Java.getVersion()).toBeRejectedWithError(CordovaError, /Failed to 
run "javac -version"/);
+            expect(emitSpy).toHaveBeenCalledWith('verbose', 'test error');
+        });
+    });
+
+    describe('_ensure', () => {
+        beforeEach(() => {
+            process.env = Object.assign({}, originalEnv);
+            Java.__set__('javaIsEnsured', false);
+        });
+
+        it('with JAVA_HOME / without javac', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('');
+            process.env.JAVA_HOME = '/tmp/jdk';
+
+            await Java._ensure();
+
+            expect(process.env.PATH.split(path.delimiter))
+                .toContain(path.join(process.env.JAVA_HOME, 'bin'));
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - success', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            const fsSpy = jasmine.createSpy('fs').and.returnValue(true);
+            Java.__set__('fs', {
+                existsSync: fsSpy
+            });
+            Java.__set__('execa', 
jasmine.createSpy('execa').and.returnValue(Promise.resolve({
+                stdout: '/tmp/jdk'
+            })));
+
+            await Java._ensure();
+
+            expect(fsSpy).toHaveBeenCalledWith('/usr/libexec/java_home');
+            expect(process.env.JAVA_HOME).toBe('/tmp/jdk');
+        });
+
+        it('without JAVA_HOME / with javac - Mac OS X - error', async () => {
+            spyOn(utils, 'forgivingWhichSync').and.returnValue('/tmp/jdk/bin');
+            process.env.JAVA_HOME = '';
+            Java.__set__('fs', {
+                existsSync: jasmine.createSpy('fs').and.returnValue(true)
+            });

Review comment:
       Could also be simplified by using plain functions:
   ```suggestion
               Java.__set__('fs', { existsSync: () => true });
   ```

##########
File path: bin/templates/cordova/lib/Java.js
##########
@@ -0,0 +1,157 @@
+/*
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+*/
+
+const execa = require('execa');
+const fs = require('fs-extra');
+const path = require('path');
+const glob = require('fast-glob');
+const { CordovaError, events } = require('cordova-common');
+const utils = require('./utils');
+
+let javaIsEnsured = false;
+
+module.exports = class Java {
+    /**
+     * Gets the version from the javac executable.
+     * @returns {Object}
+     * {
+     *      major: number
+     *      minor: number
+     *      patch: number
+     *      build: number
+     * }
+     */
+    static async getVersion () {
+        await Java._ensure();

Review comment:
       To avoid having to restore the global `process.env` properly 
before/after each test, I would explicitly pass the `env` object to be modified 
into `Java._ensure` like this:
   ```suggestion
           await Java._ensure(process.env);
   ```
   Then tests can just pass fake environments to `_ensure`.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to