Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
cr1ma committed Oct 10, 2024
0 parents commit 974faf3
Show file tree
Hide file tree
Showing 7 changed files with 547 additions and 0 deletions.
43 changes: 43 additions & 0 deletions .github/workflows/static.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Simple workflow for deploying static content to GitHub Pages
name: Deploy static content to Pages

on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false

jobs:
# Single deploy job since we're just deploying
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
# Upload entire repository
path: '.'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 cr1ma

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# NeuroCommit

NeuroCommit - це веб-інструмент, який допомагає розробникам створювати якісні повідомлення для комітів на основі виводу команди `git diff`. Цей інструмент перетворює технічні зміни у зрозумілі та інформативні повідомлення для комітів, які можна використовувати з нейромережами для подальшого покращення.

Спробуйте NeuroCommit зараз: [https://cr1ma.github.io/neuro-commit/](https://cr1ma.github.io/neuro-commit/)

## Особливості

- Перетворення виводу `git diff` у структурований промт для нейромережі
- Інтуїтивно зрозумілий веб-інтерфейс
- Підсвічування синтаксису для diff
- Можливість копіювання згенерованого промту одним кліком

## Як використовувати

1. Відкрийте термінал у вашому Git-репозиторії.
2. Виконайте команду `git diff` для перегляду змін у робочій директорії:
```
git diff
```
Або використовуйте `git diff --staged` для перегляду змін у індексі (staged changes):
```
git add .
git diff --staged
```
3. Скопіюйте вивід команди.
4. Відкрийте [https://cr1ma.github.io/neuro-commit/](https://cr1ma.github.io/neuro-commit/) у вашому браузері.
5. Вставте скопійований diff у ліве текстове поле.
6. Справа з'явиться згенерований промт для нейромережі.
7. Натисніть кнопку "Скопіювати промт", щоб скопіювати згенерований текст.
8. Використовуйте цей промт з вашою улюбленою нейромережею для генерації повідомлення коміту.

## Ліцензія

Цей проект розповсюджується під ліцензією MIT. Дивіться файл `LICENSE` для отримання додаткової інформації.
36 changes: 36 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<title>NeuroCommit</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<header>
<h1>NeuroCommit</h1>
<p>Перетворіть свій <code>git diff</code> у готовий промт для нейромережі та зробіть свій коміт кращим!</p>
</header>
<main>
<div class="split left">
<h2>Вивід команди git diff</h2>
<textarea id="gitDiffInput" placeholder="Вставте сюди результат команди git diff..."></textarea>
</div>
<div class="split right">
<h2>Згенерований промт для нейромережі</h2>
<div class="prompt-container">
<pre id="promptOutput" class="prompt"></pre>
</div>
<button id="copyButton">Скопіювати промт</button>
</div>
</main>
<footer>
<p><a href="https://github.com/cr1ma/neuro-commit" target="_blank">Приєднуйтесь до розробки на GitHub</a></p>
</footer>
</div>
<div id="toast" class="toast"></div>
<script src="script.js"></script>
</body>
</html>
32 changes: 32 additions & 0 deletions prompt.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
Ти експерт з написання повідомлень до комітів у репозиторіях. Твоє завдання — написати мені повідомлення до коміту на основі мого файлу змін (diff), який я тобі надам.

### Правила написання повідомлення до коміту:
1. Пиши на українській мові, строго враховуючи контекст.
2. Відповідь повертай з використанням розмітки markdown.
3. Використовуй імперативний стиль, як би ти давав команду системі, що відповідає стилю повідомлень, які створюють зміни в коді.
4. Перша строка повідомлення (заголовок) має бути короткою, зазвичай не довше 50 символів. Це полегшує швидке розуміння змін. Не завершуй заголовок крапкою.
5. Після заголовка залишай одну порожню строку перед початком тіла повідомлення. Це розділення допомагає інструментам для роботи з Git правильно відображати текст повідомлення.
6. Коміти з повідомленнями на кшталт "Fix" або "Update" не дають корисної інформації. Завжди пояснюй, що саме було виправлено або оновлено.
7. **Використовуй нижній регістр для опису типів змін. Використовуй** семантичні теги в заголовках повідомлень:
- `feat:` — додавання нової функції
- `fix:` — виправлення багів
- `docs:` — зміни в документації
- `style:` — зміни, що не впливають на код (наприклад, виправлення форматування)
- `refactor:` — зміна коду, яка не додає нової функціональності і не виправляє багів
- `test:` — додавання або зміна тестів

### Приклад правильного повідомлення до коміту:
```diff
refactor: оновлено конфігурацію середовища та підключення до API

- Відредаговано файл `.env` для підтримки різних середовищ (production, development) та режимів підключення до API (docker, local, remote).
- Оновлено `config.py` для завантаження токенів та URL-адрес залежно від середовища та режиму API.
- Видалено логіку визначення операційної системи.
- Оновлено `api_client.py` для використання BASE_API_URL замість URL-адрес для різних ОС.
- Зменшено кількість повторних спроб у `_make_request`.
```

### Вивід команди `git diff`, яку я виконав у своєму репозиторії:
```diff
<diff>
```
105 changes: 105 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Вибираємо елементи для подальшої роботи
const gitDiffInput = document.getElementById('gitDiffInput');
const promptOutput = document.getElementById('promptOutput');
const copyButton = document.getElementById('copyButton');
const toast = document.getElementById('toast');

let promptTemplate = '';

// Завантажуємо шаблон промпту з файлу prompt.txt
fetch('prompt.txt')
.then(response => response.text())
.then(data => {
promptTemplate = data;
})
.catch(error => {
console.error('Помилка завантаження промпту:', error);
});

// Функція для екранування HTML, щоб уникнути XSS атак
function escapeHTML(str) {
return str.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}

// Функція для підсвічування рядків у git diff
function highlightDiff(diff) {
const lines = diff.split('\n');
return lines.map(line => {
if (line.startsWith('+')) {
return `<span class="addition">${escapeHTML(line)}</span>`;
} else if (line.startsWith('-')) {
return `<span class="deletion">${escapeHTML(line)}</span>`;
} else {
return escapeHTML(line);
}
}).join('\n');
}

// Функція для очищення введеного користувачем git diff для GitHub Copilot
function sanitizeInput(input) {
const wordsToSanitize = [
'@workspace', '/explain', '/tests', '/fix', '/new', '/newNotebook', '/fixTestFailure', '/setupTests',
'@vscode', '/search', '/runCommand', '/startDebugging',
'@terminal', '@github', '#selection', '/help', '#codebase', '#editor', '#terminalLastCommand', '#terminalSelection', '#file'
];

let sanitized = input;
wordsToSanitize.forEach(word => {
const regex = new RegExp(word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
sanitized = sanitized.replace(regex, word.startsWith('/') ? word.slice(1) : word);
});

return sanitized;
}

// Функція для оновлення промпту на основі введеного користувачем git diff
function updatePrompt() {
const gitDiff = gitDiffInput.value.trim();
if (gitDiff === "") {
promptOutput.innerHTML = "";
return;
}
const sanitizedDiff = sanitizeInput(gitDiff);
const highlightedDiff = highlightDiff(sanitizedDiff);
const filledPrompt = promptTemplate.replace("<diff>", highlightedDiff);
promptOutput.innerHTML = filledPrompt;
}

// Слідкуємо за змінами у полі введення і автоматично оновлюємо промт
gitDiffInput.addEventListener('input', updatePrompt);

// Функція для показу сповіщення (toast) на екрані
function showToast(message, type = 'success') {
toast.className = 'toast';

if (type === 'success') {
toast.classList.add('success');
} else if (type === 'error') {
toast.classList.add('error');
} else if (type === 'info') {
toast.classList.add('info');
}

toast.innerHTML = message;
toast.classList.add('show');

setTimeout(() => {
toast.classList.remove('show');
toast.classList.add('hide');
}, 3500);
}

// Обробляємо натискання кнопки "Скопіювати промт"
copyButton.addEventListener('click', async () => {
const textToCopy = promptOutput.textContent;

try {
await navigator.clipboard.writeText(textToCopy);
showToast('Промт успішно скопійовано в буфер обміну!', 'success');
} catch (err) {
console.error('Не вдалося скопіювати текст: ', err);
showToast('Не вдалося скопіювати промт.', 'error');
}
});
Loading

0 comments on commit 974faf3

Please sign in to comment.