Author SHA1 Message Date
admin fab47acc95 openapi generated client
Python package / build (flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics, 3.12.3) (pull_request) Successful in 30s
Python package / build (flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics, 3.13) (pull_request) Successful in 32s
Python package / build (flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics, 3.14) (pull_request) Successful in 32s
Python package / build (flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics, 3.12.3) (pull_request) Failing after 52s
Python package / build (flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics, 3.13) (pull_request) Successful in 30s
Python package / build (flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics, 3.14) (pull_request) Successful in 34s
Python package / build (mypy --no-incremental --config-file mypy.ini backend tests, 3.12.3) (pull_request) Successful in 1m28s
Python package / build (mypy --no-incremental --config-file mypy.ini backend tests, 3.13) (pull_request) Successful in 1m35s
Python package / build (mypy --no-incremental --config-file mypy.ini backend tests, 3.14) (pull_request) Successful in 1m30s
Python package / build (pip list, 3.12.3) (pull_request) Successful in 31s
Python package / build (pip list, 3.13) (pull_request) Successful in 33s
Python package / build (pip list, 3.14) (pull_request) Successful in 31s
Python package / build (pytest --ignore=tests/integration, 3.12.3) (pull_request) Successful in 43s
Python package / build (pytest --ignore=tests/integration, 3.13) (pull_request) Successful in 46s
Python package / build (pytest --ignore=tests/integration, 3.14) (pull_request) Successful in 42s
Python package / build (python -c "import sys; print(f'Python {sys.version}'); print(f'Build: {sys.version_info}'); print(f'Implementation: {sys.implementation}')", 3.12.3) (pull_request) Successful in 29s
Python package / build (python -c "import sys; print(f'Python {sys.version}'); print(f'Build: {sys.version_info}'); print(f'Implementation: {sys.implementation}')", 3.13) (pull_request) Successful in 29s
Python package / build (python -c "import sys; print(f'Python {sys.version}'); print(f'Build: {sys.version_info}'); print(f'Implementation: {sys.implementation}')", 3.14) (pull_request) Successful in 28s
Verify OpenAPI types / Verify generated TypeScript matches committed types (pull_request) Successful in 3m15s
2026-04-14 22:06:35 +02:00
admin a453e20f49 x 2026-04-11 20:35:27 +02:00
GitHub Actions 8e77a8b1f6 Squash 2026-04-11 13:03:13 +00:00
23 changed files with 3660 additions and 796 deletions
@@ -0,0 +1,44 @@
name: Generate OpenAPI JavaScript client
on:
push:
paths:
- 'openapi.yaml'
- '.github/workflows/generate-openapi-client.yml'
workflow_dispatch: {}
jobs:
generate:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Java (required by OpenAPI Generator)
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
- name: Generate JavaScript client from OpenAPI
uses: openapitools/openapi-generator-cli@v2.5.0
with:
arguments: generate -i openapi.yaml -g javascript -o openapi-client-ts --additional-properties=useES6=true,projectName=brencher-openapi
- name: Generate Python FastAPI server from OpenAPI
uses: openapitools/openapi-generator-cli@v2.5.0
with:
arguments: generate -i openapi.yaml -g python-fastapi -o openapi-server-py --additional-properties=projectName=brencher-python-server,packageName=brencher_server
# docker run --rm -v "$PWD":/local openapitools/openapi-generator-cli generate -i /local/openapi.yaml -g python-fastapi -o /local/openapi-server-py --additional-properties=projectName=brencher-python-server,packageName=brencher_server
# docker run --rm -v "$PWD":/local openapitools/openapi-generator-cli generate -i /local/openapi.yaml -g javascript -o /local/openapi-client-ts --additional-properties=useES6=true,projectName=brencher-openapi
# - name: Commit generated client
# uses: EndBug/add-and-commit@v9
# with:
# author_name: github-actions
# author_email: actions@github.com
# message: "chore: regenerate OpenAPI JavaScript client"
# add: openapi-client-ts openapi-server-py
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -0,0 +1,34 @@
name: Verify OpenAPI types
on:
pull_request:
push:
branches: [ main ]
jobs:
verify-openapi-types:
name: Verify generated TypeScript matches committed types
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Generate types from OpenAPI
run: |
set -euo pipefail
npx --yes openapi-typescript openapi.yaml --output generated-openapi-types.ts
- name: Show diff and fail if different
run: |
set -euo pipefail
if ! command -v diff >/dev/null 2>&1; then echo "diff not found" && exit 2; fi
echo "Comparing generated types to frontend/src/types/api.ts"
if ! diff -u frontend/src/types/api.ts generated-openapi-types.ts; then
echo "OpenAPI types are out of date. Regenerate with: npx openapi-typescript openapi.yaml --output frontend/src/types/api.ts";
exit 1;
fi
+3 -1
View File
@@ -6,4 +6,6 @@ venv
.venv
LOCAL.md
.idea
docker-compose.yml.tmp
docker-compose.yml.tmp
frontend/node_modules
frontend/dist
+17 -3
View File
@@ -1,4 +1,16 @@
# Use official Python image with uv pre-installed
# Stage 1: Build React frontend
FROM node:20-alpine AS frontend-builder
WORKDIR /app/frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY openapi.yaml /app/openapi.yaml
COPY frontend/ ./
RUN npm run build
# Stage 2: Python backend
FROM python:3.12.3-alpine
# Install uv (if not present)
@@ -14,9 +26,11 @@ COPY requirements.txt ./
RUN uv venv .venv && \
uv pip install -r requirements.txt
# Copy backend and frontend
# Copy backend
COPY backend/ ./backend/
COPY frontend/ ./frontend/
# Copy built frontend from Stage 1
COPY --from=frontend-builder /app/frontend/dist ./frontend/dist
# Expose port for the web server
EXPOSE 5001
+1 -1
View File
@@ -56,7 +56,7 @@ app.add_middleware(
allow_headers=["*"],
)
FRONTEND_DIR = os.path.join(os.path.dirname(__file__), '../frontend')
FRONTEND_DIR = os.path.join(os.path.dirname(__file__), '../frontend/dist')
# In-memory state
environments: Dict[str, Environment] = {}
-501
View File
@@ -1,501 +0,0 @@
// Placeholder for frontend JS logic
// You can add your Socket.IO and UI code here
console.log('app.js loaded');
// WebSocket endpoint
const WS_URL = '/ws';
// DOM refs
const branchesList = document.getElementById('branches-list');
const statusBar = document.getElementById('status-bar');
const statusMessage = document.getElementById('status-message');
const closeStatus = document.getElementById('close-status');
const refreshBranchesBtn = document.getElementById('refresh-branches');
const applyChangesBtn = document.getElementById('apply-changes');
const branchFilter = document.getElementById('branch-filter');
// Branches list (flattened) for UI rendering: [{ envId, envName, branch, commits: [] }]
let branches = [];
let filteredBranches = [];
// Toggle state: show all branches or filtered
let showAllBranches = false;
// Environment runtime state storage:
// environmentsRaw: array as received from backend: [ [envObj, jobsArr], ... ]
let environmentsRaw = [];
// Per-environment maps
// selectedBranchesByEnv: envId -> Array<[branch, desiredCommit]>
const selectedBranchesByEnv = {};
// serverSelectedBranchesByEnv mirrors server's last known selection for diffing
const serverSelectedBranchesByEnv = {};
// columnsByEnv: envId -> { columnName: { branchName: value } }
// Populated from any step result that contains a `columns` key (e.g. GitUnmerge)
const columnsByEnv = {};
// Per-environment dry run state: envId -> bool
const dryRunByEnv = {};
// Single WebSocket connection
let ws = null;
function showStatus(message, isError = false) {
statusMessage.textContent = message;
statusBar.classList.remove('hidden');
statusBar.style.background = isError ? '#f8d7da' : '#e9ecef';
statusMessage.style.color = isError ? '#721c24' : '#333';
}
closeStatus.onclick = () => statusBar.classList.add('hidden');
function isChangesPending() {
// Determine if any environment has changed selections
return Object.keys(selectedBranchesByEnv).some(envId => {
const localSel = [...(selectedBranchesByEnv[envId] || [])].sort();
const serverSel = [...(serverSelectedBranchesByEnv[envId] || [])].sort();
return JSON.stringify(localSel) !== JSON.stringify(serverSel);
});
}
function checkForPendingChanges() {
if (isChangesPending()) applyChangesBtn.classList.remove('hidden');
else applyChangesBtn.classList.add('hidden');
}
function filterBranches() {
const filterText = branchFilter.value.toLowerCase().trim();
filteredBranches = branches.filter(({envId, branch, commits}) => {
const selList = selectedBranchesByEnv[envId] || [];
const isSelected = selList.some(([b]) => b === branch);
// Always show branches that appear in any column (e.g. deployed branches from GitUnmerge)
const envCols = columnsByEnv[envId] || {};
const isInColumns = Object.values(envCols).some(colData => branch in colData);
const isFiltered = !!filterText && branch.toLowerCase().includes(filterText);
const isFilteredByCommit = !!filterText && Array.isArray(commits) && commits.some(c => {
const shortHash = c.hexsha ? c.hexsha.substring(0, 8).toLowerCase() : '';
return (c.hexsha && c.hexsha.toLowerCase().includes(filterText)) ||
shortHash.includes(filterText) ||
(c.message && c.message.toLowerCase().includes(filterText)) ||
(c.author && c.author.toLowerCase().includes(filterText));
});
return showAllBranches || isSelected || isInColumns || isFiltered || isFilteredByCommit;
});
renderBranches();
}
function getCommitDropdownOptions(envId, branchName, desiredCommit) {
const branchObj = branches.find(b => b.envId === envId && b.branch === branchName);
let options = '';
const commits = branchObj && Array.isArray(branchObj.commits) ? branchObj.commits : [];
if (commits.length) {
const head = commits[0];
const headShort = head.hexsha ? head.hexsha.substring(0, 8) : '';
options += `<option value="HEAD" ${desiredCommit === 'HEAD' ? 'selected' : ''}>HEAD (${headShort} - ${(head.author || '').substring(0, 25)} - ${head.message ? head.message.substring(0, 50) + (head.message.length > 50 ? '...' : '') : ''})</option>`;
commits.forEach(c => {
const full = c.hexsha;
const shortHash = full ? full.substring(0, 8) : '';
const isSelected = desiredCommit === full || desiredCommit === shortHash;
options += `<option value="${full}" ${isSelected ? 'selected' : ''}>${shortHash} - ${(c.author || '').substring(0, 25)} - ${c.message ? c.message.substring(0, 50) + (c.message.length > 50 ? '...' : '') : ''}</option>`;
});
} else {
options += `<option value="HEAD" ${desiredCommit === 'HEAD' ? 'selected' : ''}>HEAD (no commits)</option>`;
}
const hasMatch = commits.some(c => {
const full = c.hexsha;
const shortHash = full ? full.substring(0, 8) : '';
return desiredCommit === full || desiredCommit === shortHash || desiredCommit === 'HEAD';
});
const isCustom = desiredCommit && desiredCommit !== 'HEAD' && !hasMatch;
options += `<option value="custom" ${isCustom ? 'selected' : ''}>Custom Commit</option>`;
return options;
}
function branchHasCommit(envId, branchName, commit) {
if (commit === 'HEAD') return true;
const branchObj = branches.find(b => b.envId === envId && b.branch === branchName);
if (!branchObj) return false;
return branchObj.commits?.some(c => {
const full = c.hexsha;
const shortHash = full ? full.substring(0, 8) : '';
return commit === full || commit === shortHash;
}) || false;
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
let renderedBranches = []
function renderBranches() {
if (JSON.stringify(filteredBranches) === JSON.stringify(renderedBranches) && JSON.stringify(dryRunByEnv) === JSON.stringify(renderedDryRunState)) {
return
}
checkForPendingChanges();
const branchesToShow = filteredBranches.length > 0 || branchFilter.value.trim() ? filteredBranches : branches;
if (!branchesToShow.length) {
branchesList.innerHTML = '<p class="loading">No branches found.</p>';
return;
}
// Group by envId for clearer separation
const groups = branchesToShow.reduce((acc, b) => {
acc[b.envId] = acc[b.envId] || {envName: b.envName, rows: []};
acc[b.envId].rows.push(b);
return acc;
}, {});
branchesList.innerHTML = Object.entries(groups).map(([envId, {envName, rows}]) => {
const envCols = columnsByEnv[envId] || {};
const colNames = Object.keys(envCols);
return `
<div class="env-block">
<h3 class="env-title">
Environment: ${envName || envId}
<button class="dry-run-btn ${dryRunByEnv[envId] ? 'dry-run-active' : ''}" data-env="${envId}" title="${dryRunByEnv[envId] ? 'Dry run on — click to resume' : 'Running — click to pause (dry run)'}">
${dryRunByEnv[envId] ? '⏸' : '▶'}
</button>
</h3>
<table class="branches-table">
<thead>
<tr>
<th>Deploy</th>
<th>Branch</th>
<th>Desired Commit</th>
${colNames.map(n => `<th>${escapeHtml(n)}</th>`).join('')}
</tr>
</thead>
<tbody>
${rows.map(({envId: eId, branch}) => {
const selList = selectedBranchesByEnv[eId] || [];
const pair = selList.find(([b]) => b === branch);
const desiredCommit = pair ? pair[1] : 'HEAD';
const hasCommit = branchHasCommit(eId, branch, desiredCommit);
return `
<tr class="branch-row" data-env="${eId}" data-branch="${branch}">
<td><input type="checkbox" value="${branch}" data-env="${eId}" ${pair ? 'checked' : ''}></td>
<td>${branch}</td>
<td>
<select class="desired-commit" data-branch="${branch}" data-env="${eId}">
${getCommitDropdownOptions(eId, branch, desiredCommit)}
</select>
<input type="text" class="commit-input" data-branch="${branch}" data-env="${eId}"
value="${desiredCommit !== 'HEAD' && !hasCommit ? desiredCommit : ''}"
placeholder="Enter commit ID" style="display: ${desiredCommit !== 'HEAD' && !hasCommit ? 'inline-block' : 'none'};" />
</td>
${colNames.map(n => `<td>${escapeHtml((envCols[n] && envCols[n][branch]) || '')}</td>`).join('')}
</tr>`;
}).join('')}
</tbody>
</table>
</div>`;
}).join('');
// Event wiring
branchesList.querySelectorAll('input[type="checkbox"]').forEach(cb => {
cb.onchange = e => {
const branch = e.target.value;
const envId = e.target.dataset.env;
selectedBranchesByEnv[envId] = selectedBranchesByEnv[envId] || [];
if (e.target.checked) {
if (!selectedBranchesByEnv[envId].some(([b]) => b === branch)) {
selectedBranchesByEnv[envId].push([branch, 'HEAD']);
}
} else {
selectedBranchesByEnv[envId] = selectedBranchesByEnv[envId].filter(([b]) => b !== branch);
}
checkForPendingChanges();
};
});
branchesList.querySelectorAll('.desired-commit').forEach(sel => {
sel.onchange = e => {
const branch = e.target.dataset.branch;
const envId = e.target.dataset.env;
const commitInput = branchesList.querySelector(`.commit-input[data-env="${envId}"][data-branch="${branch}"]`);
if (e.target.value === 'custom') {
commitInput.style.display = 'inline-block';
commitInput.focus();
} else if (e.target.value === 'HEAD') {
commitInput.style.display = 'none';
updateBranchCommit(envId, branch, 'HEAD');
} else {
commitInput.style.display = 'none';
updateBranchCommit(envId, branch, e.target.value);
}
};
});
branchesList.querySelectorAll('.commit-input').forEach(input => {
input.onchange = input.onblur = e => {
const branch = e.target.dataset.branch;
const envId = e.target.dataset.env;
const commitId = e.target.value.trim();
updateBranchCommit(envId, branch, commitId || 'HEAD');
};
});
branchesList.querySelectorAll('.dry-run-btn').forEach(btn => {
btn.onclick = e => {
const envId = e.currentTarget.dataset.env;
dryRunByEnv[envId] = !dryRunByEnv[envId];
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ update: { id: envId, dry: dryRunByEnv[envId] } }));
}
filterBranches();
};
});
renderedBranches = filteredBranches;
renderedDryRunState = {...dryRunByEnv};
}
function updateBranchCommit(envId, branch, commit) {
selectedBranchesByEnv[envId] = selectedBranchesByEnv[envId] || [];
const idx = selectedBranchesByEnv[envId].findIndex(([b]) => b === branch);
if (idx !== -1) selectedBranchesByEnv[envId][idx] = [branch, commit];
checkForPendingChanges();
}
function renderJobs() {
const jobsList = document.getElementById('jobs-list');
if (!jobsList) return;
if (!Array.isArray(environmentsRaw) || environmentsRaw.length === 0) {
jobsList.innerHTML = '<p class="loading">No jobs found.</p>';
return;
}
jobsList.innerHTML = environmentsRaw
.slice()
.sort((a, b) => (a.name || a.id || '').localeCompare(b.name || b.id || ''))
.map((envObj) => {
var linksHtml = ""
const jobsArr = envObj.pipeline || [];
if (Array.isArray(jobsArr)) {
linksHtml = jobsArr.flatMap(job => {
const userLinks = [];
const extractUserLinks = (obj) => {
if (!obj || typeof obj !== 'object') return;
if (obj.userLinks && typeof obj.userLinks === 'object') {
userLinks.push(...Object.entries(obj.userLinks));
}
for (const key in obj) {
if (typeof obj[key] === 'object') {
extractUserLinks(obj[key]);
}
}
};
extractUserLinks(job.status);
return userLinks.map(([title, url]) =>
`<a href="${url}" target="_blank" rel="noopener noreferrer">${title}</a>`
)
})
.join(' | ');
}
return `
<div class="env-jobs">
<h4>Environment: ${envObj.name || envObj.id || ''}</h4>
${linksHtml ? `<div style="float:right">${linksHtml}</div>` : ''}
${Array.isArray(jobsArr) && jobsArr.length > 0
? jobsArr.map(job => {
let statusDisplay = `<pre>` + JSON.stringify(job.status, null, 2) + `</pre>`;
statusDisplay = statusDisplay.replace(
/(https?:\/\/[^\s"']+)/g,
url => `<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`
);
const key = `${envObj.id}::${job.name}`;
const storageKey = 'jobSpoiler:' + key;
const safeId = 'spoiler-' + encodeURIComponent(key).replace(/[^a-zA-Z0-9_-]/g, '_');
const isError = job.error;
const isRunning = !!job.is_running;
const openByDefault = isError || (window._jobSpoilerState && window._jobSpoilerState[storageKey] === 'open');
return `
<div class="job-item">
<div class="job-header" style="cursor:pointer;font-weight:bold;"
onclick="toggleJobSpoiler('${key}', '${safeId}')">
${isRunning
? `<span class="step-spinner" title="Running"></span>`
: isError
? `<span style="color:#dc3545;font-weight:bold;margin-right:6px;" title="Error">!</span>`
: `<span style="color:#28a745;font-weight:bold;margin-right:6px;" title="OK">✔</span>`}
${envObj.id} - ${job.name}
</div>
<div id="${safeId}" class="job-spoiler" style="display: ${openByDefault ? 'block' : 'none'}; margin-top:8px;">
${statusDisplay}
</div>
</div>`;
}).join('')
: '<div class="job-item">No jobs found.</div>'}
</div>`;
}).join('');
}
toggleJobSpoiler = function (key, safeId) {
try {
const el = document.getElementById(safeId);
if (!el) return;
const storageKey = 'jobSpoiler:' + key;
const isHidden = window.getComputedStyle(el).display === 'none';
window._jobSpoilerState = window._jobSpoilerState || {};
if (isHidden) {
el.style.display = 'block';
window._jobSpoilerState[storageKey] = 'open';
} else {
el.style.display = 'none';
window._jobSpoilerState[storageKey] = 'closed';
}
} catch (err) {
console.error('toggleJobSpoiler error', err);
}
};
refreshBranchesBtn.onclick = () => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ update: { id: "" } }));
}
showStatus('Refreshing...');
};
// Filter event handler
branchFilter.oninput = () => {
filterBranches();
};
// Toggle show all button handler
const toggleShowAllBtn = document.getElementById('toggle-show-all');
if (toggleShowAllBtn) {
toggleShowAllBtn.onclick = () => {
showAllBranches = !showAllBranches;
toggleShowAllBtn.textContent = showAllBranches ? 'Show Filtered' : 'Show All';
filterBranches();
};
}
// Apply changes button handler
applyChangesBtn.onclick = () => {
updateEnvironment();
};
// Single WebSocket setup
function setupWebSockets() {
// Close existing connection before reconnecting
if (ws && ws.readyState !== WebSocket.CLOSED) {
ws.onclose = null; // Prevent recursive reconnect
ws.close();
}
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
ws = new WebSocket(`${protocol}//${host}${WS_URL}`);
ws.onopen = () => console.log('WebSocket connected');
ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data);
if ('branches' in message) {
const data = message.branches;
// data: { envId: { branchName: commits[] } }
branches = Object.entries(data).flatMap(([envId, branchMap]) =>
Object.entries(branchMap).map(([branchName, commitList]) => {
const envObj = (environmentsRaw.find((e) => e.id === envId) || [null])[0];
return { envId, envName: envObj ? (envObj.name || envObj.id) : envId, branch: branchName, commits: commitList };
})
);
filterBranches();
showStatus('Branches updated.');
} else if ('environments' in message) {
const data = message.environments;
payload = data || {};
environmentsRaw = Object.values(payload);
// Sync selections and column data per environment
environmentsRaw.forEach((envObj) => {
if (!envObj) return;
const envId = envObj.id || envObj.name || 'unknown';
// Always sync dry run state from server
dryRunByEnv[envId] = !!envObj.dry;
if (!isChangesPending()) {
if (Array.isArray(envObj.branches) && envObj.branches.length > 0) {
if (Array.isArray(envObj.branches[0])) {
selectedBranchesByEnv[envId] = [...envObj.branches];
} else {
selectedBranchesByEnv[envId] = envObj.branches.map(b => [b, 'HEAD']);
}
serverSelectedBranchesByEnv[envId] = [...selectedBranchesByEnv[envId]];
} else if (!selectedBranchesByEnv[envId]) {
selectedBranchesByEnv[envId] = [];
serverSelectedBranchesByEnv[envId] = [];
}
}
// Extract columns from all job statuses
columnsByEnv[envId] = {};
const jobsArr = envObj.pipeline || [];
if (Array.isArray(jobsArr)) {
jobsArr.forEach(job => {
if (job.status == null || job.error) return;
const status = job.status;
// New structured format: status is an object with a `columns` key
if (typeof status === 'object' && !Array.isArray(status) && status.columns &&
typeof status.columns === 'object') {
Object.entries(status.columns).forEach(([colName, colData]) => {
if (colData && typeof colData === 'object' && !Array.isArray(colData)) {
columnsByEnv[envId][colName] = {...colData};
}
});
}
});
}
});
// Rebuild branches list environment names for rows already present
branches = branches.map(b => {
const envEntry = environmentsRaw.find((e) => (e.id || e.name) === b.envId);
return { ...b, envName: envEntry ? (envEntry.name || envEntry.id) : b.envName };
});
filterBranches();
renderJobs();
showStatus('Environments updated.');
} else if ('error' in message) {
console.error('Error from server:', message.error);
showStatus(message.error.message || 'Unknown error', true);
}
checkForPendingChanges();
} catch (e) {
console.error('Error processing WebSocket message:', e);
}
};
ws.onclose = () => {
showStatus('Disconnected from server.', true);
setTimeout(() => setupWebSockets(), 5000);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
function updateEnvironment() {
// Emit updates only for environments whose selection changed
Object.keys(selectedBranchesByEnv).forEach(envId => {
const localSel = [...(selectedBranchesByEnv[envId] || [])].sort();
const serverSel = [...(serverSelectedBranchesByEnv[envId] || [])].sort();
if (JSON.stringify(localSel) !== JSON.stringify(serverSel)) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ update: { id: envId, branches: selectedBranchesByEnv[envId] } }));
}
// Optimistically sync server state
serverSelectedBranchesByEnv[envId] = [...selectedBranchesByEnv[envId]];
branchFilter.value = '';
}
});
checkForPendingChanges();
showStatus('Changes applied (pending server confirmation).');
}
// Initial load
setupWebSockets();
showStatus('Loading branches...');
renderBranches();
renderJobs();
+8 -48
View File
@@ -1,52 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Brencher - Branch Merger</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<header>
<h1>Brencher - Branch Merger</h1>
<div id="status-bar" class="status-bar hidden">
<span id="status-message"></span>
<button id="close-status">×</button>
</div>
</header>
<main>
<div class="branches-section">
<h2 style="float: left;">Git Branches</h2>
<div class="filter-section" style="float: left;">
<input type="text" id="branch-filter"
placeholder="Filter branches by name, commit ID, or commit message..." class="filter-input">
</div>
<div class="control-bar" style="float: left;">
<button id="toggle-show-all" class="toggle-button">Show All</button>
</div>
<div class="control-bar" style="float: right;">
<button id="refresh-branches" class="refresh-button">Refresh Branches</button>
</div>
<div class="apply-section" style="float: right;">
<button id="apply-changes" class="apply-button hidden">Apply Changes</button>
</div>
<div style="clear: both;"/>
<div class="branches-list" id="branches-list">
<p class="loading">Loading branches...</p>
</div>
</div>
<div class="jobs-section">
<h2>Jobs</h2>
<div id="jobs-list" class="jobs-list">
<p class="loading">Loading jobs...</p>
</div>
</div>
</main>
</div>
<script src="app.js"></script>
</body>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2137
View File
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
{
"name": "brencher-frontend",
"version": "1.0.0",
"private": true,
"scripts": {
"generate-types": "openapi-typescript ../openapi.yaml -o src/types/api.ts",
"prebuild": "npm run generate-types",
"build": "vite build",
"dev": "vite"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"openapi-typescript": "^7.4.4",
"typescript": "^5.7.2",
"vite": "^6.0.5"
}
}
+239
View File
@@ -0,0 +1,239 @@
/* Base */
body {
font-family: Arial, sans-serif;
background: #f8f9fa;
margin: 0;
padding: 0;
}
.container {
max-width: 960px;
margin: 40px auto;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
padding: 32px;
}
/* Header */
header h1 {
margin: 0 0 12px;
}
/* Status bar */
.status-bar {
background: #e9ecef;
padding: 8px 16px;
border-radius: 4px;
margin-bottom: 16px;
display: flex;
align-items: center;
gap: 12px;
}
.close-status-btn {
margin-left: auto;
background: none;
border: none;
font-size: 1.2rem;
cursor: pointer;
color: #555;
line-height: 1;
}
.close-status-btn:hover {
color: #000;
}
/* Branches section header */
.branches-header {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.branches-header h2 {
margin: 0;
flex-shrink: 0;
}
.branches-controls-left {
display: flex;
flex: 1;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.branches-controls-right {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
/* Buttons */
.refresh-button,
.apply-button,
.toggle-button {
background: #28a745;
color: #fff;
border: none;
border-radius: 4px;
padding: 8px 16px;
cursor: pointer;
font-size: 0.95rem;
white-space: nowrap;
}
.refresh-button:hover,
.apply-button:hover,
.toggle-button:hover {
background: #218838;
}
/* Filter */
.filter-input {
flex: 1;
min-width: 220px;
padding: 8px 12px;
border: 1px solid #ced4da;
border-radius: 4px;
font-size: 0.95rem;
box-sizing: border-box;
}
.filter-input:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}
/* Branches list */
.branches-list {
margin-top: 8px;
}
.loading {
color: #888;
font-style: italic;
}
/* Environment block */
.env-block {
margin-bottom: 24px;
}
.env-title {
margin: 0 0 8px;
color: #495057;
}
/* Branches table */
.branches-table {
width: 100%;
border-collapse: collapse;
margin: 0;
}
.branches-table th {
background: #f8f9fa;
padding: 10px 8px;
text-align: left;
font-weight: 600;
color: #495057;
border-bottom: 2px solid #dee2e6;
}
.branches-table td {
padding: 10px 8px;
vertical-align: middle;
border-bottom: 1px solid #dee2e6;
}
.branch-row:hover {
background: #f8f9fa;
}
.branch-name {
font-weight: 500;
}
.desired-commit {
margin-right: 6px;
padding: 4px 8px;
border: 1px solid #ced4da;
border-radius: 4px;
font-size: 0.9em;
}
.commit-input {
padding: 4px 8px;
border: 1px solid #ced4da;
border-radius: 4px;
font-size: 0.9em;
width: 200px;
font-family: monospace;
}
input[type='checkbox'] {
margin: 0;
transform: scale(1.2);
cursor: pointer;
}
/* Jobs section */
.jobs-section {
margin-top: 32px;
}
.jobs-section h2 {
margin: 0 0 12px;
}
.jobs-list {
margin-top: 8px;
}
.env-jobs {
margin-bottom: 20px;
overflow: hidden;
}
.env-jobs h4 {
margin: 0 0 8px;
color: #495057;
}
.job-item {
margin-bottom: 8px;
border: 1px solid #dee2e6;
border-radius: 4px;
padding: 8px 12px;
}
.job-header {
user-select: none;
}
.job-header:hover {
color: #007bff;
}
.job-spoiler pre {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 4px;
padding: 8px 12px;
overflow-x: auto;
font-size: 0.85em;
white-space: pre-wrap;
word-break: break-all;
}
.job-spoiler a {
color: #007bff;
word-break: break-all;
}
+268
View File
@@ -0,0 +1,268 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import './App.css';
import { BranchesList } from './components/BranchesList';
import type { BranchItem, ColumnsByEnv, SelectedBranches } from './components/BranchesList';
import { JobsList } from './components/JobsList';
import { StatusBar } from './components/StatusBar';
import { useWebSocket } from './hooks/useWebSocket';
import type { BranchCommitPair, EnvironmentDto } from './types/index';
export function App() {
const { sendMessage, lastBranchesMessage, lastEnvironmentsMessage, lastError, connectionStatus } =
useWebSocket();
const [branches, setBranches] = useState<BranchItem[]>([]);
const [environments, setEnvironments] = useState<EnvironmentDto[]>([]);
const [selectedBranchesByEnv, setSelectedBranchesByEnv] = useState<SelectedBranches>({});
const [serverSelectedBranchesByEnv, setServerSelectedBranchesByEnv] = useState<SelectedBranches>({});
const [columnsByEnv, setColumnsByEnv] = useState<ColumnsByEnv>({});
const [filterText, setFilterText] = useState('');
const [showAll, setShowAll] = useState(false);
const [statusMessage, setStatusMessage] = useState<string | null>('Loading branches...');
const [isStatusError, setIsStatusError] = useState(false);
const showStatus = useCallback((message: string, isError = false) => {
setStatusMessage(message);
setIsStatusError(isError);
}, []);
// Handle incoming branches
useEffect(() => {
if (!lastBranchesMessage) return;
const data = lastBranchesMessage;
setBranches(() => {
const next: BranchItem[] = Object.entries(data).flatMap(([envId, branchMap]) =>
Object.entries(branchMap).map(([branchName, commitList]) => ({
envId,
branch: branchName,
commits: commitList,
}))
);
// Replace all branches with the latest data from the server
return next;
});
showStatus('Branches updated.');
}, [lastBranchesMessage, showStatus]);
// Handle incoming environments
useEffect(() => {
if (!lastEnvironmentsMessage) return;
const payload = lastEnvironmentsMessage;
const envList = Object.values(payload);
setEnvironments(envList);
setSelectedBranchesByEnv((prevSelected) => {
// We need server state inline to check pending changes; use functional update
let nextSelected = prevSelected;
setServerSelectedBranchesByEnv((prevServer) => {
// Check if changes are pending before overwriting selections
const hasPending = Object.keys(prevSelected).some((envId) => {
const localSel = [...(prevSelected[envId] ?? [])].sort((a, b) =>
JSON.stringify(a).localeCompare(JSON.stringify(b))
);
const serverSel = [...(prevServer[envId] ?? [])].sort((a, b) =>
JSON.stringify(a).localeCompare(JSON.stringify(b))
);
return JSON.stringify(localSel) !== JSON.stringify(serverSel);
});
const nextServerState = { ...prevServer };
const updatedSelected = { ...prevSelected };
envList.forEach((envObj) => {
const envId = envObj.id;
if (!hasPending) {
if (Array.isArray(envObj.branches) && envObj.branches.length > 0) {
const pairs: BranchCommitPair[] = Array.isArray(envObj.branches[0])
? (envObj.branches as BranchCommitPair[])
: envObj.branches.map((b) => [b as unknown as string, 'HEAD'] as BranchCommitPair);
updatedSelected[envId] = [...pairs];
nextServerState[envId] = [...pairs];
} else if (!updatedSelected[envId]) {
updatedSelected[envId] = [];
nextServerState[envId] = [];
}
}
});
nextSelected = updatedSelected;
return nextServerState;
});
return nextSelected;
});
// Extract column data from pipeline steps
setColumnsByEnv((prev) => {
const next = { ...prev };
envList.forEach((envObj) => {
const envId = envObj.id;
next[envId] = {};
const jobsArr = envObj.pipeline ?? [];
jobsArr.forEach((job) => {
if (job.status == null || job.error) return;
const status = job.status;
if (
typeof status === 'object' &&
!Array.isArray(status) &&
status !== null &&
'columns' in status
) {
const cols = (status as Record<string, unknown>).columns;
if (cols && typeof cols === 'object' && !Array.isArray(cols)) {
Object.entries(cols as Record<string, unknown>).forEach(([colName, colData]) => {
if (colData && typeof colData === 'object' && !Array.isArray(colData)) {
next[envId][colName] = colData as Record<string, string>;
}
});
}
}
});
});
return next;
});
showStatus('Environments updated.');
}, [lastEnvironmentsMessage, showStatus]);
// Handle incoming errors
useEffect(() => {
if (!lastError) return;
showStatus(lastError.message || 'Unknown error', true);
}, [lastError, showStatus]);
// Show connection status changes
useEffect(() => {
if (connectionStatus === 'disconnected') {
showStatus('Disconnected from server.', true);
}
}, [connectionStatus, showStatus]);
const isChangesPending = useMemo(() => {
return Object.keys(selectedBranchesByEnv).some((envId) => {
const localSel = [...(selectedBranchesByEnv[envId] ?? [])].sort((a, b) =>
JSON.stringify(a).localeCompare(JSON.stringify(b))
);
const serverSel = [...(serverSelectedBranchesByEnv[envId] ?? [])].sort((a, b) =>
JSON.stringify(a).localeCompare(JSON.stringify(b))
);
return JSON.stringify(localSel) !== JSON.stringify(serverSel);
});
}, [selectedBranchesByEnv, serverSelectedBranchesByEnv]);
const filteredBranches = useMemo(() => {
const text = filterText.toLowerCase().trim();
return branches.filter(({ envId, branch, commits }) => {
const selList = selectedBranchesByEnv[envId] ?? [];
const isSelected = selList.some(([b]) => b === branch);
const envCols = columnsByEnv[envId] ?? {};
const isInColumns = Object.values(envCols).some((colData) => branch in colData);
if (showAll) return true;
if (isSelected || isInColumns) return true;
if (!text) return false;
if (branch.toLowerCase().includes(text)) return true;
return commits.some((c) => {
const shortHash = c.hexsha ? c.hexsha.substring(0, 8).toLowerCase() : '';
return (
c.hexsha?.toLowerCase().includes(text) ||
shortHash.includes(text) ||
c.message?.toLowerCase().includes(text) ||
c.author?.toLowerCase().includes(text)
);
});
});
}, [branches, filterText, showAll, selectedBranchesByEnv, columnsByEnv]);
const handleSelectionChange = useCallback((envId: string, updated: BranchCommitPair[]) => {
setSelectedBranchesByEnv((prev) => ({ ...prev, [envId]: updated }));
}, []);
const handleApplyChanges = useCallback(() => {
Object.keys(selectedBranchesByEnv).forEach((envId) => {
const localSel = [...(selectedBranchesByEnv[envId] ?? [])].sort((a, b) =>
JSON.stringify(a).localeCompare(JSON.stringify(b))
);
const serverSel = [...(serverSelectedBranchesByEnv[envId] ?? [])].sort((a, b) =>
JSON.stringify(a).localeCompare(JSON.stringify(b))
);
if (JSON.stringify(localSel) !== JSON.stringify(serverSel)) {
sendMessage({ update: { id: envId, branches: selectedBranchesByEnv[envId] } });
setServerSelectedBranchesByEnv((prev) => ({
...prev,
[envId]: [...(selectedBranchesByEnv[envId] ?? [])],
}));
}
});
setFilterText('');
showStatus('Changes applied (pending server confirmation).');
}, [selectedBranchesByEnv, serverSelectedBranchesByEnv, sendMessage, showStatus]);
const handleRefresh = useCallback(() => {
sendMessage({ update: { id: '' } });
showStatus('Refreshing...');
}, [sendMessage, showStatus]);
return (
<div className="container">
<header>
<h1>Brencher - Branch Merger</h1>
<StatusBar
message={statusMessage}
isError={isStatusError}
onClose={() => setStatusMessage(null)}
/>
</header>
<main>
<div className="branches-section">
<div className="branches-header">
<h2>Git Branches</h2>
<div className="branches-controls-left">
<input
type="text"
className="filter-input"
placeholder="Filter branches by name, commit ID, or commit message..."
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
/>
<button
className="toggle-button"
onClick={() => setShowAll((v) => !v)}
>
{showAll ? 'Show Filtered' : 'Show All'}
</button>
</div>
<div className="branches-controls-right">
{isChangesPending && (
<button className="apply-button" onClick={handleApplyChanges}>
Apply Changes
</button>
)}
<button className="refresh-button" onClick={handleRefresh}>
Refresh Branches
</button>
</div>
</div>
<div className="branches-list">
<BranchesList
branches={filteredBranches}
environments={environments}
selectedBranchesByEnv={selectedBranchesByEnv}
columnsByEnv={columnsByEnv}
onSelectionChange={handleSelectionChange}
/>
</div>
</div>
<div className="jobs-section">
<h2>Jobs</h2>
<JobsList environments={environments} />
</div>
</main>
</div>
);
}
+208
View File
@@ -0,0 +1,208 @@
import type { BranchCommitPair, CommitInfo, EnvironmentDto } from '../types/index';
export interface BranchItem {
envId: string;
branch: string;
commits: CommitInfo[];
}
export type SelectedBranches = Record<string, BranchCommitPair[]>;
export type ColumnsByEnv = Record<string, Record<string, Record<string, string>>>;
interface BranchesListProps {
branches: BranchItem[];
environments: EnvironmentDto[];
selectedBranchesByEnv: SelectedBranches;
columnsByEnv: ColumnsByEnv;
onSelectionChange: (envId: string, branches: BranchCommitPair[]) => void;
}
function getCommitOptions(commits: CommitInfo[], desiredCommit: string): { value: string; label: string; selected: boolean }[] {
const opts: { value: string; label: string; selected: boolean }[] = [];
if (commits.length > 0) {
const head = commits[0];
const headShort = head.hexsha ? head.hexsha.substring(0, 8) : '';
const headAuthor = (head.author || '').substring(0, 25);
const headMsg = head.message
? head.message.substring(0, 50) + (head.message.length > 50 ? '...' : '')
: '';
opts.push({
value: 'HEAD',
label: `HEAD (${headShort} - ${headAuthor} - ${headMsg})`,
selected: desiredCommit === 'HEAD',
});
for (const c of commits) {
const full = c.hexsha;
const shortHash = full ? full.substring(0, 8) : '';
const author = (c.author || '').substring(0, 25);
const msg = c.message
? c.message.substring(0, 50) + (c.message.length > 50 ? '...' : '')
: '';
opts.push({
value: full,
label: `${shortHash} - ${author} - ${msg}`,
selected: desiredCommit === full || desiredCommit === shortHash,
});
}
} else {
opts.push({ value: 'HEAD', label: 'HEAD (no commits)', selected: desiredCommit === 'HEAD' });
}
const hasMatch = commits.some(
(c) => desiredCommit === c.hexsha || desiredCommit === c.hexsha?.substring(0, 8) || desiredCommit === 'HEAD'
);
const isCustom = desiredCommit && desiredCommit !== 'HEAD' && !hasMatch;
opts.push({ value: 'custom', label: 'Custom Commit', selected: isCustom });
return opts;
}
function branchHasCommit(commits: CommitInfo[], commit: string): boolean {
if (commit === 'HEAD') return true;
return commits.some((c) => c.hexsha === commit || c.hexsha?.substring(0, 8) === commit);
}
interface BranchRowProps {
envId: string;
branch: string;
commits: CommitInfo[];
selectedBranches: BranchCommitPair[];
colNames: string[];
colData: Record<string, Record<string, string>>;
onSelectionChange: (branches: BranchCommitPair[]) => void;
}
function BranchRow({ envId, branch, commits, selectedBranches, colNames, colData, onSelectionChange }: BranchRowProps) {
const pair = selectedBranches.find(([b]) => b === branch);
const isChecked = !!pair;
const desiredCommit = pair ? pair[1] : 'HEAD';
const isCustom = desiredCommit !== 'HEAD' && !branchHasCommit(commits, desiredCommit);
const updateCommit = (commit: string) => {
const updated = selectedBranches.map(([b, c]) => (b === branch ? [b, commit] as BranchCommitPair : [b, c] as BranchCommitPair));
onSelectionChange(updated);
};
const handleCheckbox = (checked: boolean) => {
if (checked) {
if (!selectedBranches.some(([b]) => b === branch)) {
onSelectionChange([...selectedBranches, [branch, 'HEAD']]);
}
} else {
onSelectionChange(selectedBranches.filter(([b]) => b !== branch));
}
};
const handleDropdownChange = (value: string) => {
if (value === 'custom') {
// show text input - handled via isCustom state derived from desiredCommit
updateCommit('');
} else if (value === 'HEAD') {
updateCommit('HEAD');
} else {
updateCommit(value);
}
};
const dropdownValue = isCustom ? 'custom' : desiredCommit;
const options = getCommitOptions(commits, desiredCommit);
return (
<tr className="branch-row" data-env={envId} data-branch={branch}>
<td>
<input
type="checkbox"
checked={isChecked}
onChange={(e) => handleCheckbox(e.target.checked)}
/>
</td>
<td className="branch-name">{branch}</td>
<td>
<select
className="desired-commit"
value={dropdownValue}
onChange={(e) => handleDropdownChange(e.target.value)}
>
{options.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
{isCustom && (
<input
type="text"
className="commit-input"
value={desiredCommit}
placeholder="Enter commit ID"
onChange={(e) => updateCommit(e.target.value)}
onBlur={(e) => {
const val = e.target.value.trim();
updateCommit(val || 'HEAD');
}}
/>
)}
</td>
{colNames.map((colName) => (
<td key={colName}>{colData[colName]?.[branch] ?? ''}</td>
))}
</tr>
);
}
export function BranchesList({
branches,
environments: _environments,
selectedBranchesByEnv,
columnsByEnv,
onSelectionChange,
}: BranchesListProps) {
if (branches.length === 0) {
return <p className="loading">No branches found.</p>;
}
// Group branches by envId
const groups = branches.reduce<Record<string, BranchItem[]>>((acc, b) => {
acc[b.envId] = acc[b.envId] ?? [];
acc[b.envId].push(b);
return acc;
}, {});
return (
<>
{Object.entries(groups).map(([envId, rows]) => {
const envCols = columnsByEnv[envId] ?? {};
const colNames = Object.keys(envCols);
const selectedBranches = selectedBranchesByEnv[envId] ?? [];
return (
<div key={envId} className="env-block">
<h3 className="env-title">Environment: {envId}</h3>
<table className="branches-table">
<thead>
<tr>
<th>Deploy</th>
<th>Branch</th>
<th>Desired Commit</th>
{colNames.map((n) => <th key={n}>{n}</th>)}
</tr>
</thead>
<tbody>
{rows.map(({ branch, commits }) => (
<BranchRow
key={`${envId}-${branch}`}
envId={envId}
branch={branch}
commits={commits}
selectedBranches={selectedBranches}
colNames={colNames}
colData={envCols}
onSelectionChange={(updated) => onSelectionChange(envId, updated)}
/>
))}
</tbody>
</table>
</div>
);
})}
</>
);
}
+145
View File
@@ -0,0 +1,145 @@
import { useRef, useState } from 'react';
import type { EnvironmentDto, PipelineStep } from '../types/index';
interface JobsListProps {
environments: EnvironmentDto[];
}
function extractUserLinks(obj: unknown): [string, string][] {
if (!obj || typeof obj !== 'object') return [];
const result: [string, string][] = [];
const rec = obj as Record<string, unknown>;
if (rec.userLinks && typeof rec.userLinks === 'object' && !Array.isArray(rec.userLinks)) {
const links = rec.userLinks as Record<string, unknown>;
for (const [title, url] of Object.entries(links)) {
if (typeof url === 'string') result.push([title, url]);
}
}
for (const key of Object.keys(rec)) {
if (typeof rec[key] === 'object') {
result.push(...extractUserLinks(rec[key]));
}
}
return result;
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function isValidHttpUrl(url: string): boolean {
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch {
return false;
}
}
function linkifyText(text: string): string {
const escaped = escapeHtml(text);
return escaped.replace(
/(https?:\/\/[^\s&"'<>]+)/g,
(url) => {
// Decode HTML entities that may have been escaped (e.g. &amp; → &)
const rawUrl = url.replace(/&amp;/g, '&');
if (!isValidHttpUrl(rawUrl)) return url;
const safeHref = escapeHtml(rawUrl);
return `<a href="${safeHref}" target="_blank" rel="noopener noreferrer">${url}</a>`;
}
);
}
interface JobItemProps {
envId: string;
job: PipelineStep;
defaultOpen: boolean;
}
function JobItem({ envId, job, defaultOpen }: JobItemProps) {
const [open, setOpen] = useState(defaultOpen);
const initialOpenRef = useRef(defaultOpen);
// Keep error jobs open by default (tracked via ref so it doesn't reset on re-render)
const isOpen = job.error ? (initialOpenRef.current ? true : open) : open;
const statusJson = JSON.stringify(job.status, null, 2);
const statusHtml = linkifyText(statusJson);
return (
<div className="job-item">
<div
className="job-header"
style={{ cursor: 'pointer', fontWeight: 'bold' }}
onClick={() => setOpen((o) => !o)}
>
{job.error ? (
<span style={{ color: '#dc3545', fontWeight: 'bold', marginRight: 6 }} title="Error">!</span>
) : (
<span style={{ color: '#28a745', fontWeight: 'bold', marginRight: 6 }} title="OK">✔</span>
)}
{envId} - {job.name}
</div>
{isOpen && (
<div className="job-spoiler" style={{ marginTop: 8 }}>
<pre dangerouslySetInnerHTML={{ __html: statusHtml }} />
</div>
)}
</div>
);
}
export function JobsList({ environments }: JobsListProps) {
if (environments.length === 0) {
return (
<div className="jobs-list">
<p className="loading">No jobs found.</p>
</div>
);
}
return (
<div className="jobs-list">
{environments.map((envObj) => {
const jobsArr = envObj.pipeline ?? [];
const allLinks: [string, string][] = jobsArr.flatMap((job) =>
extractUserLinks(job.status)
);
return (
<div key={envObj.id} className="env-jobs">
<h4>Environment: {envObj.id}</h4>
{allLinks.length > 0 && (
<div style={{ float: 'right' }}>
{allLinks.map(([title, url], i) => (
<span key={i}>
{i > 0 && ' | '}
<a href={url} target="_blank" rel="noopener noreferrer">{title}</a>
</span>
))}
</div>
)}
{jobsArr.length > 0 ? (
jobsArr.map((job, idx) => (
<JobItem
key={`${envObj.id}::${job.name}::${idx}`}
envId={envObj.id}
job={job}
defaultOpen={job.error === true}
/>
))
) : (
<div className="job-item">No jobs found.</div>
)}
</div>
);
})}
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
interface StatusBarProps {
message: string | null;
isError?: boolean;
onClose: () => void;
}
export function StatusBar({ message, isError = false, onClose }: StatusBarProps) {
if (message === null) return null;
return (
<div
className="status-bar"
style={{ background: isError ? '#f8d7da' : '#e9ecef' }}
>
<span style={{ color: isError ? '#721c24' : '#333' }}>{message}</span>
<button className="close-status-btn" onClick={onClose}>×</button>
</div>
);
}
+85
View File
@@ -0,0 +1,85 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { BranchesData, EnvironmentsData, WsOutgoingMessage } from '../types/index';
export type ConnectionStatus = 'connecting' | 'connected' | 'disconnected';
export interface UseWebSocketReturn {
sendMessage: (msg: WsOutgoingMessage) => void;
lastBranchesMessage: BranchesData | null;
lastEnvironmentsMessage: EnvironmentsData | null;
lastError: { message: string } | null;
connectionStatus: ConnectionStatus;
}
export function useWebSocket(): UseWebSocketReturn {
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [lastBranchesMessage, setLastBranchesMessage] = useState<BranchesData | null>(null);
const [lastEnvironmentsMessage, setLastEnvironmentsMessage] = useState<EnvironmentsData | null>(null);
const [lastError, setLastError] = useState<{ message: string } | null>(null);
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('connecting');
const connect = useCallback(() => {
if (wsRef.current && wsRef.current.readyState !== WebSocket.CLOSED) {
wsRef.current.onclose = null;
wsRef.current.close();
}
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
const ws = new WebSocket(`${protocol}//${host}/ws`);
wsRef.current = ws;
setConnectionStatus('connecting');
ws.onopen = () => {
setConnectionStatus('connected');
};
ws.onmessage = (event: MessageEvent) => {
try {
const message: unknown = JSON.parse(event.data as string);
if (message && typeof message === 'object') {
const msg = message as Record<string, unknown>;
if ('branches' in msg) {
setLastBranchesMessage(msg.branches as BranchesData);
} else if ('environments' in msg) {
setLastEnvironmentsMessage(msg.environments as EnvironmentsData);
} else if ('error' in msg) {
setLastError(msg.error as { message: string });
}
}
} catch (e) {
console.error('Error processing WebSocket message:', e);
}
};
ws.onclose = () => {
setConnectionStatus('disconnected');
reconnectTimerRef.current = setTimeout(() => connect(), 5000);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}, []);
useEffect(() => {
connect();
return () => {
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
if (wsRef.current) {
wsRef.current.onclose = null;
wsRef.current.close();
}
};
}, [connect]);
const sendMessage = useCallback((msg: WsOutgoingMessage) => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(msg));
}
}, []);
return { sendMessage, lastBranchesMessage, lastEnvironmentsMessage, lastError, connectionStatus };
}
+12
View File
@@ -0,0 +1,12 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
const rootEl = document.getElementById('root');
if (!rootEl) throw new Error('Root element not found');
createRoot(rootEl).render(
<StrictMode>
<App />
</StrictMode>
);
+151
View File
@@ -0,0 +1,151 @@
/**
* This file was auto-generated by openapi-typescript.
* Do not make direct changes to the file.
*/
export interface paths {
"/state": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/** Get current environment state */
get: operations["getState"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/branches": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/** Get branches for all environments */
get: operations["getBranches"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
schemas: {
CommitInfo: {
/** @description Full commit SHA */
hexsha: string;
/** @description Commit author name */
author: string;
/** @description Commit message */
message: string;
};
/** @description Tuple of [branchName, commitHash] */
BranchCommitPair: string[];
PipelineStep: {
/** @description Step name */
name: string;
/** @description Step status (any shape) */
status: unknown;
/** @description Whether this step has an error */
error?: boolean;
};
EnvironmentDto: {
/** @description Environment identifier */
id: string;
/** @description Array of [branchName, commitHash] pairs */
branches: components["schemas"]["BranchCommitPair"][];
/** @description Whether this is a dry-run environment */
dry: boolean;
/** @description Repository path or URL */
repo: string;
/** @description Pipeline steps with their statuses */
pipeline: components["schemas"]["PipelineStep"][];
};
WsIncomingMessage: {
branches?: components["schemas"]["BranchesData"];
environments?: components["schemas"]["EnvironmentsData"];
error?: {
message?: string;
};
};
WsUpdatePayload: {
/** @description Environment ID (empty string to trigger refresh) */
id: string;
branches?: components["schemas"]["BranchCommitPair"][];
};
WsOutgoingMessage: {
update: components["schemas"]["WsUpdatePayload"];
};
/** @description Dict[envId, Dict[branchName, CommitInfo[]]] */
BranchesData: {
[key: string]: {
[key: string]: components["schemas"]["CommitInfo"][];
};
};
/** @description Dict[envId, EnvironmentDto] */
EnvironmentsData: {
[key: string]: components["schemas"]["EnvironmentDto"];
};
StateResponse: components["schemas"]["EnvironmentsData"];
BranchesResponse: components["schemas"]["BranchesData"];
};
responses: never;
parameters: never;
requestBodies: never;
headers: never;
pathItems: never;
}
export type $defs = Record<string, never>;
export interface operations {
getState: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Current state of all environments */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["StateResponse"];
};
};
};
};
getBranches: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Branches grouped by environment and branch name */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["BranchesResponse"];
};
};
};
};
}
+11
View File
@@ -0,0 +1,11 @@
import type { components } from './api';
export type CommitInfo = components['schemas']['CommitInfo'];
export type BranchCommitPair = [string, string];
export type PipelineStep = components['schemas']['PipelineStep'];
export type EnvironmentDto = components['schemas']['EnvironmentDto'];
export type BranchesData = components['schemas']['BranchesData'];
export type EnvironmentsData = components['schemas']['EnvironmentsData'];
export type WsIncomingMessage = components['schemas']['WsIncomingMessage'];
export type WsUpdatePayload = components['schemas']['WsUpdatePayload'];
export type WsOutgoingMessage = components['schemas']['WsOutgoingMessage'];
-242
View File
@@ -1,242 +0,0 @@
/* Placeholder for frontend styles */
body {
font-family: Arial, sans-serif;
background: #f8f9fa;
margin: 0;
padding: 0;
}
.container {
max-width: 900px;
margin: 40px auto;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
padding: 32px;
}
.primary-button {
background: #007bff;
color: #fff;
border: none;
border-radius: 4px;
padding: 10px 20px;
cursor: pointer;
font-size: 1rem;
}
.primary-button:hover {
background: #0056b3;
}
.refresh-button {
background: #28a745;
color: #fff;
border: none;
border-radius: 4px;
padding: 10px 20px;
cursor: pointer;
font-size: 1rem;
margin-bottom: 16px;
margin-left: 8px;
}
.refresh-button:hover {
background: #218838;
}
.apply-button {
background: #28a745;
color: #fff;
border: none;
border-radius: 4px;
padding: 10px 20px;
cursor: pointer;
font-size: 1rem;
margin-bottom: 16px;
margin-left: 8px;
}
.apply-button:hover {
background: #218838;
}
.toggle-button {
background: #28a745;
color: #fff;
border: none;
border-radius: 4px;
padding: 10px 20px;
cursor: pointer;
font-size: 1rem;
margin-bottom: 16px;
margin-left: 8px;
}
.toggle-button:hover {
background: #218838;
}
.apply-section {
text-align: center;
margin: 16px 0;
}
.control-bar {
text-align: center;
margin: 16px 0;
}
.loading {
color: #888;
font-style: italic;
}
.status-bar {
background: #e9ecef;
padding: 8px 16px;
border-radius: 4px;
margin-bottom: 16px;
display: flex;
align-items: center;
}
.status-bar.hidden {
display: none;
}
.hidden {
display: none;
}
/* Filter styling */
.filter-section {
margin: 16px 0;
}
.filter-input {
width: 100%;
padding: 12px 16px;
border: 1px solid #ced4da;
border-radius: 4px;
font-size: 1rem;
box-sizing: border-box;
}
.filter-input:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}
/* Branches table styling */
.branches-table {
width: 100%;
border-collapse: collapse;
margin: 16px 0;
}
.branches-table th {
background: #f8f9fa;
padding: 12px 8px;
text-align: left;
font-weight: 600;
color: #495057;
border-bottom: 2px solid #dee2e6;
}
.branches-table td {
padding: 12px 8px;
vertical-align: middle;
border-bottom: 1px solid #dee2e6;
}
.branch-row:hover {
background: #f8f9fa;
}
.branch-name {
font-weight: 500;
}
.env-label {
color: #6c757d;
font-size: 0.9em;
font-weight: normal;
}
.desired-commit {
margin-right: 8px;
padding: 4px 8px;
border: 1px solid #ced4da;
border-radius: 4px;
font-size: 0.9em;
}
.commit-input {
padding: 4px 8px;
border: 1px solid #ced4da;
border-radius: 4px;
font-size: 0.9em;
width: 200px;
font-family: monospace;
}
.deployed-commit {
font-family: monospace;
font-size: 0.9em;
color: #6c757d;
}
/* Checkbox styling */
input[type="checkbox"] {
margin: 0;
transform: scale(1.2);
}
/* Dry run play/pause button */
.env-title {
display: flex;
align-items: center;
gap: 12px;
}
.dry-run-btn {
margin-left: auto;
background: none;
border: none;
cursor: pointer;
font-size: 1.2rem;
line-height: 1;
padding: 2px 6px;
border-radius: 4px;
color: #28a745;
transition: color 0.15s, background 0.15s;
}
.dry-run-btn:hover {
background: rgba(0,0,0,0.06);
}
.dry-run-btn.dry-run-active {
color: #ffc107;
}
/* Step spinner */
@keyframes step-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.step-spinner {
display: inline-block;
width: 12px;
height: 12px;
border: 2px solid #007bff;
border-top-color: transparent;
border-radius: 50%;
animation: step-spin 0.7s linear infinite;
margin-right: 6px;
vertical-align: middle;
flex-shrink: 0;
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+25
View File
@@ -0,0 +1,25 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
const backendUrl = process.env.VITE_BACKEND_URL ?? 'http://localhost:5001';
export default defineConfig({
plugins: [react()],
build: {
outDir: 'dist',
sourcemap: true,
},
server: {
proxy: {
'/ws': {
target: backendUrl,
ws: true,
changeOrigin: true,
},
'/api': {
target: backendUrl,
changeOrigin: true,
},
},
},
});
+191
View File
@@ -0,0 +1,191 @@
openapi: 3.1.0
info:
title: Brencher API
version: 1.0.0
description: |
Brencher branch merger API.
## WebSocket /ws
Connect to `/ws` for real-time updates.
### Incoming messages (server → client)
**Branches update:**
```json
{ "branches": { "<envId>": { "<branchName>": [CommitInfo, ...] } } }
```
**Environments update:**
```json
{ "environments": { "<envId>": EnvironmentDto } }
```
**Error:**
```json
{ "error": { "message": "string" } }
```
### Outgoing messages (client → server)
**Update environment branches:**
```json
{ "update": { "id": "<envId>", "branches": [["<branchName>", "<commitHash>"], ...] } }
```
**Refresh (send empty id to trigger refresh):**
```json
{ "update": { "id": "" } }
```
paths:
/state:
get:
operationId: getState
summary: Get current environment state
responses:
"200":
description: Current state of all environments
content:
application/json:
schema:
$ref: "#/components/schemas/StateResponse"
/branches:
get:
operationId: getBranches
summary: Get branches for all environments
responses:
"200":
description: Branches grouped by environment and branch name
content:
application/json:
schema:
$ref: "#/components/schemas/BranchesResponse"
components:
schemas:
CommitInfo:
type: object
required:
- hexsha
- author
- message
properties:
hexsha:
type: string
description: Full commit SHA
author:
type: string
description: Commit author name
message:
type: string
description: Commit message
BranchCommitPair:
type: array
items:
type: string
minItems: 2
maxItems: 2
description: Tuple of [branchName, commitHash]
PipelineStep:
type: object
required:
- name
- status
properties:
name:
type: string
description: Step name
status:
description: Step status (any shape)
error:
type: boolean
description: Whether this step has an error
EnvironmentDto:
type: object
required:
- id
- branches
- dry
- repo
- pipeline
properties:
id:
type: string
description: Environment identifier
branches:
type: array
items:
$ref: "#/components/schemas/BranchCommitPair"
description: Array of [branchName, commitHash] pairs
dry:
type: boolean
description: Whether this is a dry-run environment
repo:
type: string
description: Repository path or URL
pipeline:
type: array
items:
$ref: "#/components/schemas/PipelineStep"
description: Pipeline steps with their statuses
WsIncomingMessage:
type: object
properties:
branches:
$ref: "#/components/schemas/BranchesData"
environments:
$ref: "#/components/schemas/EnvironmentsData"
error:
type: object
properties:
message:
type: string
WsUpdatePayload:
type: object
required:
- id
properties:
id:
type: string
description: Environment ID (empty string to trigger refresh)
branches:
type: array
items:
$ref: "#/components/schemas/BranchCommitPair"
WsOutgoingMessage:
type: object
required:
- update
properties:
update:
$ref: "#/components/schemas/WsUpdatePayload"
BranchesData:
type: object
additionalProperties:
type: object
additionalProperties:
type: array
items:
$ref: "#/components/schemas/CommitInfo"
description: "Dict[envId, Dict[branchName, CommitInfo[]]]"
EnvironmentsData:
type: object
additionalProperties:
$ref: "#/components/schemas/EnvironmentDto"
description: "Dict[envId, EnvironmentDto]"
StateResponse:
$ref: "#/components/schemas/EnvironmentsData"
BranchesResponse:
$ref: "#/components/schemas/BranchesData"