Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Data Liberation] Edit static files directly in a git repository #2109

Draft
wants to merge 71 commits into
base: support-static-pages
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
4da97f0
Remount NODEFS and other mounts after hotswapPhpRuntime is called
adamziel Dec 23, 2024
9456b22
Preserve the /internal directory when hotSwapPhpRuntime is called
adamziel Dec 23, 2024
fc74f35
Test with 4 mounts
adamziel Dec 23, 2024
199bc5e
Local files browser in the post editor
adamziel Dec 23, 2024
e46e7e9
Add Editor UI and hooks to synchronize WordPress pages to local files
adamziel Dec 24, 2024
7b5b125
Implement Git sparse checkout in PHP
adamziel Dec 25, 2024
e821059
Plug in WP_Git_Filesystem to directly browse and edit the static file…
adamziel Dec 26, 2024
4d10e75
Prototype git push
adamziel Dec 27, 2024
45d7a88
Put all pack-related methods in WP_Git_Pack_Processor
adamziel Dec 27, 2024
0d8f88f
WP_Git_Filesystem that can read and write files from a Git repo
adamziel Dec 27, 2024
cefacc2
Tweak new file creation and metadata loading
adamziel Dec 27, 2024
18e73b8
Add specific exception for renaming directories
adamziel Dec 27, 2024
0da6447
Support renaming and deleting files
adamziel Dec 27, 2024
88b57b7
Tweak the user experience of the file picker. Enable drag&drop
adamziel Dec 27, 2024
74e671a
Replace recursive props with a context
adamziel Dec 27, 2024
7a4a0dc
Enable file uploading by drag&drop
adamziel Dec 27, 2024
e55b94a
Enable deleting file subtrees
adamziel Dec 27, 2024
718bbe6
Dsplay directories before files, use a more useful default commit
adamziel Dec 27, 2024
d9c0ead
Display a visually consistent selection in the Local Files tab without a
adamziel Dec 27, 2024
f945ec3
Use the vertical three dots icon for "more"
adamziel Dec 27, 2024
e5679d2
CSS tweaks
adamziel Dec 27, 2024
1fbfbfc
CSS tweaks
adamziel Dec 27, 2024
7e5e96a
Restrict the local files tab to the list view sidebar
adamziel Dec 28, 2024
6951723
WP_Git_Client: Use AsyncHttp\Client for HTTP requests
adamziel Dec 29, 2024
8b764c1
Fix disappearing editor, add post loading overlay
adamziel Dec 29, 2024
fdf9393
Add WP_Git_Cached_Index that stores objects in a local directory
adamziel Dec 29, 2024
63ed39a
Expand WP_Git_Cached_Index to support more operations and commits
adamziel Dec 30, 2024
59884ed
Streaming git read, ability to compute objects newly added in a commit
adamziel Dec 30, 2024
6200a4a
Implement git pull and push
adamziel Dec 30, 2024
d56adb5
Rename Git_Cached_Index to Git_Repository ane enable remote management
adamziel Dec 30, 2024
724e177
Support user.name and user.email git settings and auto push mode in t…
adamziel Dec 30, 2024
c07add9
Use serialize_blocks to store custom blocks in markdown
adamziel Dec 30, 2024
decd81e
Resolve minor papercuts to enable using the plugin with git
adamziel Dec 30, 2024
96f52a3
Store auto-saves on the disk
adamziel Dec 31, 2024
270737d
Improve Blocks/Markdown conversion
adamziel Dec 31, 2024
7bef2bc
Implement reparent, squash, amend
adamziel Dec 31, 2024
e368495
Send autosaves as commit amends
adamziel Dec 31, 2024
1676afa
Drag and drop from the editor to desktop
adamziel Jan 1, 2025
d33b84f
Preview static files
adamziel Jan 1, 2025
620755d
Only force pull at most once every 10 minutes, exclude .autosaves fro…
adamziel Jan 1, 2025
8594402
Reduce waiting in the UI – server provides each page's ID, the editor…
adamziel Jan 1, 2025
6956b58
Import attachments on boot and on upload
adamziel Jan 1, 2025
b2755d7
Suport UTF-8 filenames in download_file_endpoint
adamziel Jan 1, 2025
a9202bb
Rewrite WordPress URLs to relative URLs when serializing to markdown
adamziel Jan 2, 2025
802a6f0
Preserve images as blocks
adamziel Jan 2, 2025
875c89a
Upload media files to the static files filesystem
adamziel Jan 2, 2025
0077659
Use the correct paths in wp_handle_upload
adamziel Jan 2, 2025
11638c6
Delete files when backspace is pressed
adamziel Jan 2, 2025
a11d520
Store updated media files when they're, e.g., rotated
adamziel Jan 2, 2025
34e08ff
Media files preview
adamziel Jan 2, 2025
86ab57d
Derive WP_Block_Markup_Processor from WP_HTML_Tag_Processor, not WP_H…
adamziel Jan 2, 2025
6be33e3
Preserve the correct last href in Blocks -> Markdown conversion
adamziel Jan 2, 2025
1f27630
Don't explicitly force pull after writes
adamziel Jan 3, 2025
2ad968b
Rudimentary commit diffing and text diffing
adamziel Jan 3, 2025
12c3fb2
Clarify a TODO comment
adamziel Jan 3, 2025
b13b833
Implement three way merge
adamziel Jan 3, 2025
65c73bb
Support for the HTML format and changing file extensions
adamziel Jan 4, 2025
6357abd
Start implementing a git server
adamziel Jan 5, 2025
dd73f79
Parse Git Client messages
adamziel Jan 5, 2025
bb3928e
Add unit tests
adamziel Jan 5, 2025
b28b46a
Functional fetch support
adamziel Jan 6, 2025
4d90846
Implement git push in WP_Git_Server
adamziel Jan 6, 2025
32af23d
Remove debug comment
adamziel Jan 6, 2025
122fe94
Add TODO
adamziel Jan 6, 2025
149f8b4
git fetch WordPress pages
adamziel Jan 6, 2025
75f7601
Add readme for the git repo plugin
adamziel Jan 6, 2025
9b09454
Add a todo
adamziel Jan 6, 2025
8dd84b3
git push to update content
adamziel Jan 6, 2025
2d5da28
When fetching, fetch all the relevant objects without leaving out any
adamziel Jan 7, 2025
d4afa36
Comment out the failure in find_objects_added_in
adamziel Jan 7, 2025
bbea7ae
Handle content deletions in the git endpoint
adamziel Jan 8, 2025
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ testem.log
*.timestamp-1678999213403.mjs
/.env
packages/playground/website/cypress/downloads
packages/playground/data-liberation-static-files-editor/secrets.php
vite.config.ts.timestamp-*.mjs

