← 返回 Skills 市场
534422530

代码生成器

作者 534422530 · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
24
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install laosi-code-generator
功能描述
代码生成 - 项目脚手架/函数模板/配置文件生成,支持Python/JS/Go多语言,自动创建目录结构
使用说明 (SKILL.md)

Code Generator - 代码生成器

激活词: 生成代码 / code generate / 项目脚手架

功能

  • 项目脚手架生成(Python/JS/Go)
  • 函数模板(API handler/CronJob/CLI)
  • 配置文件生成(YAML/JSON/TOML)
  • 自动创建目录结构
  • 代码片段库

Python 实现

import os, json
from datetime import datetime
from typing import Dict, List, Optional
from dataclasses import dataclass, field

@dataclass
class FileSpec:
    """文件规格"""
    path: str          # 相对路径, e.g. "src/main.py"
    content: str       # 文件内容
    overwrite: bool = False  # 是否允许覆盖
    
@dataclass
class ProjectTemplate:
    """项目模板"""
    name: str
    language: str
    description: str
    files: List[FileSpec] = field(default_factory=list)
    
    def add_file(self, path: str, content: str, overwrite: bool = False):
        self.files.append(FileSpec(path=path, content=content, overwrite=overwrite))
    
    def generate(self, output_dir: str) -> Dict:
        """生成项目到指定目录"""
        results = {"created": [], "skipped": [], "errors": []}
        for file_spec in self.files:
            full_path = os.path.join(output_dir, file_spec.path)
            os.makedirs(os.path.dirname(full_path), exist_ok=True)
            
            if os.path.exists(full_path) and not file_spec.overwrite:
                results["skipped"].append(file_spec.path)
                continue
            
            try:
                with open(full_path, "w", encoding="utf-8") as f:
                    f.write(file_spec.content)
                results["created"].append(file_spec.path)
            except Exception as e:
                results["errors"].append(f"{file_spec.path}: {e}")
        
        return results

class CodeGenerator:
    def __init__(self):
        self.templates: Dict[str, ProjectTemplate] = {}
        self._register_defaults()
    
    def _register_defaults(self):
        """注册内置模板"""
        # Python CLI项目
        py_cli = ProjectTemplate(
            name="python-cli",
            language="python",
            description="Python CLI application with argparse"
        )
        py_cli.add_file("main.py", """#!/usr/bin/env python3
import argparse

def main():
    parser = argparse.ArgumentParser(description="CLI tool")
    parser.add_argument("--verbose", action="store_true", help="Enable verbose")
    args = parser.parse_args()
    
    if args.verbose:
        print("Verbose mode enabled")
    print("Hello from CLI!")

if __name__ == "__main__":
    main()
""")
        py_cli.add_file("requirements.txt", "# Dependencies\
# requests>=2.28.0\
")
        py_cli.add_file(".gitignore", "*.pyc\
__pycache__/\
.env\
venv/\
")
        py_cli.add_file("README.md", f"# CLI Tool\
\
Auto-generated Python CLI project\
")
        self.templates["python-cli"] = py_cli
        
        # FastAPI服务
        fastapi_t = ProjectTemplate(
            name="fastapi-service",
            language="python",
            description="FastAPI REST API service"
        )
        fastapi_t.add_file("main.py", """from fastapi import FastAPI
app = FastAPI(title="API Service")

@app.get("/health")
def health():
    return {"status": "ok"}

@app.get("/api/v1/items")
def list_items():
    return {"items": []}
""")
        fastapi_t.add_file("requirements.txt", "fastapi==0.110.0\
uvicorn==0.29.0\
")
        self.templates["fastapi-service"] = fastapi_t
        
        # JS项目
        js_t = ProjectTemplate(
            name="node-express",
            language="javascript",
            description="Node.js Express API"
        )
        js_t.add_file("index.js", """const express = require('express');
const app = express();
app.use(express.json());

app.get('/health', (req, res) => {
    res.json({ status: 'ok' });
});

app.listen(3000, () => console.log('Server running on :3000'));
""")
        js_t.add_file("package.json", json.dumps({
            "name": "api-service",
            "version": "1.0.0",
            "main": "index.js",
            "dependencies": {"express": "^4.18.0"}
        }, indent=2))
        self.templates["node-express"] = js_t
    
    def list_templates(self) -> List[Dict]:
        return [
            {"name": t.name, "language": t.language,
             "description": t.description, "files": len(t.files)}
            for t in self.templates.values()
        ]
    
    def generate_from_template(self, template_name: str, output_dir: str) -> Dict:
        """从模板生成项目"""
        if template_name not in self.templates:
            return {"error": f"Unknown template: {template_name}. Available: {list(self.templates.keys())}"}
        
        template = self.templates[template_name]
        os.makedirs(output_dir, exist_ok=True)
        return template.generate(output_dir)
    
    def generate_api_handler(self, name: str, methods: List[str]) -> str:
        """生成API handler代码"""
        method_handlers = "\
\
".join([
            f"async def {m.lower()}_{name}(request):\
    \"\"\"{m} /api/{name}\"\"\"\
    return {{'method': '{m}', 'handler': '{name}'}}"
            for m in methods
        ])
        return f"""
from typing import Dict, Any

# Auto-generated API handler: {name}
{method_handlers}

def register_routes(app):
    \"\"\"Register all routes for {name}\"\"\"
    pass
"""
    
    def generate_config(self, config_type: str = "yaml") -> str:
        """生成配置文件"""
        configs = {
            "yaml": """# Auto-generated config
app:
  name: my-app
  version: 0.1.0
  debug: true
  env: development

server:
  host: 0.0.0.0
  port: 8080

database:
  url: sqlite:///data.db
  pool_size: 5
  timeout: 30

logging:
  level: info
  format: json
""",
            "json": json.dumps({
                "app": {"name": "my-app", "version": "0.1.0", "debug": True},
                "server": {"host": "0.0.0.0", "port": 8080},
                "database": {"url": "sqlite:///data.db", "pool_size": 5}
            }, indent=2),
            "toml": """[app]
name = "my-app"
version = "0.1.0"

[server]
host = "0.0.0.0"
port = 8080

[database]
url = "sqlite:///data.db"
"""
        }
        return configs.get(config_type, configs["yaml"])

