diff --git a/src/gradle-plugins.ts b/src/gradle-plugins.ts new file mode 100644 index 0000000..6bfff8b --- /dev/null +++ b/src/gradle-plugins.ts @@ -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(); + } +}; diff --git a/src/index.ts b/src/index.ts index 4ae4870..af3d681 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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');