Skip to content
Back to search

open-agent-skills

We are dedicated to building a set of open agent skills that deliver superior performance, higher determinism, and greater consistency on targeted tasks, while operating at a lower cost and with reduced context usage.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/masslab-sii--open-agent-skills/badge.svg)](/listings/masslab-sii--open-agent-skills)

HTML

<a href="/listings/masslab-sii--open-agent-skills"><img src="/api/listings/masslab-sii--open-agent-skills/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Prerequisites

- Python 3.11+ - [uv](https://github.com/astral-sh/uv) package manager (recommended, for faster installs)

Quick Install

# Clone the repository
git clone https://github.com/zjtco-yr/open-agent-skills.git
cd open-agent-skills

# install with uv (faster)
uv pip install -e .

Environment Configuration

Create a `.mcp_env` file with your API credentials:

# Example: OpenAI
OPENAI_BASE_URL="https://api.openai.com/v1"
OPENAI_API_KEY="sk-..."

# Optional: Notion (only for Notion tasks)
# SOURCE_NOTION_API_KEY="your-source-notion-api-key"
# EVAL_NOTION_API_KEY="your-eval-notion-api-key"
# EVAL_PARENT_PAGE_TITLE="MCPMark Eval Hub"

# Optional: Playwright (only for Playwright tasks)
PLAYWRIGHT_BROWSER="chromium"   # chromium | firefox
PLAYWRIGHT_HEADLESS="True"

# Optional: GitHub (only for GitHub tasks)
GITHUB_TOKENS="token1,token2"   # token pooling for rate limits
GITHUB_EVAL_ORG="your-eval-org"

For more detailed environment configuration, service setup, and authentication instructions, please refer to [MCPMark](https://github.com/mcpmark/mcpmark).

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 327 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <div align="center">
  2. <img src="assets/logo.png" alt="Open Agent Skills" width="400">
  3. **Enhancing AI Agent Efficiency Through Domain-Specific Skills**
  4. ![Skill with MCP](assets/skill_with_mcp.png)
  5. </div>
  6. ---
  7. > **"Model Context Protocol (MCP) connects Claude to third-party tools, and skills teach Claude how to use them well."**
  8. > — *[Extending Claude's capabilities with skills and MCP servers](https://claude.com/blog/extending-claude-capabilities-with-skills-mcp-servers)*, Anthropic
  9. ## 📖 Introduction
  10. As AI agents evolve, there is a growing need for modular, reusable approaches to equip them with domain-specific expertise while mitigating issues like excessive MCP context consumption. To address this, Anthropic introduced **[Agent Skills](https://agentskills.io/home)** as an open standard on December 18, 2025, allowing agents to dynamically load structured instructions and resources for more effective task execution. Although platforms such as **[OpenAI Codex](https://developers.openai.com/codex/skills/)** have adopted this standard, native support remains limited to specific ecosystems.
  11. However, many LLM providers have not yet adopted the Agent Skills standard, leaving this efficient approach temporarily inaccessible to a broader audience. We, **the Project Q team at SII**, bridge this gap by providing a lightweight, efficient open-source framework fully compatible with the Agent Skills standard, extending these capabilities to any LLM provider. Our implementation focuses on the synergy between **Model Context Protocol (MCP)** and **Skills**: MCP provides access to external tools and systems, while Skills provide the procedural knowledge to utilize tools (including MCP) effectively. With our skill-based implementation, we achieved up to **~20x context reduction** compared to pure MCP approaches.
  12. This project builds upon [MCPMark](https://github.com/mcpmark/mcpmark), a comprehensive evaluation suite for assessing the agentic capabilities of frontier models. We extend MCPMark's benchmark capabilities by introducing a **skill-based Implementation**.
  13. ### Key Features
  14. - ⚡ **Lightweight Skill Implementation**: Built with a minimal framework approach, making skills implementation easy to read and quick to understand
  15. - 🔗 **Skill + MCP Integration**: See how skills leverage MCP's external knowledge capabilities and organize multiple MCP services to collaboratively complete tasks
  16. - 🔌 **Claude Agent Standard Compatible**: Skills can be directly executed in Claude and other compatible agent environments
  17. - 🔀 **LLM provider Agnostic**: Not limited to Claude or Codex, any LLM can leverage skills to enhance efficiency
  18. ---
  19. ## 🛠️ Installation
  20. ### Prerequisites
  21. - Python 3.11+
  22. - [uv](https://github.com/astral-sh/uv) package manager (recommended, for faster installs)
  23. ### Quick Install
  24. ```bash
  25. # Clone the repository
  26. git clone https://github.com/zjtco-yr/open-agent-skills.git
  27. cd open-agent-skills
  28. # install with uv (faster)
  29. uv pip install -e .
  30. ```
  31. ### Environment Configuration
  32. Create a `.mcp_env` file with your API credentials:
  33. ```bash
  34. # Example: OpenAI
  35. OPENAI_BASE_URL="https://api.openai.com/v1"
  36. OPENAI_API_KEY="sk-..."
  37. # Optional: Notion (only for Notion tasks)
  38. # SOURCE_NOTION_API_KEY="your-source-notion-api-key"
  39. # EVAL_NOTION_API_KEY="your-eval-notion-api-key"
  40. # EVAL_PARENT_PAGE_TITLE="MCPMark Eval Hub"
  41. # Optional: Playwright (only for Playwright tasks)
  42. PLAYWRIGHT_BROWSER="chromium" # chromium | firefox
  43. PLAYWRIGHT_HEADLESS="True"
  44. # Optional: GitHub (only for GitHub tasks)
  45. GITHUB_TOKENS="token1,token2" # token pooling for rate limits
  46. GITHUB_EVAL_ORG="your-eval-org"
  47. ```
  48. For more detailed environment configuration, service setup, and authentication instructions, please refer to [MCPMark](https://github.com/mcpmark/mcpmark).
  49. ---
  50. ## 📊 Performance Results
  51. We conducted preliminary benchmark evaluations comparing MCP with Open-Agent-Skills **(Skill with MCP)** using the Claude-Sonnet-4.5 model. Results demonstrate that **Skill with MCP** achieves significant advantages in both **task performance** and **token efficiency**.
  52. ### Overall Pass@1 Accuracy
  53. <div align="center">
  54. | Benchmark | MCP | Skills |
  55. |:----------|:---:|:------:|
  56. | **GitHub** | 29.35% | **43.48%** |
  57. | **Filesystem** | 32.5% | **53.3%** |
  58. | **Playwright WebArena** | 32.14% | **52.38%** |
  59. </div>
  60. ### Token Efficiency (Successful Tasks Only)
  61. <div align="center">
  62. | Benchmark | MCP Tokens | Skills Tokens | Reduction |
  63. |:----------|:----------:|:-------------:|:---------:|
  64. | **GitHub** | 7.36M | 4.47M | **39.25%** |
  65. | **Filesystem** | 2.27M | 1.55M | **31.55%** |
  66. | **Playwright WebArena** | 10.25M | 8.27M | **19.30%** |
  67. </div>
  68. ### Extreme Cases
  69. <div align="center">
  70. | Task | MCP Tokens | Skills Tokens | Reduction |
  71. |:-----|:----------:|:-------------:|:---------:|
  72. | `english_talent` (Filesystem) | 1.05M | 0.053M | **95.00%** (~20x) |
  73. | `find_commit_date` (GitHub) | 1.21M | 0.23M | **80.84%** |
  74. | `marketing_customer_analysis`<br>(Playwright_webarena) | 1.45M | 0.67M | **54.00%** |
  75. </div>
  76. ### Key Insights
  77. 1. **Significant Accuracy Improvement**: Average Pass@1 accuracy increased by ~**18 percentage points** across all three benchmarks
  78. 2. **Excellent Token Efficiency**: Token consumption for successful tasks reduced by **20-40%**, with extreme cases reaching **80-95%**
  79. ---
  80. ## 🎬 Demo: How Skills Work
  81. ### Example: budget_europe_travel in reddit
  82. **Task**: This task involves multiple operations including account registration, creating posts, and setting up forums. For the complete task description, see `tasks/playwright_webarena/standard/reddit/budget_europe_travel`.
  83. <table style="table-layout: fixed; width: 100%;">
  84. <tr>
  85. <td style="padding: 10px; width: 50%; vertical-align: top;">
  86. <strong>Sign Up - Skill with MCP</strong>
  87. </td>
  88. <td style="padding: 10px; width: 50%; vertical-align: top;">
  89. <strong>Sign Up - MCP</strong>
  90. </td>
  91. </tr>
  92. <tr>
  93. <td style="padding: 10px; width: 50%; vertical-align: top;">
  94. <img src="assets/gifs/sign_up_skill.gif" width="100%">
  95. </td>
  96. <td style="padding: 10px; width: 50%; vertical-align: top;">
  97. <img src="assets/gifs/sign_up_mcp.gif" width="100%">
  98. </td>
  99. </tr>
  100. <tr>
  101. <td style="padding: 10px; width: 50%; vertical-align: top;">
  102. <strong>Create Forum - Skill with MCP</strong>
  103. </td>
  104. <td style="padding: 10px; width: 50%; vertical-align: top;">
  105. <strong>Create Forum - MCP</strong>
  106. </td>
  107. </tr>
  108. <tr>
  109. <td style="padding: 10px; width: 50%; vertical-align: top;">
  110. <img src="assets/gifs/create_forum_skill.gif" width="100%">
  111. </td>
  112. <td style="padding: 10px; width: 50%; vertical-align: top;">
  113. <img src="assets/gifs/create_forum_mcp.gif" width="100%">
  114. </td>
  115. </tr>
  116. <tr>
  117. <td style="padding: 10px; width: 50%; vertical-align: top;">
  118. <strong>Create Page - Skill with MCP</strong>
  119. </td>
  120. <td style="padding: 10px; width: 50%; vertical-align: top;">
  121. <strong>Create Page - MCP</strong>
  122. </td>
  123. </tr>
  124. <tr>
  125. <td style="padding: 10px; width: 50%; vertical-align: top;">
  126. <img src="assets/gifs/create_page_skill.gif" width="100%">
  127. </td>
  128. <td style="padding: 10px; width: 50%; vertical-align: top;">
  129. <img src="assets/gifs/create_page_mcp.gif" width="100%">
  130. </td>
  131. </tr>
  132. <tr>
  133. <td style="padding: 10px; width: 50%; vertical-align: top;">
  134. <strong>Create Submission - Skill with MCP</strong>
  135. </td>
  136. <td style="padding: 10px; width: 50%; vertical-align: top;">
  137. <strong>Create Submission - MCP</strong>
  138. </td>
  139. </tr>
  140. <tr>
  141. <td style="padding: 10px; width: 50%; vertical-align: top;">
  142. <img src="assets/gifs/create_submission_skill.gif" width="100%">
  143. </td>
  144. <td style="padding: 10px; width: 50%; vertical-align: top;">
  145. <img src="assets/gifs/create_submission_mcp.gif" width="100%">
  146. </td>
  147. </tr>
  148. <tr>
  149. <td style="padding: 10px; width: 50%; vertical-align: top;">
  150. <strong>Full Demo - Skill with MCP</strong>
  151. </td>
  152. <td style="padding: 10px; width: 50%; vertical-align: top;">
  153. <strong>Full Demo - MCP</strong>
  154. </td>
  155. </tr>
  156. <tr>
  157. <td style="padding: 10px; width: 50%; vertical-align: top;">
  158. <video src="https://github.com/user-attachments/assets/15664a10-0cce-4241-9448-cf57ef9eade3" controls muted preload="metadata" width="100%" style="border-radius: 8px;"></video>
  159. </td>
  160. <td style="padding: 10px; width: 50%; vertical-align: top;">
  161. <video src="https://github.com/user-attachments/assets/b7db7bbb-dafd-42e5-8a98-75786d4640cb" controls muted preload="metadata" width="100%" style="border-radius: 8px;"></video>
  162. </td>
  163. </tr>
  164. </table>
  165. **Result**: Using 4 skills, achieved 2x context reduction.
  166. ### Running the Demo
  167. ```bash
  168. # Start the browser server
  169. uv run skills/scripts/reddit/browser_server.py &
  170. # Execute a reddit task with skills
  171. python -m pipeline \
  172. --mcp playwright_webarena \
  173. --models claude-sonnet-4.5 \
  174. --tasks reddit/budget_europe_travel \
  175. --exp-name skill-demo \
  176. --k 1
  177. ```
  178. ---
  179. ## 🚀 Future Plans
  180. We acknowledge that the current implementation has room for improvement. This project is intended as a **starting point** to demonstrate the potential of combining MCP with domain-specific skills.
  181. ### Planned Improvements
  182. 1. **Balancing Specificity and Generalization**: While some of our skills are designed with broad applicability (e.g., Playwright-based skills for registration, posting, forum creation), others remain highly task-specific (e.g., time-based file classification in filesystem skills). We will focus on improving skill design patterns to strike a better balance between task-specific performance and cross-domain generalization.
  183. 2. **Skill-MCP Integration**: We plan to:
  184. - Develop better coordination patterns between skills and MCP tools
  185. - Enable smoother handoffs between skill scripts and MCP operations
  186. 3. **Extended Domain Coverage**:
  187. - Advanced database operations and Notion workspace automation
  188. - Common daily life use cases (productivity, personal automation, etc.)
  189. ---
  190. ## 🔒 Security
  191. Security is a primary consideration in our skill execution framework. It inherits and leverages several security features from [MCPMark](https://github.com/eval-sys/mcpmark/), including:
  192. - **Directory Isolation**: MCP/Skill file operations are confined to specific directories
  193. - **Docker Containerization**: Tasks run in isolated containers
  194. However, we strongly recommend that you **always review skill scripts** before execution in production, whether creating new skills or using existing ones.
  195. ---
  196. ## 📚 References & Resources
  197. ### Open Standards
  198. - **[Model Context Protocol (MCP)](https://modelcontextprotocol.io/)** - Anthropic's protocol for connecting AI assistants to external tools
  199. - **[Agent Skills Standard](https://agentskills.io/home)** - A simple, open format for giving agents new capabilities and expertise.
  200. ### Documentation
  201. - **[Agent Skills Overview](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview)** - Anthropic's official guide for Claude agent skills
  202. - **[Skills Docs](https://code.claude.com/docs/en/skills)** - Skills integration in Claude Code
  203. - **[Skills in Codex](https://developers.openai.com/codex/skills/)** - Give Codex new capabilities with support for explicit and implicit invocation
  204. ---
  205. ## ▶️ Quick Start
  206. After configuring the relevant APIs and Docker environment (if needed), you can run the following commands:
  207. ### Run a Playwright WebArena Task
  208. ```bash
  209. python -m pipeline --mcp playwright_webarena \
  210. --models claude-sonnet-4.5 \
  211. --tasks reddit/marketing_customer_analysis \
  212. --exp-name webarena-test \
  213. --k 1
  214. ```
  215. ### Run a Filesystem Task
  216. ```bash
  217. python -m pipeline --mcp filesystem \
  218. --models claude-sonnet-4.5 \
  219. --tasks student_database/english_talent \
  220. --exp-name filesystem-test \
  221. --k 1
  222. ```
  223. ### Run a Github Task
  224. ```bash
  225. python -m pipeline --mcp github \
  226. --models claude-sonnet-4.5 \
  227. --tasks build_your_own_x/find_commit_date \
  228. --exp-name github-test \
  229. --k 1
  230. ```
  231. ## 📄 License
  232. This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
  233. ---
  234. <div align="center">
  235. **Open-Agent-Skills** - Making AI agents more effective through domain expertise skill
  236. [Report Bug](https://github.com/zjtco-yr/open-agent-skills/issues) · [Request Feature](https://github.com/zjtco-yr/open-agent-skills/issues)
  237. </div>
portable-skills/github/scripts/file_editor.py · Bundled script · 430 lines · 1 finding marked
  1. """
  2. File Editor Script (Using utils.py)
  3. ===================================
  4. General purpose file editor for GitHub repositories.
  5. This script allows for modifying existing files, applying specific fixes,
  6. or pushing multiple files in a single atomic commit.
  7. Usage:
  8. python file_editor.py <command> <owner> <repo> [options]
  9. Commands:
  10. edit Edit/Overwrite a file
  11. apply_fix Apply a search and replace fix to a single file
  12. batch Push multiple files in a single commit
  13. Content Input Methods (for edit and batch commands):
  14. --content Direct content string (may have shell escaping issues with quotes)
  15. --content-base64 Base64 encoded content (recommended for code with special chars)
  16. --content-file Read content from a local file
  17. --stdin Read content from stdin (for piping)
  18. Examples:
  19. # Edit/Overwrite a configuration file
  20. python file_editor.py edit mcpmark-source build-your-own-x --path "src/config.py" --content "DEBUG = False" --message "Disable debug mode"
  21. # Edit with base64 encoded content (recommended for code)
  22. python file_editor.py edit owner repo --path "src/app.js" --content-base64 "Y29uc3QgbXNnID0gJ2hlbGxvJzs=" --message "Add app.js"
  23. # Apply a specific fix (search and replace in a single file)
  24. python file_editor.py apply_fix mcpmark-source build-your-own-x --path "src/buggy.py" --pattern "if x = y:" --replacement "if x == y:" --message "Fix syntax error"
  25. # Batch push multiple files in a single commit
  26. python file_editor.py batch mcpmark-source build-your-own-x --files '[{"path": ".github/workflows/lint.yml", "content": "..."}, {"path": "eslint.config.js", "content": "..."}]' --message "Add linting workflow and config"
  27. # Batch push with base64 encoded files (recommended)
  28. python file_editor.py batch owner repo --files-base64 "W3sicGF0aCI6ICJzcmMvYXBwLmpzIiwgImNvbnRlbnQiOiAiY29uc3QgeCA9IDE7In1d" --message "Add files"
    • Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 37 on GitHub
  29. """
  30. import argparse
  31. import asyncio
  32. import sys
  33. import os
  34. import traceback
  35. import base64
  36. from utils import (
  37. GitHubTools,
  38. extract_sha_from_result,
  39. extract_file_content,
  40. check_api_success,
  41. )
  42. class FileEditor:
  43. """Editor class for modifying files in GitHub repositories"""
  44. def __init__(self):
  45. """Initialize the editor with GitHubTools"""
  46. self.github = GitHubTools()
  47. def _check_api_success(self, result: any) -> bool:
  48. """Check if API result indicates success."""
  49. return check_api_success(result)
  50. def _extract_sha(self, result) -> str:
  51. """Extract SHA from get_file_contents result."""
  52. return extract_sha_from_result(result)
  53. async def edit_file(
  54. self,
  55. owner: str,
  56. repo: str,
  57. path: str,
  58. content: str,
  59. message: str,
  60. branch: str = "main",
  61. ) -> bool:
  62. """Edit an existing file or create if it doesn't exist."""
  63. async with self.github:
  64. print(f"Fetching current state of {path} in {owner}/{repo} on {branch}...")
  65. existing_file = await self.github.get_file_contents(
  66. owner, repo, path, ref=branch
  67. )
  68. sha = None
  69. if isinstance(existing_file, dict) and "sha" in existing_file:
  70. sha = existing_file["sha"]
  71. print(f"Found existing file (SHA: {sha}), updating...")
  72. else:
  73. print("File not found, creating new file...")
  74. # Note: For now, we simply overwrite the content.
  75. # In a more advanced version, we could support 'replace' logic (read -> str replace -> write).
  76. result = await self.github.create_or_update_file(
  77. owner=owner,
  78. repo=repo,
  79. path=path,
  80. content=content,
  81. message=message,
  82. branch=branch,
  83. sha=sha,
  84. )
  85. # Check for actual success: result should contain GitHub API success indicators
  86. success = self._check_api_success(result)
  87. if success:
  88. print(f"Successfully edited {path}")
  89. return True
  90. else:
  91. print(f"Failed to edit {path}: {result}")
  92. return False
  93. def _extract_file_content(self, result) -> str:
  94. """Extract actual file content from MCP get_file_contents result."""
  95. return extract_file_content(result) or ""
  96. async def apply_fix(
  97. self,
  98. owner: str,
  99. repo: str,
  100. path: str,
  101. pattern: str,
  102. replacement: str,
  103. message: str,
  104. branch: str = "main",
  105. ) -> bool:
  106. """Apply a fix by replacing a specific pattern in a file.
  107. Args:
  108. owner: Repository owner
  109. repo: Repository name
  110. path: File path in repository
  111. pattern: Text pattern to find and replace
  112. replacement: Replacement text
  113. message: Commit message
  114. branch: Target branch
  115. Returns:
  116. True if fix was applied successfully, False otherwise
  117. Note:
  118. This method does NOT assume a fix was already applied just because
  119. the replacement text exists. It requires the exact pattern to be present.
  120. """
  121. async with self.github:
  122. print(f"Fetching current state of {path} in {owner}/{repo} on {branch}...")
  123. existing_file = await self.github.get_file_contents(
  124. owner, repo, path, ref=branch
  125. )
  126. if not existing_file:
  127. print(f"Error: Could not fetch file {path}")
  128. return False
  129. # Extract file content properly from MCP result
  130. file_content = self._extract_file_content(existing_file)
  131. sha = self._extract_sha(existing_file)
  132. if not file_content:
  133. print(f"Error: Could not extract content from {path}")
  134. return False
  135. if pattern not in file_content:
  136. # Pattern not found - check if this might be an idempotent case
  137. # Only consider it "already applied" if:
  138. # 1. The replacement text exists in the file
  139. # 2. The pattern and replacement are different (not a no-op)
  140. # 3. The replacement appears in a context that suggests it replaced the pattern
  141. # (e.g., similar line structure)
  142. if replacement in file_content and pattern != replacement:
  143. # More careful check: see if the replacement is on a line by itself
  144. # or in a similar context where the pattern would have been
  145. pattern_lines = pattern.strip().split('\n')
  146. replacement_lines = replacement.strip().split('\n')
  147. # If both are single-line and replacement exists, it's likely already applied
  148. if len(pattern_lines) == 1 and len(replacement_lines) == 1:
  149. print(f"Pattern not found, but replacement text exists in file.")
  150. print(f"Note: Cannot confirm if fix was previously applied or if pattern never existed.")
  151. print(f"Returning success (idempotent behavior).")
  152. return True
  153. # For multi-line patterns, be more conservative
  154. print(f"Pattern not found in file.")
  155. print(f"Replacement text exists but cannot confirm prior application.")
  156. print(f"Pattern '{pattern[:100]}{'...' if len(pattern) > 100 else ''}' not found in file.")
  157. print(f"File content preview (first 500 chars):")
  158. print(file_content[:500])
  159. return False
  160. new_content = file_content.replace(pattern, replacement)
  161. # Verify the replacement actually changed something
  162. if new_content == file_content:
  163. print(f"Warning: Replacement did not change file content")
  164. return False
  165. result = await self.github.create_or_update_file(
  166. owner=owner,
  167. repo=repo,
  168. path=path,
  169. content=new_content,
  170. message=message,
  171. branch=branch,
  172. sha=sha,
  173. )
  174. # Check for actual success
  175. success = self._check_api_success(result)
  176. if success:
  177. print(f"Successfully applied fix to {path}")
  178. return True
  179. else:
  180. print(f"Failed to apply fix: {result}")
  181. return False
  182. async def batch_push(
  183. self,
  184. owner: str,
  185. repo: str,
  186. files: list,
  187. message: str,
  188. branch: str = "main",
  189. ) -> bool:
  190. """
  191. Push multiple files to a repository in a single commit.
  192. This is useful when you need to create/update multiple files atomically,
  193. ensuring all changes are in one commit (e.g., adding workflow + config files).
  194. Args:
  195. owner: Repository owner
  196. repo: Repository name
  197. files: List of file dicts with 'path' and 'content' keys
  198. message: Commit message
  199. branch: Target branch (default: main)
  200. Returns:
  201. True if successful, False otherwise
  202. Example:
  203. files = [
  204. {"path": ".github/workflows/lint.yml", "content": "name: Lint..."},
  205. {"path": "eslint.config.js", "content": "module.exports = {...}"}
  206. ]
  207. await editor.batch_push(owner, repo, files, "Add linting", "main")
  208. """
  209. async with self.github:
  210. print(f"Pushing {len(files)} files to {owner}/{repo} on {branch} in a single commit...")
  211. # Validate files format
  212. for i, f in enumerate(files):
  213. if not isinstance(f, dict) or 'path' not in f or 'content' not in f:
  214. print(f"Error: File at index {i} must have 'path' and 'content' keys")
  215. return False
  216. result = await self.github.push_files(
  217. owner=owner,
  218. repo=repo,
  219. branch=branch,
  220. files=files,
  221. message=message,
  222. )
  223. # Check for success
  224. success = self._check_api_success(result)
  225. if success:
  226. print(f"Successfully pushed {len(files)} files in a single commit")
  227. for f in files:
  228. print(f" - {f['path']}")
  229. return True
  230. else:
  231. print(f"Failed to push files: {result}")
  232. return False
  233. async def main():
  234. """Main entry point"""
  235. parser = argparse.ArgumentParser(
  236. description="Edit files in GitHub repository.",
  237. formatter_class=argparse.RawDescriptionHelpFormatter,
  238. epilog="""
  239. Examples:
  240. # Edit/Overwrite a file
  241. python file_editor.py edit owner repo --path "src/config.py" --content "data" --message "upd"
  242. # Apply a fix
  243. python file_editor.py apply_fix owner repo --path "src/bug.py" --pattern "bad" --replacement "good" --message "fix"
  244. """
  245. )
  246. subparsers = parser.add_subparsers(dest="command", help="Command to execute")
  247. # Command: edit
  248. edit_parser = subparsers.add_parser("edit", help="Edit/Overwrite a file")
  249. edit_parser.add_argument("owner", help="Repository owner")
  250. edit_parser.add_argument("repo", help="Repository name")
  251. edit_parser.add_argument("--path", required=True, help="Path to the file")
  252. # Content input options (mutually exclusive)
  253. content_group = edit_parser.add_mutually_exclusive_group(required=True)
  254. content_group.add_argument("--content", help="New content of the file (direct string)")
  255. content_group.add_argument("--content-base64", help="Base64 encoded content (recommended for code)")
  256. content_group.add_argument("--content-file", help="Read content from local file")
  257. content_group.add_argument("--stdin", action="store_true", help="Read content from stdin")
  258. edit_parser.add_argument("--message", required=True, help="Commit message")
  259. edit_parser.add_argument("--branch", default="main", help="Target branch")
  260. # Command: apply_fix
  261. fix_parser = subparsers.add_parser("apply_fix", help="Apply a search and replace fix")
  262. fix_parser.add_argument("owner", help="Repository owner")
  263. fix_parser.add_argument("repo", help="Repository name")
  264. fix_parser.add_argument("--path", required=True, help="Path to the file")
  265. fix_parser.add_argument("--pattern", required=True, help="Text pattern to find")
  266. fix_parser.add_argument("--replacement", required=True, help="Replacement text")
  267. fix_parser.add_argument("--message", required=True, help="Commit message")
  268. fix_parser.add_argument("--branch", default="main", help="Target branch")
  269. # Command: batch
  270. batch_parser = subparsers.add_parser("batch", help="Push multiple files in a single commit")
  271. batch_parser.add_argument("owner", help="Repository owner")
  272. batch_parser.add_argument("repo", help="Repository name")
  273. # Files input options (mutually exclusive)
  274. files_group = batch_parser.add_mutually_exclusive_group(required=True)
  275. files_group.add_argument("--files", help='JSON array of files: [{"path": "...", "content": "..."}]')
  276. files_group.add_argument("--files-base64", help="Base64 encoded JSON array of files (recommended)")
  277. files_group.add_argument("--files-file", help="Read files JSON from local file")
  278. batch_parser.add_argument("--message", required=True, help="Commit message")
  279. batch_parser.add_argument("--branch", default="main", help="Target branch")
  280. args = parser.parse_args()
  281. editor = FileEditor()
  282. try:
  283. if args.command == "edit":
  284. # Resolve content from various input methods
  285. content = None
  286. if args.content:
  287. content = args.content
  288. elif args.content_base64:
  289. try:
  290. content = base64.b64decode(args.content_base64).decode('utf-8')
  291. except Exception as e:
  292. print(f"Error: Failed to decode base64 content: {e}")
  293. sys.exit(1)
  294. elif args.content_file:
  295. try:
  296. with open(args.content_file, 'r', encoding='utf-8') as f:
  297. content = f.read()
  298. except Exception as e:
  299. print(f"Error: Failed to read content file: {e}")
  300. sys.exit(1)
  301. elif args.stdin:
  302. content = sys.stdin.read()
  303. if content is None:
  304. print("Error: No content provided")
  305. sys.exit(1)
  306. success = await editor.edit_file(
  307. args.owner, args.repo, args.path, content, args.message, args.branch
  308. )
  309. if not success: sys.exit(1)
  310. elif args.command == "apply_fix":
  311. success = await editor.apply_fix(
  312. args.owner, args.repo, args.path, args.pattern, args.replacement, args.message, args.branch
  313. )
  314. if not success: sys.exit(1)
  315. elif args.command == "batch":
  316. import json
  317. files_json = None
  318. # Resolve files from various input methods
  319. if args.files:
  320. files_json = args.files
  321. elif args.files_base64:
  322. try:
  323. files_json = base64.b64decode(args.files_base64).decode('utf-8')
  324. except Exception as e:
  325. print(f"Error: Failed to decode base64 files: {e}")
  326. sys.exit(1)
  327. elif args.files_file:
  328. try:
  329. with open(args.files_file, 'r', encoding='utf-8') as f:
  330. files_json = f.read()
  331. except Exception as e:
  332. print(f"Error: Failed to read files file: {e}")
  333. sys.exit(1)
  334. if files_json is None:
  335. print("Error: No files provided")
  336. sys.exit(1)
  337. try:
  338. files = json.loads(files_json)
  339. if not isinstance(files, list):
  340. print("Error: files must be a JSON array")
  341. sys.exit(1)
  342. except json.JSONDecodeError as e:
  343. print(f"Error: Invalid JSON in files: {e}")
  344. sys.exit(1)
  345. success = await editor.batch_push(
  346. args.owner, args.repo, files, args.message, args.branch
  347. )
  348. if not success: sys.exit(1)
  349. else:
  350. parser.print_help()
  351. sys.exit(1)
  352. except Exception as e:
  353. print(f"\nError during execution: {e}")
  354. import traceback
  355. traceback.print_exc()
  356. sys.exit(1)
  357. if __name__ == "__main__":
  358. asyncio.run(main())

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.