포스트

코드 project 내에서 코드를 트리구조로 한 파일에 생성하기(python 코드) (2)

지난 게시글에서는 코드 프로젝트의 각 파일의 경로를 모두 모아서 텍스트 파일로 모아서 보는 코드를 작성했습니다.

다음 링크를 참조해주세요.

[20241123] 코드 project 내에서 코드를 트리구조로 한 파일에 생성하기 (python 코드) (1) chatgpt에게 묻기 위해서는 단편적인 코드만이 아니라 폴더 구조와 전체 구조 맥락을 함께 줘야 좋을 때가 … chatgpt에게 묻기 위해서는 단편적인 코드만이 아니라 폴더 구조와 전체 구조 맥락을 함께 줘야 좋을 때가 …

이번 게시글에서는 이렇게 모은 파일 경로들을 가지고 보기 좋은 markdown 형식, json 형식으로 바꿔보는 코드를 작성하겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
## convert_file_tree.py

from collections import defaultdict
import json

def build_tree(file_paths):
    tree = defaultdict(dict)

    for path in file_paths:
        parts = path.split("\\")
        current = tree
        for part in parts[:-1]:  # 모든 디렉토리 파트를 순회
            current = current.setdefault(part, {})
        current.setdefault(parts[-1], None)  # 파일은 None 값으로 추가

    return tree

def save_tree_as_json(tree, file_path):
    def convert_tree_to_dict(tree):
        """Helper function to convert defaultdict to a regular dict for JSON serialization."""
        return {key: convert_tree_to_dict(value) if isinstance(value, dict) else None for key, value in tree.items()}

    with open(file_path, "w", encoding="utf-8") as file:
        json.dump(convert_tree_to_dict(tree), file, indent=4, ensure_ascii=False)


def print_tree(tree, prefix="", is_root=True):
    entries = list(tree.items())
    for i, (key, value) in enumerate(entries):
        # 루트 노드 처리: 루트에서는 기호 없이 출력
        connector = "" if is_root else ("└── " if i == len(entries) - 1 else "├── ")
        print(f"{prefix}{connector}{key}/" if value is not None else f"{prefix}{connector}{key}")
        if value is not None:  # 디렉토리라면
            # 들여쓰기 조정: 루트 이후 단계에서는 들여쓰기가 적용됨
            extension = "    " if i == len(entries) - 1 else "│   "
            print_tree(value, prefix + extension, is_root=False)


def save_tree(tree, file_path):
    with open(file_path, "w", encoding="utf-8") as file:
        # Markdown 코드 블록 시작
        file.write("```\n")

        def write_tree(tree, prefix="", is_root=False):
            entries = list(tree.items())
            for i, (key, value) in enumerate(entries):
                # 루트에서는 connector를 비우고, 이후 단계에서는 └── 또는 ├── 사용
                connector = "" if is_root else ("└── " if i == len(entries) - 1 else "├── ")
                file.write(f"{prefix}{connector}{key}/\n" if value is not None else f"{prefix}{connector}{key}\n")
                if value is not None:  # 디렉토리라면
                    # 들여쓰기 수준 조정: 루트 이후의 디렉토리들은 단계적으로 줄어듦
                    extension = "    " if i == len(entries) - 1 else "│   "
                    write_tree(value, prefix + ("" if is_root else extension), is_root=False)

        write_tree(tree, is_root=True)

        # Markdown 코드 블록 끝
        file.write("```\n")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 입력 파일 경로 목록
