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

nextjs - pages to app shallow migration python script #96

Open
NaClYen opened this issue May 16, 2023 · 0 comments
Open

nextjs - pages to app shallow migration python script #96

NaClYen opened this issue May 16, 2023 · 0 comments
Assignees

Comments

@NaClYen
Copy link
Owner

NaClYen commented May 16, 2023

目標

因為兩者路徑的對應規格是有規則的, 理論上不用太複雜的腳本就可以完成
但實際上會因為你的 layout 結構有出入, 但至少可以做個開端XD

腳本

import os
import shutil

# 開始的目錄
start_dir = './src/pages'

# 目標的目錄
target_dir = './src/app'

# 走訪所有位於 start_dir 資料夾底下的檔案
for dirpath, dirnames, filenames in os.walk(start_dir):
    # 除了 `_` 開頭的
    dirnames[:] = [d for d in dirnames if not d.startswith('_')]
    for filename in filenames:
        if not filename.startswith('_') and filename.endswith('.tsx'):
            # 取得每一個檔案相對於 start_dir 的路徑
            relative_path = os.path.relpath(dirpath, start_dir)
            new_file_path = filename
            if filename == "index.tsx":
                new_file_path = "page.tsx"
            else:
                new_file_path = os.path.join(os.path.splitext(filename)[0], 'page.tsx')

            # 將上一步的路徑轉換成位於 target_dir 的新路徑
            new_dir_path = os.path.join(target_dir, relative_path)
            os.makedirs(new_dir_path, exist_ok=True)
            new_path = os.path.join(new_dir_path, new_file_path)
            new_file_dir = os.path.dirname(new_path)
            os.makedirs(new_file_dir, exist_ok=True)

            # 搬遷檔案
            shutil.move(os.path.join(dirpath, filename), new_path)
            print(f"Moved file {os.path.join(dirpath, filename)} to {new_path}")

使用方式

在專案根目錄放置此腳本 & 執行即可

後記

一開始先用 ChatGPT 3.5 產腳本, 但一直鬼打牆無用的 page 資料夾的問題

改用 4 版就只再提醒他確保目標資料夾, 第二版就完成, 程度真的有差!!

tags: nextjs approuter python
@NaClYen NaClYen self-assigned this May 16, 2023
@NaClYen NaClYen changed the title nextjs - pages to app migration python script nextjs - pages to app shallow migration python script May 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant