From 04174fff3b10bee506e179109cd162958c3e7eac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Zieli=C5=84ski?= Date: Mon, 13 Oct 2025 22:15:23 +0200 Subject: [PATCH] tokenize --- .gitea/scripts/replaceTokens.js | 100 ++++++++++++++------------------ 1 file changed, 43 insertions(+), 57 deletions(-) diff --git a/.gitea/scripts/replaceTokens.js b/.gitea/scripts/replaceTokens.js index 2121886..a0b993a 100644 --- a/.gitea/scripts/replaceTokens.js +++ b/.gitea/scripts/replaceTokens.js @@ -1,10 +1,25 @@ -// Replaces #{TOKEN-NAME}# with values from SECRETS/VARIABLES -// Converts: #{api-base-url}# -> API_BASE_URL (uppercase, - to _) -// Special: #{buildid}# -> RUN_ID +// .gitea/scripts/replaceTokens.js +// Skanuje: +// - artifacts/frontend/**/*.js +// - artifacts/webapi/appsettings.json (jeśli jest) +// - artifacts/webapi/client_secrets.json (jeśli jest) +// Tokeny: #{NAME}# -> wartość z VARIABLES/SECRETS (NAME: uppercased, '-'->'_') +// Dodatkowo: #{BUILDID}# -> RUN_ID (z ENV) const fs = require('fs'); const path = require('path'); +function walk(dir, predicate) { + const out = []; + if (!fs.existsSync(dir)) return out; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) out.push(...walk(full, predicate)); + else if (predicate(full)) out.push(full); + } + return out; +} + function replaceInFile(file, mapToken) { let data = fs.readFileSync(file, 'utf8'); const re = /#\{(.*?)\}#/g; @@ -12,74 +27,51 @@ function replaceInFile(file, mapToken) { data = data.replace(re, (_, raw) => { const token = (raw || '').replace(/-/g, '_').toUpperCase(); const val = mapToken(token); - if (val == null || val === '') { - return `#{${raw}}#`; // leave unchanged, will error later - } + if (val == null || val === '') return `#{${raw}}#`; // zostaw bez zmian, podbijemy błąd później changed = true; return String(val); }); - if (changed) { - fs.writeFileSync(file, data, 'utf8'); - } + fs.writeFileSync(file, data, 'utf8'); return changed; } (async () => { - // DEFENSIVE: handle null/undefined gracefully - let secrets = {}; - let variables = {}; - - try { - secrets = JSON.parse(process.env.SECRETS || '{}'); - } catch (e) { - console.warn('⚠️ Failed to parse SECRETS:', e.message); - } - - try { - variables = JSON.parse(process.env.VARIABLES || '{}'); - } catch (e) { - console.warn('⚠️ Failed to parse VARIABLES:', e.message); - } - + const secrets = JSON.parse(process.env.SECRETS || '{}'); + const variables = JSON.parse(process.env.VARIABLES || '{}'); const RUN_ID = process.env.RUN_ID || process.env.GITHUB_RUN_ID || ''; - console.log(`📦 Loaded ${Object.keys(secrets).length} secrets, ${Object.keys(variables).length} variables`); - const mapToken = (token) => { if (token === 'BUILDID') return RUN_ID; - - // Check variables first, then secrets - if (variables && variables[token] != null) { - return variables[token]; - } - if (secrets && secrets[token] != null) { - return secrets[token]; - } - return null; + return (variables[token] != null ? variables[token] : secrets[token]); }; - const files = [ - 'artifacts/api/appsettings.Production.json', - 'artifacts/ui/appsettings.Production.json' - ].map(f => path.resolve(f)).filter(f => fs.existsSync(f)); + // 1) Frontend: wszystkie .js + const feRoot = path.resolve('artifacts/frontend'); + const feFiles = walk(feRoot, (f) => f.endsWith('.js')); + + // 2) Backend: wybrane pliki jeśli istnieją + const beRoot = path.resolve('artifacts/webapi'); + const beFiles = [] + ;['appsettings.json', 'client_secrets.json'].forEach((name) => { + const p = path.join(beRoot, name); + if (fs.existsSync(p)) beFiles.push(p); + }); + + const files = [...feFiles, ...beFiles]; if (files.length === 0) { - console.error('❌ No appsettings.Production.json files found in artifacts/'); + console.error('❌ No candidate files found to tokenize (frontend .js / backend json).'); process.exit(1); } - console.log(`🔎 Tokenizing ${files.length} file(s):`); - files.forEach(f => console.log(` - ${f}`)); - + console.log(`🔎 Tokenizing ${files.length} file(s)`); const missing = new Set(); - // First pass: replace tokens + // drugi przebieg: wypisz brakujące tokeny, jeśli jakieś zostały w plikach for (const file of files) { - console.log(`\n📝 Processing: ${path.basename(file)}`); + // pierwsze podejście: podstaw wartości replaceInFile(file, mapToken); } - - // Second pass: check for remaining tokens for (const file of files) { const content = fs.readFileSync(file, 'utf8'); const reLeft = /#\{(.*?)\}#/g; @@ -91,15 +83,9 @@ function replaceInFile(file, mapToken) { } if (missing.size > 0) { - console.error(`\n❌ Missing values for tokens: ${Array.from(missing).join(', ')}`); - console.error('\n💡 Make sure these secrets/variables are configured in Gitea repo settings:'); - console.error(' Settings → Secrets → Add secret'); + console.error(`❌ Missing values for tokens: ${Array.from(missing).join(', ')}`); process.exit(1); } - console.log('\n✅ Tokenization complete. All placeholders replaced.'); -})().catch(err => { - console.error('❌ Error during tokenization:'); - console.error(err.stack || err.message || String(err)); - process.exit(1); -}); \ No newline at end of file + console.log('✅ Tokenization complete.'); +})(); \ No newline at end of file