Files
szci/ts/mod_trigger/index.ts

102 lines
2.6 KiB
TypeScript
Raw Normal View History

import * as plugins from './mod.plugins.ts';
import { logger } from '../szci.logging.ts';
2016-06-01 06:30:21 +02:00
2025-12-14 01:42:14 +00:00
/**
* Interface for parsed trigger configuration
*/
interface ITriggerConfig {
domain: string;
projectId: string;
triggerToken: string;
refName: string;
triggerName: string;
}
2016-06-23 22:22:03 +02:00
2025-12-14 01:42:14 +00:00
/**
* Regex to parse trigger env var format:
* domain|projectId|triggerToken|refName|triggerName (optional)
*/
const TRIGGER_VALUE_REGEX =
/^([a-zA-Z0-9.]+)\|([a-zA-Z0-9.]+)\|([a-zA-Z0-9.]+)\|([a-zA-Z0-9.]+)\|?([a-zA-Z0-9.\-/]*)$/;
/**
* Execute all configured triggers from environment variables
*/
export const trigger = async (): Promise<void> => {
2018-11-24 15:00:19 +01:00
logger.log('info', 'now running triggers');
2025-12-14 01:42:14 +00:00
// Get all env vars and filter for triggers
const envVars = Deno.env.toObject();
const triggerEnvVars = Object.entries(envVars).filter(([key]) =>
key.startsWith('SZCI_TRIGGER_')
);
if (triggerEnvVars.length === 0) {
logger.log('info', 'no triggers configured');
return;
}
// Process each trigger
for (const [key, value] of triggerEnvVars) {
logger.log('info', `Processing trigger from ${key}`);
await executeTrigger(value);
}
logger.log('ok', `executed ${triggerEnvVars.length} trigger(s)`);
2018-04-04 22:25:13 +02:00
};
2016-06-23 22:22:03 +02:00
2025-12-14 01:42:14 +00:00
/**
* Parse a trigger env var string into a config object
*/
const parseTriggerConfig = (triggerEnvVar: string): ITriggerConfig | null => {
const match = TRIGGER_VALUE_REGEX.exec(triggerEnvVar);
if (!match) {
return null;
}
return {
domain: match[1],
projectId: match[2],
triggerToken: match[3],
refName: match[4],
triggerName: match[5] || 'Unnamed Trigger',
};
};
/**
* Execute a single trigger by calling the GitLab API
*/
const executeTrigger = async (triggerEnvVar: string): Promise<void> => {
const config = parseTriggerConfig(triggerEnvVar);
if (!config) {
logger.log('error', 'malformed trigger env var, expected format: domain|projectId|token|ref|name');
2025-12-13 13:27:51 +00:00
return;
}
2025-12-14 01:42:14 +00:00
logger.log('info', `Found Trigger: ${config.triggerName}`);
logger.log('info', `Triggering build for ref "${config.refName}" of "${config.triggerName}"`);
try {
await plugins.smartrequest.postFormData(
`https://${config.domain}/api/v3/projects/${config.projectId}/trigger/builds`,
{},
[
{
name: 'token',
payload: config.triggerToken,
type: 'string',
},
{
name: 'ref',
payload: config.refName,
type: 'string',
},
]
);
logger.log('ok', `Trigger "${config.triggerName}" executed successfully`);
} catch (error) {
logger.log('error', `Failed to execute trigger: ${(error as Error).message}`);
2017-03-08 14:50:41 +01:00
}
2018-04-04 22:25:13 +02:00
};