Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(gerrit): not auto-merging if Code-Review changed from +2 to +1 #32818

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
46f8eed
fix(gerrit): not auto-approving if change already had a Code-Review +1
felipecrs Nov 29, 2024
107a298
chore(gerrit): improve auto-approve on new patchset workaround
felipecrs Nov 30, 2024
6ac7b9e
chore(gerrit): try auto-approve right before auto-merge
felipecrs Nov 30, 2024
6ffa5b6
Merge branch 'main' into fix-auto-merge-if-plus-one
felipecrs Nov 30, 2024
7877331
Merge branch 'main' of https://github.com/renovatebot/renovate into f…
felipecrs Dec 1, 2024
1d8daf5
test(gerrit): fix approvePr coverage
felipecrs Dec 1, 2024
5eb2846
chore(gerrit): still approve if change was approved another user
felipecrs Dec 1, 2024
c679c28
feat(gitlab,azure): try approving before auto-merge
felipecrs Dec 1, 2024
dbdf41a
chore: add better jsdoc for approvePr
felipecrs Dec 1, 2024
bd05816
test(gerrit): fix lint in client.spec.ts
felipecrs Dec 1, 2024
ac30f2b
test(automerge): add test for auto approve before merging
felipecrs Dec 1, 2024
539c12f
Merge branch 'main' into fix-auto-merge-if-plus-one
felipecrs Dec 2, 2024
7923d5b
Revert "feat(gitlab,azure): try approving before auto-merge"
felipecrs Dec 2, 2024
c4c81e3
chore: rename approvePr to approvePrForAutomerge
felipecrs Dec 2, 2024
4dfc817
Revert "chore(gerrit): still approve if change was approved another u…
felipecrs Dec 2, 2024
bb317ce
chore(gerrit): improve approve method to avoid some API calls
felipecrs Dec 2, 2024
b1ce02b
Merge branch 'main' of https://github.com/renovatebot/renovate into f…
felipecrs Dec 2, 2024
53743b2
chore: fix type import
felipecrs Dec 2, 2024
e0b6f8d
chore: remove spurious comment
felipecrs Dec 2, 2024
74137a8
Merge branch 'main' of https://github.com/renovatebot/renovate into f…
felipecrs Dec 29, 2024
b93ee7a
Address review comments
felipecrs Dec 29, 2024
add6ca5
Add tests for approvePrForAutomerge
felipecrs Dec 29, 2024
933f13d
Merge
felipecrs Jan 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 50 additions & 60 deletions lib/modules/platform/gerrit/client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,10 +399,20 @@ describe('modules/platform/gerrit/client', () => {

describe('approveChange()', () => {
it('already approved - do nothing', async () => {
const change = partial<GerritChange>({});
const change = partial<GerritChange>({
labels: {
'Code-Review': {
all: [{ value: 2 }],
},
},
});
httpMock
.scope(gerritEndpointUrl)
.get((url) => url.includes('/a/changes/123456?o='))
.get(
(url) =>
url.includes('/a/changes/123456?o=') &&
url.includes('o=DETAILED_LABELS'),
)
.reply(200, gerritRestResponse(change), jsonResultHeader);
await expect(client.approveChange(123456)).toResolve();
});
Expand All @@ -411,17 +421,27 @@ describe('modules/platform/gerrit/client', () => {
const change = partial<GerritChange>({ labels: {} });
httpMock
.scope(gerritEndpointUrl)
.get((url) => url.includes('/a/changes/123456?o='))
.get(
(url) =>
url.includes('/a/changes/123456?o=') &&
url.includes('o=DETAILED_LABELS'),
)
.reply(200, gerritRestResponse(change), jsonResultHeader);

await expect(client.approveChange(123456)).toResolve();
});

it('not already approved - approve now', async () => {
const change = partial<GerritChange>({ labels: { 'Code-Review': {} } });
const change = partial<GerritChange>({
labels: { 'Code-Review': { all: [] } },
});
httpMock
.scope(gerritEndpointUrl)
.get((url) => url.includes('/a/changes/123456?o='))
.get(
(url) =>
url.includes('/a/changes/123456?o=') &&
url.includes('o=DETAILED_LABELS'),
)
.reply(200, gerritRestResponse(change), jsonResultHeader);
const approveMock = httpMock
.scope(gerritEndpointUrl)
Expand All @@ -433,62 +453,32 @@ describe('modules/platform/gerrit/client', () => {
await expect(client.approveChange(123456)).toResolve();
expect(approveMock.isDone()).toBeTrue();
});
});

describe('wasApprovedBy()', () => {
it('label not exists', () => {
expect(
client.wasApprovedBy(partial<GerritChange>({}), 'user'),
).toBeUndefined();
});

it('not approved by anyone', () => {
expect(
client.wasApprovedBy(
partial<GerritChange>({
labels: {
'Code-Review': {},
},
}),
'user',
),
).toBeUndefined();
});

it('approved by given user', () => {
expect(
client.wasApprovedBy(
partial<GerritChange>({
labels: {
'Code-Review': {
approved: {
_account_id: 1,
username: 'user',
},
},
},
}),
'user',
),
).toBeTrue();
});

it('approved by given other', () => {
expect(
client.wasApprovedBy(
partial<GerritChange>({
labels: {
'Code-Review': {
approved: {
_account_id: 1,
username: 'other',
},
},
},
}),
'user',
),
).toBeFalse();
it('not already approved because of +1 - approve now', async () => {
const change = partial<GerritChange>({
labels: {
'Code-Review': {
all: [{ value: 1 }],
},
},
});
httpMock
.scope(gerritEndpointUrl)
.get(
(url) =>
url.includes('/a/changes/123456?o=') &&
url.includes('o=DETAILED_LABELS'),
)
.reply(200, gerritRestResponse(change), jsonResultHeader);
const approveMock = httpMock
.scope(gerritEndpointUrl)
.post('/a/changes/123456/revisions/current/review', {
labels: { 'Code-Review': +2 },
notify: 'NONE',
})
.reply(200, gerritRestResponse(''), jsonResultHeader);
await expect(client.approveChange(123456)).toResolve();
expect(approveMock.isDone()).toBeTrue();
});
});
});
Expand Down
21 changes: 10 additions & 11 deletions lib/modules/platform/gerrit/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,13 @@ class GerritClient {
return changes.body;
}

async getChange(changeNumber: number): Promise<GerritChange> {
async getChange(
changeNumber: number,
extraOptions?: string[],
): Promise<GerritChange> {
const options = [...this.requestDetails, ...(extraOptions ?? [])];
const changes = await this.gerritHttp.getJson<GerritChange>(
`a/changes/${changeNumber}?` +
this.requestDetails.map((det) => `o=${det}`).join('&'),
`a/changes/${changeNumber}?` + options.map((det) => `o=${det}`).join('&'),
felipecrs marked this conversation as resolved.
Show resolved Hide resolved
);
return changes.body;
}
Expand Down Expand Up @@ -196,15 +199,11 @@ class GerritClient {
}

async checkIfApproved(changeId: number): Promise<boolean> {
const change = await client.getChange(changeId);
const reviewLabels = change?.labels?.['Code-Review'];
return reviewLabels === undefined || reviewLabels.approved !== undefined;
}

wasApprovedBy(change: GerritChange, username: string): boolean | undefined {
const change = await client.getChange(changeId, ['DETAILED_LABELS']);
const reviewLabel = change?.labels?.['Code-Review'];
return (
change.labels?.['Code-Review'].approved &&
change.labels['Code-Review'].approved.username === username
reviewLabel === undefined ||
Boolean(reviewLabel.all?.some((label) => label.value === 2))
felipecrs marked this conversation as resolved.
Show resolved Hide resolved
);
}

Expand Down
4 changes: 4 additions & 0 deletions lib/modules/platform/gerrit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,7 @@
export function getIssueList(): Promise<Issue[]> {
return Promise.resolve([]);
}

export async function approvePr(number: number): Promise<void> {
await client.approveChange(number);

Check warning on line 439 in lib/modules/platform/gerrit/index.ts

View check run for this annotation

Codecov / codecov/patch

lib/modules/platform/gerrit/index.ts#L439

Added line #L439 was not covered by tests
}
7 changes: 2 additions & 5 deletions lib/modules/platform/gerrit/scm.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,6 @@ describe('modules/platform/gerrit/scm', () => {
},
});
clientMock.findChanges.mockResolvedValueOnce([existingChange]);
clientMock.wasApprovedBy.mockReturnValueOnce(true);
git.prepareCommit.mockResolvedValueOnce({
commitSha: 'commitSha' as LongCommitSha,
parentCommitSha: 'parentSha' as LongCommitSha,
Expand All @@ -385,6 +384,7 @@ describe('modules/platform/gerrit/scm', () => {
message: 'commit msg',
files: [],
prTitle: 'pr title',
autoApprove: true,
}),
).toBe('commitSha');
expect(git.prepareCommit).toHaveBeenCalledWith({
Expand All @@ -396,6 +396,7 @@ describe('modules/platform/gerrit/scm', () => {
'Renovate-Branch: renovate/dependency-1.x\nChange-Id: ...',
],
prTitle: 'pr title',
autoApprove: true,
force: true,
});
expect(git.fetchRevSpec).toHaveBeenCalledWith('refs/changes/1/2');
Expand All @@ -404,10 +405,6 @@ describe('modules/platform/gerrit/scm', () => {
sourceRef: 'renovate/dependency-1.x',
targetRef: 'refs/for/main%notify=NONE',
});
expect(clientMock.wasApprovedBy).toHaveBeenCalledWith(
existingChange,
'user',
);
expect(clientMock.approveChange).toHaveBeenCalledWith(123456);
});
});
Expand Down
7 changes: 2 additions & 5 deletions lib/modules/platform/gerrit/scm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,8 @@ export class GerritScm extends DefaultGitScm {
files: commit.files,
});
if (pushResult) {
//existingChange was the old change before commit/push. we need to approve again, if it was previously approved from renovate
if (
existingChange &&
client.wasApprovedBy(existingChange, username)
) {
// New patchsets dismisses the approval, so we need to approve it again
if (existingChange && commit.autoApprove) {
await client.approveChange(existingChange._number);
}
return commitSha;
Expand Down
7 changes: 7 additions & 0 deletions lib/modules/platform/gerrit/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ export interface GerritChangeMessageInfo {
export interface GerritLabelInfo {
approved?: GerritAccountInfo;
rejected?: GerritAccountInfo;
/** List of votes. Only set when o=DETAILED_LABELS. */
all?: GerritApprovalInfo[];
}

export interface GerritActionInfo {
Expand All @@ -99,3 +101,8 @@ export interface GerritMergeableInfo {
| 'CHERRY_PICK';
mergeable: boolean;
}

export interface GerritApprovalInfo {
value?: number;
username?: string;
}
1 change: 1 addition & 0 deletions lib/modules/platform/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ export interface Platform {

maxBodyLength(): number;
labelCharLimit?(): number;
approvePr?(number: number): Promise<void>;
}

export interface PlatformScm {
Expand Down
2 changes: 2 additions & 0 deletions lib/util/git/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ export interface CommitFilesConfig {
platformCommit?: PlatformCommitOptions;
/** Only needed by Gerrit platform */
prTitle?: string;
/** Only needed by Gerrit platform */
autoApprove?: boolean;
}

export interface PushFilesConfig {
Expand Down
2 changes: 2 additions & 0 deletions lib/workers/repository/update/branch/commit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,7 @@ export function commitFilesToBranch(
platformCommit: config.platformCommit,
// Only needed by Gerrit platform
prTitle: config.prTitle,
// Only needed by Gerrit platform
autoApprove: config.autoApprove,
});
}
6 changes: 6 additions & 0 deletions lib/workers/repository/update/pr/automerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@
prAutomergeBlockReason: 'PlatformNotReady',
};
}
// Usually the PR will already be approved, this is a last resort in case the
// approval was lost for some reason
if (config.autoApprove && platform.approvePr) {
logger.debug('Auto-approving PR if needed before automerge');
await platform.approvePr(pr.number);

Check warning on line 76 in lib/workers/repository/update/pr/automerge.ts

View check run for this annotation

Codecov / codecov/patch

lib/workers/repository/update/pr/automerge.ts#L75-L76

Added lines #L75 - L76 were not covered by tests
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this cause each PR to be approved on each run? i.e. one extra API call per PR per run?

Copy link
Contributor Author

@felipecrs felipecrs Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this cause each PR to be approved on each run?

Only if the PR is not yet approved. I implemented all approvePr functions to account for this case.

i.e. one extra API call per PR per run?

Per auto-merge attempt, there will be one extra API call to verify whether the PR is not yet approved, and one more API call to approve it in case it's not yet approved.

Just remember:

  1. this is only applicable for azure, gitlab, and gerrit
  2. and for people who have autoApprove: true
  3. and all other conditions in automerge.ts already passed (except branchStatus, which depends on the approval to be green)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But if you believe it's not a good idea, I can find another way.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly it could be optimized so that it doesn't perform this "is the PR already approved?" check right after we create the PR? i.e. because we know it's impossible that we approved it already.

const branchStatus = await resolveBranchStatus(
branchName,
!!config.internalChecksAsSuccess,
Expand Down
Loading