статичный вариант с докером

This commit is contained in:
denzel committed 2026-11-12 00:39:07 -05:00
commit 96fdbeb3df
12 files changed
+387

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
**
!Dockerfile
!build.py
!VERSION
!docs/
!docs/content.md
!web/
!web/index.html
!web/style.css
!web/app.js
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
python3 scripts/bump_version.py
+2
View File
@@ -0,0 +1,2 @@
dist/
__pycache__/
+18
View File
@@ -0,0 +1,18 @@
FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app
COPY build.py VERSION ./
COPY docs/content.md ./docs/content.md
COPY web/index.html web/style.css web/app.js ./web/
RUN python3 build.py
USER 10001:10001
EXPOSE 8080
CMD ["python3", "-m", "http.server", "8080", "--bind", "0.0.0.0", "--directory", "/app/dist"]
+63
View File
@@ -0,0 +1,63 @@
# OKTP · документация инфраструктуры
Одностраничный адаптивный портал с поиском по разделам и навигацией. Контент хранится в [docs/content.md](docs/content.md). Данные о сервере и проектах нужно заполнить: это справочник, не мониторинг.
## Запуск
Нужен Python 3.9 или новее. Сторонние зависимости не требуются.
```bash
python3 build.py
python3 -m http.server 8080 --bind 127.0.0.1 --directory dist
```
Откройте http://localhost:8080. Остановка сервера: Ctrl+C.
## Запуск в Docker
Из корня репозитория:
```bash
docker build -t oktp-docs .
docker run --rm --name oktp-docs -p 127.0.0.1:8080:8080 oktp-docs
```
Откройте http://localhost:8080. Остановка: Ctrl+C или `docker stop oktp-docs` из другого терминала. Контейнер автоматически удалится после остановки.
Используется один Python-образ: `RUN python3 build.py` собирает страницу при сборке образа, а `CMD` запускает HTTP-сервер при старте контейнера. Процесс работает без root и раздаёт только `/app/dist`. Это простой сервер для внутренней документации; TLS и авторизация при необходимости настраиваются на внешнем reverse proxy.
После изменения Markdown или нового коммита остановите контейнер, повторите `docker build` и `docker run`: содержимое и `VERSION` копируются в образ, поэтому обычный перезапуск не обновляет страницу. Git hook выполняется на хосте при коммите; сборка образа счётчик не увеличивает.
Для доступа с других устройств локальной сети замените `-p 127.0.0.1:8080:8080` на `-p 8080:8080` и откройте `http://<адрес-сервера>:8080`. Такой вариант публикует порт на всех сетевых интерфейсах хоста.
## Редактирование
1. Измените `docs/content.md`.
2. Выполните `python3 build.py`.
3. Обновите страницу браузера.
Заголовки `##` создают разделы и пункты меню. Поиск фильтрует разделы целиком. Клавиша `/` переводит фокус в поиск, Escape очищает его.
Поддерживается ограниченное подмножество Markdown: заголовки уровней 1–3, отдельные абзацы, **жирный текст**, inline code, fenced code blocks, однострочные цитаты, плоские нумерованные и маркированные списки, таблицы, ссылки HTTP(S), mailto и якоря. HTML отображается текстом. Вложенные списки, изображения, курсив и расширения CommonMark не поддерживаются. Разделяйте абзацы пустой строкой; пишите каждый абзац одной строкой. В ячейках таблиц не используйте символ `|`.
Оформление: `web/style.css`. Шаблон: `web/index.html`. Поведение поиска: `web/app.js`. Сборка: `build.py`.
## Размещение
Сборка создаёт `dist/`: её содержимое можно разместить на статическом веб-сервере. Исходники и Markdown посетителям не требуются. Для внутренней документации настройте доступ на вашем сервере; встроенной авторизации нет. Автоматический деплой не настроен.
## Версия документации
Версия хранится в `VERSION` и отображается внизу страницы. Начальное значение — `0.0.0`; каждый коммит через `git commit` увеличивает последнее число: `0.0.1`, `0.0.2`, … . Файл версии автоматически включается в коммит.
После клонирования один раз включите hook (настройка Git не переносится при клонировании):
```bash
git config core.hooksPath .githooks
```
Hook требует Python 3 и исполняемый `.githooks/pre-commit`. Версия вычисляется из `HEAD:VERSION`, поэтому повторная попытка после отменённого коммита не увеличивает её дважды. При отмене коммита подготовленный `VERSION` остаётся в index и рабочей директории. `git commit --amend` также увеличивает счётчик.
После коммита выполните `python3 build.py` и обновите страницу, чтобы увидеть новую версию. Сборка сама счётчик не увеличивает.
Это локальный счётчик ветки: параллельные ветки могут получить одинаковую версию. Hook не обеспечивает глобальную нумерацию, не вызывается при fast-forward, а также может быть пропущен через `--no-verify` или при операциях переписывания истории. Не редактируйте `VERSION` вручную: следующий коммит вычислит значение из предыдущего коммита.
+1
View File
@@ -0,0 +1 @@
0.0.1
+102
View File
@@ -0,0 +1,102 @@
"""Build a static documentation page using a documented Markdown subset."""
from pathlib import Path
import html
import re
import shutil
ROOT = Path(__file__).resolve().parent
def inline(value):
# Escape HTML first; only explicitly supported markup becomes HTML.
value = html.escape(value)
tokens = []
def token(markup):
tokens.append(markup)
return f'\x00{len(tokens) - 1}\x00'
value = re.sub(r'`([^`]+)`', lambda m: token(f'<code>{m[1]}</code>'), value)
def link(match):
label, url = match.groups()
if not re.match(r'^(https?://|mailto:|#)', html.unescape(url), re.I):
return label
return token(f'<a href="{url}">{label}</a>')
value = re.sub(r'\[([^\]]+)\]\(([^\s)]+)\)', link, value)
value = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', value)
for i in reversed(range(len(tokens))):
value = value.replace(f'\x00{i}\x00', tokens[i])
return value
def render(source):
lines = source.splitlines()
output, navigation = [], []
index, section, heading = 0, False, 0
while index < len(lines):
line = lines[index].strip()
index += 1
if not line:
continue
if line.startswith('```'):
code = []
while index < len(lines) and not lines[index].strip().startswith('```'):
code.append(lines[index])
index += 1
index += 1
output.append('<pre><code>' + html.escape('\n'.join(code)) + '</code></pre>')
elif re.match(r'^#{1,3} ', line):
level = len(line.split(' ', 1)[0])
title = line[level + 1:]
if level == 2:
if section:
output.append('</section>')
heading += 1
anchor = f'section-{heading}'
navigation.append(f'<a href="#{anchor}"><span>{heading:02}</span>{html.escape(title)}</a>')
output.append(f'<section id="{anchor}">')
section = True
output.append(f'<h{level}>{inline(title)}</h{level}>')
elif line.startswith('|') and index < len(lines) and re.match(r'^\|[\s:|\-]+\|$', lines[index].strip()):
cells = lambda row: [inline(cell.strip()) for cell in row.strip().strip('|').split('|')]
output.append('<div class="table-wrap" tabindex="0" role="region" aria-label="Таблица"><table><thead><tr>' + ''.join(f'<th scope="col">{cell}</th>' for cell in cells(line)) + '</tr></thead><tbody>')
index += 1
while index < len(lines) and lines[index].strip().startswith('|'):
output.append('<tr>' + ''.join(f'<td>{cell}</td>' for cell in cells(lines[index])) + '</tr>')
index += 1
output.append('</tbody></table></div>')
elif re.match(r'^(\d+\. |[-*] )', line):
ordered = bool(re.match(r'^\d+\.', line))
tag, pattern = ('ol', r'^\d+\. ') if ordered else ('ul', r'^[-*] ')
items = [re.sub(pattern, '', line)]
while index < len(lines) and re.match(pattern, lines[index].strip()):
items.append(re.sub(pattern, '', lines[index].strip()))
index += 1
output.append(f'<{tag}>' + ''.join(f'<li>{inline(item)}</li>' for item in items) + f'</{tag}>')
elif line.startswith('> '):
output.append(f'<blockquote>{inline(line[2:])}</blockquote>')
else:
output.append(f'<p>{inline(line)}</p>')
if section:
output.append('</section>')
return '\n'.join(output), '\n'.join(navigation)
def build():
version = (ROOT / 'VERSION').read_text(encoding='utf-8').strip()
if not re.fullmatch(r'\d+\.\d+\.\d+', version):
raise ValueError('VERSION must contain major.minor.patch')
content, navigation = render((ROOT / 'docs/content.md').read_text())
template = (ROOT / 'web/index.html').read_text()
target = ROOT / 'dist'
target.mkdir(exist_ok=True)
(target / 'index.html').write_text(template.replace('{{version}}', version).replace('{{navigation}}', navigation).replace('{{content}}', content))
for name in ('style.css', 'app.js'):
shutil.copyfile(ROOT / 'web' / name, target / name)
print('Built dist/index.html')
if __name__ == '__main__':
build()
+86
View File
@@ -0,0 +1,86 @@
# Инфраструктура в одном месте
Рабочая документация локального сервера: окружение, исходники и тестовые проекты. Обновляйте этот файл вместе с изменениями инфраструктуры.
## Обзор
Единая точка входа для разработки и сопровождения проектов.
### Быстрый старт
1. Заполните паспорт сервера и способ подключения.
2. Добавьте ссылки на репозитории и их зависимости.
3. Опишите тестовые стенды и процесс обновления.
## Сервер
### Паспорт окружения
| Параметр | Значение |
| ------------------------ | -------------------------------------- |
| Имя сервера | oktpser |
| Назначение | Локальная разработка и тестовые стенды |
| Адрес в локальной сети | http://oktpserver.local/ |
| Операционная система | Заполнить |
| CPU / RAM / диск | Заполнить |
| Ответственный | Заполнить |
| Дата проверки информации | Заполнить |
### Доступ
SSH-подключению и выдаче доступа.
### Сервисы и порты
| Сервис | Порт | Назначение | Проверка работоспособности |
| --------- | ---- | ---------- | -------------------------- |
| Заполнить | — | — | — |
## Репозитории
Добавьте ссылки в формате `[Название](https://адрес)` и укажите порядок запуска зависимых сервисов.
| Репозиторий | Назначение | Зависимости | Команда запуска |
| ----------- | ------------------------------- | ----------- | --------------- |
| Заполнить | Frontend / API / инфраструктура | Заполнить | Заполнить |
### Настройка окружения
Перечислите необходимые версии runtime, package manager, переменные окружения и расположение `.env.example`. Значения секретов не добавляйте.
## Тестовые проекты
| Проект | URL стенда | Ветка / версия | Обновление | Ответственный |
| --------- | ---------- | -------------- | ------------ | ------------- |
| Заполнить | — | — | Вручную / CI | Заполнить |
### Проверка после деплоя
1. Открыть стенд и проверить основной пользовательский сценарий.
2. Проверить соединение с API и зависимыми сервисами.
3. Просмотреть логи и записать развернутую версию.
## Эксплуатация
### Деплой и откат
Опишите команды деплоя, расположение конфигурации, порядок миграций и способ возврата к предыдущей версии.
### Логи и диагностика
Укажите расположение логов, команды просмотра и типовые причины ошибок.
### Резервные копии
Укажите, что копируется, куда, с какой периодичностью и как проверить восстановление.
## Как обновлять документацию
Редактируйте `docs/content.md` и пересоберите страницу:
```bash
python3 build.py
python3 -m http.server 8080 --bind 127.0.0.1 --directory dist
```
Откройте [локальный портал](http://localhost:8080). Новые разделы с заголовком второго уровня автоматически появятся в меню. После изменения Markdown повторите сборку и обновите страницу.
+33
View File
@@ -0,0 +1,33 @@
"""Stage the next version, based on HEAD so an aborted commit can be retried."""
from pathlib import Path
import re
import subprocess
def git(*args, check=True):
return subprocess.run(['git', *args], check=check, capture_output=True, text=True)
def main():
root = Path(git('rev-parse', '--show-toplevel').stdout.strip())
previous = git('show', 'HEAD:VERSION', check=False)
if previous.returncode:
# Allow adoption in an existing repository or the first commit.
tracked = git('ls-tree', '--name-only', 'HEAD', '--', 'VERSION', check=False)
if tracked.stdout.strip():
raise SystemExit('Cannot read HEAD:VERSION; commit cancelled.')
version = '0.0.0'
else:
version = previous.stdout.strip()
match = re.fullmatch(r'(\d+)\.(\d+)\.(\d+)', version)
if not match:
raise SystemExit('Invalid HEAD:VERSION; expected major.minor.patch.')
major, minor, patch = map(int, match.groups())
next_version = f'{major}.{minor}.{patch + 1}'
(root / 'VERSION').write_text(next_version + '\n', encoding='utf-8')
git('add', '--', 'VERSION')
print(f'Documentation version: {next_version}')
if __name__ == '__main__':
main()
+37
View File
@@ -0,0 +1,37 @@
const input = document.querySelector('#search');
const sections = [...document.querySelectorAll('article section')];
const status = document.querySelector('#search-status');
const links = [...document.querySelectorAll('nav a')];
input.addEventListener('input', () => {
const query = input.value.trim().toLocaleLowerCase('ru');
let count = 0;
sections.forEach((section, index) => {
const matches = section.textContent.toLocaleLowerCase('ru').includes(query);
section.hidden = !matches;
links[index].hidden = !matches;
if (matches) count++;
});
status.hidden = !query;
status.textContent = count ? `Найдено разделов: ${count}` : 'Ничего не найдено. Попробуйте другой запрос.';
});
document.addEventListener('keydown', (event) => {
if (event.key === '/' && !event.ctrlKey && !event.metaKey && !['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName) && !document.activeElement.isContentEditable) {
event.preventDefault();
input.focus();
}
if (event.key === 'Escape' && document.activeElement === input) {
input.value = '';
input.dispatchEvent(new Event('input'));
}
});
function updateNavigation() {
links.forEach(link => {
if (link.hash === location.hash) link.setAttribute('aria-current', 'location');
else link.removeAttribute('aria-current');
});
}
window.addEventListener('hashchange', updateNavigation);
updateNavigation();
+31
View File
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Документация локального сервера, репозиториев и тестовых окружений.">
<title>OKTP — инфраструктура и документация</title>
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
</head>
<body>
<a class="skip" href="#content">К документации</a>
<aside>
<a class="brand" href="#"><b>O<span>↗</span></b><div>OKTP<span>DEVELOPER WORKSPACE</span></div></a>
<div class="workspace"><span class="dot"></span> Локальная инфраструктура</div>
<div class="nav-label">ДОКУМЕНТАЦИЯ</div>
<nav aria-label="Разделы документации">{{navigation}}</nav>
<div class="sidebar-footer"><span class="file-icon">↳</span> Источник документации<br><code>docs/content.md</code></div>
</aside>
<div class="page">
<header><span>Workspace <i>/</i> <strong>Документация</strong></span><span class="badge">MD <span>·</span> KNOWLEDGE BASE</span></header>
<main id="content">
<div class="eyebrow"><span></span> ИНФРАСТРУКТУРА / СПРАВОЧНИК</div>
<div class="search-box"><label for="search">Поиск по документации</label><div><span aria-hidden="true">⌕</span><input id="search" type="search" placeholder="Сервер, зависимости, деплой…" autocomplete="off"><kbd>/</kbd></div></div>
<p id="search-status" role="status" aria-live="polite" hidden></p>
<article>{{content}}</article>
<footer><span>OKTP <b> / </b> Engineering documentation <b> / </b> <strong aria-label="Версия документации">v{{version}}</strong></span><span>Контент хранится в Markdown ↗</span></footer>
</main>
</div>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
:root{color-scheme:light;--ink:#243a35;--muted:#697973;--line:#e0e6df;--accent:#32694b;--paper:#fafbf7}*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:30px}body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.75 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}a{color:var(--accent);text-underline-offset:4px}aside{position:fixed;inset:0 auto 0 0;width:280px;background:#f0f3ec;border-right:1px solid var(--line);padding:36px 24px;display:flex;flex-direction:column}.brand{display:flex;align-items:center;gap:12px;text-decoration:none;color:var(--ink);font-size:23px;font-weight:750;letter-spacing:1px}.brand>b{display:grid;place-items:center;width:42px;height:44px;background:#244d3b;color:#fff;border-radius:11px;position:relative;font-size:29px}.brand>b span{position:absolute;font-size:16px;right:2px;top:-7px;color:#c6e6a3}.brand div>span{display:block;font-size:8px;letter-spacing:1.7px;color:var(--muted);font-weight:600}.workspace{margin:36px 0 38px;padding:12px 10px;border:1px solid #d8dfd3;border-radius:8px;font-size:11px;background:#f8faf4}.dot{display:inline-block;width:7px;height:7px;margin-right:7px;border-radius:50%;background:#7e8c76}.nav-label{font-size:10px;letter-spacing:1.7px;color:#73816d;margin:0 12px 13px}nav{display:grid;gap:6px;overflow:auto}nav a{padding:10px 12px;text-decoration:none;font-size:13px;border-radius:7px;color:#526158}nav a span{font-size:10px;color:#8a9684;margin-right:13px;font-family:monospace}nav a:hover,nav a[aria-current]{background:#e0e8d8;color:#264c35}.sidebar-footer{margin-top:auto;padding:28px 12px 0;color:#778371;font-size:11px}.sidebar-footer code{font-size:11px;color:#40573e}.file-icon{color:#4d7250}.page{margin-left:280px}header{height:82px;padding:0 54px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;font-size:12px;color:var(--muted)}header strong{font-weight:500;color:var(--ink)}header i{margin:0 14px;color:#a0aca1;font-style:normal}.badge{font-size:9px;letter-spacing:1.4px}.badge span{margin:0 8px}main{max-width:1140px;padding:56px 64px 20px;margin:auto}.eyebrow{color:#608153;font-size:10px;letter-spacing:2px;margin-bottom:25px}.eyebrow>span{display:inline-block;width:22px;height:2px;background:#759859;vertical-align:middle;margin-right:9px}h1{font-size:clamp(34px,4vw,56px);line-height:1.13;font-weight:620;letter-spacing:-2px;max-width:680px;margin:0 0 24px}article>p{font-size:16px;color:var(--muted);max-width:700px;margin-bottom:44px}section{scroll-margin-top:30px;padding:28px 0 24px;border-top:1px solid var(--line)}h2{font-size:26px;line-height:1.3;letter-spacing:-.7px;margin:0 0 22px;font-weight:620}h3{font-size:16px;margin:27px 0 12px;font-weight:650}p{margin:12px 0;color:#53645b}blockquote{margin:24px 0;padding:19px 24px;background:#edf2e5;border-left:3px solid #91a96c;border-radius:0 8px 8px 0;color:#526447;font-size:13px}li{padding:4px 0;color:#53645b}ol,ul{padding-left:23px}.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:10px;margin:20px 0;background:#fff}table{border-collapse:collapse;width:100%;font-size:13px;text-align:left}th{background:#f0f3eb;font-size:11px;font-weight:600;color:#637359}th,td{padding:14px 18px;border-bottom:1px solid var(--line);min-width:130px}tr:last-child td{border-bottom:0}td{color:#56635b}td:first-child{font-weight:550;color:#33483c}code{font:12px/1.7 ui-monospace,SFMono-Regular,Consolas,monospace;background:#edf0e8;padding:3px 6px;border-radius:4px;overflow-wrap:anywhere}pre{background:#20362d;color:#dbe8ce;padding:23px;border-radius:10px;overflow:auto}pre code{background:transparent;padding:0;color:inherit;overflow-wrap:normal}footer{border-top:1px solid var(--line);padding:26px 0;display:flex;justify-content:space-between;gap:14px;font-size:10px;color:#7b8779}footer b{margin:0 8px;font-weight:400}.search-box{margin:0 0 35px;max-width:440px}.search-box label{font-size:11px;color:var(--muted)}.search-box>div{display:flex;align-items:center;gap:12px;border:1px solid #d9e1d4;background:#fff;border-radius:9px;padding:8px 14px;margin-top:6px}.search-box span{font-size:24px;color:#809374}input{width:100%;border:0;background:none;font:13px system-ui;color:var(--ink);min-width:0;padding:5px 0}input:focus{outline:0}.search-box>div:focus-within{outline:2px solid #6d8b55;outline-offset:2px}kbd{font:11px monospace;border:1px solid var(--line);border-radius:4px;padding:0 6px;color:#819076}a:focus-visible,.table-wrap:focus-visible{outline:2px solid var(--accent);outline-offset:3px}.skip{position:fixed;top:-80px;left:20px;z-index:10;padding:10px;background:white}.skip:focus{top:10px}[hidden]{display:none!important}#search-status{padding:15px;background:#edf2e5;border-radius:8px}@media(min-width:1400px){main{padding-top:70px}}@media(max-width:1000px){aside{width:235px;padding:28px 16px}.page{margin-left:235px}main{padding:38px 30px}header{padding:0 30px}.badge{display:none}}@media(max-width:700px){aside{position:static;Line truncated