# System Files
Expand Down
9,729 changes: 7,303 additions & 2,426 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"@types/react-transition-group": "4.4.11",
"@types/wicg-file-system-access": "2023.10.5",
"@wordpress/dataviews": "4.5.0",
"@wordpress/scripts": "30.7.0",
"ajv": "8.12.0",
"async-lock": "1.4.1",
"axios": "1.6.1",
Expand Down Expand Up @@ -126,7 +127,7 @@
"@nx/web": "16.9.0",
"@nx/webpack": "16.9.0",
"@nx/workspace": "16.9.0",
"@playwright/test": "1.47.1",
"@playwright/test": "1.48.1",
"@rollup/plugin-url": "^8.0.1",
"@swc-node/register": "~1.6.7",
"@swc/core": "~1.3.85",
Expand Down
2 changes: 1 addition & 1 deletion packages/php-wasm/node/src/lib/node-fs-mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export function createNodeFsMountHandler(localPath: string): MountHandler {
return async function (php, FS, vfsMountPoint) {
FS.mount(FS.filesystems['NODEFS'], { root: localPath }, vfsMountPoint);
return () => {
FS!.unmount(localPath);
FS!.unmount(vfsMountPoint);
};
};
}
176 changes: 176 additions & 0 deletions packages/php-wasm/node/src/test/rotate-php-runtime.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,182 @@ const recreateRuntime = async (version: any = LatestSupportedPHPVersion) =>
await loadNodeRuntime(version);