# file_paths = [
#     "sweet_auto\\lib\\agm_pm.dart",
#     "sweet_auto\\lib\\main.dart",
#     "sweet_auto\\lib\\run_example_script_pm.dart",
#     "sweet_auto\\lib\\etc\\model\\PM_AssetEntity\\asset_entity_info.dart",
#     "sweet_auto\\lib\\etc\\model\\PM_AssetEntity\\converter.dart",
#     "sweet_auto\\lib\\etc\\model\\PM_AssetEntity\\make_asset_entity.dart",
#     "sweet_auto\\lib\\etc\\model\\PM_AssetEntity\\m_asset_entity.dart",
#     "sweet_auto\\lib\\etc\\model\\PM_AssetEntity\\photobook_data.dart",
#     "sweet_auto\\lib\\etc\\model\\PM_AssetEntity\\recognition_data.dart",
#     "sweet_auto\\lib\\etc\\model\\PM_AssetEntity\\sweet_photo.dart",
#     "sweet_auto\\lib\\etc\\utils\\autogen_constants.dart",
#     "sweet_auto\\lib\\etc\\utils\\const_data.dart",
#     "sweet_auto\\lib\\etc\\utils\\dev_prints.dart",
#     "sweet_auto\\lib\\etc\\utils\\end_page_canvas_builder_helper.dart",
#     "sweet_auto\\lib\\etc\\utils\\pid2starting.dart",
#     "sweet_auto\\lib\\etc\\utils\\urls.dart",
#     "sweet_auto\\lib\\etc\\utils\\util.dart",
#     "sweet_auto\\lib\\etc\\utils\\refactored_const_data\\constants.dart",
#     "sweet_auto\\lib\\etc\\utils\\refactored_const_data\\constants_utils.dart",
#     "sweet_auto\\lib\\etc\\utils\\refactored_const_data\\left_right_page.dart",
#     "sweet_auto\\lib\\etc\\view\\page_canvas_agm_widget.dart",
#     "sweet_auto\\lib\\etc\\view\\v_preview_screen_agm_widget.dart",
#     # ... 나머지 파일 경로들
# ]

# dart_file_tree.txt 파일 읽기 및 file_paths 생성
file_paths = []
with open("dart_file_tree.txt", "r", encoding="utf-8") as file:
    for line in file:
        line = line.strip()
        if ": " in line:  # 기준에 따라 디렉토리와 파일 구분
            base, file_name = line.split(": ", 1)
            full_path = f"{base}\\{file_name}".replace("/", "\\")  # 경로 형식 통일
            file_paths.append(full_path)


# 트리 생성 및 출력
tree = build_tree(file_paths)
print_tree(tree)
save_tree_as_json(tree, "dart_file_tree.json")
print("JSON 파일로 저장되었습니다.")
save_tree(tree, "dart_file_tree.md")
print("Markdown 파일로 저장되었습니다.")

결과물을 다음과 같습니다.

