0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

複数ファイルをコード修正プロンプトに入れるのを少し楽する小技

Posted at

前提

複数ファイルを同時編集できるAIエディタが登場しています。しかし、有償プロダクトの利用を増やしたくない方もいるでしょう。ChatGPTやLLM既に契約・所有しており、それらを有効活用したいと考えている方向けの話です。複数ファイルを同時に修正するには、以下のように複数のファイルを含んだプロンプト作成することが求められます。このプロンプト作りを少し楽にする小技です。

プロンプトのイメージ

スクリーンショット 2024-09-13 21.07.06.png

結論:ファイルパスを渡せばファイルの中身を転記してくれるスニペットを持っておくと楽

ファイルパスの部分を変更し、zsh (インタラクティブシェル)で実行すれば、プロンプトがクリップボードにコピーされます。

スニペット:

python3 - <<'EOF' | pbcopy
print("""
<既存のコード> に対して以下の変更を加えた結果を出力してください。
出力する際に省略しないことを心がけてください。
- hogeな機能を追加する
- fugaな機能を追加する
""")
dist_file_paths : str = """
path/to/file1 path/to/file2
path/to/file3
"""
def get_language_from_extension(file_path):
    extension_to_language = {
        ".py": "python",
        ".ts": "typescript",
        ".tsx": "tsx",
        # 他の拡張子と言語のマッピングが必要な場合、ここに追加
    }
    for ext, lang in extension_to_language.items():
        if file_path.endswith(ext):
            return lang
    return None
def print_file_contents(file_paths):
    sorted_file_paths = sorted(file_paths)
    print("<既存のコード>")
    for path in sorted_file_paths:
        try:
            with open(path, 'r') as file:
                content = file.read()
            language = get_language_from_extension(path)
            print(f"\n# {path}\n")
            if language:
                print(f"```{language}")  # コードブロックの言語を指定
            else:
                print("```")  # 言語指定がない場合のデフォルト
            print(f"{content}\n")
            print("```\n")
        except Exception:
            print(f"Error reading {path} \n")
    print("</既存のコード>")
print_file_contents(dist_file_paths.split())
EOF

zsh、pbcopy、python、プロンプトはお好みの環境に合わせてください。
コマンド化までせずスニペットとして、取り出しやすいところに持っておくのが丁度良いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?