Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ So when `flashlight: true`, the action writes a `.env.local` for the run, built

1. every `PRESTAFLOW_*` variable set on the step with `env:` (works whatever `variables_order` is);
2. the values imposed by the Flashlight container: `PRESTAFLOW_FO_URL`,
`PRESTAFLOW_BO_URL` (`<fo>admin-dev/`) and `PRESTAFLOW_PS_VERSION`;
`PRESTAFLOW_BO_URL` (`<fo>admin-dev/`) and `PRESTAFLOW_PS_VERSION`. The version is
read from the `ps-version` tag (`8.2.8-nginx` gives `8.2.8`), or from the shop for a
tag without version such as `latest`;
3. your own dotenv file, copied as is: `.env.local` if it exists, otherwise `.env`;
4. the Flashlight credentials: the back office (`[email protected]`,
`PRESTAFLOW_BO_PASSWD=prestashop`) and the demo customer of the PrestaShop fixtures
Expand Down
8 changes: 8 additions & 0 deletions __tests__/flashlight/dotenv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ describe('renderFlashlightDotenv', () => {
expect(v.PRESTAFLOW_FO_PASSWD).toBe(`'${FLASHLIGHT_FO_PASSWD}'`);
});

it('leaves PRESTAFLOW_PS_VERSION to the user when the version is unknown', () => {
const v = lastValues(renderFlashlightDotenv({
...base, psVersion: null, userContent: 'PRESTAFLOW_PS_VERSION=8.2.8', processEnv: {},
}));
expect(v.PRESTAFLOW_PS_VERSION).toBe('8.2.8');
expect(v.PRESTAFLOW_FO_URL).toBe(`'http://localhost:8000/'`);
});