# 使用示例
gen = CodeGenerator()

# 列出可用模板
print("可用模板:")
for t in gen.list_templates():
    print(f"  [{t['language']}] {t['name']}: {t['description']} ({t['files']}个文件)")

# 生成Python CLI项目
result = gen.generate_from_template("python-cli", "./my-cli-tool")
print(f"\
生成结果: created={result['created']}, skipped={result['skipped']}")

# 生成API handler
handler_code = gen.generate_api_handler("users", ["GET", "POST", "PUT", "DELETE"])
print(f"\
Handler代码 ({len(handler_code)} chars):")
print(handler_code[:200] + "...")

# 生成配置
config = gen.generate_config("yaml")
print(f"\
配置文件 ({len(config)} chars)")

支持的模板

模板名 语言 用途 文件数
python-cli Python CLI工具 4
fastapi-service Python REST API 2
node-express JavaScript Web API 2

使用场景

  1. 项目启动: 新项目一键生成标准目录结构
  2. API开发: 快速生成增删改查handler
  3. 微服务: 统一的服务模板,保证团队一致性
  4. 学习实验: 快速生成实验项目脚手架

依赖

  • Python 3.8+
  • 无第三方依赖
安全使用建议
Install this if you want a helper for generating starter project files. Before using it, choose the output directory deliberately and ask the agent to preview paths before creating files, especially inside an existing repository.
能力评估
Purpose & Capability
The stated purpose is code generation and project scaffolding, and the artifact’s capabilities match that purpose: built-in Python CLI, FastAPI, and Node Express templates, API handler generation, config generation, and directory creation.
Instruction Scope
The activation phrases are broad, so it may trigger on ordinary development requests, but the resulting behavior is still aligned with code-generation intent and there are no hidden role changes, exfiltration instructions, or unrelated actions.
Install Mechanism
The package contains a single markdown skill file with embedded Python example code; metadata and scans show no executable install scripts, package dependencies, background workers, or registry install steps.
Credentials
The skill does not request credentials, network access, shell execution, or broad environment access. Its filesystem use is limited to creating scaffold files under a chosen output directory.
Persistence & Privilege
It persists generated files and directories locally, which is expected for a scaffolding tool. Overwrite is disabled by default in the included implementation, reducing accidental replacement risk.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install laosi-code-generator
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /laosi-code-generator 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release – code generator for multi-language project scaffolding and templates. - Generate project scaffolding for Python, JavaScript, and Go with automatic directory creation. - Includes built-in templates: Python CLI, FastAPI service, Node.js Express API. - Supports API handler/function template generation. - Provides configuration file generation (YAML/JSON/TOML). - Simple, dependency-free Python implementation.
元数据
Slug laosi-code-generator
版本 1.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

代码生成器 是什么?

代码生成 - 项目脚手架/函数模板/配置文件生成,支持Python/JS/Go多语言,自动创建目录结构. 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 24 次。

如何安装 代码生成器?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install laosi-code-generator」即可一键安装,无需额外配置。

代码生成器 是免费的吗?

是的,代码生成器 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

代码生成器 支持哪些平台?

代码生成器 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 代码生成器?

由 534422530(@534422530)开发并维护,当前版本 v1.0.0。

💬 留言讨论