mirror of
https://github.com/dexoron/dcr.git
synced 2026-10-21 21:39:36 +00:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fcb0ae7be | |||
| 676cd86b3b | |||
| c9e9423d2c | |||
| 9e842e8021 | |||
| 35dd8812ad | |||
| 675352afc0 | |||
| 43d93762c3 | |||
| d510efdaef | |||
|
|
f831183b25 | ||
| f31dc0d217 | |||
| 314142ad78 | |||
| 203836fd3f | |||
| b30176f05e | |||
|
|
b5d50a8312 | ||
| c3c17c6603 | |||
| 1ebf2b44c6 | |||
| b61bd57d7c |
16
CHANGELOG.md
16
CHANGELOG.md
@@ -1,5 +1,20 @@
|
||||
# Changelog
|
||||
|
||||
## [0.1.2] - 2026-02-12
|
||||
Добавлено:
|
||||
- Команда обновления
|
||||
- Скрипт установки `install.sh` и инструкции по установке в README
|
||||
- Флаг `--version` для вывода версии
|
||||
|
||||
Изменено:
|
||||
- Улучшен консольный вывод команд, добавлены цвета и обновлена справка `--help`
|
||||
- Обновлен запуск проекта и обработка сборки в `run.py`/`build.py`
|
||||
|
||||
## [0.1.1] - 2026-02-11
|
||||
Изменено:
|
||||
- Обновлена справка `--help`
|
||||
- `main.py` теперь корректно запускается при прямом выполнении
|
||||
|
||||
## [0.1.0] - 2026-02-11
|
||||
Первый публичный релиз.
|
||||
|
||||
@@ -7,4 +22,3 @@
|
||||
- Базовые команды `new`, `init`, `build`, `run`, `clean`
|
||||
- Профили сборки `debug` и `release`
|
||||
- Шаблоны `dcr.toml` и `src/main.c`
|
||||
|
||||
|
||||
21
README.md
21
README.md
@@ -16,6 +16,23 @@ DCR — это утилита для управления проектами н
|
||||
- Очистка результатов сборки
|
||||
- Генерация минимального шаблона C-проекта
|
||||
|
||||
## Установка
|
||||
|
||||
### Автоматическая установка(Рекомендуется)
|
||||
|
||||
**GNU/Linux**
|
||||
```sh
|
||||
curl -L dcr.zov.tatar | bash
|
||||
```
|
||||
|
||||
### Самостоятельная установка
|
||||
|
||||
```sh
|
||||
git clone https://github.com/dexoron/dcr.git "~/.local/share/dcr"
|
||||
chmod +x "~/.local/share/dcr/dcr"
|
||||
ln -sf ~/.local/share/dcr/dcr ~/.local/bin
|
||||
```
|
||||
|
||||
## Быстрый старт
|
||||
Создать новый проект:
|
||||
`dcr new hello`
|
||||
@@ -31,6 +48,10 @@ hello/
|
||||
- dcr.toml
|
||||
```
|
||||
|
||||
Сборка и запуск проекта:
|
||||
`dcr run` или `dcr run --release` - для сбрки с оптимизацией
|
||||
|
||||
|
||||
## Команды
|
||||
|
||||
### `dcr new <name>`
|
||||
|
||||
11
dcr
11
dcr
@@ -1,3 +1,10 @@
|
||||
#!/bin/sh
|
||||
#!/usr/bin/env bash
|
||||
BASE_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
|
||||
|
||||
uv run run "$@"
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
PYTHON_BIN="python3"
|
||||
else
|
||||
PYTHON_BIN="$BASE_DIR/Python/bin/python3"
|
||||
fi
|
||||
|
||||
PYTHONPATH="$BASE_DIR/src" exec "$PYTHON_BIN" -m dcr.main "$@"
|
||||
|
||||
182
install.sh
Executable file
182
install.sh
Executable file
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# ===== CONFIG =====
|
||||
TMPDIR="/tmp/dcr-temp"
|
||||
INSTALL_PATH="$HOME/.local/share/dcr"
|
||||
PYTHON_DIR="$INSTALL_PATH/Python"
|
||||
BINPATH="$HOME/.local/bin"
|
||||
LOGFILE="$HOME/.cache/dcr-install.log"
|
||||
|
||||
PYTHON_DOWNLOAD_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20260203/cpython-3.10.19+20260203-x86_64-unknown-linux-gnu-install_only.tar.gz"
|
||||
GITHUB_API="https://api.github.com/repos/dexoron/dcr/releases/latest"
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m'
|
||||
|
||||
mkdir -p "$(dirname "$LOGFILE")"
|
||||
exec > >(tee -a "$LOGFILE") 2>&1
|
||||
|
||||
log() { echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"; }
|
||||
success() { echo -e "${GREEN}✔ $1${NC}"; }
|
||||
warn() { echo -e "${YELLOW}⚠ $1${NC}"; }
|
||||
error() { echo -e "${RED}✖ $1${NC}"; }
|
||||
|
||||
trap 'error "Ошибка на строке $LINENO"; exit 1' ERR
|
||||
|
||||
check_dependencies() {
|
||||
log "Проверка зависимостей..."
|
||||
|
||||
command -v curl >/dev/null 2>&1 || { error "curl не установлен"; exit 1; }
|
||||
command -v tar >/dev/null 2>&1 || { error "tar не установлен"; exit 1; }
|
||||
|
||||
success "Зависимости в порядке"
|
||||
}
|
||||
|
||||
check_os() {
|
||||
if [[ "$(uname -s)" != "Linux" ]]; then
|
||||
error "Поддерживается только Linux"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
get_latest_version() {
|
||||
curl -fsSL "$GITHUB_API" | sed -n 's/.*"tag_name": "\(.*\)".*/\1/p'
|
||||
}
|
||||
|
||||
get_installed_version() {
|
||||
if [[ -f "$INSTALL_PATH/VERSION" ]]; then
|
||||
cat "$INSTALL_PATH/VERSION"
|
||||
else
|
||||
echo ""
|
||||
fi
|
||||
}
|
||||
|
||||
install_python() {
|
||||
log "Python не найден, установка встроенного Python..."
|
||||
|
||||
mkdir -p "$PYTHON_DIR"
|
||||
mkdir -p "$TMPDIR"
|
||||
|
||||
curl -fsSL "$PYTHON_DOWNLOAD_URL" -o "$TMPDIR/python.tar.gz"
|
||||
tar -xf "$TMPDIR/python.tar.gz" -C "$PYTHON_DIR" --strip-components=1
|
||||
rm -f "$TMPDIR/python.tar.gz"
|
||||
|
||||
success "Встроенный Python установлен"
|
||||
}
|
||||
|
||||
install_app() {
|
||||
log "Получение последнего релиза..."
|
||||
|
||||
TAG=$(get_latest_version)
|
||||
|
||||
if [[ -z "$TAG" ]]; then
|
||||
error "Не удалось определить версию релиза"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
INSTALLED_VERSION=$(get_installed_version)
|
||||
|
||||
if [[ -n "$INSTALLED_VERSION" ]]; then
|
||||
log "Установленная версия: $INSTALLED_VERSION"
|
||||
log "Последняя версия: $TAG"
|
||||
|
||||
if [[ "$INSTALLED_VERSION" == "$TAG" ]]; then
|
||||
success "Установлена последняя версия ($TAG), обновление не требуется"
|
||||
exit 0
|
||||
else
|
||||
warn "Найдена устаревшая версия, выполняется обновление"
|
||||
fi
|
||||
|
||||
else
|
||||
log "DCR не установлен, выполняется установка"
|
||||
fi
|
||||
|
||||
mkdir -p "$TMPDIR"
|
||||
curl -fsSL -o "$TMPDIR/sources.tar.gz" \
|
||||
"https://github.com/dexoron/dcr/archive/refs/tags/$TAG.tar.gz"
|
||||
|
||||
rm -rf "$INSTALL_PATH"
|
||||
mkdir -p "$INSTALL_PATH"
|
||||
|
||||
tar -xf "$TMPDIR/sources.tar.gz" -C "$INSTALL_PATH" --strip-components=1
|
||||
rm -f "$TMPDIR/sources.tar.gz"
|
||||
|
||||
echo "$TAG" > "$INSTALL_PATH/VERSION"
|
||||
|
||||
success "Приложение установлено (версия $TAG)"
|
||||
}
|
||||
|
||||
install_wrapper() {
|
||||
log "Создание launcher..."
|
||||
|
||||
mkdir -p "$INSTALL_PATH"
|
||||
|
||||
cat > "$INSTALL_PATH/dcr" <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
BASE_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
|
||||
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
PYTHON_BIN="python3"
|
||||
else
|
||||
PYTHON_BIN="$BASE_DIR/Python/bin/python3"
|
||||
fi
|
||||
|
||||
PYTHONPATH="$BASE_DIR/src" exec "$PYTHON_BIN" -m dcr.main "$@"
|
||||
EOF
|
||||
|
||||
chmod +x "$INSTALL_PATH/dcr"
|
||||
|
||||
success "Launcher создан"
|
||||
}
|
||||
|
||||
install_link() {
|
||||
log "Создание симлинка..."
|
||||
|
||||
mkdir -p "$BINPATH"
|
||||
ln -sf "$INSTALL_PATH/dcr" "$BINPATH/dcr"
|
||||
|
||||
success "Команда 'dcr' добавлена в $BINPATH"
|
||||
}
|
||||
|
||||
check_path() {
|
||||
if ! echo "$PATH" | grep -q "$BINPATH"; then
|
||||
warn "Каталог $BINPATH не найден в PATH"
|
||||
echo "Добавь в ~/.bashrc или ~/.zshrc:"
|
||||
echo "export PATH=\"$BINPATH:\$PATH\""
|
||||
fi
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
rm -rf "$TMPDIR" 2>/dev/null || true
|
||||
}
|
||||
|
||||
main() {
|
||||
log "Запуск установки DCR"
|
||||
|
||||
check_os
|
||||
check_dependencies
|
||||
|
||||
cleanup
|
||||
|
||||
install_app
|
||||
|
||||
if ! command -v python3 >/dev/null 2>&1; then
|
||||
install_python
|
||||
else
|
||||
success "Найден системный Python"
|
||||
fi
|
||||
|
||||
install_wrapper
|
||||
install_link
|
||||
check_path
|
||||
cleanup
|
||||
|
||||
success "Установка завершена успешно"
|
||||
log "Лог сохранён в $LOGFILE"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -1,17 +1,11 @@
|
||||
[project]
|
||||
name = "dcr"
|
||||
version = "0.1.0"
|
||||
description = "Add your description here"
|
||||
description = "Утилита для управления проектами для C/C++"
|
||||
readme = "README.md"
|
||||
license = "LICENSE"
|
||||
authors = [
|
||||
{ name = "Dexoron", email = "probrovova1@gmail.com" }
|
||||
{ name = "Dexoron" },
|
||||
{ name = "F1F1FISHKA" }
|
||||
]
|
||||
requires-python = ">=3.14.2"
|
||||
dependencies = []
|
||||
|
||||
[project.scripts]
|
||||
run = "dcr.main:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.10.0,<0.11.0"]
|
||||
build-backend = "uv_build"
|
||||
requires-python = ">=3.10"
|
||||
@@ -4,6 +4,7 @@ from .new import new
|
||||
from .run import run
|
||||
from .build import build
|
||||
from .clean import clean
|
||||
from .flag_update import flag_update
|
||||
|
||||
|
||||
__all__ = [
|
||||
@@ -13,4 +14,5 @@ __all__ = [
|
||||
"run",
|
||||
"build",
|
||||
"clean",
|
||||
"flag_update",
|
||||
]
|
||||
|
||||
@@ -2,47 +2,69 @@ import time
|
||||
import os
|
||||
import subprocess
|
||||
from ..config import flags, profile, c_comp
|
||||
from dcr.utils.fs import check_dir
|
||||
from ..utils.fs import check_dir
|
||||
from ..utils.text import colored, BRIGHT_GREEN, BOLD, BRIGHT_RED
|
||||
|
||||
|
||||
def build(args: list[str] | None = None) -> int:
|
||||
active_profile: str = profile
|
||||
project_name = os.path.basename(os.getcwd())
|
||||
if "dcr.toml" not in check_dir():
|
||||
print("Ошибка: не найден файл dcr.toml")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": не найден файл dcr.toml")
|
||||
return 1
|
||||
if "target" not in check_dir():
|
||||
os.mkdir("./target")
|
||||
|
||||
if args:
|
||||
if len(args) >= 1 and args[0].startswith("--"):
|
||||
candidate: str = args[0][2:]
|
||||
if candidate in flags:
|
||||
active_profile: str = candidate
|
||||
else:
|
||||
print("Ошибка: неверный флаг сборки")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": неизвестный флаг сборки")
|
||||
return 1
|
||||
else:
|
||||
print("Ошибка: флаг сборки не найден")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": неизвестный аргумент")
|
||||
return 1
|
||||
|
||||
print(
|
||||
" Сборка проекта `"
|
||||
+ colored(project_name, BRIGHT_GREEN + BOLD)
|
||||
+ "`\n Профиль: "
|
||||
+ colored(active_profile, BRIGHT_GREEN + BOLD)
|
||||
+ "\n Компилятор: "
|
||||
+ colored(c_comp, BRIGHT_GREEN + BOLD)
|
||||
+ "\n"
|
||||
)
|
||||
|
||||
if "target" not in check_dir():
|
||||
os.mkdir("./target")
|
||||
if active_profile not in check_dir("target"):
|
||||
os.mkdir(f"./target/{active_profile}")
|
||||
if "main.c" in check_dir("src"):
|
||||
print(f"Запуск сборки с профилем {active_profile}")
|
||||
compile_flags = flags[active_profile]
|
||||
start_time: float = time.time()
|
||||
subprocess.run(
|
||||
[
|
||||
c_comp,
|
||||
"./src/main.c",
|
||||
*compile_flags,
|
||||
"-o",
|
||||
f"./target/{active_profile}/main",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
end_time: float = time.time()
|
||||
times: float = end_time - start_time
|
||||
times: float = int(times * 100) / 100
|
||||
print(f"Сборка завершена, за {times} секунд")
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
c_comp,
|
||||
"./src/main.c",
|
||||
*compile_flags,
|
||||
"-o",
|
||||
f"./target/{active_profile}/main",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
end_time: float = time.time()
|
||||
times: float = end_time - start_time
|
||||
times: float = int(times * 100) / 100
|
||||
print(
|
||||
" "
|
||||
+ colored("✔", BRIGHT_GREEN + BOLD)
|
||||
+ " Сборка завершена успешно, за "
|
||||
+ colored(str(times), BRIGHT_GREEN + BOLD)
|
||||
+ " секунд"
|
||||
)
|
||||
return 0
|
||||
except:
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": сборка не удалась")
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
@@ -1,20 +1,53 @@
|
||||
from dcr.utils.fs import check_dir
|
||||
import os
|
||||
import shutil
|
||||
from ..utils.fs import check_dir
|
||||
from ..utils.text import colored, BRIGHT_RED, BOLD, BRIGHT_GREEN, BRIGHT_YELLOW
|
||||
from ..config import flags
|
||||
|
||||
|
||||
def clean(args: list[str]) -> int:
|
||||
def clean(args: list[str] | None = None) -> int:
|
||||
project_name = os.path.basename(os.getcwd())
|
||||
items: list[str] = check_dir()
|
||||
if len(args) >= 1:
|
||||
print("Ошибка: команда не поддежривает аргументы")
|
||||
|
||||
if args and len(args) > 1:
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": неизвестный аргумент")
|
||||
return 1
|
||||
|
||||
if "dcr.toml" not in items:
|
||||
print("Ошибка: вы находитесь не в корне проекта")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": не найден файл dcr.toml")
|
||||
return 1
|
||||
|
||||
print(" Очистка проекта `" + colored(project_name, BRIGHT_GREEN + BOLD) + "`")
|
||||
|
||||
if "target" not in items:
|
||||
print("Вы уже очистили сборки")
|
||||
print(colored("warn", BRIGHT_YELLOW + BOLD) + ": директория target не найдена")
|
||||
return 1
|
||||
|
||||
if args:
|
||||
profile = args[0]
|
||||
|
||||
if profile.startswith("--"):
|
||||
profile = profile[2:]
|
||||
|
||||
if profile not in flags:
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": неизвестный профиль")
|
||||
return 1
|
||||
|
||||
if profile not in check_dir("target"):
|
||||
print(
|
||||
colored("warn", BRIGHT_YELLOW + BOLD)
|
||||
+ f": директория target/{profile} не найдена"
|
||||
)
|
||||
return 1
|
||||
|
||||
print(" Профиль: " + colored(profile, BRIGHT_GREEN + BOLD))
|
||||
shutil.rmtree(os.path.join("target", profile))
|
||||
print(
|
||||
colored("\n ✔", BRIGHT_GREEN + BOLD)
|
||||
+ f" Удалена директория target/{profile}"
|
||||
)
|
||||
return 0
|
||||
|
||||
shutil.rmtree("target")
|
||||
print("Сборки очишены")
|
||||
print(colored("\n ✔", BRIGHT_GREEN + BOLD) + " Удалена директория target")
|
||||
return 0
|
||||
|
||||
23
src/dcr/cli/flag_update.py
Normal file
23
src/dcr/cli/flag_update.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
def flag_update(args: list[str] | None = None) -> int:
|
||||
if args and len(args) > 0:
|
||||
print("Ошибка: команда не поддежривает аргументы")
|
||||
return 1
|
||||
if platform.system() != "Linux":
|
||||
print("Ошибка: обновление поддерживается только на Linux")
|
||||
return 1
|
||||
if shutil.which("curl") is None:
|
||||
print("Ошибка: не найден curl")
|
||||
return 1
|
||||
try:
|
||||
subprocess.run(
|
||||
["bash", "-c", "curl -fsSL dcr.zov.tatar | bash"], check=True
|
||||
)
|
||||
return 0
|
||||
except subprocess.CalledProcessError:
|
||||
print("Ошибка: не удалось выполнить обновление")
|
||||
return 1
|
||||
@@ -1,3 +1,39 @@
|
||||
from ..utils.text import colored, BRIGHT_GREEN, BRIGHT_CYAN, BOLD
|
||||
|
||||
|
||||
def help() -> int:
|
||||
print("Help")
|
||||
print(
|
||||
"\n".join(
|
||||
[
|
||||
"DCR (Dexoron Cargo Realization)",
|
||||
"Менеджер C-проектов, вдохновленный Cargo.",
|
||||
"",
|
||||
colored("ИСПОЛЬЗОВАНИЕ:", BRIGHT_GREEN + BOLD),
|
||||
colored(" dcr <команда> [опции]", BRIGHT_CYAN + BOLD),
|
||||
"",
|
||||
colored("КОМАНДЫ:", BRIGHT_GREEN + BOLD),
|
||||
" new <name> Создать новый проект",
|
||||
" init Инициализировать текущую директорию как проект",
|
||||
" build [--profile] Собрать проект (по умолчанию: --debug)",
|
||||
" run [--profile] Собрать и запустить (по умолчанию: --debug)",
|
||||
" clean Удалить директорию target",
|
||||
colored("ФЛАГИ:", BRIGHT_GREEN + BOLD),
|
||||
" --help Показать справку по команде",
|
||||
" --update Обновить dcr до актуальной версии",
|
||||
" --version Показать версию dcr",
|
||||
"",
|
||||
colored("ОПЦИИ:", BRIGHT_GREEN + BOLD),
|
||||
" --debug Сборка с профилем debug",
|
||||
" --release Сборка с профилем release",
|
||||
"",
|
||||
colored("ПРИМЕРЫ:", BRIGHT_GREEN + BOLD),
|
||||
colored(" dcr new hello", BRIGHT_CYAN + BOLD),
|
||||
colored(" dcr build --release", BRIGHT_CYAN + BOLD),
|
||||
colored(" dcr run --debug", BRIGHT_CYAN + BOLD),
|
||||
"",
|
||||
colored("ПОДСКАЗКА:", BRIGHT_GREEN + BOLD),
|
||||
" Запусти 'dcr <команда> --help' для справки по команде.",
|
||||
]
|
||||
)
|
||||
)
|
||||
return 0
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from dcr.config import (
|
||||
from ..utils.text import colored, BRIGHT_RED, BOLD, printc, BRIGHT_GREEN, BRIGHT_CYAN
|
||||
from ..config import (
|
||||
file_dcr_toml,
|
||||
file_main_c,
|
||||
project_version,
|
||||
@@ -6,25 +7,26 @@ from dcr.config import (
|
||||
project_compiler,
|
||||
)
|
||||
import os
|
||||
from dcr.utils.fs import check_dir
|
||||
from ..utils.fs import check_dir
|
||||
|
||||
|
||||
def init(args: list[str] | None = None) -> int:
|
||||
if args:
|
||||
print("Ошибка: команда init не поддерживает аргументы")
|
||||
print(
|
||||
colored("error", BRIGHT_RED + BOLD)
|
||||
+ ": команда не поддерживает доп. аргументы"
|
||||
)
|
||||
return 1
|
||||
items = check_dir()
|
||||
items: list[str] = check_dir()
|
||||
project_name = os.path.basename(os.getcwd())
|
||||
|
||||
if items:
|
||||
print("Ошибка: директория не пустая")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": директория не пуста")
|
||||
return 1
|
||||
|
||||
os.mkdir("src")
|
||||
print("Инициализация проекта в " + os.getcwd())
|
||||
|
||||
with open("./src/main.c", "w") as file:
|
||||
file.write(file_main_c)
|
||||
|
||||
with open("./dcr.toml", "w") as file:
|
||||
with open(f"./dcr.toml", "w") as file:
|
||||
file.write(
|
||||
file_dcr_toml.format(
|
||||
project_name=project_name,
|
||||
@@ -33,5 +35,27 @@ def init(args: list[str] | None = None) -> int:
|
||||
project_compiler=project_compiler,
|
||||
)
|
||||
)
|
||||
print(
|
||||
" "
|
||||
+ colored("✔", BRIGHT_GREEN + BOLD)
|
||||
+ " Создан файл "
|
||||
+ colored("dcr.toml", BRIGHT_CYAN + BOLD)
|
||||
)
|
||||
|
||||
os.mkdir("src")
|
||||
with open("./src/main.c", "w") as file:
|
||||
file.write(file_main_c)
|
||||
print(
|
||||
" "
|
||||
+ colored("✔", BRIGHT_GREEN + BOLD)
|
||||
+ " Создан файл "
|
||||
+ colored("src/main.c\n", BRIGHT_CYAN + BOLD)
|
||||
)
|
||||
|
||||
print(
|
||||
"Проект `" + colored(project_name, BRIGHT_GREEN + BOLD) + "` успешно создан\n"
|
||||
)
|
||||
printc("Следуюший шаг:", BRIGHT_GREEN + BOLD)
|
||||
printc(" dcr run", BRIGHT_CYAN + BOLD)
|
||||
|
||||
return 0
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
from dcr.config import (
|
||||
from ..utils.text import (
|
||||
colored,
|
||||
printc,
|
||||
BRIGHT_GREEN,
|
||||
BOLD,
|
||||
BRIGHT_CYAN,
|
||||
BRIGHT_RED,
|
||||
)
|
||||
from ..config import (
|
||||
file_dcr_toml,
|
||||
file_main_c,
|
||||
project_version,
|
||||
@@ -6,26 +14,45 @@ from dcr.config import (
|
||||
project_compiler,
|
||||
)
|
||||
import os
|
||||
from dcr.utils.fs import check_dir
|
||||
from ..utils.fs import check_dir
|
||||
|
||||
|
||||
def new(args: list[str]) -> int:
|
||||
items: list[str] = check_dir()
|
||||
if len(args) == 0:
|
||||
print("Ошибка: не указано название проекта")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": не указанно название проекта")
|
||||
return 1
|
||||
if len(args) > 1:
|
||||
print("Ошибка: команда не поддежривает аргументы")
|
||||
print(
|
||||
colored("error", BRIGHT_RED + BOLD)
|
||||
+ ": команда не поддерживает доп. аргументы"
|
||||
)
|
||||
return 1
|
||||
project_name: str = args[0]
|
||||
print("Создание проекта `" + colored(project_name, BRIGHT_GREEN + BOLD) + "`...")
|
||||
|
||||
if project_name in items:
|
||||
print(f"Ошибка: директория {project_name} занята")
|
||||
print(
|
||||
colored("error", BRIGHT_RED + BOLD)
|
||||
+ ": директория `"
|
||||
+ colored(project_name, BRIGHT_GREEN + BOLD)
|
||||
+ "` уже существует\n"
|
||||
)
|
||||
printc("Подсказка:", BRIGHT_GREEN + BOLD)
|
||||
print(
|
||||
" Используй `"
|
||||
+ colored("dcr init", BRIGHT_CYAN + BOLD)
|
||||
+ "` для инициализации существующего проекта\n или задай другое имя проекта"
|
||||
)
|
||||
return 1
|
||||
|
||||
os.makedirs(f"./{project_name}/src")
|
||||
|
||||
with open(f"./{project_name}/src/main.c", "w") as file:
|
||||
file.write(file_main_c)
|
||||
os.mkdir(project_name)
|
||||
print(
|
||||
" "
|
||||
+ colored("✔", BRIGHT_GREEN + BOLD)
|
||||
+ " Создана директория "
|
||||
+ project_name
|
||||
)
|
||||
|
||||
with open(f"./{project_name}/dcr.toml", "w") as file:
|
||||
file.write(
|
||||
@@ -36,5 +63,27 @@ def new(args: list[str]) -> int:
|
||||
project_compiler=project_compiler,
|
||||
)
|
||||
)
|
||||
print(
|
||||
" "
|
||||
+ colored("✔", BRIGHT_GREEN + BOLD)
|
||||
+ " Создан файл "
|
||||
+ colored("dcr.toml", BRIGHT_CYAN + BOLD)
|
||||
)
|
||||
|
||||
os.makedirs(f"./{project_name}/src")
|
||||
with open(f"./{project_name}/src/main.c", "w") as file:
|
||||
file.write(file_main_c)
|
||||
print(
|
||||
" "
|
||||
+ colored("✔", BRIGHT_GREEN + BOLD)
|
||||
+ " Создан файл "
|
||||
+ colored("src/main.c\n", BRIGHT_CYAN + BOLD)
|
||||
)
|
||||
|
||||
print(
|
||||
"Проект `" + colored(project_name, BRIGHT_GREEN + BOLD) + "` успешно создан\n"
|
||||
)
|
||||
printc("Следуюший шаг:", BRIGHT_GREEN + BOLD)
|
||||
printc(" cd " + project_name + "\n dcr run", BRIGHT_CYAN + BOLD)
|
||||
|
||||
return 0
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
import os
|
||||
import subprocess
|
||||
import os
|
||||
|
||||
from dcr.utils.fs import check_dir
|
||||
from ..utils.fs import check_dir
|
||||
from ..utils.text import colored, BRIGHT_RED, BOLD
|
||||
from ..config import flags, profile
|
||||
from .build import build
|
||||
|
||||
|
||||
def run(args: list[str] | None = None) -> int:
|
||||
project_name = os.path.basename(os.getcwd())
|
||||
active_profile: str = profile
|
||||
if "dcr.toml" not in check_dir():
|
||||
print("Ошибка: не найден файл dcr.toml")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": не найден файл dcr.toml")
|
||||
return 1
|
||||
|
||||
if args:
|
||||
if len(args) >= 1 and args[0].startswith("--"):
|
||||
candidate: str = args[0][2:]
|
||||
if candidate in flags:
|
||||
active_profile: str = candidate
|
||||
else:
|
||||
print("Ошибка: неверный флаг сборки")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": неизвестный флаг сборки")
|
||||
return 1
|
||||
else:
|
||||
print("Ошибка: флаг сборки не найден")
|
||||
print(colored("error", BRIGHT_RED + BOLD) + ": неизвестный аргумент")
|
||||
return 1
|
||||
|
||||
build(args)
|
||||
print("Запуск проекта")
|
||||
return subprocess.run([f"./target/{active_profile}/main"]).returncode
|
||||
build_status: int = build(args)
|
||||
if build_status == 0:
|
||||
print("\n Запуск " + "target/" + active_profile + "/main")
|
||||
print("--------------------------------")
|
||||
return subprocess.run([f"./target/{active_profile}/main"]).returncode
|
||||
else:
|
||||
if active_profile in check_dir("target/" + active_profile):
|
||||
print("Запуск последнего релиза")
|
||||
return subprocess.run([f"./target/{active_profile}/main"]).returncode
|
||||
else:
|
||||
print("Исправьте ошибки в коде для запуска проекта")
|
||||
return 0
|
||||
|
||||
@@ -9,7 +9,7 @@ compiler = "{project_compiler}"
|
||||
file_main_c: str = """#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
printf("Hello World!\n");
|
||||
printf("Hello World!\\n");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
@@ -40,3 +40,5 @@ flags: dict[str, list[str]] = {
|
||||
"release": ["-O3", "-DNDEBUG", "-march=native"],
|
||||
"debug": ["-O0", "-g", "-Wall", "-Wextra", "-fno-omit-frame-pointer", "-DDEBUG"],
|
||||
}
|
||||
|
||||
VERSION = "v0.1.1"
|
||||
@@ -1,9 +1,10 @@
|
||||
from .config import VERSION
|
||||
import dcr.cli as cli
|
||||
import sys
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 2 or sys.argv[1] == "--help":
|
||||
if len(sys.argv) < 2:
|
||||
cli.help()
|
||||
return 0
|
||||
|
||||
@@ -21,7 +22,17 @@ def main() -> int:
|
||||
cli.run(args)
|
||||
case "clean":
|
||||
cli.clean(args)
|
||||
case "--version":
|
||||
print(f"dcr {VERSION} (GNU/Linux)")
|
||||
case "--help":
|
||||
cli.help()
|
||||
case "--update":
|
||||
cli.flag_update(args)
|
||||
case _:
|
||||
print("Unknown command")
|
||||
print("Неизвестная команда или аргумент")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
40
src/dcr/utils/text.py
Normal file
40
src/dcr/utils/text.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# RESET
|
||||
RESET = "\033[0m"
|
||||
|
||||
# TEXT STYLES
|
||||
BOLD = "\033[1m"
|
||||
DIM = "\033[2m"
|
||||
ITALIC = "\033[3m"
|
||||
UNDERLINE = "\033[4m"
|
||||
BLINK = "\033[5m"
|
||||
REVERSE = "\033[7m"
|
||||
HIDDEN = "\033[8m"
|
||||
STRIKETHROUGH = "\033[9m"
|
||||
|
||||
# STANDARD COLORS (Foreground)
|
||||
BLACK = "\033[30m"
|
||||
RED = "\033[31m"
|
||||
GREEN = "\033[32m"
|
||||
YELLOW = "\033[33m"
|
||||
BLUE = "\033[34m"
|
||||
MAGENTA = "\033[35m"
|
||||
CYAN = "\033[36m"
|
||||
WHITE = "\033[37m"
|
||||
|
||||
# BRIGHT COLORS
|
||||
BRIGHT_BLACK = "\033[90m"
|
||||
BRIGHT_RED = "\033[91m"
|
||||
BRIGHT_GREEN = "\033[92m"
|
||||
BRIGHT_YELLOW = "\033[93m"
|
||||
BRIGHT_BLUE = "\033[94m"
|
||||
BRIGHT_MAGENTA = "\033[95m"
|
||||
BRIGHT_CYAN = "\033[96m"
|
||||
BRIGHT_WHITE = "\033[97m"
|
||||
|
||||
|
||||
def colored(msg: str, style: str) -> str:
|
||||
return style + msg + RESET
|
||||
|
||||
|
||||
def printc(msg: str, style: str) -> None:
|
||||
print(style + msg + RESET)
|
||||
Reference in New Issue
Block a user