How to Leverage Batch Processing with JSON Arrays to Execute Multiple OfficeCLI Commands Atomically
OfficeCLI enables atomic batch processing by accepting a JSON array of commands via the batch subcommand, validating each instruction against a temporary document copy, and committing changes only when every operation succeeds.
The iOfficeAI/OfficeCLI repository provides a robust batch processing mechanism that allows developers to execute multiple document manipulation commands transactionally using JSON arrays. This architecture prevents partial state modifications by ensuring all operations either complete successfully or leave the original document untouched. By utilizing the batch subcommand with structured JSON input, you can orchestrate complex Office document automation workflows through a single, atomic invocation.
Core Architecture of JSON Array Batch Processing
The batch processing engine in src/officecli/CommandBuilder.Batch.cs orchestrates command parsing, validation, and execution strategy selection. The system handles input sanitization, automatic envelope detection, and transaction management through a unified pipeline.
Input Handling and BOM Detection
When receiving JSON input via --input or --commands, OfficeCLI automatically detects and strips UTF-8 Byte Order Marks (BOM) that may originate from piped data or file reads. This sanitization occurs early in CommandBuilder.Batch.cs to ensure clean parsing regardless of input source encoding variations.
Automatic Envelope Unwrapping
The batch parser recognizes JSON envelopes produced by officecli dump --json and automatically extracts the internal data array. This design eliminates manual jq processing when piping dump output directly into batch commands, enabling seamless workflows such as dump --json | batch --input - without intermediate transformation steps.
Strict Validation Rules
Each element in the JSON array undergoes rigorous validation before execution. The parser rejects null entries, validates that every item is a properly structured object, and generates explicit error messages for unknown fields. This strict validation prevents silent failures and ensures command integrity prior to document modification.
Structured JSON Output
When invoking the batch command with --json, results are wrapped in the standard envelope format ({"success":true,"data":…}) even for empty batches. This consistent output structure, implemented in CommandBuilder.Batch.cs, simplifies automated parsing in CI/CD pipelines and SDK integrations.
Atomic vs. Best-Effort Execution Modes
OfficeCLI provides two distinct execution strategies controlled via command-line flags, allowing developers to balance data safety against performance requirements.
Atomic Transaction Mode (Default)
By default, the batch command operates atomically to guarantee data integrity. The system creates a temporary copy of the target document, applies all commands sequentially to this copy, and replaces the original file only if every command succeeds. If any operation fails, the temporary copy is discarded and the original document remains unmodified, preventing partial updates.
Best-Effort Mode
Specifying --best-effort disables atomic copy-and-replace semantics. In this mode, commands execute directly against the target document in-place. When combined with --stop-on-error, you can configure whether the batch halts immediately on the first failure or continues processing remaining commands regardless of individual failures.
Resident Server Integration
When a resident OfficeCLI process is active via officecli watch, batch operations leverage high-performance in-memory execution. The entire JSON payload transmits as a single "batch" request to ResidentServer.cs, ensuring all commands execute within the same resident session without file system overhead. The ResidentClient.cs module handles payload transmission and response parsing, returning formatted results through the established IPC channel.
Practical Implementation Examples
Atomic Batch Processing from File
Create a JSON array describing multiple operations:
cat > batch.json <<'EOF'
[
{"command":"add","path":"/slide[1]","type":"shape","prop":"text=Hello"},
{"command":"set","path":"/slide[1]/shape[1]","prop":"color=FF0000"},
{"command":"remove","path":"/slide[1]/shape[2]"}
]
EOF
Execute atomically against a PowerPoint presentation:
officecli batch deck.pptx --input batch.json
The original deck.pptx remains unchanged if any command fails, ensuring transactional safety.
Inline JSON with Best-Effort Execution
For rapid testing or non-critical updates where partial modifications are acceptable:
officecli batch report.docx \
--commands '[{"command":"set","path":"/body/p[1]","prop":"bold=true"},
{"command":"add","path":"/body","type":"paragraph","prop":"text=Note"}]' \
--best-effort
Changes apply immediately to the source file; use --stop-on-error to halt on first failure.
Pipeline Processing from Document Dumps
Leverage automatic envelope unwrapping when transforming existing document states:
officecli dump deck.pptx --json | \
officecli batch deck.pptx --input -
The batch command automatically extracts the data array from the dump envelope, eliminating intermediate processing steps.
Resident Server Batch Execution
For live preview environments with immediate visual feedback:
# Terminal 1: Start resident watch session
officecli watch deck.pptx
# Terminal 2: Execute batch in-memory
officecli batch deck.pptx \
--commands '[{"command":"add","path":"/","type":"slide","prop":"title=Agenda"}]' \
--force
The resident server applies changes instantly without file I/O, providing real-time preview updates.
Programmatic Batch Processing with SDKs
OfficeCLI exposes batch functionality through official SDKs for Python and Node.js applications.
Python SDK Implementation
The Python wrapper in sdk/python/officecli.py exposes batch operations via the batchJson parameter:
import officecli
client = officecli.Client()
client.batch(
"document.docx",
batchJson=[
{"command": "set", "path": "/title", "prop": "text=New Title"},
{"command": "add", "path": "/body", "type": "paragraph"}
]
)
Node.js SDK Implementation
The Node.js implementation in sdk/node/index.js similarly accepts batchJson arguments:
const officecli = require('officecli');
await officecli.batch('document.docx', {
batchJson: [
{command: 'remove', path: '/header'},
{command: 'set', path: '/footer', prop: 'text=Confidential'}
]
});
Summary
- Atomic execution is the default behavior in
CommandBuilder.Batch.cs: OfficeCLI creates temporary document copies and commits changes only when all batch commands succeed, preventing partial updates. - JSON array input accepts commands via
--input <file>,--commands <json>, or stdin, with automatic UTF-8 BOM removal and envelope unwrapping fordump --jsonpipelines. - Validation occurs upfront in
CommandBuilder.Batch.cs, rejecting null entries and validating object structure while providing clear error messages for unknown fields. - Resident server mode transmits the entire payload as a single batch request to
ResidentServer.cs, enabling high-performance in-memory processing without file system overhead. - Best-effort mode (
--best-effort) disables atomicity for direct in-place modification, useful for debugging or scenarios where partial updates are acceptable. - SDK support extends batch functionality to Python (
sdk/python/officecli.py) and Node.js (sdk/node/index.js) applications through thebatchJsoninterface.
Frequently Asked Questions
How does OfficeCLI ensure atomicity during batch processing?
OfficeCLI ensures atomicity by creating a temporary copy of the target document before executing any commands in CommandBuilder.Batch.cs. All operations in the JSON array apply to this temporary instance, and only after every command succeeds does the system replace the original file. If any command fails, the temporary copy is discarded and the original remains untouched.
Can I mix different command types in a single JSON batch array?
Yes, you can combine any valid OfficeCLI commands within a single JSON array. The batch processor validates each object independently, allowing you to sequence add, set, remove, and other operations in any order. Each object must specify the command field and appropriate parameters like path and prop to execute correctly.
What happens if the JSON input contains malformed commands?
The batch parser in CommandBuilder.Batch.cs performs strict validation before execution. It rejects null entries, validates that each item is an object, and reports unknown fields with specific error messages. If validation fails, the entire batch aborts before modifying the document, preserving the atomic guarantee.
How do I process the output from officecli dump --json in a batch command?
OfficeCLI automatically handles JSON envelopes from dump --json operations in CommandBuilder.Batch.cs. When piping dump output directly into batch --input -, the parser detects the envelope structure and extracts the data array automatically. This eliminates the need for manual JSON manipulation with tools like jq.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →