add legacy gradle plugin url redirecting

This commit is contained in:
Hassan Yousefi 2024-10-03 06:25:37 +03:30
parent a440ed9dc0
commit d22e677683
2 changed files with 56 additions and 1 deletions

53
src/gradle-plugins.ts Normal file
View file

@ -0,0 +1,53 @@
import { RequestHandler } from 'express';
import got from 'got';
const gradleApi = 'https://plugins.gradle.org/api/gradle/4.10/plugin/use';
export const LegacyGradlePluginsHandler: RequestHandler = (req, res, next) => {
const url = req.originalUrl ?? req.url;
if (!url.includes('.gradle.plugin/')) {
next();
}
if (req.method !== 'HEAD' && req.method !== 'GET') {
return res.sendStatus(403);
}
try {
const basePath = /^\/[^/]*(?=\/)/.exec(url)?.[0];
const fileName = /[^/]+$/.exec(url)?.[0];
const version = /[^/]+$/.exec(url.replace(`/${fileName}`, ''))?.[0];
const packageId = fileName?.replace(/\.gradle\.plugin.*$/, '');
const endpoint = `${gradleApi}/${packageId}/${version}`;
got
.get(endpoint)
.then((result) => {
const info = JSON.parse(result.body) as {
id: string;
version: string;
implementation: {
gav: string;
repo: string;
};
implementationType: string;
legacy: boolean;
};
const newId =
/(?<=:).+(?=:)/.exec(info.implementation.gav)?.[0] ?? 'new-id';
const newFileName = /[^/]+$/.exec(
url.replaceAll(`${info.id}.gradle.plugin`, newId)
)?.[0];
const newUrl = `${basePath}/${/^[\w.]+(?=:)/.exec(info.implementation.gav)?.[0]?.replaceAll('.', '/')}/${newId}/${version}/${newFileName}`;
console.log('🔀 [301]', url);
req.url = newUrl;
next();
})
.catch(() => {
next();
});
} catch (error) {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
error;
next();
}
};

View file

@ -15,11 +15,12 @@ import {
} from './config';
import { getCachedServer, printServedEndpoints } from './utils';
import { GotDownloader } from './downloader/got';
import { LegacyGradlePluginsHandler } from './gradle-plugins';
const downloader = new GotDownloader();
const cacheRequestHandler: RequestHandler = (req, res, next) => {
const url = (req.originalUrl || req.url).replace(/^\/\w+\//, '/');
const url = req.url.replace(/^\/\w+\//, '/');
if (req.method !== 'HEAD' && req.method !== 'GET') {
return res.sendStatus(403);
}
@ -76,6 +77,7 @@ const app = express();
if (VERBOSE) {
app.use(morgan('combined'));
}
app.get('*', LegacyGradlePluginsHandler);
app.get('*', cacheRequestHandler);
app.listen(PORT, () => {
console.log('add this ⬇️ in build.gradle');