describe('rotatePHPRuntime()', () => {
it('Preserves the /internal directory through PHP runtime recreation', async () => {
// Rotate the PHP runtime
const recreateRuntimeSpy = vitest.fn(recreateRuntime);

const php = new PHP(await recreateRuntime());
rotatePHPRuntime({
php,
cwd: '/test-root',
recreateRuntime: recreateRuntimeSpy,
maxRequests: 10,
});

// Create a temporary directory and a file in it
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'temp-'));
const tempFile = path.join(tempDir, 'file');
fs.writeFileSync(tempFile, 'playground');

// Mount the temporary directory
php.mkdir('/internal/shared');
php.writeFile('/internal/shared/test', 'playground');

// Confirm the file is there
expect(php.fileExists('/internal/shared/test')).toBe(true);

// Rotate the PHP runtime
for (let i = 0; i < 15; i++) {
await php.run({ code: `` });
}

expect(recreateRuntimeSpy).toHaveBeenCalledTimes(1);

// Confirm the file is still there
expect(php.fileExists('/internal/shared/test')).toBe(true);
expect(php.readFileAsText('/internal/shared/test')).toBe('playground');
});

it('Preserves a single NODEFS mount through PHP runtime recreation', async () => {
// Rotate the PHP runtime
const recreateRuntimeSpy = vitest.fn(recreateRuntime);

const php = new PHP(await recreateRuntime());
rotatePHPRuntime({
php,
cwd: '/test-root',
recreateRuntime: recreateRuntimeSpy,
maxRequests: 10,
});

// Create a temporary directory and a file in it
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'temp-'));
const tempFile = path.join(tempDir, 'file');
fs.writeFileSync(tempFile, 'playground');

// Mount the temporary directory
php.mkdir('/test-root');
await php.mount('/test-root', createNodeFsMountHandler(tempDir));

// Confirm the file is still there
expect(php.readFileAsText('/test-root/file')).toBe('playground');

// Rotate the PHP runtime
for (let i = 0; i < 15; i++) {
await php.run({ code: `` });
}

expect(recreateRuntimeSpy).toHaveBeenCalledTimes(1);

// Confirm the local NODEFS mount is lost
expect(php.readFileAsText('/test-root/file')).toBe('playground');
});

