chore [P-0]: сhore

This commit is contained in:
Vitaly committed 2026-12-01 16:13:26 +03:00
1 parent dbe5dcae2d
commit d13d02fadb
3 files changed
+788 -78

No files matched your search

+621 -30
View File
@@ -1,37 +1,628 @@
#!/usr/bin/env sh
LC_ALL=C; export LC_ALL
LANG=C; export LANG
commit_msg_file="$1"
ACHIEVEMENTS_SERVICE="${ACHIEVEMENTS_SERVICE:-https://scores.9966hub.ru}"
# Читаем сообщение коммита
commit_msg=$(cat "$commit_msg_file")
# Проверяем, был ли передан аргумент
if [ -z "$commit_msg" ]; then
echo "Ошибка: Необходимо передать сообщение коммита."
exit 1
REPO_ROOT=$(git rev-parse --show-toplevel)
RESULTS_DIR="$REPO_ROOT/.git/linter-results"
HTML_FILE="$REPO_ROOT/linter_errors.html"
# ============================================
# ДАННЫЕ О КОММИТЕ
# ============================================
GIT_LOGIN=$(git config user.name 2>/dev/null | cut -d@ -f1 | tr '[:upper:]' '[:lower:]' | tr ' ' '_')
[ -z "$GIT_LOGIN" ] && GIT_LOGIN=$(git config user.email 2>/dev/null | cut -d@ -f1 | tr '[:upper:]' '[:lower:]')
[ -z "$GIT_LOGIN" ] && GIT_LOGIN="unknown"
commit_msg=$(sed '/^#/d' "$commit_msg_file" | sed '/^[[:space:]]*$/d' | head -n 1)
[ -z "$commit_msg" ] && { echo "Ошибка: пустое сообщение коммита."; exit 1; }
case "$commit_msg" in
Merge\ *|merge\ *|Release\ *|release\ *)
echo "Служебный коммит — сервис не дёргаем."
exit 0
;;
esac
PROJECT_CODE=$(echo "$commit_msg" | grep -oE '\[[A-Z0-9]+-[0-9]+\]' | head -1 | tr -d '[]' | cut -d- -f1)
PROJECT_SLUG=$(echo "$PROJECT_CODE" | tr '[:upper:]' '[:lower:]')
[ -z "$PROJECT_SLUG" ] && PROJECT_SLUG="${ACHIEVEMENTS_PROJECT_SLUG:-p}"
COMMIT_SHA=$(git rev-parse HEAD 2>/dev/null || echo "")
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
PATTERN="^(feat|fix|docs|style|refactor|perf|test|chore) \[[A-Z0-9]+-[0-9]+\]: .+$"
MSG_OK=0
echo "$commit_msg" | grep -qE "$PATTERN" && MSG_OK=1
STATS=$(git diff --cached --shortstat 2>/dev/null)
LINES_ADDED=$(echo "$STATS" | grep -oE '[0-9]+ insertion' | grep -oE '[0-9]+')
LINES_DELETED=$(echo "$STATS" | grep -oE '[0-9]+ deletion' | grep -oE '[0-9]+')
FILES_CHANGED=$(echo "$STATS" | grep -oE '[0-9]+ file' | grep -oE '[0-9]+')
LINES_ADDED=${LINES_ADDED:-0}
LINES_DELETED=${LINES_DELETED:-0}
FILES_CHANGED=${FILES_CHANGED:-0}
# ============================================
# ЛИНТЕРЫ
# ============================================
HAS_ANY_ERRORS=0
HAS_JS=0; JS_OUTPUT=""; JS_STATUS=0; ESLINT_ERRORS=0; ESLINT_WARNINGS=0
if [ -f "$RESULTS_DIR/js.status" ]; then
HAS_JS=1
JS_STATUS=$(cat "$RESULTS_DIR/js.status" | tr -cd '0-9'); JS_STATUS=${JS_STATUS:-0}
JS_OUTPUT=$(cat "$RESULTS_DIR/js.out")
[ "$JS_STATUS" -ne 0 ] && HAS_ANY_ERRORS=1
ESLINT_ERRORS=$(echo "$JS_OUTPUT" | grep -oE '[0-9]+ errors?' | grep -oE '[0-9]+' | head -1)
ESLINT_WARNINGS=$(echo "$JS_OUTPUT" | grep -oE '[0-9]+ warnings?' | grep -oE '[0-9]+' | head -1)
ESLINT_ERRORS=$(echo "$ESLINT_ERRORS" | tr -cd '0-9'); ESLINT_ERRORS=${ESLINT_ERRORS:-0}
ESLINT_WARNINGS=$(echo "$ESLINT_WARNINGS" | tr -cd '0-9'); ESLINT_WARNINGS=${ESLINT_WARNINGS:-0}
fi
HAS_PYLINT=0; PYLINT_OUTPUT=""; PYLINT_STATUS=0; PYLINT_SCORE=0
if [ -f "$RESULTS_DIR/pylint.status" ]; then
HAS_PYLINT=1
PYLINT_STATUS=$(cat "$RESULTS_DIR/pylint.status" | tr -cd '0-9'); PYLINT_STATUS=${PYLINT_STATUS:-0}
PYLINT_OUTPUT=$(cat "$RESULTS_DIR/pylint.out")
[ "$PYLINT_STATUS" -ne 0 ] && HAS_ANY_ERRORS=1
# Определяем шаблон для проверки
PATTERN="^(feat|fix|docs|style|refactor|perf|test|chore) \[[A-Z]+\-[0-9]+]: .+$"
# Проверяем соответствие шаблону
if echo "$commit_msg" | grep -qE "$PATTERN"; then
exit 0
else
echo "Ошибка: Сообщение коммита не соответствует шаблону."
echo "Ожидается: feat|fix|docs|style|refactor|perf|test|chore [X-01]: ваше сообщение"
echo "Заголовок должен содержать тип, номер задачи и название коммита. Формат: <тип> [<номер задачи>]: <название>"
echo " 'feat' - Новый функционал"
echo " 'fix' - Исправление ошибки"
echo " 'docs' - Изменения в документации"
echo " 'style' - Изменения, не влияющие на функциональность"
echo " 'refactor' - Изменения кода, не исправляющие ошибки и не добавляющие функционал"
echo " 'perf' - Изменения, улучшающие производительность"
echo " 'test' - Добавление тестов"
echo " 'chore' - Изменения в процессе сборки или вспомогательных инструментах."
echo " Например: feat [X-01]: я тут накоммитил"
exit 1
if [ -f "$RESULTS_DIR/pylint.score" ]; then
PYLINT_SCORE=$(cat "$RESULTS_DIR/pylint.score" | tr ',' '.')
PYLINT_SCORE=$(echo "$PYLINT_SCORE" | tr -cd '0-9.')
case "$PYLINT_SCORE" in *.*.*) PYLINT_SCORE=0 ;; esac
PYLINT_SCORE=${PYLINT_SCORE:-0}
fi
fi
HAS_MYPY=0; MYPY_OUTPUT=""; MYPY_STATUS=0; MYPY_SCORE=0; MYPY_ERRORS=0; MYPY_LINES=0
if [ -f "$RESULTS_DIR/mypy.status" ]; then
HAS_MYPY=1
MYPY_STATUS=$(cat "$RESULTS_DIR/mypy.status" | tr -cd '0-9'); MYPY_STATUS=${MYPY_STATUS:-0}
MYPY_OUTPUT=$(cat "$RESULTS_DIR/mypy.out")
[ "$MYPY_STATUS" -ne 0 ] && HAS_ANY_ERRORS=1
if [ -f "$RESULTS_DIR/mypy.score" ]; then
MYPY_SCORE=$(cat "$RESULTS_DIR/mypy.score" | tr ',' '.')
MYPY_SCORE=$(echo "$MYPY_SCORE" | tr -cd '0-9.')
case "$MYPY_SCORE" in *.*.*) MYPY_SCORE=0 ;; esac
MYPY_SCORE=${MYPY_SCORE:-0}
fi
[ -f "$RESULTS_DIR/mypy.errors" ] && MYPY_ERRORS=$(cat "$RESULTS_DIR/mypy.errors" | tr -cd '0-9')
[ -f "$RESULTS_DIR/mypy.lines" ] && MYPY_LINES=$(cat "$RESULTS_DIR/mypy.lines" | tr -cd '0-9')
MYPY_ERRORS=${MYPY_ERRORS:-0}
MYPY_LINES=${MYPY_LINES:-0}
fi
# ============================================
# ОЦЕНКИ FRONT / BACK / TOTAL
# ============================================
XP_PYLINT=""; XP_MYPY=""; XP_JS=""
if [ -n "$PYLINT_SCORE" ] && [ "$PYLINT_SCORE" != "0" ]; then
XP_PYLINT=$(awk -v s="$PYLINT_SCORE" 'BEGIN {
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
fi
if [ -n "$MYPY_SCORE" ] && [ "$MYPY_SCORE" != "0" ]; then
XP_MYPY=$(awk -v s="$MYPY_SCORE" 'BEGIN {
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
fi
if [ "$HAS_JS" -eq 1 ]; then
JS_FILES=$(cat "$RESULTS_DIR/js.files" 2>/dev/null | tr -cd '0-9')
JS_FILES=${JS_FILES:-1}
[ "$JS_FILES" -lt 1 ] && JS_FILES=1
XP_JS=$(awk -v err="$ESLINT_ERRORS" -v warn="$ESLINT_WARNINGS" -v files="$JS_FILES" 'BEGIN {
s = 10 - (err / files) * 3 - (warn / files) * 1
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
fi
FRONT_ACTIVE=0
BACK_ACTIVE=0
[ "$HAS_JS" -eq 1 ] && FRONT_ACTIVE=1
if [ "$HAS_PYLINT" -eq 1 ] || [ "$HAS_MYPY" -eq 1 ]; then BACK_ACTIVE=1; fi
FRONT_SCORE=""
[ "$FRONT_ACTIVE" -eq 1 ] && FRONT_SCORE="$XP_JS"
BACK_SCORE=""
if [ "$BACK_ACTIVE" -eq 1 ]; then
if [ -n "$XP_PYLINT" ] && [ -n "$XP_MYPY" ]; then
BACK_SCORE=$(awk -v p="$XP_PYLINT" -v m="$XP_MYPY" 'BEGIN {
avg = (p + m) / 2
diff = (p > m) ? (p - m) : (m - p)
s = avg - diff * 0.5
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
elif [ -n "$XP_PYLINT" ]; then BACK_SCORE="$XP_PYLINT"
elif [ -n "$XP_MYPY" ]; then BACK_SCORE="$XP_MYPY"
else BACK_SCORE=10
fi
fi
TOTAL_SCORE=""
if [ "$FRONT_ACTIVE" -eq 1 ] && [ "$BACK_ACTIVE" -eq 1 ]; then
TOTAL_SCORE=$(awk -v f="$FRONT_SCORE" -v b="$BACK_SCORE" 'BEGIN {
avg = (f + b) / 2
diff = (f > b) ? (f - b) : (b - f)
s = avg - diff * 0.5
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
elif [ "$FRONT_ACTIVE" -eq 1 ]; then TOTAL_SCORE="$FRONT_SCORE"
elif [ "$BACK_ACTIVE" -eq 1 ]; then TOTAL_SCORE="$BACK_SCORE"
fi
# ============================================
# ДЕФОЛТЫ
# ============================================
XP=0
LEVEL=0
RANK_ICON="❓"
RANK_TITLE="Сервис недоступен"
DELTA_XP=0
CURRENT_XP=0
NEED_XP=100
PERCENT=0
COMMIT_COUNT=0
NEW_ACHIEVEMENTS=""
SERVICE_RESPONSE="{}"
# ============================================
# ОТПРАВКА В СЕРВИС
# ============================================
if command -v curl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && [ "$MSG_OK" -eq 1 ]; then
HAD_ERRORS_JSON=$([ "$HAS_ANY_ERRORS" -eq 1 ] && echo true || echo false)
XP_DELTA=0
[ -n "$TOTAL_SCORE" ] && XP_DELTA=$(awk -v s="$TOTAL_SCORE" 'BEGIN {
xp = int(s + 0.5)
if (xp < 0) xp = 0
print xp
}')
PAYLOAD=$(jq -n \
--arg login "$GIT_LOGIN" \
--arg project_slug "$PROJECT_SLUG" \
--arg commit_sha "$COMMIT_SHA" \
--arg commit_msg "$commit_msg" \
--arg branch "$BRANCH" \
--argjson had_errors "$HAD_ERRORS_JSON" \
--argjson front "${FRONT_SCORE:-null}" \
--argjson back "${BACK_SCORE:-null}" \
--argjson total "${TOTAL_SCORE:-null}" \
--argjson pylint "${PYLINT_SCORE:-null}" \
--argjson mypy "${MYPY_SCORE:-null}" \
--argjson mypy_errors "${MYPY_ERRORS:-null}" \
--argjson mypy_lines "${MYPY_LINES:-null}" \
--argjson eslint_errors "${ESLINT_ERRORS:-null}" \
--argjson eslint_warnings "${ESLINT_WARNINGS:-null}" \
--argjson js_files "${JS_FILES:-null}" \
--argjson lines_added "$LINES_ADDED" \
--argjson lines_deleted "$LINES_DELETED" \
--argjson files_changed "$FILES_CHANGED" \
--argjson xp_delta "$XP_DELTA" \
'{
login: $login, project_slug: $project_slug,
commit_sha: $commit_sha, commit_msg: $commit_msg, branch: $branch,
had_errors: $had_errors,
front_score: $front, back_score: $back, total_score: $total,
pylint_score: $pylint, mypy_score: $mypy,
mypy_errors: $mypy_errors, mypy_lines: $mypy_lines,
eslint_errors: $eslint_errors, eslint_warnings: $eslint_warnings,
js_files: $js_files,
lines_added: $lines_added,
lines_deleted: $lines_deleted,
files_changed: $files_changed,
xp_delta: $xp_delta
}')
HTTP_CODE=$(curl -s -o /tmp/ach_resp.json -w "%{http_code}" --max-time 5 \
-X POST "$ACHIEVEMENTS_SERVICE/progress" \
-H "Content-Type: application/json" \
-d "$PAYLOAD" 2>/dev/null)
SERVICE_RESPONSE=$(cat /tmp/ach_resp.json 2>/dev/null)
[ -z "$SERVICE_RESPONSE" ] && SERVICE_RESPONSE="{}"
if [ "${ACHIEVEMENTS_DEBUG:-0}" = "1" ]; then
echo "ACH: POST $ACHIEVEMENTS_SERVICE/progress → HTTP $HTTP_CODE"
echo "ACH: payload: $PAYLOAD"
echo "ACH: response: $SERVICE_RESPONSE"
fi
XP=$(echo "$SERVICE_RESPONSE" | jq -r '.xp // 0')
LEVEL=$(echo "$SERVICE_RESPONSE" | jq -r '.level // 0')
RANK_ICON=$(echo "$SERVICE_RESPONSE" | jq -r '.rank_icon // "❓"')
RANK_TITLE=$(echo "$SERVICE_RESPONSE" | jq -r '.rank_title // "Неизвестный"')
DELTA_XP=$(echo "$SERVICE_RESPONSE" | jq -r '.xp_delta // 0')
CURRENT_XP=$(echo "$SERVICE_RESPONSE" | jq -r '.current_xp // 0')
NEED_XP=$(echo "$SERVICE_RESPONSE" | jq -r '.need_xp // 100')
PERCENT=$(echo "$SERVICE_RESPONSE" | jq -r '.percent // 0')
COMMIT_COUNT=$(echo "$SERVICE_RESPONSE" | jq -r '.commit_count // 0')
NEW_ACHIEVEMENTS=$(echo "$SERVICE_RESPONSE" | jq -r '.new_achievements // [] | join(", ")')
fi
if [ "${PERCENT:-0}" -lt 30 ]; then PERCENT_COLOR="#f14c4c"
elif [ "${PERCENT:-0}" -lt 70 ]; then PERCENT_COLOR="#e5c07b"
else PERCENT_COLOR="#4ec9b0"; fi
# ============================================
# ПРЕДЗАГРУЗКА ПРОФИЛЯ ЧЕРЕЗ CURL
# ============================================
PROFILE_JSON="null"
if command -v curl >/dev/null 2>&1 && [ -n "$GIT_LOGIN" ] && [ "$GIT_LOGIN" != "unknown" ]; then
PROFILE_JSON=$(curl -s --max-time 5 \
"$ACHIEVEMENTS_SERVICE/users/$(printf '%s' "$GIT_LOGIN" | jq -sRr @uri)/overview" \
2>/dev/null)
[ -z "$PROFILE_JSON" ] && PROFILE_JSON="null"
printf '%s' "$PROFILE_JSON" | jq -e . >/dev/null 2>&1 || PROFILE_JSON="null"
fi
PROFILE_JSON_ESCAPED=$(printf '%s' "$PROFILE_JSON" | sed 's/</\\u003c/g; s/>/\\u003e/g; s/&/\\u0026/g')
# ============================================
# HTML-ОТЧЁТ
# ============================================
if [ "$HAS_JS" -eq 1 ] || [ "$HAS_PYLINT" -eq 1 ] || [ "$HAS_MYPY" -eq 1 ]; then
DATETIME=$(date '+%Y-%m-%d %H:%M:%S')
cat > "$HTML_FILE" << EOF
<!DOCTYPE html>
<html lang="ru"><head><meta charset="UTF-8">
<title>$commit_msg</title>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { background:#1e1e1e; color:#d4d4d4; font-family:'Segoe UI',monospace; padding:30px; line-height:1.6; }
.container { max-width:1200px; margin:0 auto; background:#252526; border-radius:12px; padding:30px; box-shadow:0 10px 40px rgba(0,0,0,0.5); }
h1 { color:#f14c4c; font-size:28px; border-bottom:2px solid #333; padding-bottom:15px; margin-bottom:20px; }
/* Табы */
.tabs { display:flex; gap:4px; border-bottom:2px solid #333; margin-bottom:25px; }
.tab-btn { background:#2d2d2d; color:#888; border:none; padding:12px 24px; font-family:inherit; font-size:14px; cursor:pointer; border-radius:8px 8px 0 0; border-bottom:3px solid transparent; transition:all 0.2s; }
.tab-btn:hover { color:#d4d4d4; background:#333; }
.tab-btn.active { color:#4ec9b0; background:#252526; border-bottom-color:#4ec9b0; }
.tab-content { display:none; }
.tab-content.active { display:block; }
/* Карточка пользователя */
.user-card { display:flex; align-items:center; gap:20px; background:#2d2d2d; padding:20px; border-radius:10px; margin-bottom:25px; }
.user-info { flex:1; }
.user-name { font-size:20px; color:#4ec9b0; font-weight:bold; }
.user-stats { display:flex; gap:25px; margin-top:8px; }
.user-stat { font-size:13px; color:#888; }
.user-stat b { color:#d4d4d4; font-size:16px; }
.level-bar { margin-top:10px; background:#1e1e1e; height:8px; border-radius:4px; overflow:hidden; position:relative; }
.level-fill { height:100%; min-width:4px; background:$PERCENT_COLOR; transition:width 0.5s; border-radius:4px; }
.level-bar::after { content:""; position:absolute; inset:0; border-radius:4px; box-shadow: inset 0 0 0 1px rgba(78,201,176,0.15); pointer-events:none; }
.level-text { margin-top:6px; font-size:12px; color:#666; text-align:right; }
.user-rank { text-align:center; padding:20px 25px; background:#1e1e1e; border-radius:10px; border:1px solid #4ec9b0; min-width:180px; }
.rank-icon { font-size:56px; line-height:1; }
.rank-title { color:#4ec9b0; font-size:20px; font-weight:bold; margin-top:10px; letter-spacing:1px; }
.meta { color:#888; font-size:14px; margin-bottom:25px; padding:10px; background:#2d2d2d; border-radius:6px; }
.summary { margin-bottom:25px; }
.summary-title { color:#4ec9b0; font-size:16px; margin-bottom:12px; text-transform:uppercase; letter-spacing:1px; }
.summary-grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:12px; }
.summary-card { background:#2d2d2d; padding:16px 20px; border-radius:10px; border-left:4px solid #4ec9b0; display:flex; flex-direction:column; gap:6px; }
.summary-card.summary-total { border-left-color:#f14c4c; background:linear-gradient(135deg, #2d2d2d 0%, #3a2626 100%); }
.summary-label { font-size:13px; color:#888; text-transform:uppercase; letter-spacing:1px; }
.summary-value { font-size:32px; font-weight:bold; color:#4ec9b0; line-height:1; }
.summary-card.summary-total .summary-value { color:#f14c4c; }
.summary-value span { font-size:14px; color:#666; font-weight:normal; }
.achievements-section { margin-bottom:25px; }
.achievements-title { color:#4ec9b0; font-size:16px; margin-bottom:12px; text-transform:uppercase; letter-spacing:1px; }
.achievements-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(220px,1fr)); gap:12px; }
.achievement { background:#2d2d2d; padding:12px; border-radius:8px; display:flex; gap:12px; align-items:center; border-left:3px solid #4ec9b0; }
.ach-desc { color:#aaa; font-size:13px; }
.chapter { margin-top:20px; border:1px solid #333; border-radius:8px; overflow:hidden; }
.chapter-header { background:#2d2d2d; padding:15px 20px; }
.chapter-header h2 { font-size:18px; color:#4ec9b0; }
.badge { background:#f14c4c; color:white; padding:2px 12px; border-radius:12px; font-size:12px; margin-left:10px; }
.badge.success { background:#4ec9b0; }
.badge.score { background:#0e639c; }
.chapter-body { padding:20px; }
.chapter-body pre { background:#1e1e1e; padding:20px; border-radius:6px; white-space:pre-wrap; font-size:13px; border:1px solid #333; max-height:600px; overflow-y:auto; }
.no-errors { color:#4ec9b0; text-align:center; padding:20px; font-size:16px; }
.footer { margin-top:30px; text-align:center; color:#555; font-size:12px; border-top:1px solid #333; padding-top:20px; }
/* Профиль (таб 2) */
.profile-msg { padding:40px; color:#888; text-align:center; font-size:14px; }
.profile-msg.error { color:#f14c4c; }
.profile-totals { color:#888; font-size:14px; margin-bottom:20px; padding:12px 16px; background:#2d2d2d; border-radius:6px; }
.profile-totals b { color:#d4d4d4; font-size:16px; }
.profile-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(340px,1fr)); gap:16px; margin-bottom:25px; }
.profile-card { background:#2d2d2d; border-radius:10px; padding:18px; border-left:4px solid #4ec9b0; }
.profile-card h3 { color:#4ec9b0; font-size:15px; margin-bottom:10px; }
.profile-rank { font-size:28px; display:flex; align-items:center; gap:10px; margin:6px 0; }
.profile-rank .title { font-size:13px; color:#4ec9b0; font-weight:bold; letter-spacing:1px; }
.profile-stats { display:flex; gap:18px; font-size:12px; color:#888; margin-top:6px; }
.profile-stats b { color:#d4d4d4; font-size:14px; }
.profile-bar { background:#1e1e1e; height:8px; border-radius:4px; overflow:hidden; margin-top:12px; position:relative; }
.profile-bar-fill { height:100%; min-width:4px; border-radius:4px; }
.profile-bar-text { font-size:11px; color:#666; margin-top:4px; text-align:right; }
.profile-ach { margin-top:12px; font-size:12px; color:#aaa; }
.profile-ach div { padding:4px 0; border-top:1px solid #333; }
.profile-ach div:first-child { border-top:none; }
.profile-empty { color:#555; font-style:italic; padding:6px 0; }
.profile-chart { background:#2d2d2d; border-radius:10px; padding:18px; margin-bottom:25px; }
.profile-chart h2 { color:#4ec9b0; font-size:13px; margin-bottom:14px; text-transform:uppercase; letter-spacing:1px; }
.profile-bars { display:flex; align-items:flex-end; gap:4px; height:110px; }
.profile-bar-item { flex:1; background:linear-gradient(180deg,#4ec9b0,#2d7a68); border-radius:3px 3px 0 0; min-height:2px; position:relative; cursor:help; }
.profile-bar-item:hover::after { content:attr(data-label); position:absolute; bottom:100%; left:50%; transform:translateX(-50%); background:#000; color:#4ec9b0; padding:2px 8px; border-radius:4px; font-size:11px; white-space:nowrap; z-index:10; }
.profile-commits { background:#2d2d2d; border-radius:10px; padding:18px; }
.profile-commits h2 { color:#4ec9b0; font-size:13px; margin-bottom:14px; text-transform:uppercase; letter-spacing:1px; }
.profile-commit-row { display:grid; grid-template-columns:150px 80px 1fr 60px; gap:10px; padding:6px 0; border-top:1px solid #333; font-size:12px; align-items:center; }
.profile-commit-row:first-child { border-top:none; }
.profile-commit-row .proj { color:#4ec9b0; font-weight:bold; }
.profile-commit-row .delta { text-align:right; color:#e5c07b; }
.profile-commit-row .delta.neg { color:#f14c4c; }
.profile-commit-row .msg { color:#ccc; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
</style></head><body>
<div class="container">
<h1>📋 Результаты проверки кода</h1>
<div class="tabs">
<button class="tab-btn active" data-tab="report">📋 Проверка</button>
<button class="tab-btn" data-tab="profile">👤 Профиль в сервисе</button>
</div>
<div class="tab-content active" id="tab-report">
<div class="user-card">
<div class="user-info">
<div class="user-name">$GIT_LOGIN</div>
<div class="user-stats">
<div class="user-stat">XP: <b>$XP</b></div>
<div class="user-stat">Уровень: <b>$LEVEL</b></div>
<div class="user-stat">Коммитов: <b>$COMMIT_COUNT</b></div>
<div class="user-stat">Δ: <b>$DELTA_XP</b></div>
</div>
<div class="level-bar"><div class="level-fill" style="width:$PERCENT%"></div></div>
<div class="level-text">$CURRENT_XP / $NEED_XP XP · $PERCENT%</div>
</div>
<div class="user-rank">
<div class="rank-icon">$RANK_ICON</div>
<div class="rank-title">$RANK_TITLE</div>
</div>
</div>
<div class="meta">📅 $DATETIME &nbsp;|&nbsp; 📝 $commit_msg &nbsp;|&nbsp; 🏗️ $PROJECT_SLUG</div>
<div class="summary">
<div class="summary-title">📊 Сводка оценок</div>
<div class="summary-grid">
<div class="summary-card">
<div class="summary-label">🟨 FRONT (JS/TS)</div>
<div class="summary-value">${FRONT_SCORE:-N/A}<span>/10</span></div>
</div>
<div class="summary-card">
<div class="summary-label">🐍 BACK (Python)</div>
<div class="summary-value">${BACK_SCORE:-N/A}<span>/10</span></div>
</div>
<div class="summary-card summary-total">
<div class="summary-label">🏆 TOTAL</div>
<div class="summary-value">${TOTAL_SCORE:-N/A}<span>/10</span></div>
</div>
</div>
</div>
EOF
if [ -n "$NEW_ACHIEVEMENTS" ]; then
cat >> "$HTML_FILE" << EOF
<div class="achievements-section">
<div class="achievements-title">🏅 Новые достижения</div>
<div class="achievements-grid">
<div class="achievement"><div class="ach-desc">$NEW_ACHIEVEMENTS</div></div>
</div>
</div>
EOF
fi
add_chapter() {
local TITLE="$1" OUTPUT="$2" HAS_ERRORS="$3" ICON="$4" SCORE="$5"
local BADGE_CLASS="" STATUS_TEXT="❌ Есть ошибки"
[ "$HAS_ERRORS" -eq 0 ] && { BADGE_CLASS="success"; STATUS_TEXT="✅ Ошибок нет"; }
local SCORE_HTML=""
[ -n "$SCORE" ] && [ "$SCORE" != "0" ] && SCORE_HTML=" <span class='badge score'>Оценка: $SCORE/10</span>"
local ESCAPED=$(echo "$OUTPUT" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g')
cat >> "$HTML_FILE" << EOF
<div class="chapter">
<div class="chapter-header"><h2>$ICON $TITLE <span class="badge $BADGE_CLASS">$STATUS_TEXT</span>$SCORE_HTML</h2></div>
<div class="chapter-body">
EOF
if [ "$HAS_ERRORS" -eq 0 ]; then
echo '<div class="no-errors">Все проверки пройдены успешно</div>' >> "$HTML_FILE"
else
echo "<pre>$ESCAPED</pre>" >> "$HTML_FILE"
fi
echo '</div></div>' >> "$HTML_FILE"
}
[ "$HAS_JS" -eq 1 ] && add_chapter "JavaScript / Vue / TypeScript" "$JS_OUTPUT" "$JS_STATUS" "🟨" "$XP_JS"
[ "$HAS_PYLINT" -eq 1 ] && add_chapter "Pylint" "$PYLINT_OUTPUT" "$PYLINT_STATUS" "🐍" "$PYLINT_SCORE"
[ "$HAS_MYPY" -eq 1 ] && add_chapter "Mypy (types)" "$MYPY_OUTPUT" "$MYPY_STATUS" "🔎" "$MYPY_SCORE"
cat >> "$HTML_FILE" << EOF
<div class="footer">Сгенерировано commit-msg хуком • $GIT_LOGIN</div>
</div> <!-- /tab-report -->
<div class="tab-content" id="tab-profile">
<div class="profile-msg" id="profile-status">Нажми вкладку, чтобы загрузить…</div>
<div id="profile-body" style="display:none"></div>
</div>
</div> <!-- /container -->
<script>
(function() {
var ACHIEVEMENTS_SERVICE = "$ACHIEVEMENTS_SERVICE";
var LOGIN = "$GIT_LOGIN";
var profileLoaded = false;
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c];
});
}
function colorFor(p) {
if (p < 30) return '#f14c4c';
if (p < 70) return '#e5c07b';
return '#4ec9b0';
}
function renderProfile(data) {
var status = document.getElementById('profile-status');
var body = document.getElementById('profile-body');
var maxXP = Math.max(1, ...data.daily_xp.map(function(d){ return d.xp; }));
var projectsHTML = data.projects.map(function(p) {
var ach = p.recent_achievements.length
? p.recent_achievements.map(function(a) {
return '<div>' + a.icon + ' ' + esc(a.title) + '</div>';
}).join('')
: '<div class="profile-empty">пока нет достижений</div>';
return ''
+ '<div class="profile-card">'
+ '<h3>🏗️ ' + esc(p.project_slug) + '</h3>'
+ '<div class="profile-rank">'
+ '<span>' + p.rank_icon + '</span>'
+ '<span class="title">' + esc(p.rank_title) + '</span>'
+ '</div>'
+ '<div class="profile-stats">'
+ '<div>Уровень: <b>' + p.level + '</b></div>'
+ '<div>Коммитов: <b>' + p.commit_count + '</b></div>'
+ '<div>Ачивок: <b>' + p.achievements_count + '</b></div>'
+ '</div>'
+ '<div class="profile-bar">'
+ '<div class="profile-bar-fill" style="width:' + p.percent + '%;background:' + colorFor(p.percent) + ';"></div>'
+ '</div>'
+ '<div class="profile-bar-text">' + p.current_xp + ' / ' + p.need_xp + ' XP · ' + p.percent + '%</div>'
+ '<div class="profile-ach">' + ach + '</div>'
+ '</div>';
}).join('');
var chartHTML = data.daily_xp.length
? '<div class="profile-bars">' + data.daily_xp.map(function(d) {
var h = Math.max(2, (d.xp / maxXP) * 110);
return '<div class="profile-bar-item" style="height:' + h + 'px" data-label="' + d.date + ': ' + d.xp + ' XP"></div>';
}).join('') + '</div>'
: '<div class="profile-empty">нет данных за последние 30 дней</div>';
var commitsHTML = data.recent_commits.length
? data.recent_commits.map(function(c) {
var deltaCls = c.xp_delta < 0 ? 'delta neg' : 'delta';
var deltaTxt = 'Δ ' + (c.xp_delta > 0 ? '+' : '') + c.xp_delta;
var dt = (c.created_at || '').replace('T', ' ').slice(0, 16);
return ''
+ '<div class="profile-commit-row">'
+ '<span>' + esc(dt) + '</span>'
+ '<span class="proj">' + esc(c.project_slug || '—') + '</span>'
+ '<span class="msg" title="' + esc(c.commit_msg) + '">' + esc(c.commit_msg || '') + '</span>'
+ '<span class="' + deltaCls + '">' + deltaTxt + '</span>'
+ '</div>';
}).join('')
: '<div class="profile-empty">нет коммитов</div>';
body.innerHTML = ''
+ '<div class="profile-totals">'
+ 'Всего XP: <b>' + data.total_xp + '</b> · '
+ 'Коммитов: <b>' + data.total_commits + '</b> · '
+ 'Проектов: <b>' + data.projects_count + '</b>'
+ '</div>'
+ '<div class="profile-grid">' + projectsHTML + '</div>'
+ '<div class="profile-chart"><h2>📈 XP за 30 дней</h2>' + chartHTML + '</div>'
+ '<div class="profile-commits"><h2>📜 Последние коммиты</h2>' + commitsHTML + '</div>';
status.style.display = 'none';
body.style.display = 'block';
}
var PROFILE_DATA = $PROFILE_JSON_ESCAPED;
var profileLoaded = false;
function loadProfile() {
if (profileLoaded) return;
var status = document.getElementById('profile-status');
if (!PROFILE_DATA || PROFILE_DATA === null) {
status.textContent = 'Профиль недоступен (сервис не ответил).';
status.className = 'profile-msg error';
return;
}
try {
profileLoaded = true;
renderProfile(PROFILE_DATA);
} catch (e) {
status.textContent = 'Ошибка отображения: ' + e;
status.className = 'profile-msg error';
}
}
document.querySelectorAll('.tab-btn').forEach(function(btn) {
btn.addEventListener('click', function() {
var tab = btn.dataset.tab;
document.querySelectorAll('.tab-btn').forEach(function(b) {
b.classList.toggle('active', b === btn);
});
document.querySelectorAll('.tab-content').forEach(function(c) {
c.classList.toggle('active', c.id === 'tab-' + tab);
});
if (tab === 'profile') loadProfile();
});
});
})();
</script>
</body></html>
EOF
if [ "$HAS_ANY_ERRORS" -eq 1 ]; then
notify-send -u normal -i dialog-warning "Проверка кода" \
"Найдены ошибки. Открой отчёт." 2>/dev/null || true
(xdg-open "$HTML_FILE" >/dev/null 2>&1 || flatpak-spawn --host xdg-open "$HTML_FILE" >/dev/null 2>&1) &
else
rm -f "$HTML_FILE"
fi
fi
# ============================================
# БЛОКИРОВКА — ТОЛЬКО ОФОРМЛЕНИЕ
# ============================================
if [ "$MSG_OK" -eq 0 ]; then
cat <<EOF
... --- ... Ошибка ... --- ...
$commit_msg
Сообщение коммита не соответствует шаблону.
Формат: <тип> [<номер задачи>]: <название>
Пример: feat [P-01]: я тут накоммитил
Тип Описание Рыба
--------- -------------------- ------------------------------
feat Новый функционал feat [P-]:
fix Исправление ошибки fix [P-]:
docs Документация docs [P-]:
style Форматирование style [P-]:
refactor Рефакторинг refactor [P-]:
perf Производительность perf [P-]:
test Тесты test [P-]:
chore Сборка, сервер chore [P-]:
EOF
exit 1
fi
exit 0
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env sh
LC_ALL=C
export LC_ALL
LANG=C
export LANG
# ============================================
# ЗАПУСК ЛИНТЕРОВ И СОХРАНЕНИЕ РЕЗУЛЬТАТОВ
# ============================================
REPO_ROOT=$(git rev-parse --show-toplevel)
RESULTS_DIR="$REPO_ROOT/.git/linter-results"
mkdir -p "$RESULTS_DIR"
# Сбрасываем старые результаты
rm -f "$RESULTS_DIR"/*.out "$RESULTS_DIR"/*.status "$RESULTS_DIR"/*.files \
"$RESULTS_DIR"/*.errors "$RESULTS_DIR"/*.score "$RESULTS_DIR"/*.lines
USER_ID=$(id -u)
GROUP_ID=$(id -g)
# ============================================
# JS / VUE / TS
# ============================================
filesjs=$(git diff --cached --name-only --diff-filter=ACM | grep '^src/front/' | grep -E '\.vue$|\.js$|\.ts$')
if [ -n "$filesjs" ]; then
filesjs_modified=$(echo "$filesjs" | sed 's|^src/front/||' | tr '\n' ' ')
if [ "$(docker compose -f docker-compose.yml ps -q frontend 2>/dev/null)" ]; then
JS_RAW=$(docker compose -f docker-compose.yml exec -T --user "$USER_ID:$GROUP_ID" frontend sh -c \
"npm run formatter -- $filesjs_modified && npm run linter -- $filesjs_modified; echo __EXIT__:\$?" 2>&1)
else
JS_RAW=$(docker compose -f docker-compose.yml -f docker/composes/docker-compose.dev.yml run --rm --user "$USER_ID:$GROUP_ID" --entrypoint sh frontend -c \
"npm run formatter -- $filesjs_modified && npm run linter -- $filesjs_modified; echo __EXIT__:\$?" 2>&1)
fi
LINTER_STATUS_JS=$(echo "$JS_RAW" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
LINTER_STATUS_JS=${LINTER_STATUS_JS:-0}
LINTER_OUTPUT_JS=$(echo "$JS_RAW" | sed 's/__EXIT__:[0-9]*$//')
echo "$LINTER_OUTPUT_JS" > "$RESULTS_DIR/js.out"
echo "$LINTER_STATUS_JS" > "$RESULTS_DIR/js.status"
echo "$filesjs" | grep -c . > "$RESULTS_DIR/js.files"
# Возвращаем отформатированные файлы в индекс
echo "$filesjs" | while read -r file; do
[ -f "$file" ] && git add "$file"
done
fi
# ============================================
# PYTHON
# ============================================
pyfiles=$(git diff --cached --name-only --diff-filter=ACM | grep '^src/back/' | grep '\.py$')
if [ -n "$pyfiles" ]; then
pyfiles_mod=$(echo "$pyfiles" | sed 's|^src/back/||' | tr '\n' ' ')
if [ -z "$(echo "$pyfiles_mod" | tr -d ' ')" ]; then
# Все файлы — тесты, линтеры не запускаем
: > "$RESULTS_DIR/fmt.out"; echo 0 > "$RESULTS_DIR/fmt.status"
: > "$RESULTS_DIR/pylint.out"; echo 0 > "$RESULTS_DIR/pylint.status"
echo 0 > "$RESULTS_DIR/pylint.score"
: > "$RESULTS_DIR/mypy.out"; echo 0 > "$RESULTS_DIR/mypy.status"
echo 0 > "$RESULTS_DIR/mypy.errors"
echo 0 > "$RESULTS_DIR/mypy.lines"
echo 0 > "$RESULTS_DIR/mypy.score"
: > "$RESULTS_DIR/py.out"; echo 0 > "$RESULTS_DIR/py.status"
echo 0 > "$RESULTS_DIR/py.files"
else
BACKEND_RUNNING=0
[ "$(docker compose -f docker-compose.yml ps -q backend 2>/dev/null)" ] && BACKEND_RUNNING=1
run_backend() {
local cmd="$1"
if [ "$BACKEND_RUNNING" -eq 1 ]; then
docker compose -f docker-compose.yml exec -T --user "$USER_ID:$GROUP_ID" backend \
sh -c "$cmd; echo __EXIT__:\$?" 2>&1
else
docker compose -f docker-compose.yml run --rm --user "$USER_ID:$GROUP_ID" \
--entrypoint sh backend -c "$cmd; echo __EXIT__:\$?" 2>&1
fi
}
# --- isort + black ---
fmt_raw=$(run_backend "poetry run ruff check $pyfiles_mod --fix; poetry run ruff format $pyfiles_mod")
fmt_status=$(echo "$fmt_raw" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
fmt_status=${fmt_status:-0}
fmt_out=$(echo "$fmt_raw" | sed 's/__EXIT__:[0-9]*$//')
echo "$fmt_out" > "$RESULTS_DIR/fmt.out"
echo "$fmt_status" > "$RESULTS_DIR/fmt.status"
# --- pylint ---
pylint_raw=$(run_backend "PYLINTHOME=/tmp poetry run pylint $pyfiles_mod")
pylint_status=$(echo "$pylint_raw" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
pylint_status=${pylint_status:-0}
pylint_out=$(echo "$pylint_raw" | sed 's/__EXIT__:[0-9]*$//')
echo "$pylint_out" > "$RESULTS_DIR/pylint.out"
echo "$pylint_status" > "$RESULTS_DIR/pylint.status"
# --- оценка pylint (пробуем достать из вывода, иначе 0) ---
PYLINT_SCORE=$(echo "$pylint_out" | grep -oE 'rated at [0-9]+\.[0-9]+' \
| grep -oE '[0-9]+\.[0-9]+' | tail -1)
PYLINT_SCORE=$(echo "$PYLINT_SCORE" | tr -cd '0-9.')
case "$PYLINT_SCORE" in
*.*.*) PYLINT_SCORE=0 ;;
esac
PYLINT_SCORE=${PYLINT_SCORE:-0}
echo "$PYLINT_SCORE" > "$RESULTS_DIR/pylint.score"
# --- mypy ---
mypy_raw=$(run_backend "poetry run mypy --cache-dir /dev/null --show-traceback $pyfiles_mod")
mypy_status=$(echo "$mypy_raw" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
mypy_status=${mypy_status:-0}
mypy_out=$(echo "$mypy_raw" | sed 's/__EXIT__:[0-9]*$//')
echo "$mypy_out" > "$RESULTS_DIR/mypy.out"
echo "$mypy_status" > "$RESULTS_DIR/mypy.status"
# --- метрики mypy: errors / lines ---
MYPY_ERRORS=$(echo "$mypy_out" | grep -oE 'Found [0-9]+ error' | grep -oE '[0-9]+' | tail -1)
MYPY_ERRORS=${MYPY_ERRORS:-0}
if echo "$mypy_out" | grep -q 'Success: no issues found'; then
MYPY_ERRORS=0
fi
# Считаем суммарное количество строк в проверяемых файлах
MYPY_LINES=0
for f in $pyfiles; do
if [ -f "$REPO_ROOT/$f" ]; then
L=$(wc -l < "$REPO_ROOT/$f" | tr -cd '0-9')
MYPY_LINES=$((MYPY_LINES + L))
fi
done
[ "$MYPY_LINES" -lt 1 ] && MYPY_LINES=1
# Оценка mypy 0..10: 10 - 10 * errors / lines
MYPY_SCORE=$(awk -v err="$MYPY_ERRORS" -v lines="$MYPY_LINES" 'BEGIN {
if (lines < 1) lines = 1
s = 10.0 - (10.0 * err / lines)
if (s < 0) s = 0
if (s > 10) s = 10
printf "%.2f", s
}')
echo "$MYPY_ERRORS" > "$RESULTS_DIR/mypy.errors"
echo "$MYPY_LINES" > "$RESULTS_DIR/mypy.lines"
echo "$MYPY_SCORE" > "$RESULTS_DIR/mypy.score"
# Итоговый статус Python: любой ненулевой → ошибка
PY_TOTAL_STATUS=0
[ "$fmt_status" -ne 0 ] && PY_TOTAL_STATUS=1
[ "$pylint_status" -ne 0 ] && PY_TOTAL_STATUS=1
[ "$mypy_status" -ne 0 ] && PY_TOTAL_STATUS=1
# Склейка для совместимости / общей сводки
cat "$RESULTS_DIR/fmt.out" "$RESULTS_DIR/pylint.out" "$RESULTS_DIR/mypy.out" > "$RESULTS_DIR/py.out"
echo "$PY_TOTAL_STATUS" > "$RESULTS_DIR/py.status"
echo "$pyfiles" | grep -c . > "$RESULTS_DIR/py.files"
# Возвращаем отформатированные файлы в индекс
echo "$pyfiles" | while read -r file; do
[ -f "$file" ] && git add "$file"
done
fi
fi
exit 0
-48
View File
@@ -1,48 +0,0 @@
#!/usr/bin/env sh
# # Получение списка всех Vue/js/ts-файлов, подготовленных для коммита
filesjs=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.vue$|\.js$|\.ts$'| grep -v 'test\.js$')
if [ -n "$filesjs" ]; then
filesjs_modified=$(echo "$filesjs" | sed 's|^src/front/src/|src/|'| tr '\n' ' ')
# Запускаем команду formatter в контейнере
echo $filesjs_modified
if [ "$(docker compose -f docker-compose.yml ps -q frontend)" ]; then
docker compose -f docker-compose.yml exec frontend sh -c "npm run formatter $filesjs_modified && npm run linter $filesjs_modified"
else
docker compose -f docker-compose.yml run --rm frontend sh -c "npm run formatter $filesjs_modified && npm run linter $filesjs_modified"
fi
fi
if [ $? -ne 0 ]; then
echo "Ошибка: eslint обнаружил проблемы в коде."
exit 1 # Выход с кодом ошибки
fi
# # Получение списка всех Python-файлов, подготовленных для коммита
pyfiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$')
# # | sed 's|/|.|g; s|\.py$||'
if [ -n "$pyfiles" ]; then
pyfiles_mod=$(echo "$pyfiles" | sed 's|^src/back/||'| tr '\n' ' ')
if [ "$(docker compose -f docker-compose.yml ps -q backend)" ]; then
echo $pyfiles_mod
docker compose -f docker-compose.yml exec backend sh -c "poetry run isort $pyfiles_mod && poetry run black $pyfiles_mod && poetry run pylint $pyfiles_mod"
else
docker compose -f docker-compose.yml run --rm --entrypoint sh backend -c "poetry run isort $pyfiles_mod && poetry run black $pyfiles_mod && poetry run pylint $pyfiles_mod"
fi
# # Запуск pylint для всех подготовленных Python-файлов
# # echo 1
fi
if [ $? -ne 0 ]; then
echo "Ошибка: pylint обнаружил проблемы в коде."
exit 1 # Выход с кодом ошибки
fi