it('user file and step env override the Flashlight demo customer', () => {
const fromFile = lastValues(renderFlashlightDotenv({
...base, userContent: '[email protected]\nPRESTAFLOW_FO_PASSWD=secret', processEnv: {},
Expand Down
82 changes: 82 additions & 0 deletions __tests__/flashlight/ps-version.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const execMock = jest.fn();
jest.mock('@actions/exec', () => ({ exec: (...a: unknown[]) => execMock(...a) }));

import * as core from '@actions/core';
import { psVersionFromImageTag, readPsVersionFromContainer, resolvePsVersion } from '../../src/flashlight/ps-version';

type ExecOpts = { listeners?: { stdout?: (b: Buffer) => void } };

function execPrinting(stdout: string) {
return async (_cmd: string, _args: string[], opts: ExecOpts) => {
opts.listeners?.stdout?.(Buffer.from(stdout));
return 0;
};
}

beforeEach(() => {
execMock.mockReset();
jest.spyOn(core, 'info').mockImplementation(() => undefined);
jest.spyOn(core, 'warning').mockImplementation(() => undefined);
});

describe('psVersionFromImageTag', () => {
it.each([
['9.0.0', '9.0.0'],
['1.7.8.11', '1.7.8.11'],
['8.2.8-nginx', '8.2.8'],
['8.2.8-8.1-fpm-alpine3.21-nginx', '8.2.8'],
['1.7.8.11-7.4-fpm-alpine-nginx', '1.7.8.11'],
[' 9.2.1-8.2-apache ', '9.2.1'],
])('%s → %s', (tag, version) => {
expect(psVersionFromImageTag(tag)).toBe(version);
});

it.each(['latest', 'nightly', 'base-8.2-fpm-alpine3.23-nginx', '8.2', '', '8.2.8nginx'])('%s → null', tag => {
expect(psVersionFromImageTag(tag)).toBeNull();
});
});

describe('readPsVersionFromContainer', () => {
it('reads PS_VERSION from the image environment', async () => {
execMock.mockImplementation(execPrinting('9.2.1\n'));
await expect(readPsVersionFromContainer('/tmp/c.yml')).resolves.toBe('9.2.1');
const args = execMock.mock.calls[0][1] as string[];
expect(args).toEqual(['compose', '-f', '/tmp/c.yml', 'exec', '-T', 'prestashop', 'printenv', 'PS_VERSION']);
expect(execMock).toHaveBeenCalledTimes(1);
});

it('falls back on AppKernel when PS_VERSION is missing', async () => {
execMock
.mockImplementationOnce(execPrinting(''))
.mockImplementationOnce(execPrinting('8.1.7'));
await expect(readPsVersionFromContainer('/tmp/c.yml')).resolves.toBe('8.1.7');
expect((execMock.mock.calls[1][1] as string[]).slice(6, 8)).toEqual(['php', '-r']);
});

it('returns null on empty or unexpected output, or when docker fails', async () => {
execMock.mockImplementation(execPrinting(''));
await expect(readPsVersionFromContainer('/tmp/c.yml')).resolves.toBeNull();
execMock.mockImplementation(execPrinting('PHP Warning: nope'));
await expect(readPsVersionFromContainer('/tmp/c.yml')).resolves.toBeNull();
execMock.mockRejectedValue(new Error('docker gone'));
await expect(readPsVersionFromContainer('/tmp/c.yml')).resolves.toBeNull();
});
});

describe('resolvePsVersion', () => {
it('takes the version from the tag without asking the shop', async () => {
await expect(resolvePsVersion({ imageTag: '8.2.8-nginx', composePath: '/c' })).resolves.toBe('8.2.8');
expect(execMock).not.toHaveBeenCalled();
});

it('asks the shop for a tag without version', async () => {
execMock.mockImplementation(execPrinting('9.2.1'));
await expect(resolvePsVersion({ imageTag: 'latest', composePath: '/c' })).resolves.toBe('9.2.1');
});

it('warns and returns null when neither says', async () => {
execMock.mockImplementation(execPrinting(''));
await expect(resolvePsVersion({ imageTag: 'latest', composePath: '/c' })).resolves.toBeNull();
expect(core.warning).toHaveBeenCalledWith(expect.stringContaining('PRESTAFLOW_PS_VERSION is not set'));
});
});
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ inputs:
required: false
default: 'false'
ps-version:
description: "Flashlight image tag (e.g. 9.0.0, 8.1.7, latest). Ignored when flashlight is false."
description: "Flashlight image tag (e.g. 9.0.0, 8.2.8-nginx, latest). The PrestaShop version given to the tests (PRESTAFLOW_PS_VERSION) is read from the tag, or from the shop for a tag without version. Ignored when flashlight is false."
required: false
default: 'latest'
flashlight-mount:
Expand Down
119 changes: 115 additions & 4 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -126375,11 +126375,13 @@ function flashlightDefaults() {
};
}
function flashlightForced(foUrl, psVersion) {
return {
const forced = {
PRESTAFLOW_FO_URL: foUrl,
PRESTAFLOW_BO_URL: `${foUrl}${exports.FLASHLIGHT_ADMIN_DIR}/`,
PRESTAFLOW_PS_VERSION: psVersion,
};
if (psVersion)
forced.PRESTAFLOW_PS_VERSION = psVersion;
return forced;
}
/**
* Build the .env.local body. phpdotenv loads a single file (the first of
Expand Down Expand Up @@ -126580,6 +126582,112 @@ function resolveMount(p) {
}


/***/ }),

/***/ 49800:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.psVersionFromImageTag = psVersionFromImageTag;
exports.readPsVersionFromContainer = readPsVersionFromContainer;
exports.resolvePsVersion = resolvePsVersion;
const core = __importStar(__nccwpck_require__(37484));
const exec = __importStar(__nccwpck_require__(95236));
/**
* PrestaShop version carried by a Flashlight image tag: `8.2.8-nginx`,
* `8.2.8-8.1-fpm-alpine3.21-nginx` and `9.0.0` all start with it. Tags without
* a version (`latest`, `nightly`, `base-8.2-…`) return null.
*
* prestaflow/php-library only parses a bare version (`1.7.8.11`, `8.2.8`), and
* fails the whole run on anything else, so the tag is never passed as is.
*/
function psVersionFromImageTag(tag) {
const m = /^(\d+\.\d+\.\d+(?:\.\d+)?)(?:-|$)/.exec(tag.trim());
return m ? m[1] : null;
}
/** Last line of a command run in the PrestaShop container, '' when it fails. */
async function execInShop(composePath, command) {
let output = '';
try {
await exec.exec('docker', ['compose', '-f', composePath, 'exec', '-T', 'prestashop', ...command], {
ignoreReturnCode: true, silent: true, listeners: { stdout: (b) => { output += b.toString(); } },
});
}
catch {
return '';
}
return output.trim().split('\n').pop()?.trim() ?? '';
}
const isBareVersion = (v) => v !== '' && psVersionFromImageTag(v) === v;
// Fallback for an image without PS_VERSION: releases up to 9.1 declare it in AppKernel.
const READ_APPKERNEL_PHP = `echo preg_match("/const VERSION = '([0-9.]+)'/", (string) @file_get_contents('/var/www/html/app/AppKernel.php'), $m) ? $m[1] : '';`;
/**
* Read the version from the running shop, for a tag that does not carry it.
* Flashlight images declare it in their PS_VERSION environment variable
* (`latest` is 9.2.1 at the time of writing).
*/
async function readPsVersionFromContainer(composePath) {
const fromEnv = await execInShop(composePath, ['printenv', 'PS_VERSION']);
if (isBareVersion(fromEnv))
return fromEnv;
const fromKernel = await execInShop(composePath, ['php', '-r', READ_APPKERNEL_PHP]);
return isBareVersion(fromKernel) ? fromKernel : null;
}
/**
* Version given to the library as PRESTAFLOW_PS_VERSION: from the tag, else
* from the shop. Null when neither says: the variable is then left to the
* user's dotenv file or step env, with a warning.
*/
async function resolvePsVersion(p) {
const fromTag = psVersionFromImageTag(p.imageTag);
if (fromTag)
return fromTag;
const fromShop = await readPsVersionFromContainer(p.composePath);
if (fromShop) {
core.info(`Flashlight image ${p.imageTag}: PrestaShop ${fromShop} read from the shop.`);
return fromShop;
}
core.warning(`Could not tell the PrestaShop version of Flashlight image "${p.imageTag}": PRESTAFLOW_PS_VERSION is not set by the action. `
+ 'Set it with env: on the step, or use a versioned ps-version (e.g. 8.2.8-nginx).');
return null;
}


/***/ }),

/***/ 38422:
Expand Down Expand Up @@ -126718,6 +126826,7 @@ const inputs_1 = __nccwpck_require__(38422);
const mount_1 = __nccwpck_require__(71255);
const compose_template_1 = __nccwpck_require__(17513);
const dotenv_1 = __nccwpck_require__(58570);
const ps_version_1 = __nccwpck_require__(49800);
const install_module_1 = __nccwpck_require__(56886);
const docker_1 = __nccwpck_require__(60704);
const suites_1 = __nccwpck_require__(24529);
Expand Down Expand Up @@ -126800,13 +126909,15 @@ async function run() {
// through `env:` is both invisible to the lib and blocks the same key
// from the file. Hence: everything goes into .env.local (user file and
// step env merged in), and those keys are stripped from the PHP env.
// The image tag (8.2.8-nginx, latest…) is not a version the library parses.
const psVersion = await (0, ps_version_1.resolvePsVersion)({ imageTag: inputs.psVersion, composePath: flashlight.composePath });
dotenv = (0, dotenv_1.writeFlashlightDotenv)({
workspace,
foUrl: `${flashlight.url}/`,
psVersion: inputs.psVersion,
psVersion,
processEnv: process.env,
});
core.info(`Flashlight ready at ${flashlight.url} (PS ${inputs.psVersion})`);
core.info(`Flashlight ready at ${flashlight.url} (image ${inputs.psVersion}, PS ${psVersion ?? 'unknown'})`);
}
try {
await (0, prepare_1.prepareVisualBaselines)({
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

12 changes: 7 additions & 5 deletions src/flashlight/dotenv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ function block(title: string, vars: Record<string, string>): string[] {

export interface RenderParams {
foUrl: string;
psVersion: string;
/** Bare PrestaShop version, or null when it could not be told (not written then). */
psVersion: string | null;
/** Raw content of the user's dotenv file (.env.local or .env), if any. */
userContent: string | null;
/** PRESTAFLOW_* variables from the Action's process env (step `env:`). */
Expand All @@ -68,12 +69,13 @@ export function flashlightDefaults(): Record<string, string> {
};
}

export function flashlightForced(foUrl: string, psVersion: string): Record<string, string> {
return {
export function flashlightForced(foUrl: string, psVersion: string | null): Record<string, string> {
const forced: Record<string, string> = {
PRESTAFLOW_FO_URL: foUrl,
PRESTAFLOW_BO_URL: `${foUrl}${FLASHLIGHT_ADMIN_DIR}/`,
PRESTAFLOW_PS_VERSION: psVersion,
};
if (psVersion) forced.PRESTAFLOW_PS_VERSION = psVersion;
return forced;
}

/**
Expand Down Expand Up @@ -103,7 +105,7 @@ export function renderFlashlightDotenv(p: RenderParams): string {
export interface WriteParams {
workspace: string;
foUrl: string;
psVersion: string;
psVersion: string | null;
processEnv: NodeJS.ProcessEnv;
}

Expand Down
66 changes: 66 additions & 0 deletions src/flashlight/ps-version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as core from '@actions/core';
import * as exec from '@actions/exec';

/**
* PrestaShop version carried by a Flashlight image tag: `8.2.8-nginx`,
* `8.2.8-8.1-fpm-alpine3.21-nginx` and `9.0.0` all start with it. Tags without
* a version (`latest`, `nightly`, `base-8.2-…`) return null.
*
* prestaflow/php-library only parses a bare version (`1.7.8.11`, `8.2.8`), and
* fails the whole run on anything else, so the tag is never passed as is.
*/
export function psVersionFromImageTag(tag: string): string | null {
const m = /^(\d+\.\d+\.\d+(?:\.\d+)?)(?:-|$)/.exec(tag.trim());
return m ? m[1] : null;
}

/** Last line of a command run in the PrestaShop container, '' when it fails. */
async function execInShop(composePath: string, command: string[]): Promise<string> {
let output = '';
try {
await exec.exec('docker', ['compose', '-f', composePath, 'exec', '-T', 'prestashop', ...command], {
ignoreReturnCode: true, silent: true, listeners: { stdout: (b: Buffer) => { output += b.toString(); } },
});
} catch {
return '';
}
return output.trim().split('\n').pop()?.trim() ?? '';
}

const isBareVersion = (v: string): boolean => v !== '' && psVersionFromImageTag(v) === v;

// Fallback for an image without PS_VERSION: releases up to 9.1 declare it in AppKernel.
const READ_APPKERNEL_PHP =
`echo preg_match("/const VERSION = '([0-9.]+)'/", (string) @file_get_contents('/var/www/html/app/AppKernel.php'), $m) ? $m[1] : '';`;

/**
* Read the version from the running shop, for a tag that does not carry it.
* Flashlight images declare it in their PS_VERSION environment variable
* (`latest` is 9.2.1 at the time of writing).
*/
export async function readPsVersionFromContainer(composePath: string): Promise<string | null> {
const fromEnv = await execInShop(composePath, ['printenv', 'PS_VERSION']);
if (isBareVersion(fromEnv)) return fromEnv;
const fromKernel = await execInShop(composePath, ['php', '-r', READ_APPKERNEL_PHP]);
return isBareVersion(fromKernel) ? fromKernel : null;
}

/**
* Version given to the library as PRESTAFLOW_PS_VERSION: from the tag, else
* from the shop. Null when neither says: the variable is then left to the
* user's dotenv file or step env, with a warning.
*/
export async function resolvePsVersion(p: { imageTag: string; composePath: string }): Promise<string | null> {
const fromTag = psVersionFromImageTag(p.imageTag);
if (fromTag) return fromTag;
const fromShop = await readPsVersionFromContainer(p.composePath);
if (fromShop) {
core.info(`Flashlight image ${p.imageTag}: PrestaShop ${fromShop} read from the shop.`);
return fromShop;
}
core.warning(
`Could not tell the PrestaShop version of Flashlight image "${p.imageTag}": PRESTAFLOW_PS_VERSION is not set by the action. `
+ 'Set it with env: on the step, or use a versioned ps-version (e.g. 8.2.8-nginx).',
);
return null;
}
Loading
Loading