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

flagまわりのリファクタリング #23

Merged
merged 2 commits into from
Sep 22, 2024
Merged

flagまわりのリファクタリング #23

merged 2 commits into from
Sep 22, 2024

Conversation

ikura-hamu
Copy link
Owner

@ikura-hamu ikura-hamu commented Sep 22, 2024

  • ♻️ rootのフラグのグローバル変数をやめてcontextに渡す
  • ♻️ rootのテストを1つにまとめる

今までflagをグローバル変数で管理していたが、init関数の中でcontextに渡し、呼び出すときにcontextから取り出すようにした。

Summary by CodeRabbit

  • 新機能

    • コマンドラインフラグの管理を簡素化するための新しい構造体 rootFlags を導入しました。
    • バージョン情報を表示するための新しいフラグ printVersion を追加し、関連するテストケースを強化しました。
  • バグ修正

    • 不完全な構成時におけるバージョン情報の出力に関するエラーハンドリングを改善しました。

Copy link

coderabbitai bot commented Sep 22, 2024

Walkthrough

この変更は、コマンドラインフラグオプションを管理するために新しい構造体rootFlagsを導入し、グローバル変数の代わりにコンテキストを使用してフラグの値を管理することを目的としています。また、テストケースに新しいフィールドprintVersionを追加し、バージョン情報の出力を確認するための新しいシナリオを実装しています。

Changes

ファイル 変更の概要
cmd/root.go 新しい構造体rootFlagsを追加し、コマンドラインフラグを管理。グローバル変数を削除し、コンテキストを使用してフラグの値を取得。新しいコンテキストキーrootFlagsCtxKeyを定義。
cmd/root_test.go テストケースのinput構造体にprintVersionフィールドを追加。バージョン印刷に関する新しいテストケースを追加。標準出力と入力をリダイレクトするヘルパー関数を導入。

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Context
    participant rootFlags

    User->>CLI: コマンド実行
    CLI->>Context: `rootFlags`インスタンスを作成
    Context->>rootFlags: フラグの値を設定
    CLI->>Context: コマンド実行のために`rootFlags`を取得
    Context->>CLI: フラグの値を返す
    CLI->>User: 結果を表示
Loading

Poem

🐰 うさぎの歌 🐰
新しいフラグが登場し、
コマンドがスムーズに流れる、
バージョンも忘れずに、
うさぎは跳ねて喜ぶ、
これからの道を照らして、
みんなで進もう、楽しい未来へ! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 877cca4 and de5fe04.

Files selected for processing (2)
  • cmd/root.go (7 hunks)
  • cmd/root_test.go (7 hunks)
Additional comments not posted (8)
cmd/root.go (5)

8-8: コンテキストパッケージのインポートについて

コンテキストパッケージをインポートすることで、リクエストスコープの値、キャンセル信号、デッドラインなどをAPIの境界を越えて、リクエストの処理に関わるすべてのゴルーチンに渡すことができます。これは、状態管理や値の受け渡しに役立ちます。


61-66: コンテキストを使用した rootFlags データの管理

コンテキストを使用して rootFlags データを取得することで、グローバル変数の使用を避け、フラグの状態をよりよくカプセル化し、管理することができています。これは良い実践です。

また、必要なデータがコンテキストに見つからない場合にエラーを返すことで、適切にエラーハンドリングを行っています。


Line range hint 101-115: コードブロックのフォーマット処理

rootFlagsData を使用して codeBlock フラグをチェックし、codeBlockLang を取得していることは正しいです。

メッセージ内の先頭のバッククォートの最大数を決定するロジックにより、メッセージにすでにバッククォートが含まれている場合でも、コードブロックが適切にフォーマットされることが保証されます。

また、codeBlockLang を使用してコードブロックの構文でメッセージをフォーマットする処理も正しく行われています。


119-124: チャンネルIDの取得処理

rootFlagsData から channelName を取得していることは正しいです。

conf.channels マップからチャンネルIDを取得することで、有効なチャンネル名のみが使用されることが保証されます。

また、チャンネルが見つからない場合のエラーハンドリングも適切に行われています。


Line range hint 143-197: rootFlags 構造体とコンテキストでの使用

フラグオプションを rootFlags 構造体にカプセル化することで、コードの構成と可読性が向上しています。これは良い実践です。

専用のコンテキストキータイプ rootFlagsCtxKey を使用することで、他のコンテキストキーとの競合を防いでいます。

rootFlags インスタンスをコマンドコンテキストに設定することで、コマンドの実行全体を通してフラグの値に簡単にアクセスできるようになっています。

cmd/root_test.go (3)

26-26: input構造体へのprintVersionフィールドの追加

input構造体にprintVersion boolが追加され、バージョン情報の表示制御が可能になりました。


101-112: バージョン情報表示のテストケース追加

バージョン情報の表示に関するテストケースが追加され、設定が不十分な場合でも期待通りに動作することを確認しています。テストケースの追加により、バージョン表示機能の信頼性が向上しています。


197-230: 標準入出力のモック化関数の追加

ReplaceStdoutおよびReplaceStdin関数が追加され、標準入出力をモック化することでテストが容易になっています。これにより、テスト時の標準入出力の操作が安全に行えます。

Comment on lines +136 to +145
rootFlagsData := rootFlags{
codeBlock: tt.codeBlock,
codeBlockLang: tt.codeBlockLang,
channelName: tt.channelName,
}
rootCmd.SetContext(context.WithValue(context.Background(), rootFlagsCtxKey{}, &rootFlagsData))

printVersion = tt.printVersion
t.Cleanup(func() {
withCodeBlock = false
codeBlockLang = ""
channelName = ""
printVersion = false
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

グローバル変数printVersionの使用を避け、テスト間の副作用を防止

テスト内でグローバル変数printVersionを直接設定・リセットしていますが、これはテスト間で状態が共有され、副作用を引き起こす可能性があります。代わりに、rootFlags構造体にprintVersionフィールドを追加し、コンテキスト経由で渡す方法を検討してください。

以下の差分を適用して修正できます:

+type rootFlags struct {
+    codeBlock     bool
+    codeBlockLang string
+    channelName   string
+    printVersion  bool
+}

 rootFlagsData := rootFlags{
     codeBlock:     tt.codeBlock,
     codeBlockLang: tt.codeBlockLang,
     channelName:   tt.channelName,
+    printVersion:  tt.printVersion,
 }

 rootCmd.SetContext(context.WithValue(context.Background(), rootFlagsCtxKey{}, &rootFlagsData))

- printVersion = tt.printVersion
- t.Cleanup(func() {
-     printVersion = false
- })

// コマンド内でグローバル変数ではなく、rootFlagsからprintVersionを取得
if rootFlags.printVersion {
    // バージョン情報を表示する処理
}

Committable suggestion was skipped due to low confidence.

@ikura-hamu ikura-hamu merged commit 677c49f into main Sep 22, 2024
4 checks passed
@ikura-hamu ikura-hamu deleted the refactor/args branch September 22, 2024 08:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant