Skip to content

Commit 68b5193

Browse files
authored
fix(git): Revert "feat(git): use git fetching for forkMode" (renovatebot#36045)
1 parent 601ec93 commit 68b5193

File tree

5 files changed

+30
-86
lines changed

5 files changed

+30
-86
lines changed

lib/modules/platform/github/index.spec.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,7 @@ describe('modules/platform/github/index', () => {
648648
it('should update fork when using forkToken and forkOrg', async () => {
649649
const scope = httpMock.scope(githubApiHost);
650650
forkInitRepoMock(scope, 'some/repo', true);
651+
scope.patch('/repos/forked/repo/git/refs/heads/master').reply(200);
651652
const config = await github.initRepo({
652653
repository: 'some/repo',
653654
forkToken: 'true',
@@ -665,6 +666,7 @@ describe('modules/platform/github/index', () => {
665666
});
666667
scope.post('/repos/forked/repo/git/refs').reply(200);
667668
scope.patch('/repos/forked/repo').reply(200);
669+
scope.patch('/repos/forked/repo/git/refs/heads/master').reply(200);
668670
const config = await github.initRepo({
669671
repository: 'some/repo',
670672
forkToken: 'true',

lib/modules/platform/github/index.ts

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import type { HttpResponse } from '../../../util/http/types';
4242
import { coerceObject } from '../../../util/object';
4343
import { regEx } from '../../../util/regex';
4444
import { sanitize } from '../../../util/sanitize';
45-
import { fromBase64, looseEquals } from '../../../util/string';
45+
import { coerceString, fromBase64, looseEquals } from '../../../util/string';
4646
import { ensureTrailingSlash } from '../../../util/url';
4747
import { incLimitedValue } from '../../../workers/global/limits';
4848
import type {
@@ -680,6 +680,31 @@ export async function initRepo({
680680
logger.warn({ err }, 'Could not set default branch');
681681
} /* v8 ignore stop */
682682
}
683+
// This is a lovely "hack" by GitHub that lets us force update our fork's default branch
684+
// with the base commit from the parent repository
685+
const url = `repos/${config.repository}/git/refs/heads/${config.defaultBranch}`;
686+
const sha = repo.defaultBranchRef.target.oid;
687+
try {
688+
logger.debug(
689+
`Updating forked repository default sha ${sha} to match upstream`,
690+
);
691+
await githubApi.patchJson(url, {
692+
body: {
693+
sha,
694+
force: true,
695+
},
696+
token: coerceString(forkToken, opts.token),
697+
});
698+
} catch (err) /* v8 ignore start */ {
699+
logger.warn(
700+
{ url, sha, err: err.err ?? err },
701+
'Error updating fork from upstream - cannot continue',
702+
);
703+
if (err instanceof ExternalHostError) {
704+
throw err;
705+
}
706+
throw new ExternalHostError(err);
707+
} /* v8 ignore stop */
683708
} else if (forkCreation) {
684709
logger.debug('Forked repo is not found - attempting to create it');
685710
forkedRepo = await createFork(forkToken, repository, forkOrg);
@@ -708,15 +733,9 @@ export async function initRepo({
708733
);
709734
parsedEndpoint.pathname = `${config.repository}.git`;
710735
const url = URL.format(parsedEndpoint);
711-
let upstreamUrl = undefined;
712-
if (forkCreation && config.parentRepo) {
713-
parsedEndpoint.pathname = config.parentRepo + '.git';
714-
upstreamUrl = URL.format(parsedEndpoint);
715-
}
716736
await git.initRepo({
717737
...config,
718738
url,
719-
upstreamUrl,
720739
});
721740
const repoConfig: RepoResult = {
722741
defaultBranch: config.defaultBranch,

lib/util/git/index.spec.ts

Lines changed: 0 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,60 +1226,5 @@ describe('util/git/index', { timeout: 10000 }, () => {
12261226
).trim();
12271227
expect(branch).toBe('develop');
12281228
});
1229-
1230-
it('should fetch from upstream and update local branch', async () => {
1231-
const newBase = await tmp.dir({ unsafeCleanup: true });
1232-
const upstream = Git(newBase.path);
1233-
await upstream.init();
1234-
defaultBranch = (await upstream.raw('branch', '--show-current')).trim();
1235-
await upstream.addConfig('user.email', 'other@example.com');
1236-
await upstream.addConfig('user.name', 'Other');
1237-
await fs.writeFile(newBase.path + '/past_file', 'past');
1238-
await upstream.addConfig('commit.gpgsign', 'false');
1239-
await upstream.add(['past_file']);
1240-
await upstream.commit('past message');
1241-
await upstream.raw(['checkout', '-B', defaultBranch]);
1242-
1243-
const upstreamOrigin = await tmp.dir({ unsafeCleanup: true });
1244-
const upstreamRepo = Git(upstreamOrigin.path);
1245-
await upstreamRepo.clone(newBase.path, '.', ['--bare']);
1246-
await upstreamRepo.addConfig('commit.gpgsign', 'false');
1247-
1248-
tmpDir = await tmp.dir({ unsafeCleanup: true });
1249-
GlobalConfig.set({ localDir: tmpDir.path });
1250-
1251-
await git.initRepo({
1252-
url: origin.path,
1253-
defaultBranch,
1254-
upstreamUrl: upstreamOrigin.path,
1255-
});
1256-
1257-
await git.syncGit();
1258-
const tmpGit = Git(tmpDir.path);
1259-
1260-
// make sure origin exists ie. fork repo is cloned
1261-
const originRemote = (
1262-
await tmpGit.raw(['remote', 'get-url', 'origin'])
1263-
).trim();
1264-
expect(originRemote.trim()).toBe(origin.path);
1265-
1266-
// make sure upstream exists
1267-
const upstreamRemote = (
1268-
await tmpGit.raw(['remote', 'get-url', 'upstream'])
1269-
).trim();
1270-
expect(upstreamRemote).toBe(upstreamOrigin.path);
1271-
1272-
// verify fetch from upstream happened
1273-
// by checking the `upstream/main` branch in the forked repo's remote branches
1274-
const branches = await tmpGit.branch(['-r']);
1275-
expect(branches.all).toContain(`upstream/${defaultBranch}`);
1276-
1277-
// verify that the HEAD's match
1278-
const headSha = (await tmpGit.revparse(['HEAD'])).trim();
1279-
const upstreamSha = (
1280-
await tmpGit.revparse([`upstream/${defaultBranch}`])
1281-
).trim();
1282-
expect(headSha).toBe(upstreamSha);
1283-
});
12841229
});
12851230
});

lib/util/git/index.ts

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -194,11 +194,9 @@ export async function validateGitVersion(): Promise<boolean> {
194194
return true;
195195
}
196196

197-
async function fetchBranchCommits(preferUpstream = true): Promise<void> {
197+
async function fetchBranchCommits(): Promise<void> {
198198
config.branchCommits = {};
199-
const url =
200-
preferUpstream && config.upstreamUrl ? config.upstreamUrl : config.url;
201-
const opts = ['ls-remote', '--heads', url];
199+
const opts = ['ls-remote', '--heads', config.url];
202200
if (config.extraCloneOpts) {
203201
Object.entries(config.extraCloneOpts).forEach((e) =>
204202
// TODO: types (#22198)
@@ -496,25 +494,6 @@ export async function syncGit(): Promise<void> {
496494
(await getDefaultBranch(git));
497495
/* v8 ignore next -- TODO: add test */
498496
delete getCache()?.semanticCommits;
499-
500-
if (config.upstreamUrl) {
501-
logger.debug(`Resetting ${config.currentBranch} to upstream`);
502-
await git.addRemote('upstream', config.upstreamUrl);
503-
await git.fetch(['upstream']);
504-
await resetToBranch(config.currentBranch);
505-
const resetLog = await git.reset([
506-
'--hard',
507-
`upstream/${config.currentBranch}`,
508-
]);
509-
logger.debug({ resetLog }, 'git reset log');
510-
const pushLog = await git.push(['origin', config.currentBranch, '--force']);
511-
logger.debug({ pushLog }, 'git push log');
512-
await fetchBranchCommits(false);
513-
}
514-
config.currentBranchSha = (
515-
await git.raw(['rev-parse', 'HEAD'])
516-
).trim() as LongCommitSha;
517-
logger.debug(`Current branch SHA: ${config.currentBranchSha}`);
518497
}
519498

520499
export async function getRepoStatus(path?: string): Promise<StatusResult> {

lib/util/git/types.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ export interface StorageConfig {
1919
currentBranch?: string;
2020
defaultBranch?: string;
2121
url: string;
22-
upstreamUrl?: string;
2322
extraCloneOpts?: GitOptions;
2423
cloneSubmodules?: boolean;
2524
cloneSubmodulesFilter?: string[];

0 commit comments

Comments
 (0)