it('Preserves 4 WordPress plugin mounts through PHP runtime recreation', async () => {
// Rotate the PHP runtime
const recreateRuntimeSpy = vitest.fn(recreateRuntime);

const php = new PHP(await recreateRuntime());
rotatePHPRuntime({
php,
cwd: '/wordpress',
recreateRuntime: recreateRuntimeSpy,
maxRequests: 10,
});

// Create temporary directories and files for plugins and uploads
const tempDirs = [
fs.mkdtempSync(path.join(os.tmpdir(), 'data-liberation-')),
fs.mkdtempSync(path.join(os.tmpdir(), 'data-liberation-markdown-')),
fs.mkdtempSync(
path.join(os.tmpdir(), 'data-liberation-static-files-editor-')
),
fs.mkdtempSync(path.join(os.tmpdir(), 'static-pages-')),
];

// Add test files to each directory
tempDirs.forEach((dir, i) => {
fs.writeFileSync(path.join(dir, 'test.php'), `plugin-${i}`);
});

// Create WordPress directory structure
php.mkdir('/wordpress/wp-content/plugins/data-liberation');
php.mkdir('/wordpress/wp-content/plugins/z-data-liberation-markdown');
php.mkdir(
'/wordpress/wp-content/plugins/z-data-liberation-static-files-editor'
);
php.mkdir('/wordpress/wp-content/uploads/static-pages');

// Mount the directories using WordPress paths
await php.mount(
'/wordpress/wp-content/plugins/data-liberation',
createNodeFsMountHandler(tempDirs[0])
);
await php.mount(
'/wordpress/wp-content/plugins/z-data-liberation-markdown',
createNodeFsMountHandler(tempDirs[1])
);
await php.mount(
'/wordpress/wp-content/plugins/z-data-liberation-static-files-editor',
createNodeFsMountHandler(tempDirs[2])
);
await php.mount(
'/wordpress/wp-content/uploads/static-pages',
createNodeFsMountHandler(tempDirs[3])
);

// Verify files exist
expect(
php.readFileAsText(
'/wordpress/wp-content/plugins/data-liberation/test.php'
)
).toBe('plugin-0');
expect(
php.readFileAsText(
'/wordpress/wp-content/plugins/z-data-liberation-markdown/test.php'
)
).toBe('plugin-1');
expect(
php.readFileAsText(
'/wordpress/wp-content/plugins/z-data-liberation-static-files-editor/test.php'
)
).toBe('plugin-2');
expect(
php.readFileAsText(
'/wordpress/wp-content/uploads/static-pages/test.php'
)
).toBe('plugin-3');

// Rotate the PHP runtime
for (let i = 0; i < 15; i++) {
await php.run({ code: `` });
}

expect(recreateRuntimeSpy).toHaveBeenCalledTimes(1);

// Verify files still exist after rotation
expect(
php.readFileAsText(
'/wordpress/wp-content/plugins/data-liberation/test.php'
)
).toBe('plugin-0');
expect(
php.readFileAsText(
'/wordpress/wp-content/plugins/z-data-liberation-markdown/test.php'
)
).toBe('plugin-1');
expect(
php.readFileAsText(
'/wordpress/wp-content/plugins/z-data-liberation-static-files-editor/test.php'
)
).toBe('plugin-2');
expect(
php.readFileAsText(
'/wordpress/wp-content/uploads/static-pages/test.php'
)
).toBe('plugin-3');
});

