작업실(studio): 작품 검색·수정·커밋·되돌리기 화면 (로컬 8081)

This commit is contained in:
koreafood committed 2026-10-31 10:37:16 +09:00
1 parent 8248ba94d8
commit 6249317528
10 files changed
+1204 -1

No files matched your search

+545
View File
@@ -0,0 +1,545 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>한땀 작업실</title>
<style>
:root {
--paper: #f7f4ee;
--card: #fffdf9;
--ink: #1f1c18;
--muted: #7a726a;
--line: #ddd5c9;
--accent: #7c5c3e;
--ok: #2f6b47;
--warn: #a4471f;
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
background: var(--paper);
color: var(--ink);
font: 15px/1.55 -apple-system, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif;
display: flex;
flex-direction: column;
}
header.top {
display: flex;
align-items: baseline;
gap: 14px;
padding: 14px 20px;
border-bottom: 1px solid var(--line);
background: var(--card);
}
header.top h1 { font-size: 17px; margin: 0; letter-spacing: .08em; }
header.top .meta { color: var(--muted); font-size: 12.5px; }
header.top .spacer { flex: 1; }
main.split { display: flex; flex: 1; min-height: 0; }
/* ---------- 목록 ---------- */
aside.list {
width: 330px;
border-right: 1px solid var(--line);
display: flex;
flex-direction: column;
min-height: 0;
background: var(--card);
}
.search-wrap { padding: 12px 12px 8px; }
input[type=search], input[type=text], input[type=number], input[type=date], input[type=url], textarea, select {
width: 100%;
font: inherit;
color: inherit;
background: #fff;
border: 1px solid var(--line);
border-radius: 4px;
padding: 7px 9px;
}
input[type=search] { font-size: 14px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 12px 8px; }
.chip {
font-size: 12px;
padding: 3px 9px;
border: 1px solid var(--line);
border-radius: 999px;
background: #fff;
color: var(--muted);
cursor: pointer;
}
.chip[aria-pressed=true] { border-color: var(--accent); color: var(--accent); font-weight: 600; }
.listbar { display: flex; gap: 8px; align-items: center; padding: 0 12px 8px; }
.listbar select { width: auto; font-size: 12.5px; padding: 4px 6px; }
.listbar .count { font-size: 12px; color: var(--muted); margin-left: auto; }
ul.rows { list-style: none; margin: 0; padding: 0 6px 24px; overflow-y: auto; flex: 1; }
ul.rows li { padding: 0; margin: 0 0 2px; }
ul.rows button.row {
display: flex;
gap: 9px;
align-items: center;
width: 100%;
text-align: left;
background: none;
border: 0;
border-radius: 4px;
padding: 7px 8px;
cursor: pointer;
font: inherit;
color: inherit;
}
ul.rows button.row:hover { background: #f1ece2; }
ul.rows button.row[aria-current=true] { background: #ece4d5; outline: 1px solid var(--accent); }
.thumb {
width: 40px; height: 40px; flex: 0 0 40px;
object-fit: cover; border-radius: 3px;
background: #eee; border: 1px solid var(--line);
}
.row-main { min-width: 0; flex: 1; }
.row-title { font-size: 13.5px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row-sub { font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.badge {
font-size: 10.5px; padding: 1px 6px; border-radius: 3px;
border: 1px solid var(--line); color: var(--muted); white-space: nowrap;
}
.badge.sold { color: #fff; background: var(--warn); border-color: var(--warn); }
.badge.feat { color: var(--accent); border-color: var(--accent); }
.empty { padding: 20px 14px; color: var(--muted); font-size: 13px; }
/* ---------- 편집기 ---------- */
section.editor { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.editor-head {
display: flex; align-items: center; gap: 10px;
padding: 12px 20px; border-bottom: 1px solid var(--line);
}
.editor-head h2 { font-size: 15px; margin: 0; }
.editor-head code { font-size: 12px; color: var(--muted); background: #f2ece1; padding: 2px 6px; border-radius: 3px; }
.editor-body { overflow-y: auto; padding: 18px 20px 28px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 16px; }
.grid .wide { grid-column: 1 / -1; }
label.field { display: block; }
label.field > span.lbl { display: block; font-size: 12px; color: var(--muted); margin-bottom: 4px; }
label.field input[type=checkbox] { width: 15px; height: 15px; margin-right: 6px; vertical-align: -2px; }
.check-line { display: flex; align-items: center; gap: 4px; padding-top: 19px; }
textarea { resize: vertical; min-height: 90px; font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 13px; line-height: 1.6; }
.img-line { display: flex; gap: 8px; align-items: center; }
.img-line input { flex: 1; }
.img-preview { width: 52px; height: 52px; object-fit: cover; border: 1px solid var(--line); border-radius: 3px; background: #eee; }
.drop-hint { font-size: 11.5px; color: var(--muted); margin-top: 4px; }
.drop-hint.hot { color: var(--accent); font-weight: 600; }
.divider { height: 1px; background: var(--line); margin: 18px 0 14px; }
.section-label { font-size: 11.5px; letter-spacing: .12em; color: var(--muted); margin-bottom: 6px; }
footer.savebar {
display: flex; align-items: center; gap: 10px;
padding: 11px 20px; border-top: 1px solid var(--line); background: var(--card);
}
footer.savebar .state { font-size: 12.5px; color: var(--muted); }
footer.savebar .spacer { flex: 1; }
button {
font: inherit; cursor: pointer; border-radius: 4px;
border: 1px solid var(--line); background: #fff; color: inherit; padding: 7px 13px;
}
button:hover:not(:disabled) { border-color: var(--accent); }
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
button.primary:hover:not(:disabled) { background: #6a4d33; }
button:disabled { opacity: .45; cursor: default; }
button.ghost { background: none; border-color: transparent; color: var(--muted); }
button.ghost:hover { color: var(--accent); }
/* ---------- 이력 서랍 ---------- */
#drawer {
position: fixed; inset: 0; background: rgba(31, 28, 24, .28);
display: none; justify-content: flex-end; z-index: 40;
}
#drawer.open { display: flex; }
.drawer-panel {
width: min(460px, 92vw); background: var(--card); height: 100%;
border-left: 1px solid var(--line); display: flex; flex-direction: column;
}
.drawer-panel header {
display: flex; align-items: center; gap: 10px;
padding: 13px 16px; border-bottom: 1px solid var(--line);
}
.drawer-panel header h3 { font-size: 14px; margin: 0; }
.drawer-panel header .spacer { flex: 1; }
ul.commits { list-style: none; margin: 0; padding: 6px; overflow-y: auto; }
ul.commits li {
display: flex; gap: 10px; align-items: center;
padding: 8px 10px; border-bottom: 1px solid #f0eae0; font-size: 13px;
}
ul.commits .sha { font-family: ui-monospace, Menlo, monospace; font-size: 11.5px; color: var(--muted); }
ul.commits .subject { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
ul.commits .when { font-size: 11px; color: var(--muted); }
ul.commits button { padding: 3px 9px; font-size: 12px; }
/* ---------- 토스트 ---------- */
#toast {
position: fixed; left: 50%; bottom: 22px; transform: translateX(-50%) translateY(20px);
background: #241f19; color: #f7f4ee; padding: 10px 16px; border-radius: 5px;
font-size: 13px; max-width: min(720px, 92vw); opacity: 0; pointer-events: none;
transition: opacity .18s, transform .18s; z-index: 60; white-space: pre-wrap;
}
#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
#toast.err { background: #6d2410; }
#toast.ok { background: #1f4a33; }
.hint { font-size: 12px; color: var(--muted); }
kbd {
font: 11px ui-monospace, Menlo, monospace; border: 1px solid var(--line);
border-bottom-width: 2px; border-radius: 3px; padding: 0 4px; background: #fff;
}
</style>
</head>
<body>
<header class="top">
<h1>한땀 작업실</h1>
<span class="meta" id="topmeta">불러오는 중…</span>
<span class="spacer"></span>
<span class="hint"><kbd>/</kbd> 검색 · <kbd>↑↓</kbd> 이동 · <kbd>⌘S</kbd> 저장</span>
<button id="btnHistory" class="ghost">이력 / 되돌리기</button>
</header>
<main class="split">
<aside class="list">
<div class="search-wrap">
<input type="search" id="q" placeholder="제목 · 슬러그 · 소재 · 본문 검색" autocomplete="off">
</div>
<div class="chips" id="chips">
<button class="chip" data-f="all" aria-pressed="true">전체</button>
<button class="chip" data-f="on" aria-pressed="false">판매중</button>
<button class="chip" data-f="sold" aria-pressed="false">품절</button>
<button class="chip" data-f="feat" aria-pressed="false">대표작</button>
<button class="chip" data-f="year" aria-pressed="false">올해</button>
</div>
<div class="listbar">
<select id="sort">
<option value="modified">최근 수정</option>
<option value="date">날짜 최신</option>
<option value="title">이름</option>
<option value="price">가격</option>
</select>
<span class="count" id="rowcount"></span>
</div>
<ul class="rows" id="rows"></ul>
</aside>
<section class="editor">
<div class="editor-head">
<h2 id="edTitle">작품을 고르세요</h2>
<code id="edSlug"></code>
<span class="spacer"></span>
<span class="hint" id="edModified"></span>
</div>
<div class="editor-body" id="edBody">
<p class="empty">왼쪽 목록에서 작품을 고르면 여기서 바로 고칠 수 있습니다.</p>
</div>
<footer class="savebar">
<button id="btnSave" class="primary" disabled>저장 (커밋)</button>
<label class="hint" style="display:flex;align-items:center;gap:5px;">
<input type="checkbox" id="deployToo"> 배포까지
</label>
<span class="state" id="state">—</span>
<span class="spacer"></span>
<button id="btnReload" class="ghost" disabled>되돌리기(저장 전)</button>
</footer>
</section>
</main>
<div id="drawer">
<div class="drawer-panel">
<header>
<h3>최근 이력</h3>
<span class="spacer"></span>
<label class="hint" style="display:flex;align-items:center;gap:5px;">
<input type="checkbox" id="revertDeploy"> 되돌린 뒤 배포
</label>
<button class="ghost" id="btnCloseDrawer">닫기</button>
</header>
<ul class="commits" id="commits"></ul>
</div>
</div>
<div id="toast"></div>
<script>
const state = { rows: [], fields: [], current: null, dirty: false, filter: 'all', q: '', sort: 'modified' };
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
let toastTimer = null;
function toast(msg, kind = '') {
const el = $('toast');
el.textContent = msg;
el.className = 'show ' + kind;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { el.className = ''; }, kind === 'err' ? 7000 : 3200);
}
async function api(path, opts) {
const res = await fetch(path, opts);
try { return await res.json(); } catch (e) { return { ok: false, error: '응답을 읽을 수 없습니다 (' + res.status + ')' }; }
}
function markDirty(dirty) {
state.dirty = dirty;
$('state').textContent = dirty ? '저장하지 않은 변경' : '변경 없음';
$('btnSave').disabled = !state.current || !dirty;
}
/* ------------------------------------------------------------ 목록 */
function visibleRows() {
const q = state.q.trim().toLowerCase();
let rows = state.rows.filter((r) => {
if (state.filter === 'on' && r.sold_out) return false;
if (state.filter === 'sold' && !r.sold_out) return false;
if (state.filter === 'feat' && !r.featured) return false;
if (state.filter === 'year' && !String(r.date || '').startsWith(String(new Date().getFullYear()))) return false;
if (q && !(r.search || '').includes(q)) return false;
return true;
});
const k = state.sort;
rows.sort((a, b) => {
if (k === 'modified') return (b.mtime || 0) - (a.mtime || 0);
if (k === 'date') return String(b.date).localeCompare(String(a.date));
if (k === 'title') return String(a.title).localeCompare(String(b.title), 'ko');
if (k === 'price') return (b.price || 0) - (a.price || 0);
return 0;
});
return rows;
}
function renderList() {
const rows = visibleRows();
$('rowcount').textContent = rows.length + ' / ' + state.rows.length + '점';
const ul = $('rows');
if (!rows.length) {
ul.innerHTML = '<li class="empty">조건에 맞는 작품이 없습니다.</li>';
return;
}
ul.innerHTML = rows.map((r) => {
const active = state.current === r.slug;
const img = r.image ? '<img class="thumb" src="/media/' + encodeURI(r.image) + '" alt="" loading="lazy">' : '<span class="thumb"></span>';
const badges = [
r.sold_out ? '<span class="badge sold">품절</span>' : '',
r.featured ? '<span class="badge feat">대표</span>' : '',
].join('');
return '<li><button class="row" data-slug="' + esc(r.slug) + '" aria-current="' + active + '">' +
img +
'<span class="row-main"><span class="row-title">' + esc(r.title) + ' ' + badges + '</span>' +
'<span class="row-sub">' + esc(r.slug) + ' · ' + esc(r.date) + ' · ' + esc(r.modified) + '</span></span>' +
'</button></li>';
}).join('');
}
/* ------------------------------------------------------------ 편집기 */
function fieldHtml(f, value) {
const id = 'f_' + f.key;
const wide = ['image', 'image_alt', 'care', 'naver_url'].includes(f.key) ? ' wide' : '';
if (f.type === 'bool') {
return '<label class="field' + wide + '"><span class="check-line"><input type="checkbox" id="' + id + '" data-key="' + f.key + '"' +
(value ? ' checked' : '') + '> ' + esc(f.label) + '</span></label>';
}
if (f.type === 'lines') {
return '<label class="field wide"><span class="lbl">' + esc(f.label) + '</span>' +
'<textarea id="' + id + '" data-key="' + f.key + '" rows="3">' + esc(value) + '</textarea></label>';
}
if (f.type === 'image') {
return '<label class="field wide"><span class="lbl">' + esc(f.label) + '</span>' +
'<span class="img-line"><input type="text" id="' + id + '" data-key="' + f.key + '" value="' + esc(value) + '">' +
'<img class="img-preview" id="' + id + '_prev" src="' + (value ? '/media/' + encodeURI(value) : '') + '" alt="">' +
'<button type="button" class="ghost" id="' + id + '_pick">올리기</button></span>' +
'<span class="drop-hint" id="' + id + '_hint">JPG를 여기로 끌어다 놓아도 됩니다 (assets/img 에 저장)</span></label>';
}
const type = f.type === 'number' ? 'number' : (f.type === 'date' ? 'date' : (f.type === 'url' ? 'url' : 'text'));
return '<label class="field' + wide + '"><span class="lbl">' + esc(f.label) + '</span>' +
'<input type="' + type + '" id="' + id + '" data-key="' + f.key + '" value="' + esc(value) + '"></label>';
}
function renderEditor(p) {
const known = new Set(state.fields.map((f) => f.key));
const grid = state.fields.map((f) => fieldHtml(f, p.fields[f.key])).join('');
const extra = p.extra_keys.length
? '<p class="hint">이 파일에만 있는 키(보존됨): ' + p.extra_keys.map(esc).join(', ') + '</p>'
: '';
$('edBody').innerHTML =
'<div class="grid">' + grid + '</div>' +
'<div class="divider"></div>' +
'<div class="section-label">본문 (마크다운)</div>' +
'<textarea id="body" rows="14" style="min-height:240px">' + esc(p.body) + '</textarea>' +
'<p class="hint" style="margin-top:8px">문단은 빈 줄로 나눕니다. <code>## 제목</code>, <code>- 목록</code>, <code>![설명](assets/img/파일.jpg)</code> 지원.</p>' +
'<div style="margin-top:10px">' + extra + '</div>';
$('edTitle').textContent = p.fields.title || p.slug;
$('edSlug').textContent = p.slug;
$('edModified').textContent = '파일 수정 ' + p.modified;
$('btnReload').disabled = false;
wireEditor();
markDirty(false);
}
function wireEditor() {
document.querySelectorAll('[data-key]').forEach((el) => {
el.addEventListener('input', () => markDirty(true));
el.addEventListener('change', () => markDirty(true));
});
const img = $('f_image');
if (img) {
img.addEventListener('input', () => { $('f_image_prev').src = img.value ? '/media/' + encodeURI(img.value) : ''; });
$('f_image_pick').addEventListener('click', () => pickImage(img));
const hint = $('f_image_hint');
['dragenter', 'dragover'].forEach((ev) => hint.addEventListener(ev, (e) => { e.preventDefault(); hint.classList.add('hot'); }));
['dragleave', 'drop'].forEach((ev) => hint.addEventListener(ev, () => hint.classList.remove('hot')));
hint.addEventListener('drop', (e) => {
e.preventDefault();
const file = e.dataTransfer.files && e.dataTransfer.files[0];
if (file) uploadImage(file, img);
});
}
}
function pickImage(target) {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/jpeg';
input.addEventListener('change', () => { if (input.files[0]) uploadImage(input.files[0], target); });
input.click();
}
async function uploadImage(file, target) {
$('state').textContent = '이미지 올리는 중…';
const res = await fetch('/api/upload?name=' + encodeURIComponent(file.name), {
method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file,
});
const data = await res.json().catch(() => ({ ok: false, error: '업로드 실패' }));
if (!data.ok) { toast(data.error || '업로드 실패', 'err'); $('state').textContent = '—'; return; }
target.value = data.path;
target.dispatchEvent(new Event('input', { bubbles: true }));
target.dispatchEvent(new Event('change', { bubbles: true }));
toast('이미지 저장: ' + data.path, 'ok');
}
/* ------------------------------------------------------------ 열기/저장 */
async function openProduct(slug) {
if (state.dirty && !confirm('저장하지 않은 변경이 있습니다. 버리고 넘어갈까요?')) return;
const data = await api('/api/product?slug=' + encodeURIComponent(slug));
if (!data.ok) { toast(data.error || '작품을 열 수 없습니다', 'err'); return; }
state.current = slug;
renderList();
renderEditor(data.product);
$('state').textContent = '변경 없음';
}
function collect() {
const fields = {};
document.querySelectorAll('[data-key]').forEach((el) => {
fields[el.dataset.key] = el.type === 'checkbox' ? el.checked : el.value;
});
return { slug: state.current, fields, body: $('body').value, deploy: $('deployToo').checked };
}
async function save() {
if (!state.current) return;
const payload = collect();
$('btnSave').disabled = true;
$('state').textContent = '저장 중… (빌드 → 커밋)';
const data = await api('/api/product', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
});
if (!data.ok) {
$('state').textContent = '실패';
toast((data.error || '저장 실패') + (data.log ? '\n' + data.log : ''), 'err');
$('btnSave').disabled = false;
return;
}
markDirty(false);
const deployNote = data.deploy ? (data.deploy.ok ? ' / 배포 OK' : ' / 배포 실패') : '';
toast(data.message + (data.commit ? ' · ' + data.commit : '') + deployNote + (data.log ? '\n' + data.log : ''), data.deploy && !data.deploy.ok ? 'err' : 'ok');
await refresh({ keep: true });
}
async function refresh(opts = {}) {
const data = await api('/api/state');
if (!data.ok) { toast('상태를 읽지 못했습니다', 'err'); return; }
state.rows = data.products;
state.fields = data.fields;
$('topmeta').textContent = data.count + '점 · HEAD ' + data.head + ' · ' + data.repo;
renderList();
if (!opts.keep) {
const wanted = new URLSearchParams(location.search).get('slug');
if (wanted) openProduct(wanted);
}
}
/* ------------------------------------------------------------ 이력 */
async function openHistory() {
const data = await api('/api/history');
if (!data.ok) { toast('이력을 읽지 못했습니다', 'err'); return; }
$('commits').innerHTML = data.history.map((c) =>
'<li><span class="sha">' + esc(c.sha) + '</span>' +
'<span class="subject" title="' + esc(c.subject) + '">' + esc(c.subject) + '</span>' +
'<span class="when">' + esc(c.date) + '</span>' +
'<button data-revert="' + esc(c.sha) + '">되돌리기</button></li>'
).join('');
$('drawer').classList.add('open');
}
async function revertTo(sha, btn) {
if (!confirm(sha + ' 커밋을 되돌립니다(새 커밋으로 취소). 계속할까요?')) return;
if (btn) btn.disabled = true;
const data = await api('/api/revert', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sha, deploy: $('revertDeploy').checked }),
});
toast(data.ok ? data.message : ((data.error || '실패') + (data.log ? '\n' + data.log : '')), data.ok ? 'ok' : 'err');
if (data.ok) {
await refresh({ keep: true });
if (state.current) { const p = await api('/api/product?slug=' + encodeURIComponent(state.current)); if (p.ok) renderEditor(p.product); }
openHistory();
} else if (btn) btn.disabled = false;
}
/* ------------------------------------------------------------ 이벤트 */
$('q').addEventListener('input', (e) => { state.q = e.target.value; renderList(); });
$('sort').addEventListener('change', (e) => { state.sort = e.target.value; renderList(); });
$('chips').addEventListener('click', (e) => {
const chip = e.target.closest('.chip');
if (!chip) return;
state.filter = chip.dataset.f;
document.querySelectorAll('.chip').forEach((c) => c.setAttribute('aria-pressed', String(c === chip)));
renderList();
});
$('rows').addEventListener('click', (e) => {
const btn = e.target.closest('button.row');
if (btn) openProduct(btn.dataset.slug);
});
$('btnSave').addEventListener('click', save);
$('btnReload').addEventListener('click', () => { if (state.current) openProduct(state.current); });
$('btnHistory').addEventListener('click', openHistory);
$('btnCloseDrawer').addEventListener('click', () => $('drawer').classList.remove('open'));
$('drawer').addEventListener('click', (e) => { if (e.target.id === 'drawer') $('drawer').classList.remove('open'); });
$('commits').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-revert]');
if (btn) revertTo(btn.dataset.revert, btn);
});
document.addEventListener('keydown', (e) => {
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName);
if (e.key === '/' && !typing) { e.preventDefault(); $('q').focus(); return; }
if (e.key === 'Escape') { $('drawer').classList.remove('open'); return; }
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); save(); return; }
if (!typing && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
const rows = visibleRows();
if (!rows.length) return;
e.preventDefault();
let idx = rows.findIndex((r) => r.slug === state.current);
idx = e.key === 'ArrowDown' ? Math.min(rows.length - 1, idx + 1) : Math.max(0, idx - 1);
openProduct(rows[idx].slug);
const el = document.querySelector('button.row[data-slug="' + rows[idx].slug + '"]');
if (el) el.scrollIntoView({ block: 'nearest' });
}
});
window.addEventListener('beforeunload', (e) => { if (state.dirty) { e.preventDefault(); e.returnValue = ''; } });
refresh();
</script>
</body>
</html>
+493
View File
@@ -0,0 +1,493 @@
#!/usr/bin/env python3
"""한땀 작업실(studio) — 작품 md를 화면에서 찾아 고치는 로컬 관리 서버.
- 표준 라이브러리만 쓴다. 항상 127.0.0.1 에만 붙는다.
- 저장 = md 파일 쓰기 -> build.py -> git commit (실패하면 원본 복원)
- 이력 = git log, 되돌리기 = git revert -> 재빌드 -> (선택) 배포
실행: python3 studio/server.py [--port 8081] [--deploy-on-save]
"""
from __future__ import annotations
import argparse
import json
import mimetypes
import re
import subprocess
import sys
import urllib.parse
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Tuple
BASE = Path(__file__).resolve().parent
ROOT = BASE.parent
PRODUCTS = ROOT / "content" / "products"
ASSETS = ROOT / "assets"
APP = BASE / "app.html"
LIST_KEYS = {"gallery"}
# 폼에 노출할 필드와 순서. 여기 없는 키도 파일에 있으면 보존한다.
FIELDS: List[Dict[str, str]] = [
{"key": "title", "label": "제목", "type": "text"},
{"key": "subtitle", "label": "부제", "type": "text"},
{"key": "date", "label": "날짜", "type": "date"},
{"key": "price", "label": "가격(원)", "type": "number"},
{"key": "sold_out", "label": "품절 표시", "type": "bool"},
{"key": "featured", "label": "첫 페이지 대표작", "type": "bool"},
{"key": "image", "label": "대표 이미지", "type": "image"},
{"key": "image_alt", "label": "이미지 설명(alt)", "type": "text"},
{"key": "material", "label": "소재", "type": "text"},
{"key": "size", "label": "규격", "type": "text"},
{"key": "care", "label": "세탁", "type": "text"},
{"key": "naver_url", "label": "네이버 링크", "type": "url"},
{"key": "gallery", "label": "추가 이미지(한 줄에 하나)", "type": "lines"},
]
# ------------------------------------------------------------------ front matter
def split_front(raw: str) -> Tuple[List[str], str]:
if not raw.startswith("---"):
raise ValueError("front matter 가 없습니다")
parts = raw.split("---", 2)
if len(parts) != 3:
raise ValueError("front matter 가 닫히지 않았습니다")
return parts[1].strip("\n").splitlines(), parts[2].lstrip("\n")
def parse_value(text: str) -> Any:
value = text.strip()
if value in ("true", "false"):
return value == "true"
if value in ("", '""', "''"):
return ""
if re.fullmatch(r"-?\d+", value):
return int(value)
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
return value[1:-1]
return value
def parse_front(lines: List[str]) -> Tuple[List[str], Dict[str, Any]]:
order: List[str] = []
data: Dict[str, Any] = {}
current = None
for line in lines:
if not line.strip() or line.lstrip().startswith("#"):
continue
stripped = line.strip()
if stripped.startswith("- ") and current:
if not isinstance(data.get(current), list):
data[current] = []
data[current].append(parse_value(stripped[2:]))
continue
if ":" not in line:
continue
key, value = line.split(":", 1)
key, value = key.strip(), value.strip()
if key not in data:
order.append(key)
if value == "":
data[key] = ""
current = key
else:
data[key] = parse_value(value)
current = None
return order, data
def render_value(value: Any) -> str:
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, int):
return str(value)
text = str(value)
if text == "":
return '""'
needs_quote = (
text != text.strip()
or text.startswith(('"', "'", "-", "[", "{", "*", "&", "!", "|", ">", "%", "@", "`"))
or ": " in text
or text.endswith(":")
or " #" in text
)
if needs_quote:
return '"' + text.replace('"', "'") + '"'
return text
def as_list(value: Any) -> List[str]:
if isinstance(value, list):
return [str(item) for item in value]
text = str(value or "")
return [line.strip() for line in text.splitlines() if line.strip()]
def assemble(order: List[str], data: Dict[str, Any], body: str) -> str:
out = ["---"]
for key in order:
value = data.get(key, "")
if key in LIST_KEYS:
items = as_list(value)
out.append(f"{key}:")
out.extend(f"- {item}" for item in items)
elif isinstance(value, bool):
out.append(f"{key}: {'true' if value else 'false'}")
elif value == "" or value is None:
out.append(f'{key}: ""')
else:
out.append(f"{key}: {render_value(value)}")
out.append("---")
text = body.strip("\n")
return "\n".join(out) + "\n" + text + "\n"
# ----------------------------------------------------------------------- git/shell
def run(args: List[str], timeout: int = 120) -> Tuple[bool, str]:
try:
proc = subprocess.run(args, cwd=str(ROOT), capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return False, f"시간 초과: {' '.join(args)}"
log = (proc.stdout or "") + (proc.stderr or "")
return proc.returncode == 0, log.strip()
def git(*args: str) -> Tuple[bool, str]:
return run(["git", *args], timeout=60)
def head_sha() -> str:
ok, out = git("rev-parse", "--short", "HEAD")
return out.strip() if ok else "?"
def git_commit(message: str, paths: List[str]) -> Tuple[bool, str]:
"""지정한 경로만 스테이징해서 커밋한다(무관한 변경이 섞이지 않도록)."""
git("add", "--", *paths)
ok, staged = git("diff", "--cached", "--name-only", "--", *paths)
if not staged.strip():
return False, "스테이징된 변경 없음"
ok, out = git("commit", "-m", message, "--", *paths)
return ok, out.splitlines()[-1] if out else ""
def history(limit: int = 20) -> List[Dict[str, str]]:
ok, out = git("log", f"-n{limit}", "--date=format:%Y-%m-%d %H:%M", "--pretty=format:%h\x1f%ad\x1f%s")
if not ok:
return []
rows = []
for line in out.splitlines():
parts = line.split("\x1f")
if len(parts) == 3:
rows.append({"sha": parts[0], "date": parts[1], "subject": parts[2]})
return rows
def build() -> Tuple[bool, str]:
return run([sys.executable, "build.py"], timeout=180)
def deploy() -> Tuple[bool, str]:
return run(["bash", "scripts/deploy.sh"], timeout=300)
# -------------------------------------------------------------------- products io
def product_path(slug: str) -> Path:
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", slug or ""):
raise ValueError("슬러그가 올바르지 않습니다")
path = PRODUCTS / f"{slug}.md"
if not path.is_file():
raise FileNotFoundError(f"작품 파일이 없습니다: {slug}.md")
return path
def summaries() -> List[Dict[str, Any]]:
rows: List[Dict[str, Any]] = []
for path in sorted(PRODUCTS.glob("*.md")):
raw = path.read_text(encoding="utf-8")
try:
lines, body = split_front(raw)
order, data = parse_front(lines)
except ValueError:
rows.append({"slug": path.stem, "title": f"{path.stem} (읽기 오류)", "broken": True})
continue
rows.append(
{
"slug": str(data.get("slug") or path.stem),
"title": str(data.get("title") or path.stem),
"subtitle": str(data.get("subtitle") or ""),
"date": str(data.get("date") or ""),
"price": data.get("price") if isinstance(data.get("price"), int) else 0,
"sold_out": bool(data.get("sold_out")),
"featured": bool(data.get("featured")),
"image": str(data.get("image") or ""),
"material": str(data.get("material") or ""),
"size": str(data.get("size") or ""),
"search": " ".join([str(data.get("title") or ""), path.stem, str(data.get("material") or ""), str(data.get("size") or ""), body]).lower(),
"modified": datetime.fromtimestamp(path.stat().st_mtime).strftime("%m-%d %H:%M"),
"mtime": path.stat().st_mtime,
}
)
return rows
def load_product(slug: str) -> Dict[str, Any]:
path = product_path(slug)
lines, body = split_front(path.read_text(encoding="utf-8"))
order, data = parse_front(lines)
values = {}
for field in FIELDS:
key = field["key"]
raw = data.get(key, "")
if field["type"] == "bool":
values[key] = bool(raw) if not isinstance(raw, str) else raw == "true"
elif field["type"] == "number":
values[key] = raw if isinstance(raw, int) else ""
elif field["type"] == "lines":
values[key] = "\n".join(as_list(raw))
else:
values[key] = "" if raw is None else str(raw)
return {
"slug": slug,
"fields": values,
"body": body,
"raw": path.read_text(encoding="utf-8"),
"extra_keys": [key for key in order if key not in {f["key"] for f in FIELDS} and key != "slug"],
"modified": datetime.fromtimestamp(path.stat().st_mtime).strftime("%Y-%m-%d %H:%M"),
}
def coerce(field: Dict[str, str], value: Any) -> Any:
kind = field["type"]
if kind == "bool":
return bool(value)
if kind == "number":
text = str(value).strip()
return int(text) if re.fullmatch(r"-?\d+", text) else ""
if kind == "lines":
return as_list(value)
return str(value if value is not None else "").strip()
def save_product(payload: Dict[str, Any]) -> Dict[str, Any]:
slug = str(payload.get("slug", ""))
path = product_path(slug)
original = path.read_text(encoding="utf-8")
lines, old_body = split_front(original)
order, data = parse_front(lines)
incoming = payload.get("fields") or {}
for field in FIELDS:
key = field["key"]
if key in incoming:
value = coerce(field, incoming[key])
if key not in order:
order.append(key)
data[key] = value
body = str(payload.get("body", old_body))
updated = assemble(order, data, body)
if updated == original:
return {"ok": True, "changed": False, "message": "변경된 내용이 없습니다", "head": head_sha()}
path.write_text(updated, encoding="utf-8")
built, build_log = build()
if not built:
path.write_text(original, encoding="utf-8")
return {"ok": False, "stage": "build", "error": "빌드 실패 — 저장을 취소하고 원본을 되돌렸습니다", "log": build_log}
committed, commit_log = git_commit(f"작품 수정: {data.get('title') or slug}", [str(path.relative_to(ROOT))])
if not committed:
return {"ok": False, "stage": "git", "error": "git 커밋 실패 (파일은 저장됨)", "log": commit_log}
result: Dict[str, Any] = {
"ok": True,
"changed": True,
"message": "저장 · 커밋 완료",
"head": head_sha(),
"commit": commit_log,
"log": build_log,
}
if payload.get("deploy"):
deployed, deploy_log = deploy()
result["deploy"] = {"ok": deployed, "log": deploy_log}
result["message"] = "저장 · 커밋 · 배포 완료" if deployed else "저장 · 커밋 완료 (배포 실패)"
return result
def revert(sha: str, redeploy: bool) -> Dict[str, Any]:
if not re.fullmatch(r"[0-9a-f]{4,40}", sha or ""):
return {"ok": False, "error": "커밋 해시가 올바르지 않습니다"}
ok, log = git("revert", "--no-edit", sha)
if not ok:
git("revert", "--abort")
return {"ok": False, "error": "되돌리기 실패", "log": log}
built, build_log = build()
if not built:
return {"ok": False, "error": "되돌린 뒤 빌드 실패", "log": build_log}
result: Dict[str, Any] = {"ok": True, "message": f"{sha} 되돌림", "head": head_sha(), "log": build_log}
if redeploy:
deployed, deploy_log = deploy()
result["deploy"] = {"ok": deployed, "log": deploy_log}
result["message"] += " · 배포 완료" if deployed else " (배포 실패)"
return result
def upload_image(name: str, data: bytes) -> Dict[str, Any]:
if not data:
return {"ok": False, "error": "이미지 데이터가 비었습니다"}
ext = Path(name).suffix.lower()
if ext not in (".jpg", ".jpeg"):
return {"ok": False, "error": "JPG만 올릴 수 있습니다 (사이트가 JPEG 크기를 읽습니다)"}
stem = re.sub(r"[^a-z0-9-]+", "-", Path(name).stem.lower()).strip("-") or "image"
target_dir = ASSETS / "img"
target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / f"{stem}{ext}"
counter = 2
while target.exists():
target = target_dir / f"{stem}-{counter}{ext}"
counter += 1
target.write_bytes(data)
return {"ok": True, "path": f"assets/img/{target.name}", "bytes": len(data)}
# ------------------------------------------------------------------------ server
class Handler(BaseHTTPRequestHandler):
server_version = "hanttam-studio"
protocol_version = "HTTP/1.1"
def log_message(self, fmt: str, *args: Any) -> None:
pass
# -- helpers ---------------------------------------------------------
def send_body(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8") -> None:
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def send_json(self, obj: Any, code: int = 200) -> None:
self.send_body(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"))
def read_json(self) -> Dict[str, Any]:
length = int(self.headers.get("Content-Length") or 0)
if not length:
return {}
try:
return json.loads(self.rfile.read(length).decode("utf-8"))
except json.JSONDecodeError:
return {}
# -- GET -------------------------------------------------------------
def do_GET(self) -> None:
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
query = urllib.parse.parse_qs(parsed.query)
if path in ("/", "/index.html"):
self.send_body(200, APP.read_bytes(), "text/html; charset=utf-8")
return
if path == "/api/state":
rows = summaries()
self.send_json(
{
"ok": True,
"products": rows,
"count": len(rows),
"head": head_sha(),
"history": history(8),
"fields": FIELDS,
"repo": str(ROOT),
}
)
return
if path == "/api/product":
slug = (query.get("slug") or [""])[0]
try:
self.send_json({"ok": True, "product": load_product(slug)})
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400)
return
if path == "/api/history":
self.send_json({"ok": True, "history": history(25), "head": head_sha()})
return
if path.startswith("/media/"):
rel = urllib.parse.unquote(path[len("/media/"):])
target = (ROOT / rel).resolve()
try:
target.relative_to(ASSETS.resolve())
except ValueError:
self.send_json({"ok": False, "error": "허용되지 않은 경로"}, 403)
return
if not target.is_file():
self.send_json({"ok": False, "error": "파일 없음"}, 404)
return
ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
self.send_body(200, target.read_bytes(), ctype)
return
self.send_json({"ok": False, "error": "없는 경로"}, 404)
# -- POST ------------------------------------------------------------
def do_POST(self) -> None:
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
query = urllib.parse.parse_qs(parsed.query)
if path == "/api/product":
try:
self.send_json(save_product(self.read_json()))
except FileNotFoundError as error:
self.send_json({"ok": False, "error": str(error)}, 404)
except ValueError as error:
self.send_json({"ok": False, "error": str(error)}, 400)
return
if path == "/api/revert":
payload = self.read_json()
self.send_json(revert(str(payload.get("sha", "")), bool(payload.get("deploy"))))
return
if path == "/api/upload":
name = (query.get("name") or ["image.jpg"])[0]
length = int(self.headers.get("Content-Length") or 0)
data = self.rfile.read(length) if length else b""
self.send_json(upload_image(name, data))
return
if path == "/api/build":
ok, log = build()
self.send_json({"ok": ok, "log": log, "head": head_sha()})
return
self.send_json({"ok": False, "error": "없는 경로"}, 404)
def main() -> None:
parser = argparse.ArgumentParser(description="한땀 작업실")
parser.add_argument("--port", type=int, default=8081)
parser.add_argument("--host", default="127.0.0.1")
args = parser.parse_args()
if not PRODUCTS.is_dir():
raise SystemExit(f"작품 폴더가 없습니다: {PRODUCTS}")
server = ThreadingHTTPServer((args.host, args.port), Handler)
print(f"한땀 작업실: http://{args.host}:{args.port} (repo {ROOT})")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n종료")
if __name__ == "__main__":
main()
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""한땀 작업실 API 스모크 테스트 — 저장·커밋·되돌리기 왕복 검증."""
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
BASE = "http://127.0.0.1:8081"
ROOT = Path.home() / "Projects/teamat"
SLUG = "whitework-tea-mat"
MD = ROOT / "content/products" / f"{SLUG}.md"
fails = []
def check(name, cond, extra=""):
print(("OK " if cond else "FAIL ") + name + (f" {extra}" if extra and not cond else ""))
if not cond:
fails.append(name)
def req(path, payload=None, raw=None, method=None):
url = BASE + path
data = None
headers = {}
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
if raw is not None:
data = raw
headers["Content-Type"] = "application/octet-stream"
request = urllib.request.Request(url, data=data, headers=headers, method=method or ("POST" if data else "GET"))
try:
with urllib.request.urlopen(request, timeout=120) as res:
return res.status, json.loads(res.read().decode())
except urllib.error.HTTPError as error:
body = error.read().decode()
try:
return error.code, json.loads(body)
except json.JSONDecodeError:
return error.code, {"raw": body}
original = MD.read_text(encoding="utf-8")
# 1. 목록
code, state = req("/api/state")
check("GET /api/state", code == 200 and state["ok"] and state["count"] >= 3, str(code))
head0 = state["head"]
# 2. 작품 열기
code, data = req(f"/api/product?slug={SLUG}")
check("GET /api/product", code == 200 and data["product"]["fields"]["title"] == "목련 한 땀 티매트", str(code))
fields0 = data["product"]["fields"]
body0 = data["product"]["body"]
check("본문 읽힘", len(body0) > 50)
check("추가 이미지 필드(빈 목록)", fields0["gallery"] == "")
# 3. 변경 없이 저장 → 커밋하지 않아야 함
code, data = req("/api/product", {"slug": SLUG, "fields": fields0, "body": body0})
check("무변경 저장은 커밋 안 함", data["ok"] and data["changed"] is False, json.dumps(data)[:200])
# 4. 실제 수정 저장 (+ 추가 이미지 1장)
fields = dict(fields0)
fields["subtitle"] = "스모크 테스트 부제"
fields["price"] = "59000"
fields["gallery"] = "assets/img/work-whitework.jpg"
code, data = req("/api/product", {"slug": SLUG, "fields": fields, "body": body0})
check("수정 저장 성공", data["ok"] and data.get("changed") is True, json.dumps(data)[:300])
sha = data.get("head", "")
check("HEAD 이동", sha != head0, f"{head0} -> {sha}")
text = MD.read_text(encoding="utf-8")
check("파일 반영(subtitle)", "subtitle: 스모크 테스트 부제" in text)
check("파일 반영(price 정수)", "price: 59000" in text, text[:400])
check("목록 형식 유지(gallery)", "gallery:\n- assets/img/work-whitework.jpg" in text, text[:600])
check("front matter 순서 유지", text.splitlines()[1].startswith("slug:"), text.splitlines()[1])
code, data = req("/api/history")
check("이력에 수정 커밋", any("목련 한 땀 티매트" in row["subject"] for row in data["history"]), str(data["history"][:2]))
# 5. 이미지 업로드 거부 (JPG 아님)
code, data = req("/api/upload?name=x.png", raw=b"\x89PNG\r\n")
check("PNG 업로드 거부", data["ok"] is False, json.dumps(data))
# 6. 잘못된 슬러그
code, data = req("/api/product?slug=../../etc/passwd")
check("경로 조작 차단", code in (400, 404), str(code))
# 7. 되돌리기
code, data = req("/api/revert", {"sha": sha, "deploy": False})
check("되돌리기 성공", data["ok"] is True, json.dumps(data)[:300])
check("파일 원복", MD.read_text(encoding="utf-8") == original, "원본과 다름")
# 8. 되돌린 뒤 무변경 저장은 다시 커밋하지 않아야 함
code, data = req(f"/api/product?slug={SLUG}")
code, again = req("/api/product", {"slug": SLUG, "fields": data["product"]["fields"], "body": data["product"]["body"]})
check("원복 후 무변경", again["ok"] and again["changed"] is False, json.dumps(again)[:200])
print()
print(f"{'실패 ' + str(len(fails)) + '건: ' + ', '.join(fails) if fails else '전부 통과'}")
sys.exit(1 if fails else 0)