dart_file_tree.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
{
    "sweet_auto": {
        "lib": {
            "agm_pm.dart": null,
            "main.dart": null,
            "run_example_script_pm.dart": null,
            "etc": {
                "model": {
                    "PM_AssetEntity": {
                        "asset_entity_info.dart": null,
                        "converter.dart": null,
                        "make_asset_entity.dart": null,
                        "m_asset_entity.dart": null,
                        "photobook_data.dart": null,
                        "recognition_data.dart": null,
                        "sweet_photo.dart": null
                    }
                },
                "utils": {
                    "autogen_constants.dart": null,
                    "const_data.dart": null,
                    "dev_prints.dart": null,
                    "end_page_canvas_builder_helper.dart": null,
                    "pid2starting.dart": null,
                    "urls.dart": null,
                    "util.dart": null,
                    "refactored_const_data": {
                        "constants.dart": null,
                        "constants_utils.dart": null,
                        "left_right_page.dart": null
                    }
                },
                "view": {
                    "page_canvas_agm_widget.dart": null,
                    "v_preview_screen_agm_widget.dart": null
                }
            },
            "sub_modules": {
                "da_sm_runner.dart": null,
                "lga4abs_sm_runner_pm.dart": null,
                "pga_sm_runner.dart": null,
                "dio_api_service_module": {
                    "simple_da_service.dart": null,
                    "simple_da_module": {
                        "common": {
                            "api_constants.dart": null,
                            "api_service.dart": null,
                            "dio.dart": null,
                            "dio_interceptor.dart": null,
                            "output.dart": null,
                            "models": {
                                "ai_book_api_data_pm.dart": null,
                                "login.dart": null,
                                "user_info.dart": null
                            }
                        },
                        "processes": {
                            "proceess_1_login.dart": null,
                            "process_0_get_themeJson.dart": null,
                            "process_2_upload.dart": null,
                            "process_2_commons": {
                                "get_photos_agm.dart": null,
                                "sweetResponse_pm.dart": null,
                                "uploader_pm.dart": null,
                                "upload_task_status.dart": null
                            },
                            "process_2_steps": {
                                "step_1_create_bookId.dart": null,
                                "step_2_uploadPhotos.dart": null,
                                "step_3_uploadPageXmlString.dart": null
                            }
                        }
                    },
                    "_etc": {
                        "_connector_for_da": {
                            "core_pm.dart": null,
                            "debug.dart": null
                        }
                    }
                },
                "file_picker_service_module": {
                    "export.dart": null,
                    "s_file_picker.dart": null
                },
                "lga_sm": {
                    "lga4abs_service_pm.dart": null,
                    "simple_lga_module": {
                        "layout_aug_script_abs_pm.dart": null,
                        "layout_gen_script_abs_pm.dart": null,
                        "common": {
                            "models": {
                                "models_custom_layout_pm_etc.dart": null,
                                "models_frame_generation_pm_etc.dart": null
                            },
                            "utils": {
                                "layout_expression_template.dart": null,
                                "minValuesIndices.dart": null,
                                "positioning.dart": null,
                                "selection.dart": null,
                                "util.dart": null
                            }
                        },
                        "processes": {
                            "proc_1_gen_covers_pages_pm.dart": null,
                            "proc_2_gen_auto_layout_cons_pages_pm.dart": null,
                            "proc_2_gen_auto_layout_page_aug_agm.dart": null,
                            "proc_2_steps": {
                                "s0_gen_auto_layout_frame_cases_pm.dart": null,
                                "s1_select_auto_layout_frame_case_pm.dart": null,
                                "s2_rev_p

dart_file_tree.md

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
```
sweet_auto/
└── lib/
    ├── agm_pm.dart
    ├── main.dart
    ├── run_example_script_pm.dart
    ├── etc/
    │   ├── model/
    │   │   └── PM_AssetEntity/
    │   │       ├── asset_entity_info.dart
    │   │       ├── converter.dart
    │   │       ├── make_asset_entity.dart
    │   │       ├── m_asset_entity.dart
    │   │       ├── photobook_data.dart
    │   │       ├── recognition_data.dart
    │   │       └── sweet_photo.dart
    │   ├── utils/
    │   │   ├── autogen_constants.dart
    │   │   ├── const_data.dart
    │   │   ├── dev_prints.dart
    │   │   ├── end_page_canvas_builder_helper.dart
    │   │   ├── pid2starting.dart
    │   │   ├── urls.dart
    │   │   ├── util.dart
    │   │   └── refactored_const_data/
    │   │       ├── constants.dart
    │   │       ├── constants_utils.dart
    │   │       └── left_right_page.dart
    │   └── view/
    │       ├── page_canvas_agm_widget.dart
    │       └── v_preview_screen_agm_widget.dart
    └── sub_modules/
        ├── da_sm_runner.dart
        ├── lga4abs_sm_runner_pm.dart
        ├── pga_sm_runner.dart
        ├── dio_api_service_module/
        │   ├── simple_da_service.dart
        │   ├── simple_da_module/
        │   │   ├── common/
        │   │   │   ├── api_constants.dart
        │   │   │   ├── api_service.dart
        │   │   │   ├── dio.dart
        │   │   │   ├── dio_interceptor.dart
        │   │   │   ├── output.dart
        │   │   │   └── models/
        │   │   │       ├── ai_book_api_data_pm.dart
        │   │   │       ├── login.dart
        │   │   │       └── user_info.dart
        │   │   └── processes/
        │   │       ├── proceess_1_login.dart
        │   │       ├── process_0_get_themeJson.dart
        │   │       ├── process_2_upload.dart
        │   │       ├── process_2_commons/
        │   │       │   ├── get_photos_agm.dart
        │   │       │   ├── sweetResponse_pm.dart
        │   │       │   ├── uploader_pm.dart
        │   │       │   └── upload_task_status.dart
        │   │       └── process_2_steps/
        │   │           ├── step_1_create_bookId.dart
        │   │           ├── step_2_uploadPhotos.dart
        │   │           └── step_3_uploadPageXmlString.dart
        │   └── _etc/
        │       └── _connector_for_da/
        │           ├── core_pm.dart
        │           └── debug.dart
        ├── file_picker_service_module/
        │   ├── export.dart
        │   └── s_file_picker.dart
        ├── lga_sm/
        │   ├── lga4abs_service_pm.dart
        │   ├── simple_lga_module/
        │   │   ├── layout_aug_script_abs_pm.dart
        │   │   ├── layout_gen_script_abs_pm.dart
        │   │   ├── common/
        │   │   │   ├── models/
        │   │   │   │   ├── models_custom_layout_pm_etc.dart
        │   │   │   │   └── models_frame_generation_pm_etc.dart
        │   │   │   └── utils/
        │   │   │       ├── layout_expression_template.dart
        │   │   │       ├── minValuesIndices.dart
        │   │   │       ├── positioning.dart
        │   │   │       ├── selection.dart
        │   │   │       └── util.dart
        │   │   └── processes/
        │   │       ├── proc_1_gen_covers_pages_pm.dart
        │   │       ├── proc_2_gen_auto_layout_cons_pages_pm.dart
        │   │       ├── proc_2_gen_auto_layout_page_aug_agm.dart
        │   │       ├── proc_2_steps/
        │   │       │   ├── s0_gen_auto_layout_frame_cases_pm.dart
        │   │       │   ├── s1_select_auto_layout_frame_case_pm.dart
        │   │       │   ├── s2_rev_page_canvas_into_assetEntities_pm.dart
        │   │       │   └── step_worker_pm.dart
        │   │       └── proc_common/
        │   │           └── proc_0_collect_auto_layout_templates.dart
        │   └── _etc/
        │       └── _connector_for_lga/
        │           ├── core_pm.dart
        │           └── debug.dart
        ├── pga_sm/
        │   ├── simple_pga_service.dart
        │   ├── simple_pga_module/
        │   │   ├── very_simple_grouper_script_coupled.dart
        │   │   └── common/
        │   │       ├── models/
        │   │       │   ├── models_grouping_points.dart
        │   │       │   ├── m_al_image.dart
        │   │       │   ├── m_al_image.freezed.dart
        │   │       │   └── m_al_image.g.dart
        │   │       └── processes/
        │   │           └── step1_make_bigPages.dart
        │   └── _etc/
        │       └── _connector_for_pga/
        │           ├── core.dart
        │           └── debug.dart
        └── _etc/
            └── external_connector/
                ├── core/
                │   ├── for_da_pm_module.dart
                │   ├── for_lga_pm_module.dart
                │   └── for_pga_module.dart
                └── debug/
                    └── for_modules.dart
```

file_1

README.md 파일 작성할 때, 해당 프로젝트의 폴더 경로를 이렇게 정리해주면 좋은 것 같아서 만들었습니다.

sticker

혹시 dart, flutter가 편하신 분들은 다음 포스팅을 봐주세요. https://blog.naver.com/devramyun/223692013084

[20241213] 코드 project 내에서 코드 트리구조를 text, json, markdown로 생성하기(dart 코드) 이전 파이썬 코드 버전을 보실 분들은.. dart 코드로 재작성한 코드는 다음과 같습니다. pubspec.yaml 이전 파이썬 코드 버전을 보실 분들은.. dart 코드로 재작성한 코드는 다음과 같습니다. pubspec.yaml

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.