it('Free up the available PHP memory', async () => {
const freeMemory = (php: PHP) =>
php[__private__dont__use].HEAPU32.reduce(
Expand Down
43 changes: 41 additions & 2 deletions packages/php-wasm/universal/src/lib/php.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@
export const PHP_INI_PATH = '/internal/shared/php.ini';
const AUTO_PREPEND_SCRIPT = '/internal/shared/auto_prepend_file.php';

type MountObject = {
mountHandler: MountHandler;
unmount: () => Promise<any>;
};

/**
* An environment-agnostic wrapper around the Emscripten PHP runtime
* that universals the super low-level API and provides a more convenient
Expand All @@ -62,6 +67,7 @@
#wasmErrorsTarget: UnhandledRejectionsTarget | null = null;
#eventListeners: Map<string, Set<PHPEventListener>> = new Map();
#messageListeners: MessageListener[] = [];
#mounts: Record<string, MountObject> = {};
requestHandler?: PHPRequestHandler;

/**
Expand Down Expand Up @@ -1000,16 +1006,29 @@
* is fully decoupled from the request handler and
* accepts a constructor-level cwd argument.
*/
hotSwapPHPRuntime(runtime: number, cwd?: string) {
async hotSwapPHPRuntime(runtime: number, cwd?: string) {
// Once we secure the lock and have the new runtime ready,
// the rest of the swap handler is synchronous to make sure
// no other operations acts on the old runtime or FS.
// If there was await anywhere here, we'd risk applyng
// asynchronous changes to either the filesystem or the
// old PHP runtime without propagating them to the new
// runtime.

const oldFS = this[__private__dont__use].FS;

// Unmount all the mount handlers
const mountHandlers: { mountHandler: MountHandler; vfsPath: string }[] =
[];
for (const [vfsPath, mount] of Object.entries(this.#mounts)) {
mountHandlers.push({ mountHandler: mount.mountHandler, vfsPath });
try {
await mount.unmount();
} catch (e) {
console.error(e);

Check warning on line 1028 in packages/php-wasm/universal/src/lib/php.ts

View workflow job for this annotation

GitHub Actions / Lint and typecheck

Unexpected console statement
}
}

// Kill the current runtime
try {
this.exit();
Expand All @@ -1024,10 +1043,19 @@
this.setSapiName(this.#sapiName);
}

// Copy the old /internal directory to the new filesystem
copyFS(oldFS, this[__private__dont__use].FS, '/internal');

// Copy the MEMFS directory structure from the old FS to the new one
if (cwd) {
copyFS(oldFS, this[__private__dont__use].FS, cwd);
}

// Re-mount all the mount handlers
for (const { mountHandler, vfsPath } of mountHandlers) {
this.mkdir(vfsPath);
await this.mount(vfsPath, mountHandler);
}
}

/**
Expand All @@ -1041,11 +1069,22 @@
virtualFSPath: string,
mountHandler: MountHandler
): Promise<UnmountFunction> {
return await mountHandler(
const unmountCallback = await mountHandler(
this,
this[__private__dont__use].FS,
virtualFSPath
);
const mountObject = {
mountHandler,
unmount: async () => {
await unmountCallback();
delete this.#mounts[virtualFSPath];
},
};
this.#mounts[virtualFSPath] = mountObject;
return () => {
mountObject.unmount();
};
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/php-wasm/universal/src/lib/rotate-php-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function rotatePHPRuntime({
async function rotateRuntime() {
const release = await php.semaphore.acquire();
try {
php.hotSwapPHPRuntime(await recreateRuntime(), cwd);
await php.hotSwapPHPRuntime(await recreateRuntime(), cwd);

// A new runtime has handled zero requests.
runtimeRequestCount = 0;
Expand Down
22 changes: 18 additions & 4 deletions packages/playground/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,11 +229,13 @@ async function run() {
}
lastCaption =
e.detail.caption || lastCaption || 'Running the Blueprint';
logger.log(
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write(
'\r\x1b[K' + `${lastCaption.trim()}${e.detail.progress}%`
);
if (progress100) {
logger.log('\n');
process.stdout.write('\n');
}
});
return compileBlueprint(blueprint as Blueprint, {
Expand Down Expand Up @@ -274,8 +276,10 @@ async function run() {
Math.min(100, (100 * e.detail.loaded) / e.detail.total)
);
if (!args.quiet) {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write(
`\rDownloading WordPress ${percentProgress}%... `
`Downloading WordPress ${percentProgress}%...`
);
}
}) as any);
Expand Down Expand Up @@ -309,6 +313,7 @@ async function run() {
WP_DEBUG_DISPLAY: false,
};

logger.log(`Booting WordPress...`);
requestHandler = await bootWordPress({
siteUrl: absoluteUrl,
createPhpRuntime: async () =>
Expand All @@ -334,14 +339,23 @@ async function run() {
},
},
});
logger.log(`Booted!`);

const php = await requestHandler.getPrimaryPhp();
try {
if (wpDetails && !args.mountBeforeInstall) {
if (
wpDetails &&
!args.mountBeforeInstall &&
!fs.existsSync(preinstalledWpContentPath)
) {
logger.log(
`Caching preinstalled WordPress for the next boot...`
);
fs.writeFileSync(
preinstalledWpContentPath,
await zipDirectory(php, '/wordpress')
);
logger.log(`Cached!`);
}

if (args.mount) {
Expand Down
Loading
Loading