Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 | /**
* Embgit Sync Base Class
*
* Shared base class for git-based sync services (GitHub, Sysgit).
* Contains all common functionality for clone, push, pull, commit history, etc.
*/
import path from 'path';
import fs from 'fs-extra';
import { recurForceRemove } from '../utils/file-dir-utils.js';
import { SITE_CATEGORIES } from '../logging/index.js';
/**
* Abstract base class for embgit-based sync services
*/
export class EmbgitSyncBase {
embgit;
pathHelper;
outputConsole;
windowAdapter;
configurationProvider;
container;
workspaceKey;
progressCallback;
config;
siteKey;
fromPath;
constructor(config, siteKey, dependencies) {
this.config = config;
this.siteKey = siteKey;
this.embgit = dependencies.embgit;
this.pathHelper = dependencies.pathHelper;
this.outputConsole = dependencies.outputConsole;
this.windowAdapter = dependencies.windowAdapter;
this.configurationProvider = dependencies.configurationProvider;
this.container = dependencies.container;
this.workspaceKey = dependencies.workspaceKey || 'unknown';
this.progressCallback = dependencies.progressCallback;
this.fromPath = this.pathHelper.getLastBuildDir();
}
/**
* Dispatch sync actions
*/
async actionDispatcher(action, parameters) {
switch (action) {
case 'readRemote': {
const historyRemote = await this.historyRemoteFromCache();
if (historyRemote) {
return historyRemote;
}
return await this.historyRemote();
}
case 'refreshRemote': {
return await this.historyRemote();
}
case 'checkoutRef': {
const params = parameters;
return this.checkoutRef(params.ref);
}
case 'pullFromRemote': {
return this.pullFastForwardMerge();
}
case 'hardPush': {
return this.hardPush();
}
case 'checkoutLatest': {
return this.checkoutRef('LATEST');
}
case 'pushWithSoftMerge': {
return this.pushWithSoftMerge();
}
default:
throw new Error(`Action not implemented: ${action}`);
}
}
/**
* Hard push - force push all files to remote
*/
async hardPush() {
const tmpDir = this.pathHelper.getTempDir();
await this.ensureSyncDirEmpty(tmpDir);
const tmpCloneDir = path.join(tmpDir, 'tmpclone');
await fs.mkdir(tmpCloneDir);
const tmpKeypathPrivate = await this.tempCreatePrivateKey();
const parentPath = path.join(this.pathHelper.getRoot(), 'sites', this.siteKey, 'githubSyncRepo');
await this.ensureSyncDirEmpty(parentPath);
this.outputConsole.appendLine(`START ${this.getLogPrefix()} CHECKOUT`);
this.outputConsole.appendLine('-----------------');
this.outputConsole.appendLine(' git url: ' + this.getGitUrl());
this.outputConsole.appendLine(' private key path: ' + tmpKeypathPrivate);
this.outputConsole.appendLine(' destination path: ' + this.fullDestinationPath());
this.outputConsole.appendLine('');
this.outputConsole.appendLine(' repository: ' + this.config.repository);
this.outputConsole.appendLine(' branch: ' + this.config.branch);
this.outputConsole.appendLine(' email: ' + this.config.email);
this.outputConsole.appendLine('-----------------');
this.outputConsole.appendLine('');
this.sendProgress('Getting latest remote commit history..', 20);
await this.embgit.clonePrivateWithKey(this.getGitUrl(), tmpCloneDir, this.config.deployPrivateKey);
this.sendProgress('Copying commit history to destination directory', 30);
await fs.copy(path.join(tmpCloneDir, '.git'), path.join(this.fullDestinationPath(), '.git'));
this.sendProgress('Copying site files to git destination directory', 40);
const currentSitePath = await this.getCurrentSitePath();
const filter = this.createIgnoreFilter(currentSitePath);
await fs.copy(currentSitePath, this.fullDestinationPath(), { filter });
if (this.config.publishScope === 'source') {
if (this.config.setGitHubActions) {
await this.githubActionWorkflowSource(this.fullDestinationPath());
}
}
await this.publishStep3AddCommitPush(tmpKeypathPrivate, this.fullDestinationPath());
return true;
}
/**
* Push with soft merge - clone, copy files, commit, push
*/
async pushWithSoftMerge() {
const tmpKeypathPrivate = await this.tempCreatePrivateKey();
const resolvedDest = await this.ensureSyncRepoDir(this.siteKey);
const fullDestinationPath = path.join(resolvedDest, this.config.repository);
this.outputConsole.appendLine(`START ${this.getLogPrefix()} SYNC`);
this.outputConsole.appendLine('-----------------');
this.outputConsole.appendLine(' git url: ' + this.getGitUrl());
this.outputConsole.appendLine(' private key path: ' + tmpKeypathPrivate);
this.outputConsole.appendLine(' destination path: ' + fullDestinationPath);
this.outputConsole.appendLine(' from is: ' + this.fromPath);
this.outputConsole.appendLine('');
this.outputConsole.appendLine(' repository: ' + this.config.repository);
this.outputConsole.appendLine(' email: ' + this.config.email);
this.outputConsole.appendLine(' branch: ' + this.config.branch);
this.outputConsole.appendLine(' publishScope: ' + this.config.publishScope);
this.outputConsole.appendLine(' set actions: ' + this.config.setGitHubActions);
this.outputConsole.appendLine(' override BaseURL: ' + this.config.overrideBaseURL);
this.outputConsole.appendLine('-----------------');
this.outputConsole.appendLine('');
// Log sync start
this.container.logger.infoSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.SYNC, 'Sync push started', {
type: this.getLogPrefix(),
repository: this.config.repository,
branch: this.config.branch,
publishScope: this.config.publishScope,
gitUrl: this.getGitUrl()
});
try {
this.sendProgress('Get remote files..', 20);
await this.publishStep1InitialClone(tmpKeypathPrivate, this.getGitUrl(), fullDestinationPath);
this.sendProgress('Prepare files before uploading..', 30);
if (this.config.publishScope === 'build') {
await this.publishStep2PrepareDircontentsBuild(fullDestinationPath);
}
else {
await this.publishStep2PrepareDircontentsSource(fullDestinationPath);
}
this.sendProgress('Upload files to remote server..', 70);
await this.publishStep3AddCommitPush(tmpKeypathPrivate, fullDestinationPath);
// Log success
this.container.logger.infoSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.SYNC, 'Sync push completed', {
type: this.getLogPrefix(),
repository: this.config.repository,
branch: this.config.branch
});
return true;
}
catch (error) {
// Log error
this.container.logger.errorSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.SYNC, 'Sync push failed', {
type: this.getLogPrefix(),
repository: this.config.repository,
error: error instanceof Error ? error.message : String(error)
});
throw error;
}
}
/**
* Pull with fast-forward merge
*/
async pullFastForwardMerge() {
const tmpKeypathPrivate = await this.tempCreatePrivateKey();
this.embgit.setPrivateKeyPath(tmpKeypathPrivate);
const resolvedDest = path.join(this.pathHelper.getRoot(), 'sites', this.siteKey, 'githubSyncRepo');
const fullDestinationPath = path.join(resolvedDest, this.config.repository);
let syncSelection = 'all';
// Check if we need initial clone
if (!await fs.pathExists(path.join(fullDestinationPath, '.git'))) {
await this.publishStep1InitialClone(tmpKeypathPrivate, this.getGitUrl(), fullDestinationPath);
}
try {
await this.embgit.reset_hard(fullDestinationPath);
try {
await this.embgit.pull(fullDestinationPath);
}
catch (pullError) {
let errorOutput = "";
if (typeof pullError === 'object' && pullError != null && 'stdout' in pullError && isValidToString(pullError.stdout)) {
errorOutput = pullError.stdout.toString();
}
if (pullError instanceof Error) {
errorOutput = pullError.message;
}
if (errorOutput.includes('already up-to-date')) {
// Not an error, just no changes
}
else {
throw pullError;
}
}
const configurations = await this.configurationProvider.getConfigurations({});
const site = configurations.sites.find((x) => x.key === this.siteKey);
if (!site || !site.source?.path) {
throw new Error(`Site not found or invalid source path: ${this.siteKey}`);
}
if (this.config.syncSelection && this.config.syncSelection !== 'all') {
syncSelection = this.config.syncSelection;
}
await this.syncSourceToDestination(fullDestinationPath, site.source.path, syncSelection);
return 'reset-and-pulled-from-remote';
}
catch (err) {
let errorOutput = "";
if (typeof err === 'object' && err != null && 'stdout' in err && isValidToString(err.stdout)) {
errorOutput = err.stdout.toString();
}
if (err instanceof Error) {
errorOutput = err.message;
}
if (errorOutput.includes('already up-to-date')) {
return 'no_changes';
}
else if (errorOutput.includes('non-fast-forward update')) {
return 'non_fast_forward';
}
throw err;
}
}
/**
* Checkout a specific ref
*/
async checkoutRef(ref = 'LATEST') {
const tmpKeypathPrivate = await this.tempCreatePrivateKey();
const parentPath = path.join(this.pathHelper.getRoot(), 'sites', this.siteKey, 'githubSyncRepo');
await this.ensureSyncDirEmpty(parentPath);
this.outputConsole.appendLine(`START ${this.getLogPrefix()} CHECKOUT`);
this.outputConsole.appendLine('-----------------');
this.outputConsole.appendLine(' git url: ' + this.getGitUrl());
this.outputConsole.appendLine(' private key path: ' + tmpKeypathPrivate);
this.outputConsole.appendLine(' destination path: ' + this.fullDestinationPath());
this.outputConsole.appendLine('');
this.outputConsole.appendLine(' repository: ' + this.config.repository);
this.outputConsole.appendLine(' email: ' + this.config.email);
this.outputConsole.appendLine('');
this.outputConsole.appendLine(' git ref: ' + ref);
this.outputConsole.appendLine('-----------------');
this.outputConsole.appendLine('');
this.sendProgress('Making a fresh clone of the repository..', 20);
await this.embgit.clonePrivateWithKey(this.getGitUrl(), this.fullDestinationPath(), this.config.deployPrivateKey);
if (ref !== 'LATEST') {
this.sendProgress('Checking out ref: ' + ref, 70);
await this.embgit.checkout(ref, this.fullDestinationPath());
}
this.sendProgress('Copying to main site directory', 90);
const currentSitePath = await this.getCurrentSitePath();
await this.ensureSyncDirEmpty(currentSitePath);
// Copy without .git directory
const filter = (src) => !src.endsWith('.git') && !src.includes('/.git/');
await fs.copy(this.fullDestinationPath(), currentSitePath, { filter });
return true;
}
/**
* Get remote commit history (fresh fetch)
*/
async historyRemote() {
this.sendProgress('Getting remote commits.', 20);
const tmpKeypathPrivate = await this.tempCreatePrivateKey();
const historyRemoteArr = await this.embgit.logRemote(this.getGitUrl(), tmpKeypathPrivate);
let historyLocalArr = [];
if (await fs.pathExists(this.fullDestinationPath())) {
this.sendProgress('Comparing with local commit history', 80);
try {
historyLocalArr = await this.embgit.logLocal(this.fullDestinationPath());
}
catch (error) {
// Log local may fail if repo is in detached HEAD state after checkout
this.outputConsole.appendLine(`Warning: Could not get local commit history: ${error}`);
historyLocalArr = [];
}
}
const historyMergedArr = historyRemoteArr.map((commit) => {
const localMatch = historyLocalArr.find((e) => e.ref === commit.ref);
return {
...commit,
local: !!localMatch,
};
});
this.sendProgress('Writing commit history cache', 100);
await fs.writeFile(this.remoteHistoryCacheFile(), JSON.stringify(historyMergedArr), 'utf-8');
const stat = await fs.stat(this.remoteHistoryCacheFile());
return { lastRefresh: stat.mtime, commitList: historyMergedArr };
}
/**
* Get remote commit history from cache
*/
async historyRemoteFromCache() {
if (await fs.pathExists(this.remoteHistoryCacheFile())) {
const historyRemoteJson = await fs.readFile(this.remoteHistoryCacheFile(), 'utf-8');
const stat = await fs.stat(this.remoteHistoryCacheFile());
return { lastRefresh: stat.mtime, commitList: JSON.parse(historyRemoteJson) };
}
return null;
}
// ============================================
// Helper methods
// ============================================
/**
* Step 1: Initial clone
*/
async publishStep1InitialClone(tmpKeypathPrivate, fullGitUrl, fullDestinationPath) {
await this.embgit.clonePrivateWithKey(fullGitUrl, fullDestinationPath, this.config.deployPrivateKey);
return true;
}
/**
* Step 2: Prepare directory contents for build scope
*/
async publishStep2PrepareDircontentsBuild(fullDestinationPath) {
if (!this.fromPath) {
throw new Error('Last build directory is not set');
}
await this.syncSourceToDestination(path.join(this.fromPath, 'public'), fullDestinationPath, 'all');
this.outputConsole.appendLine('prepare and sync finished');
return true;
}
/**
* Step 2: Prepare directory contents for source scope
*/
async publishStep2PrepareDircontentsSource(fullDestinationPath) {
if (!this.fromPath) {
throw new Error('Last build directory is not set');
}
await this.syncSourceToDestination(this.fromPath, fullDestinationPath, 'all');
if (this.config.publishScope === 'source') {
if (this.config.setGitHubActions) {
await this.githubActionWorkflowSource(fullDestinationPath);
}
}
if (this.config.CNAMESwitch && this.config.CNAME) {
await this.githubCname(fullDestinationPath);
}
await fs.ensureDir(path.join(fullDestinationPath, 'static'));
this.outputConsole.appendLine('prepare and sync finished');
return true;
}
/**
* Step 3: Add, commit, and push
*/
async publishStep3AddCommitPush(tmpKeypathPrivate, fullDestinationPath) {
await this.embgit.addAll(fullDestinationPath);
const commitMessage = `push by Quiqr Desktop`;
await this.embgit.commit(fullDestinationPath, commitMessage, this.config.username || 'Quiqr', this.config.email || 'noreply@quiqr.org');
await this.embgit.push(fullDestinationPath, tmpKeypathPrivate);
return true;
}
/**
* Get current site path from configuration
*/
async getCurrentSitePath() {
const configurations = await this.configurationProvider.getConfigurations({});
const site = configurations.sites.find((x) => x.key === this.siteKey);
if (!site || !site.source?.path) {
throw new Error(`Site not found or invalid source path: ${this.siteKey}`);
}
return site.source.path;
}
/**
* Read sync ignore file to array
*/
async readSyncIgnoreFileToArray() {
try {
const currentSitePath = await this.getCurrentSitePath();
const filepath = path.join(currentSitePath, 'quiqr', 'sync_ignore.txt');
if (await fs.pathExists(filepath)) {
const strData = await fs.readFile(filepath, 'utf-8');
if (strData) {
let arrData = strData.split('\n');
arrData = [...new Set(arrData)]; // Remove duplicates
arrData = arrData.filter((item) => {
if (item === '')
return false;
if (item.trim().startsWith('#'))
return false;
return true;
});
return arrData;
}
}
}
catch {
// Ignore errors reading sync_ignore.txt
}
return [];
}
/**
* Create ignore filter function for fs.copy
*/
createIgnoreFilter(currentSitePath) {
const ignoreList = ['.git', '.quiqr-cache'];
if (this.config.publishScope === 'source') {
ignoreList.push('public');
}
return (file) => {
let rootFile = file.substring(currentSitePath.length + 1);
if (rootFile.startsWith('/')) {
rootFile = rootFile.substring(1);
}
return !ignoreList.includes(rootFile);
};
}
/**
* Sync source to destination
*/
async syncSourceToDestination(sourcePath, fullDestinationPath, syncSelection) {
if (syncSelection === 'themeandquiqr') {
await recurForceRemove(path.join(fullDestinationPath, 'themes'));
await recurForceRemove(path.join(fullDestinationPath, 'quiqr'));
await fs.copy(path.join(sourcePath, 'themes'), path.join(fullDestinationPath, 'themes'));
await fs.copy(path.join(sourcePath, 'quiqr'), path.join(fullDestinationPath, 'quiqr'));
this.outputConsole.appendLine('synced THEME AND QUIQR sources to destination ...');
}
else {
const currentSitePath = await this.getCurrentSitePath();
const filter = this.createIgnoreFilter(currentSitePath);
await fs.copy(sourcePath, fullDestinationPath, { filter });
this.outputConsole.appendLine('synced ALL source to destination ...');
}
return true;
}
/**
* Full destination path for the repository
*/
fullDestinationPath() {
const resolvedDest = path.join(this.pathHelper.getRoot(), 'sites', this.siteKey, 'githubSyncRepo');
return path.join(resolvedDest, this.config.repository);
}
/**
* Remote history cache file path
*/
remoteHistoryCacheFile() {
const resolvedDest = path.join(this.pathHelper.getRoot(), 'sites', this.siteKey);
return path.join(resolvedDest, `githubSync-${this.config.repository}-cache_remote_history.json`);
}
/**
* Create temporary private key file
*/
async tempCreatePrivateKey() {
if (!this.config.deployPrivateKey) {
throw new Error('Deploy private key is not configured');
}
return await this.embgit.createTemporaryPrivateKey(this.config.deployPrivateKey);
}
/**
* Ensure sync directory is empty
*/
async ensureSyncDirEmpty(dir) {
await fs.ensureDir(dir);
await fs.emptyDir(dir);
await fs.ensureDir(dir);
return dir;
}
/**
* Ensure sync repo directory exists
*/
async ensureSyncRepoDir(siteKey) {
const resolvedDest = path.join(this.pathHelper.getRoot(), 'sites', siteKey, 'githubSyncRepo');
await fs.ensureDir(resolvedDest);
await fs.emptyDir(resolvedDest);
await fs.ensureDir(resolvedDest);
return resolvedDest;
}
/**
* Write CNAME file for GitHub Pages
*/
async githubCname(fullDestinationPath) {
await fs.writeFile(path.join(fullDestinationPath, 'CNAME'), this.config.CNAME, 'utf-8');
}
/**
* Write GitHub Actions workflow for Hugo builds
*/
async githubActionWorkflowSource(fullDestinationPath) {
const hugoVersion = '0.81.0';
const baseUrlArg = this.config.overrideBaseURLSwitch ? `--baseURL ${this.config.overrideBaseURL}` : '';
const yaml = `
name: github pages
on:
push:
branches:
- ${this.config.branch || 'main'} # Set a branch to deploy
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: true # Fetch Hugo themes (true OR recursive)
fetch-depth: 0 # Fetch all history for .GitInfo and .Lastmod
- name: Setup Hugo
uses: peaceiris/actions-hugo@v2
with:
hugo-version: '${hugoVersion}'
extended: true
- name: Build
run: hugo --minify ${baseUrlArg}
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: \${{ secrets.GITHUB_TOKEN }}
publish_dir: ./public
`;
await fs.ensureDir(path.join(fullDestinationPath, '.github'));
await fs.ensureDir(path.join(fullDestinationPath, '.github', 'workflows'));
await fs.writeFile(path.join(fullDestinationPath, '.github', 'workflows', 'hugobuild.yml'), yaml, 'utf-8');
}
/**
* Send progress update via SSE callback or fall back to window adapter
*/
sendProgress(message, progress) {
if (this.progressCallback) {
this.progressCallback(message, progress);
}
else {
this.windowAdapter.sendToRenderer('updateProgress', { message, progress });
}
}
}
export function isValidToString(obj) {
return (typeof obj === "object" && obj !== null && typeof obj.toString === "function" && obj.toString !== Object.prototype.toString);
}
|