From 12d1b137039d3df0ffb3c0a8b90d14abd42013d3 Mon Sep 17 00:00:00 2001
From: Sergio Zharinov <zharinov@users.noreply.github.com>
Date: Sat, 1 Feb 2020 11:50:24 +0400
Subject: [PATCH] fix(release-notes): Warning message for missing token (#5245)

---
 lib/workers/pr/changelog/common.ts            | 10 ++-
 lib/workers/pr/changelog/source-github.ts     | 17 ++++--
 lib/workers/pr/index.ts                       | 46 +++++++++-----
 .../pr/__snapshots__/index.spec.ts.snap       |  2 +-
 test/workers/pr/changelog/index.spec.ts       |  9 +++
 test/workers/pr/index.spec.ts                 | 61 +++++++++++--------
 6 files changed, 94 insertions(+), 51 deletions(-)

diff --git a/lib/workers/pr/changelog/common.ts b/lib/workers/pr/changelog/common.ts
index 36a7a76c18..110e17fc95 100644
--- a/lib/workers/pr/changelog/common.ts
+++ b/lib/workers/pr/changelog/common.ts
@@ -30,10 +30,15 @@ export interface ChangeLogProject {
   repository: string;
 }
 
+export enum ChangeLogError {
+  MissingGithubToken = 1,
+}
+
 export interface ChangeLogResult {
   hasReleaseNotes?: boolean;
-  project: ChangeLogProject;
-  versions: ChangeLogRelease[];
+  project?: ChangeLogProject;
+  versions?: ChangeLogRelease[];
+  error?: ChangeLogError;
 }
 
 export interface ChangeLogConfig {
@@ -46,4 +51,5 @@ export interface ChangeLogConfig {
   sourceUrl?: string;
   toVersion: string;
   versionScheme: string;
+  changeLogError?: ChangeLogError;
 }
diff --git a/lib/workers/pr/changelog/source-github.ts b/lib/workers/pr/changelog/source-github.ts
index e4ab098ac0..1c0dac81b8 100644
--- a/lib/workers/pr/changelog/source-github.ts
+++ b/lib/workers/pr/changelog/source-github.ts
@@ -4,7 +4,12 @@ import { logger } from '../../../logger';
 import * as hostRules from '../../../util/host-rules';
 import * as versioning from '../../../versioning';
 import { addReleaseNotes } from './release-notes';
-import { ChangeLogResult, ChangeLogRelease, ChangeLogConfig } from './common';
+import {
+  ChangeLogConfig,
+  ChangeLogError,
+  ChangeLogRelease,
+  ChangeLogResult,
+} from './common';
 import { Release } from '../../../datasource';
 
 const ghGot = api.get;
@@ -73,12 +78,12 @@ export async function getChangeLogJSON({
         { manager, depName, sourceUrl },
         'No github.com token has been configured. Skipping release notes retrieval'
       );
-    } else {
-      logger.info(
-        { manager, depName, sourceUrl },
-        'Repository URL does not match any known hosts - skipping changelog retrieval'
-      );
+      return { error: ChangeLogError.MissingGithubToken };
     }
+    logger.info(
+      { manager, depName, sourceUrl },
+      'Repository URL does not match any known hosts - skipping changelog retrieval'
+    );
     return null;
   }
   const githubApiBaseURL = sourceUrl.startsWith('https://github.com/')
diff --git a/lib/workers/pr/index.ts b/lib/workers/pr/index.ts
index b2186d75bd..5b25356bd4 100644
--- a/lib/workers/pr/index.ts
+++ b/lib/workers/pr/index.ts
@@ -1,13 +1,13 @@
 import sampleSize from 'lodash/sampleSize';
 import uniq from 'lodash/uniq';
 import { logger } from '../../logger';
-import { getChangeLogJSON } from './changelog';
+import { ChangeLogError, getChangeLogJSON } from './changelog';
 import { getPrBody } from './body';
-import { platform, BranchStatus, Pr } from '../../platform';
+import { BranchStatus, platform, Pr } from '../../platform';
 import { BranchConfig } from '../common';
 import {
-  PLATFORM_INTEGRATION_UNAUTHORIZED,
   PLATFORM_FAILURE,
+  PLATFORM_INTEGRATION_UNAUTHORIZED,
   PLATFORM_RATE_LIMIT_EXCEEDED,
   REPOSITORY_CHANGED,
 } from '../../constants/error-messages';
@@ -217,19 +217,33 @@ export async function ensurePr(
     const logJSON = await getChangeLogJSON(upgrade);
 
     if (logJSON) {
-      upgrade.githubName = logJSON.project ? logJSON.project.github : undefined;
-      upgrade.hasReleaseNotes = logJSON.hasReleaseNotes;
-      upgrade.releases = [];
-      if (
-        upgrade.hasReleaseNotes &&
-        upgrade.githubName &&
-        !commitRepos.includes(upgrade.githubName)
-      ) {
-        commitRepos.push(upgrade.githubName);
-        logJSON.versions.forEach(version => {
-          const release = { ...version };
-          upgrade.releases.push(release);
-        });
+      if (typeof logJSON.error === 'undefined') {
+        if (logJSON.project) upgrade.githubName = logJSON.project.github;
+        upgrade.hasReleaseNotes = logJSON.hasReleaseNotes;
+        upgrade.releases = [];
+        if (
+          upgrade.hasReleaseNotes &&
+          upgrade.githubName &&
+          !commitRepos.includes(upgrade.githubName)
+        ) {
+          commitRepos.push(upgrade.githubName);
+          if (logJSON.versions) {
+            logJSON.versions.forEach(version => {
+              const release = { ...version };
+              upgrade.releases.push(release);
+            });
+          }
+        }
+      } else if (logJSON.error === ChangeLogError.MissingGithubToken) {
+        upgrade.prBodyNotes = [
+          ...upgrade.prBodyNotes,
+          [
+            '\n',
+            ':warning: Release Notes retrieval for this PR were skipped because no github.com credentials were available.',
+            'To add credentials for github.com to your config, please see [this guide](https://docs.renovatebot.com/install-gitlab-app/#configuring-a-token-for-githubcom-hosted-release-notes).',
+            '\n',
+          ].join('\n'),
+        ];
       }
     }
     config.upgrades.push(upgrade);
diff --git a/test/workers/pr/__snapshots__/index.spec.ts.snap b/test/workers/pr/__snapshots__/index.spec.ts.snap
index 93f61ed19f..4f5895b52a 100644
--- a/test/workers/pr/__snapshots__/index.spec.ts.snap
+++ b/test/workers/pr/__snapshots__/index.spec.ts.snap
@@ -82,7 +82,7 @@ Array [
       "gitLabAutomerge": false,
       "statusCheckVerify": false,
     },
-    "prBody": "This PR contains the following updates:\\n\\n| Package | Type | Update | Change |\\n|---|---|---|---|\\n| [dummy](https://dummy.com) ([source](https://github.com/renovateapp/dummy), [changelog](https://github.com/renovateapp/dummy/changelog.md)) | devDependencies | lockFileMaintenance | \`1.0.0\` -> \`1.1.0\` |\\n| a |  |  | \`zzzzzz\` -> \`aaaaaaa\` |\\n| b |  | pin | \`some_old_value\` -> \`some_new_value\` |\\n| c |  |  | \`\` -> \`\` |\\n| d |  | lockFileMaintenance | \`\` -> \`\` |\\n\\nnote 1\\n\\nnote 2\\n\\n:abcd: If you wish to disable git hash updates, add \`\\":disableDigestUpdates\\"\` to the extends array in your config.\\n\\n:wrench: This Pull Request updates lock files to use the latest dependency versions.\\n\\n---\\n\\n### Release Notes\\n\\n<details>\\n<summary>renovateapp/dummy</summary>\\n\\n### [\`v1.1.0\`](https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0)\\n\\n[Compare Source](https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0)\\n\\n</details>\\n\\n<details>\\n<summary>renovateapp/dummy</summary>\\n\\n</details>\\n\\n---\\n\\n### Renovate configuration\\n\\n:date: **Schedule**: At any time (no schedule defined).\\n\\n:vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied.\\n\\n:recycle: **Rebasing**: Whenever PR becomes conflicted, or if you tick the rebase/retry checkbox below.\\n\\n:ghost: **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/config-help/issues) if that's undesired.\\n\\n---\\n\\n - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box",
+    "prBody": "This PR contains the following updates:\\n\\n| Package | Type | Update | Change |\\n|---|---|---|---|\\n| [dummy](https://dummy.com) ([source](https://github.com/renovateapp/dummy), [changelog](https://github.com/renovateapp/dummy/changelog.md)) | devDependencies | lockFileMaintenance | \`1.0.0\` -> \`1.1.0\` |\\n| a |  |  | \`zzzzzz\` -> \`aaaaaaa\` |\\n| b |  | pin | \`some_old_value\` -> \`some_new_value\` |\\n| c |  |  | \`\` -> \`\` |\\n| d |  | lockFileMaintenance | \`\` -> \`\` |\\n\\nnote 1\\n\\nnote 2\\n\\n:warning: Release Notes retrieval for this PR were skipped because no github.com credentials were available.\\nTo add credentials for github.com to your config, please see [this guide](https://docs.renovatebot.com/install-gitlab-app/#configuring-a-token-for-githubcom-hosted-release-notes).\\n\\n:abcd: If you wish to disable git hash updates, add \`\\":disableDigestUpdates\\"\` to the extends array in your config.\\n\\n:wrench: This Pull Request updates lock files to use the latest dependency versions.\\n\\n---\\n\\n### Release Notes\\n\\n<details>\\n<summary>renovateapp/dummy</summary>\\n\\n### [\`v1.1.0\`](https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0)\\n\\n[Compare Source](https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0)\\n\\n</details>\\n\\n<details>\\n<summary>renovateapp/dummy</summary>\\n\\n</details>\\n\\n---\\n\\n### Renovate configuration\\n\\n:date: **Schedule**: At any time (no schedule defined).\\n\\n:vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied.\\n\\n:recycle: **Rebasing**: Whenever PR becomes conflicted, or if you tick the rebase/retry checkbox below.\\n\\n:ghost: **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://github.com/renovatebot/config-help/issues) if that's undesired.\\n\\n---\\n\\n - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box",
     "prTitle": "Update dependency dummy to v1.1.0",
     "useDefaultBranch": false,
   },
diff --git a/test/workers/pr/changelog/index.spec.ts b/test/workers/pr/changelog/index.spec.ts
index 1ae66afec7..17ce9cc637 100644
--- a/test/workers/pr/changelog/index.spec.ts
+++ b/test/workers/pr/changelog/index.spec.ts
@@ -3,6 +3,7 @@ import * as hostRules from '../../../../lib/util/host-rules';
 import {
   getChangeLogJSON,
   ChangeLogConfig,
+  ChangeLogError,
 } from '../../../../lib/workers/pr/changelog';
 import { mocked } from '../../../util';
 import { VERSION_SCHEME_SEMVER } from '../../../../lib/constants/version-schemes';
@@ -140,6 +141,14 @@ describe('workers/pr/changelog', () => {
         })
       ).toBeNull();
     });
