Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

🏗️ Refactor architecture to improve maintainability

未关闭
#67 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
30/100
Issue 类型
重构
描述清晰度
基本清楚
活跃度
停滞
技术栈
git, javascript
领域
cli, tooling

调研方向

首先阅读 index.js、utils/sanitizeCommitMessage.js 以及 claudedocs/quality-analysis-report.md 的第 1 节,以梳理当前的职责。在进行更改之前,将该结构与建议的 src/ 布局和实现阶段进行比较。满足所述验收标准、现有测试通过且 CLI 保持向后兼容,即表示完成。

由索引模型根据 Issue 内容生成。

描述

architecture high-priority refactoring

Problem

The current architecture has all logic in a single 389-line index.js file with multiple responsibilities, making it difficult to maintain and test.

Current issues:

  • Single file handles: CLI routing, OpenAI API, config I/O, git operations, user prompts
  • Global mutable state (openai, model, language, apiKey)
  • gitExtension() function is 202 lines (lines 184-386)
  • gptCommit() mixes business logic with I/O operations
  • Hard to test components in isolation

Current Structure

index.js (389 lines)
  ├─ Global variables (state)
  ├─ saveConfig() / loadConfig()
  ├─ maskApiKey()
  ├─ getGitSummary()
  ├─ gptCommit()
  └─ gitExtension() (CLI setup)
utils/
  └─ sanitizeCommitMessage.js

Proposed Modular Structure

src/
  ├─ index.js                    # Entry point (~50 lines)
  ├─ cli/
  │   ├─ commands/
  │   │   ├─ commit.js          # Commit command handler
  │   │   ├─ model.js           # Model selection command
  │   │   ├─ language.js        # Language selection command
  │   │   ├─ prefix.js          # Prefix toggle command
  │   │   ├─ apiKey.js          # API key management command
  │   │   └─ config.js          # Config display command
  │   └─ index.js               # CLI setup with Commander
  ├─ services/
  │   ├─ OpenAIService.js       # OpenAI API interactions
  │   ├─ GitService.js          # Git operations
  │   └─ ConfigService.js       # Configuration management
  ├─ prompts/
  │   ├─ modelSelection.js      # Model selection prompt
  │   ├─ languageSelection.js   # Language selection prompt
  │   ├─ confirmCommit.js       # Commit confirmation prompt
  │   └─ apiKeyPrompts.js       # API key prompts
  └─ utils/
      ├─ sanitizeCommitMessage.js
      └─ validators.js          # Input validation utilities
Example Refactoring

Before (index.js - mixed concerns):

const gptCommit = async () => {
  const gitSummary = await getGitSummary()
  if (!gitSummary) {
    console.log('No changes to commit. Commit canceled.')
    process.exit(0)
  }

  const messages = [ /* ... */ ]
  const parameters = { /* ... */ }
  const response = await openai.chat.completions.create(parameters)
  const message = response.choices[0].message.content.trim()
  const sanitizedMessage = sanitizeCommitMessage(message)

  const confirm = await prompts({ /* ... */ })
  if (confirm.value) {
    execSync(`git commit -m "${sanitizedMessage}"`)
    console.log('Committed with the suggested message.')
  } else {
    console.log('Commit canceled.')
  }
}

After (separation of concerns):

// src/services/OpenAIService.js
export class OpenAIService {
  constructor(apiKey, model, language) {
    this.openai = new OpenAI({ apiKey })
    this.model = model
    this.language = language
  }

  async generateCommitMessage(gitDiff, usePrefix) {
    const messages = this.buildMessages(gitDiff, usePrefix)
    const response = await this.callWithRetry({ 
      model: this.model, 
      messages 
    })
    return response.choices[0].message.content.trim()
  }

  buildMessages(gitDiff, usePrefix) { /* ... */ }
  async callWithRetry(params, retries = 3) { /* ... */ }
}

// src/services/GitService.js
export class GitService {
  async getStagedDiff() {
    const { stdout } = await exec(
      "git diff --cached -- . ':(exclude)*lock.json' ':(exclude)*lock.yaml'"
    )
    return stdout.trim() || null
  }

  async commit(message) {
    execSync(`git commit -m "${message}"`)
  }
}

// src/cli/commands/commit.js
export async function commitCommand(config) {
  const gitService = new GitService()
  const openaiService = new OpenAIService(
    config.apiKey, 
    config.model, 
    config.language
  )

  const gitDiff = await gitService.getStagedDiff()
  if (!gitDiff) {
    console.log('No changes to commit.')
    return
  }

  const message = await openaiService.generateCommitMessage(
    gitDiff, 
    config.prefixEnabled
  )
  const sanitized = sanitizeCommitMessage(message)

  if (await confirmCommitPrompt(sanitized)) {
    await gitService.commit(sanitized)
    console.log('✅ Committed successfully.')
  } else {
    console.log('Commit canceled.')
  }
}

Benefits

  • ✅ Single Responsibility: Each module has one clear purpose
  • ✅ Testability: Easy to test components in isolation
  • ✅ Maintainability: Easier to locate and modify functionality
  • ✅ Scalability: Simple to add new commands and features
  • ✅ Reusability: Services can be reused across commands
  • ✅ State Management: Eliminate global mutable state

Implementation Plan

Phase 1: Extract Services (Week 1)
  • Create src/services/OpenAIService.js
  • Create src/services/GitService.js
  • Create src/services/ConfigService.js
  • Add tests for each service
  • Update index.js to use services
Phase 2: Extract Commands (Week 2)
  • Create src/cli/commands/ directory
  • Extract each command to separate file
  • Add tests for command handlers
  • Update CLI setup to use command files
Phase 3: Extract Prompts (Week 3)
  • Create src/prompts/ directory
  • Extract prompt logic from commands
  • Add tests for prompts
  • Update commands to use prompt modules
Phase 4: Cleanup (Week 4)
  • Remove global state from index.js
  • Update all imports and exports
  • Run full test suite
  • Update documentation
  • Verify backward compatibility

Acceptance Criteria

  • index.js reduced to < 100 lines (entry point only)
  • Each service/command file < 200 lines
  • No global mutable state
  • 100% test coverage for new services
  • All existing tests pass
  • No breaking changes to CLI interface

Priority

High - Enables future development and maintenance

Related

Quality analysis report: claudedocs/quality-analysis-report.md section 1

Migration Notes

  • Maintain backward compatibility during refactoring
  • Use feature flags if needed for gradual rollout
  • Document breaking changes clearly
  • Update CLAUDE.md with new architecture
主要语言
JavaScript
星标
36
派生
3
PR 合并指标
30 天内没有已合并 PR

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

laststance/git-gpt-commit 的其他 Issue

查看 laststance/git-gpt-commit 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。