gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Убери создание папки copyproject [code]
- User
Убери создание папки _copy_project
code - Assistant
Убери создание папки _copy_project
import os
import shutil
def ignore_vs_folders(dir, files):
# Игнорировать папку .vs и её содержимое
ignored = []
if '.vs' in files:
ignored.append('.vs')
return ignored
def copy_full_project(src, dst):
"""
Копирует проект с игнорированием папки .vs и других временных папок, если нужно.
"""
if os.path.exists(dst):
print(f"Папка назначения {dst} уже существует. Копирование пропущено.")
return
def ignore_func(dir, contents):
# Игнорируем папки или файлы по имени
ignored = []
# Игнорируем папку .vs
if '.vs' in contents:
ignored.append('.vs')
# Добавьте сюда другие папки, если нужно игнорировать
# например: ignored.append('bin'), ignored.append('obj')
return ignored
shutil.copytree(src, dst, ignore=ignore_func)
print(f"Проект скопирован из '{src}' в '{dst}'")
# Остальной код — collect_code, записи комментариев — без изменений
# Ниже "копия" предыдущего скрипта, для полноты
def get_comment_delimiters(extension):
ext = extension.lower()
if ext == '.cs':
return ('// ', None)
elif ext in ('.xaml', '.config', '.resx'):
return ('<!--', '-->')
else:
return ('// ', None)
def write_file_header(outfile, relative_path, extension):
start_c, end_c = get_comment_delimiters(extension)
if end_c is None:
outfile.write(f"\n{start_c}====== Начало файла: {relative_path} ======\n")
else:
outfile.write(f"\n{start_c}====== Начало файла: {relative_path} ======{end_c}\n")
def write_file_footer(outfile, relative_path, extension):
start_c, end_c = get_comment_delimiters(extension)
if end_c is None:
outfile.write(f"\n{start_c}====== Конец файла: {relative_path} ======\n")
else:
outfile.write(f"\n{start_c}====== Конец файла: {relative_path} ======{end_c}\n")
def collect_code(src, dst_file, extensions=('.cs', '.xaml', '.config', '.resx')):
with open(dst_file, 'w', encoding='utf-8') as outfile:
for root, dirs, files in os.walk(src):
# Игнорируем папку .vs при обходе
if '.vs' in dirs:
dirs.remove('.vs')
for file in sorted(files):
if file.lower().endswith(extensions):
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, src)
ext = os.path.splitext(file)[1]
try:
with open(full_path, 'r', encoding='utf-8') as fin:
content = fin.read()
except Exception as e:
content = f"// Не удалось прочитать файл: {e}\n"
write_file_header(outfile, rel_path, ext)
outfile.write(content)
if not content.endswith('\n'):
outfile.write('\n')
write_file_footer(outfile, rel_path, ext)
if __name__ == "__main__":
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
source_dir = current_dir
copy_destination = os.path.join(current_dir, "_copy_project")
collected_code_file = os.path.join(current_dir, "all_code.txt")
print(f"Копируем проект из:\n{source_dir}\nв:\n{copy_destination}")
copy_full_project(source_dir, copy_destination)
print(f"Собираем весь код в файл:\n{collected_code_file}")
collect_code(source_dir, collected_code_file)
print("Готово!")
```
Чтобы убрать создание папки _copy_project и копирование в неё, нужно:
copy_full_project()copy_destination, если она больше не нужнаcollect_code() использовать исходную папку (например, current_dir), как былоВот исправленный код с комментариями:
import os
import shutil
def ignore_vs_folders(dir, files):
# Игнорировать папку .vs и её содержимое
ignored = []
if '.vs' in files:
ignored.append('.vs')
return ignored
def copy_full_project(src, dst):
"""
Копирует проект с игнорированием папки .vs и других временных папок, если нужно.
"""
if os.path.exists(dst):
print(f"Папка назначения {dst} уже существует. Копирование пропущено.")
return
def ignore_func(dir, contents):
# Игнорируем папки или файлы по имени
ignored = []
# Игнорируем папку .vs
if '.vs' in contents:
ignored.append('.vs')
# Добавьте сюда другие папки, если нужно игнорировать
# например: ignored.append('bin'), ignored.append('obj')
return ignored
shutil.copytree(src, dst, ignore=ignore_func)
print(f"Проект скопирован из '{src}' в '{dst}'")
# Остальной код — collect_code, записи комментариев — без изменений
# Ниже "копия" предыдущего скрипта, для полноты
def get_comment_delimiters(extension):
ext = extension.lower()
if ext == '.cs':
return ('// ', None)
elif ext in ('.xaml', '.config', '.resx'):
return ('<!--', '-->')
else:
return ('// ', None)
def write_file_header(outfile, relative_path, extension):
start_c, end_c = get_comment_delimiters(extension)
if end_c is None:
outfile.write(f"\n{start_c}====== Начало файла: {relative_path} ======\n")
else:
outfile.write(f"\n{start_c}====== Начало файла: {relative_path} ======{end_c}\n")
def write_file_footer(outfile, relative_path, extension):
start_c, end_c = get_comment_delimiters(extension)
if end_c is None:
outfile.write(f"\n{start_c}====== Конец файла: {relative_path} ======\n")
else:
outfile.write(f"\n{start_c}====== Конец файла: {relative_path} ======{end_c}\n")
def collect_code(src, dst_file, extensions=('.cs', '.xaml', '.config', '.resx')):
with open(dst_file, 'w', encoding='utf-8') as outfile:
for root, dirs, files in os.walk(src):
# Игнорируем папку .vs при обходе
if '.vs' in dirs:
dirs.remove('.vs')
for file in sorted(files):
if file.lower().endswith(extensions):
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, src)
ext = os.path.splitext(file)[1]
try:
with open(full_path, 'r', encoding='utf-8') as fin:
content = fin.read()
except Exception as e:
content = f"// Не удалось прочитать файл: {e}\n"
write_file_header(outfile, rel_path, ext)
outfile.write(content)
if not content.endswith('\n'):
outfile.write('\n')
write_file_footer(outfile, rel_path, ext)
if __name__ == "__main__":
current_dir = os.path.dirname(os.path.abspath(__file__))
source_dir = current_dir
# Убрали создание копии проекта
# copy_destination = os.path.join(current_dir, "_copy_project")
collected_code_file = os.path.join(current_dir, "all_code.txt")
# Комментарий к копированию удалён
# print(f"Копируем проект из:\n{source_dir}\nв:\n{copy_destination}")
# copy_full_project(source_dir, copy_destination)
print(f"Собираем весь код в файл:\n{collected_code_file}")
collect_code(source_dir, collected_code_file)
print("Готово!")
Теперь при запуске скрипта копирование в _copy_project не происходит, собирается весь код из текущей директории и сохраняется в all_code.txt.
Not yet included in a published release.