+    it('handles missing Github token', async () => {
+      expect(
+        await getChangeLogJSON({
+          ...upgrade,
+          sourceUrl: 'https://github.com',
+        })
+      ).toEqual({ error: ChangeLogError.MissingGithubToken });
+    });
     it('handles no releases', async () => {
       expect(
         await getChangeLogJSON({
diff --git a/test/workers/pr/index.spec.ts b/test/workers/pr/index.spec.ts
index 9518a75019..cdf4a41c5d 100644
--- a/test/workers/pr/index.spec.ts
+++ b/test/workers/pr/index.spec.ts
@@ -16,34 +16,42 @@ const defaultConfig = getConfig();
 
 jest.mock('../../../lib/workers/pr/changelog');
 
-changelogHelper.getChangeLogJSON = jest.fn();
-changelogHelper.getChangeLogJSON.mockResolvedValue({
-  project: {
-    githubBaseURL: 'https://github.com/',
-    github: 'renovateapp/dummy',
-    repository: 'https://github.com/renovateapp/dummy',
-  },
-  hasReleaseNotes: true,
-  versions: [
-    {
-      date: new Date('2017-01-01'),
-      version: '1.1.0',
-      changes: [
-        {
-          date: new Date('2017-01-01'),
-          sha: 'abcdefghijklmnopqrstuvwxyz',
-          message: 'foo #3\nbar',
+function setupChangelogMock() {
+  changelogHelper.getChangeLogJSON = jest.fn();
+  const resultValue = {
+    project: {
+      githubBaseURL: 'https://github.com/',
+      github: 'renovateapp/dummy',
+      repository: 'https://github.com/renovateapp/dummy',
+    },
+    hasReleaseNotes: true,
+    versions: [
+      {
+        date: new Date('2017-01-01'),
+        version: '1.1.0',
+        changes: [
+          {
+            date: new Date('2017-01-01'),
+            sha: 'abcdefghijklmnopqrstuvwxyz',
+            message: 'foo #3\nbar',
+          },
+        ],
+        releaseNotes: {
+          url: 'https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0',
+        },
+        compare: {
+          url: 'https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0',
         },
-      ],
-      releaseNotes: {
-        url: 'https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0',
-      },
-      compare: {
-        url: 'https://github.com/renovateapp/dummy/compare/v1.0.0...v1.1.0',
       },
-    },
-  ],
-});
+    ],
+  };
+  const errorValue = {
+    error: _changelogHelper.ChangeLogError.MissingGithubToken,
+  };
+  changelogHelper.getChangeLogJSON.mockResolvedValueOnce(resultValue);
+  changelogHelper.getChangeLogJSON.mockResolvedValueOnce(errorValue);
+  changelogHelper.getChangeLogJSON.mockResolvedValue(resultValue);
+}
 
 describe('workers/pr', () => {
   describe('checkAutoMerge(pr, config)', () => {
@@ -121,6 +129,7 @@ describe('workers/pr', () => {
       isModified: false,
     } as never;
     beforeEach(() => {
+      setupChangelogMock();
       config = {
         ...defaultConfig,
       };
-- 
GitLab