145 lines
5.1 KiB
JavaScript
145 lines
5.1 KiB
JavaScript
|
|
const https = require('https');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
// Konfiguracja z zmiennych środowiskowych
|
|
const config = {
|
|
baseUrl: process.env.GITEA_BASE_URL,
|
|
owner: process.env.OWNER,
|
|
repo: process.env.REPO,
|
|
token: process.env.GITEA_PAT,
|
|
requiredArtifacts: process.env.REQUIRED_ARTIFACTS?.split(',') || [],
|
|
scanLimit: parseInt(process.env.SCAN_LIMIT) || 50
|
|
};
|
|
|
|
// Walidacja konfiguracji
|
|
if (!config.baseUrl || !config.owner || !config.repo || !config.token) {
|
|
console.error('Błąd: Brak wymaganych zmiennych środowiskowych (GITEA_BASE_URL, OWNER, REPO, GITEA_PAT)');
|
|
process.exit(1);
|
|
}
|
|
|
|
console.log(`Szukam ostatniego udanego buildu dla ${config.owner}/${config.repo}`);
|
|
console.log(`Wymagane artefakty: ${config.requiredArtifacts.join(', ')}`);
|
|
|
|
// Funkcja do wykonywania zapytań HTTPS
|
|
function makeRequest(url, options = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const parsedUrl = new URL(url);
|
|
const requestOptions = {
|
|
hostname: parsedUrl.hostname,
|
|
port: parsedUrl.port || 443,
|
|
path: parsedUrl.pathname + parsedUrl.search,
|
|
method: 'GET',
|
|
headers: {
|
|
'Authorization': `token ${config.token}`,
|
|
'Accept': 'application/json',
|
|
'User-Agent': 'Gitea-Workflow-Script'
|
|
},
|
|
...options
|
|
};
|
|
|
|
const req = https.request(requestOptions, (res) => {
|
|
let data = '';
|
|
res.on('data', chunk => data += chunk);
|
|
res.on('end', () => {
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
try {
|
|
resolve(JSON.parse(data));
|
|
} catch (e) {
|
|
resolve(data);
|
|
}
|
|
} else {
|
|
reject(new Error(`HTTP ${res.statusCode}: ${data}`));
|
|
}
|
|
});
|
|
});
|
|
|
|
req.on('error', reject);
|
|
req.end();
|
|
});
|
|
}
|
|
|
|
// Funkcja do pobierania listy workflow runs
|
|
async function getWorkflowRuns() {
|
|
const url = `${config.baseUrl}/api/v1/repos/${config.owner}/${config.repo}/actions/runs?limit=${config.scanLimit}`;
|
|
console.log(`Pobieranie workflow runs z: ${url}`);
|
|
|
|
try {
|
|
const response = await makeRequest(url);
|
|
return response.workflow_runs || [];
|
|
} catch (error) {
|
|
console.error('Błąd podczas pobierania workflow runs:', error.message);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Funkcja do pobierania artefaktów dla danego run
|
|
async function getRunArtifacts(runId) {
|
|
const url = `${config.baseUrl}/api/v1/repos/${config.owner}/${config.repo}/actions/runs/${runId}/artifacts`;
|
|
|
|
try {
|
|
const response = await makeRequest(url);
|
|
return response.artifacts || [];
|
|
} catch (error) {
|
|
console.warn(`Nie można pobrać artefaktów dla run ${runId}:`, error.message);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
// Główna funkcja
|
|
async function findLatestSuccessfulRunWithArtifacts() {
|
|
try {
|
|
const runs = await getWorkflowRuns();
|
|
console.log(`Znaleziono ${runs.length} workflow runs`);
|
|
|
|
for (const run of runs) {
|
|
console.log(`Sprawdzam run ${run.id} (${run.name}): status=${run.status}, conclusion=${run.conclusion}`);
|
|
|
|
// Sprawdzaj tylko udane buildy
|
|
if (run.status === 'completed' && run.conclusion === 'success') {
|
|
console.log(`Run ${run.id} zakończony sukcesem, sprawdzam artefakty...`);
|
|
|
|
const artifacts = await getRunArtifacts(run.id);
|
|
const artifactNames = artifacts.map(a => a.name);
|
|
|
|
console.log(`Artefakty w run ${run.id}:`, artifactNames);
|
|
|
|
// Sprawdź czy wszystkie wymagane artefakty są dostępne
|
|
const hasAllRequiredArtifacts = config.requiredArtifacts.every(required =>
|
|
artifactNames.includes(required)
|
|
);
|
|
|
|
if (hasAllRequiredArtifacts) {
|
|
console.log(`✅ Znaleziono odpowiedni run: ${run.id}`);
|
|
return run.id;
|
|
} else {
|
|
const missing = config.requiredArtifacts.filter(req => !artifactNames.includes(req));
|
|
console.log(`❌ Run ${run.id} nie ma wszystkich wymaganych artefaktów. Brakuje: ${missing.join(', ')}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
throw new Error('Nie znaleziono żadnego udanego buildu z wymaganymi artefaktami');
|
|
} catch (error) {
|
|
console.error('Błąd:', error.message);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
// Wykonanie skryptu
|
|
findLatestSuccessfulRunWithArtifacts().then(runId => {
|
|
console.log(`Ostatni udany build z artefaktami: ${runId}`);
|
|
|
|
// Utworzenie katalogu cache i zapisanie ID
|
|
const cacheDir = path.join('.gitea', '.cache');
|
|
if (!fs.existsSync(cacheDir)) {
|
|
fs.mkdirSync(cacheDir, { recursive: true });
|
|
}
|
|
|
|
fs.writeFileSync(path.join(cacheDir, 'run_id'), runId.toString());
|
|
console.log(`ID zapisane do .gitea/.cache/run_id`);
|
|
}).catch(error => {
|
|
console.error('Niepowodzenie:', error.message);
|
|
process.exit(1);
|
|
}); |