From 79b62adb054eba277ba42aa88d2d206463c1b918 Mon Sep 17 00:00:00 2001
From: Bryan MacFarlane <bryanmacfarlane@github.com>
Date: Sun, 9 Feb 2020 18:09:15 -0500
Subject: [PATCH] another test and bugs

---
 __tests__/setup-go.test.ts | 61 ++++++++++++++++++++++++++++++--------
 dist/index.js              | 20 +++++++++++--
 package.json               |  2 +-
 src/installer.ts           | 20 +++++++++++--
 4 files changed, 83 insertions(+), 20 deletions(-)

diff --git a/__tests__/setup-go.test.ts b/__tests__/setup-go.test.ts
index 35b0225..3ab42ee 100644
--- a/__tests__/setup-go.test.ts
+++ b/__tests__/setup-go.test.ts
@@ -13,27 +13,29 @@ let goJsonData = require('./data/golang-dl.json');
 
 describe('setup-go', () => {
   let inSpy: jest.SpyInstance;
-  let tcSpy: jest.SpyInstance;
+  let findSpy: jest.SpyInstance;
   let cnSpy: jest.SpyInstance;
   let getSpy: jest.SpyInstance;
   let platSpy: jest.SpyInstance;
   let archSpy: jest.SpyInstance;
   let dlSpy: jest.SpyInstance;
   let exSpy: jest.SpyInstance;
+  let cacheSpy: jest.SpyInstance;
 
   beforeEach(() => {
-    tcSpy = jest.spyOn(tc, 'find');
+    findSpy = jest.spyOn(tc, 'find');
     inSpy = jest.spyOn(core, 'getInput');
     cnSpy = jest.spyOn(process.stdout, 'write');
     platSpy = jest.spyOn(sys, 'getPlatform');
     archSpy = jest.spyOn(sys, 'getArch');
     dlSpy = jest.spyOn(tc, 'downloadTool');
     exSpy = jest.spyOn(tc, 'extractTar');
+    cacheSpy = jest.spyOn(tc, 'cacheDir');
     getSpy = jest.spyOn(im, 'getVersions');
     getSpy.mockImplementation(() => <im.IGoVersion[]>goJsonData);
     cnSpy.mockImplementation(line => {
       // uncomment to debug
-      //process.stderr.write('write2:' + line + '\n');
+      // process.stderr.write('write2:' + line + '\n');
     });
   });
 
@@ -47,7 +49,7 @@ describe('setup-go', () => {
   it('finds a version of go already in the cache', async () => {
     inSpy.mockImplementation(() => '1.13.0');
     let toolPath = path.normalize('/cache/go/1.13.0/x64');
-    tcSpy.mockImplementation(() => toolPath);
+    findSpy.mockImplementation(() => toolPath);
     await run();
 
     let expPath = path.join(toolPath, 'bin');
@@ -57,7 +59,7 @@ describe('setup-go', () => {
   it('finds a version in the cache and adds it to the path', async () => {
     let toolPath = path.normalize('/cache/go/1.13.0/x64');
     inSpy.mockImplementation(() => '1.13.0');
-    tcSpy.mockImplementation(() => toolPath);
+    findSpy.mockImplementation(() => toolPath);
     await run();
 
     let expPath = path.join(toolPath, 'bin');
@@ -67,13 +69,45 @@ describe('setup-go', () => {
   it('handles unhandled error and reports error', async () => {
     let errMsg = 'unhandled error message';
     inSpy.mockImplementation(() => '1.13.0');
-    tcSpy.mockImplementation(() => {
+    findSpy.mockImplementation(() => {
       throw new Error(errMsg);
     });
     await run();
     expect(cnSpy).toHaveBeenCalledWith('::error::' + errMsg + os.EOL);
   });
 
+  it('downloads a version not in the cache', async () => {
+    platSpy.mockImplementation(() => 'linux');
+    archSpy.mockImplementation(() => 'amd64');
+
+    inSpy.mockImplementation(() => '1.13.1');
+    findSpy.mockImplementation(() => '');
+    dlSpy.mockImplementation(() => '/some/temp/path');
+    let toolPath = path.normalize('/cache/go/1.13.0/x64');
+    exSpy.mockImplementation(() => '/some/other/temp/path');
+    cacheSpy.mockImplementation(() => toolPath);
+    await run();
+
+    let expPath = path.join(toolPath, 'bin');
+
+    expect(dlSpy).toHaveBeenCalled();
+    expect(exSpy).toHaveBeenCalled();
+    expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${os.EOL}`);
+  });
+
+  it('does not find a version that does not exist', async () => {
+    platSpy.mockImplementation(() => 'linux');
+    archSpy.mockImplementation(() => 'amd64');
+
+    inSpy.mockImplementation(() => '9.99.9');
+    findSpy.mockImplementation(() => '');
+    await run();
+
+    expect(cnSpy).toHaveBeenCalledWith(
+      `::error::Could not find a version that satisfied version spec: 9.99.9${os.EOL}`
+    );
+  });
+
   it('can query versions', async () => {
     let versions: im.IGoVersion[] | null = await im.getVersions(
       'https://non.existant.com/path'
@@ -84,21 +118,21 @@ describe('setup-go', () => {
   });
 
   it('finds stable match for exact version', async () => {
-    platSpy.mockImplementation(() => 'linux');
+    platSpy.mockImplementation(() => 'windows');
     archSpy.mockImplementation(() => 'amd64');
 
     // get request is already mocked
-    // spec: 1.13.1 => 1.13.1 (exact)
-    let match: im.IGoVersion | undefined = await im.findMatch('1.13.1', true);
+    // spec: 1.13.7 => 1.13.7 (exact)
+    let match: im.IGoVersion | undefined = await im.findMatch('1.13.7', true);
     expect(match).toBeDefined();
     let version: string = match ? match.version : '';
-    expect(version).toBe('go1.13.1');
+    expect(version).toBe('go1.13.7');
     let fileName = match ? match.files[0].filename : '';
-    expect(fileName).toBe('go1.13.1.linux-amd64.tar.gz');
+    expect(fileName).toBe('go1.13.7.windows-amd64.zip');
   });
 
   it('finds stable match for exact dot zero version', async () => {
-    platSpy.mockImplementation(() => 'linux');
+    platSpy.mockImplementation(() => 'darwin');
     archSpy.mockImplementation(() => 'amd64');
 
     // spec: 1.13.0 => 1.13
@@ -107,12 +141,13 @@ describe('setup-go', () => {
     let version: string = match ? match.version : '';
     expect(version).toBe('go1.13');
     let fileName = match ? match.files[0].filename : '';
-    expect(fileName).toBe('go1.13.linux-amd64.tar.gz');
+    expect(fileName).toBe('go1.13.darwin-amd64.tar.gz');
   });
 
   it('finds latest patch version for minor version spec', async () => {
     platSpy.mockImplementation(() => 'linux');
     archSpy.mockImplementation(() => 'amd64');
+    core.debug('plat mocks ok');
 
     // spec: 1.13 => 1.13.7 (latest)
     let match: im.IGoVersion | undefined = await im.findMatch('1.13', true);
diff --git a/dist/index.js b/dist/index.js
index f910190..4aa2bd2 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -4583,26 +4583,33 @@ const path = __importStar(__webpack_require__(622));
 const semver = __importStar(__webpack_require__(280));
 const httpm = __importStar(__webpack_require__(539));
 const sys = __importStar(__webpack_require__(737));
+const core_1 = __webpack_require__(470);
 function downloadGo(versionSpec, stable) {
     return __awaiter(this, void 0, void 0, function* () {
         let toolPath;
         try {
             let match = yield findMatch(versionSpec, stable);
+            if (match) {
+                console.log('match', match.version);
+            }
             if (match) {
                 // download
+                core_1.debug(`match ${match.version}`);
                 let downloadUrl = `https://storage.googleapis.com/golang/${match.files[0].filename}`;
                 let downloadPath = yield tc.downloadTool(downloadUrl);
+                core_1.debug(`downloaded to ${downloadPath}`);
                 // extract
                 let extPath = sys.getPlatform() == 'windows'
                     ? yield tc.extractZip(downloadPath)
                     : yield tc.extractTar(downloadPath);
+                core_1.debug(`extracted to ${extPath}`);
                 // extracts with a root folder that matches the fileName downloaded
                 const toolRoot = path.join(extPath, 'go');
                 toolPath = yield tc.cacheDir(toolRoot, 'go', versionSpec);
             }
         }
         catch (error) {
-            throw `Failed to download version ${versionSpec}: ${error}`;
+            throw new Error(`Failed to download version ${versionSpec}: ${error}`);
         }
         return toolPath;
     });
@@ -4612,6 +4619,7 @@ function findMatch(versionSpec, stable) {
     return __awaiter(this, void 0, void 0, function* () {
         let archFilter = sys.getArch();
         let platFilter = sys.getPlatform();
+        let result;
         let match;
         const dlUrl = 'https://golang.org/dl/?mode=json&include=all';
         let candidates = yield module.exports.getVersions(dlUrl);
@@ -4621,6 +4629,7 @@ function findMatch(versionSpec, stable) {
         let goFile;
         for (let i = 0; i < candidates.length; i++) {
             let candidate = candidates[i];
+            console.log(JSON.stringify(candidate, null, 2));
             let version = candidate.version.replace('go', '');
             // 1.13.0 is advertised as 1.13 preventing being able to match exactly 1.13.0
             // since a semver of 1.13 would match latest 1.13
@@ -4628,20 +4637,25 @@ function findMatch(versionSpec, stable) {
             if (parts.length == 2) {
                 version = version + '.0';
             }
+            core_1.debug(`check ${version} satisfies ${versionSpec}`);
             if (semver.satisfies(version, versionSpec) && candidate.stable == stable) {
                 goFile = candidate.files.find(file => {
+                    core_1.debug(`${file.arch}===${archFilter} && ${file.os}===${platFilter}`);
                     return file.arch === archFilter && file.os === platFilter;
                 });
                 if (goFile) {
+                    core_1.debug(`matched ${candidate.version}`);
                     match = candidate;
                     break;
                 }
             }
         }
         if (match && goFile) {
-            match.files = [goFile];
+            // clone since we're mutating the file list to be only the file that matches
+            result = Object.assign({}, match);
+            result.files = [goFile];
         }
-        return match;
+        return result;
     });
 }
 exports.findMatch = findMatch;
diff --git a/package.json b/package.json
index 294349d..32af0ea 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
     "build": "tsc && ncc build",
     "format": "prettier --write **/*.ts",
     "format-check": "prettier --check **/*.ts",
-    "test": "jest",
+    "test": "jest --coverage",
     "pre-checkin": "npm run format && npm run build && npm test"
   },
   "repository": {
diff --git a/src/installer.ts b/src/installer.ts
index e75784d..4382d81 100644
--- a/src/installer.ts
+++ b/src/installer.ts
@@ -3,6 +3,7 @@ import * as path from 'path';
 import * as semver from 'semver';
 import * as httpm from '@actions/http-client';
 import * as sys from './system';
+import {debug} from '@actions/core';
 
 export async function downloadGo(
   versionSpec: string,
@@ -12,24 +13,30 @@ export async function downloadGo(
 
   try {
     let match: IGoVersion | undefined = await findMatch(versionSpec, stable);
+    if (match) {
+      console.log('match', match.version);
+    }
 
     if (match) {
       // download
+      debug(`match ${match.version}`);
       let downloadUrl: string = `https://storage.googleapis.com/golang/${match.files[0].filename}`;
       let downloadPath: string = await tc.downloadTool(downloadUrl);
+      debug(`downloaded to ${downloadPath}`);
 
       // extract
       let extPath: string =
         sys.getPlatform() == 'windows'
           ? await tc.extractZip(downloadPath)
           : await tc.extractTar(downloadPath);
+      debug(`extracted to ${extPath}`);
 
       // extracts with a root folder that matches the fileName downloaded
       const toolRoot = path.join(extPath, 'go');
       toolPath = await tc.cacheDir(toolRoot, 'go', versionSpec);
     }
   } catch (error) {
-    throw `Failed to download version ${versionSpec}: ${error}`;
+    throw new Error(`Failed to download version ${versionSpec}: ${error}`);
   }
 
   return toolPath;
@@ -55,6 +62,7 @@ export async function findMatch(
   let archFilter = sys.getArch();
   let platFilter = sys.getPlatform();
 
+  let result: IGoVersion | undefined;
   let match: IGoVersion | undefined;
 
   const dlUrl: string = 'https://golang.org/dl/?mode=json&include=all';
@@ -66,6 +74,7 @@ export async function findMatch(
   let goFile: IGoVersionFile | undefined;
   for (let i = 0; i < candidates.length; i++) {
     let candidate: IGoVersion = candidates[i];
+    console.log(JSON.stringify(candidate, null, 2));
     let version = candidate.version.replace('go', '');
 
     // 1.13.0 is advertised as 1.13 preventing being able to match exactly 1.13.0
@@ -75,12 +84,15 @@ export async function findMatch(
       version = version + '.0';
     }
 
+    debug(`check ${version} satisfies ${versionSpec}`);
     if (semver.satisfies(version, versionSpec) && candidate.stable == stable) {
       goFile = candidate.files.find(file => {
+        debug(`${file.arch}===${archFilter} && ${file.os}===${platFilter}`);
         return file.arch === archFilter && file.os === platFilter;
       });
 
       if (goFile) {
+        debug(`matched ${candidate.version}`);
         match = candidate;
         break;
       }
@@ -88,10 +100,12 @@ export async function findMatch(
   }
 
   if (match && goFile) {
-    match.files = [goFile];
+    // clone since we're mutating the file list to be only the file that matches
+    result = <IGoVersion>Object.assign({}, match);
+    result.files = [goFile];
   }
 
-  return match;
+  return result;
 }
 
 export async function getVersions(dlUrl: string): Promise<IGoVersion[] | null> {