SVCS - Русская документация
Загрузка...
Поиск...
Не найдено
RepositoryManager.hxx
См. документацию.
1
20
21#pragma once
22
24
25#include <optional>
26#include <string>
27#include <filesystem>
28#include <vector>
29#include <memory>
30
38 * @russian
39 * @namespace svcs::core
40 * @brief Основные структуры данных СКВ и модель объектов.
41 * @details Содержит фундаментальные типы объектов СКВ, такие как Blob, Tree, Commit,
42 * которые формируют строительные блоки системы контроля версий.
43 */
44namespace svcs::core {
45
46using namespace svcs::services;
57struct CommitInfo {
65 std::string hash;
66
69
74 std::string message;
75
78 * @brief The count of files included in this commit.
79 *
80 * @russian
81 * @brief Количество файлов, включенных в этот коммит.
82 */
83 int files_count = 0;
84
92 std::string author;
93
101 std::string timestamp;
102
110 std::string branch;
111};
112
128class RepositoryManager {
129private:
137 std::string currentRepoPath;
138
146 std::shared_ptr<ISubject> eventBus;
147
148 // --- Private Utility Methods for Logging / Приватные служебные методы для логирования ---
149
159 void logError(const std::string& message) const;
160
170 void logDebug(const std::string& message) const;
171
181 void logInfo(const std::string& message) const;
182
183 // --- Private Utility Methods for File System Operations / Приватные служебные методы для операций с файловой системой ---
184
196 bool createDirectory(const std::filesystem::path& path) const;
197
211 bool createFile(const std::filesystem::path& path, const std::string& content = "") const;
212
222 std::string getCurrentBranchFromHead() const;
223
224public:
234 explicit RepositoryManager(std::shared_ptr<ISubject> bus);
235
245 void updateHead(const std::string& commit_hash) const;
246
262 bool initializeRepository(const std::string& path, bool force = false);
263
275 bool isRepositoryInitialized(const std::string& path = ".");
276
288 void updateBranchReference(const std::string& branchName, const std::string& commitHash) const;
289
299 [[nodiscard]] std::filesystem::path getRepositoryPath() const;
300
301 // --- Staging and History Management Methods / Методы управления подготовкой и историей ---
302
316 bool addFileToStaging(const std::string& filePath);
317
327 std::string getHeadCommit() const;
328
339
340 std::string createCommit(const std::string& message);
341
353 void updateCommitReferences(const std::string& removedCommitHash, const std::string& newParentHash) const;
354
368 bool revertCommit(const std::string& commit_hash);
369
381 std::optional<CommitInfo> getCommitByHash(const std::string& commit_hash) const;
382
394 std::string getParentCommitHash(const std::string& commit_hash) const;
395
407 static std::string generateCommitHash(const std::string& content);
408
420 bool restoreFilesFromCommit(const CommitInfo& commit) const;
421
431 bool clearStagingArea();
432
444 bool saveStagedChanges(const std::string& message);
445
455 std::vector<std::string> getStagedFiles();
456
466 std::vector<CommitInfo> getCommitHistory() const;
467
479 std::vector<CommitInfo> getBranchHistory(const std::string& branch_name) const;
480
490 std::string getCurrentBranch() const;
491
503 bool removeRepository(const std::filesystem::path& path) const;
504
516 bool branchExists(const std::string& branch_name) const;
517
529 std::string getBranchHead(const std::string& branch_name) const;
530
544 std::string getFileContentAtCommit(const std::string& commit_hash, const std::string& file_path) const;
545
557 std::vector<std::string> getCommitFiles(const std::string& commit_hash) const;
558
570 void setMergeState(const std::string& branch_name, const std::string& commit_hash) const;
571
579 void clearMergeState() const;
580
590 bool isMergeInProgress() const;
591
601 std::string getMergeBranch() const;
602};
603
604}
Определяет интерфейс для компонента Subject (Издатель) шаблона Observer.
Управляет всеми физическими операциями с файлами и директориями в репозитории SVCS.
Определения RepositoryManager.hxx:78
std::vector< std::string > getStagedFiles()
Извлекает список всех файлов, в настоящее время помеченных как подготовленные (индексированные).
Определения RepositoryManager.cxx:365
std::string getHeadCommit() const
Извлекает хеш текущего коммита HEAD в репозитории.
Определения RepositoryManager.cxx:774
void updateBranchReference(const std::string &branchName, const std::string &commitHash) const
Обновляет файл ссылки ветви хешем коммита.
Определения RepositoryManager.cxx:259
std::string getCurrentBranch() const
Получает имя текущей ветви.
Определения RepositoryManager.cxx:891
std::string getParentCommitHash(const std::string &commit_hash) const
Извлекает хеш родительского коммита для заданного коммита.
Определения RepositoryManager.cxx:541
std::string getBranchHead(const std::string &branch_name) const
Получает головной коммит ветви.
Определения RepositoryManager.cxx:906
std::filesystem::path getRepositoryPath() const
Возвращает определенный корневой путь текущего активного репозитория.
Определения RepositoryManager.cxx:1063
void setMergeState(const std::string &branch_name, const std::string &commit_hash) const
Устанавливает состояние слияния (для разрешения конфликтов).
Определения RepositoryManager.cxx:985
bool saveStagedChanges(const std::string &message)
Создает коммит из подготовленных изменений. (Удобный метод, часто используемый SaveCommand).
Определения RepositoryManager.cxx:763
void updateCommitReferences(const std::string &removedCommitHash, const std::string &newParentHash) const
Обновляет ссылки коммитов при удалении коммита.
Определения RepositoryManager.cxx:580
std::vector< CommitInfo > getCommitHistory() const
Извлекает полную историю коммитов для текущей ветви.
Определения RepositoryManager.cxx:815
bool isMergeInProgress() const
Проверяет, выполняется ли слияние.
Определения RepositoryManager.cxx:1025
bool isRepositoryInitialized(const std::string &path=".")
Проверяет, инициализирован ли репозиторий SVCS по заданному пути или его родителям.
Определения RepositoryManager.cxx:311
bool restoreFilesFromCommit(const CommitInfo &commit) const
Восстанавливает файлы рабочей директории до состояния, записанного в конкретном коммите.
Определения RepositoryManager.cxx:715
std::string createCommit(const std::string &message)
Создает коммит из текущих подготовленных файлов.
Определения RepositoryManager.cxx:462
std::string getMergeBranch() const
Получает ветвь, которая сливается.
Определения RepositoryManager.cxx:1036
void clearMergeState() const
Очищает состояние слияния (после завершения/прерывания слияния).
Определения RepositoryManager.cxx:1005
RepositoryManager(std::shared_ptr< ISubject > bus)
Конструирует RepositoryManager.
Определения RepositoryManager.cxx:27
bool clearStagingArea()
Очищает содержимое области подготовки (индекса).
Определения RepositoryManager.cxx:391
std::vector< std::string > getCommitFiles(const std::string &commit_hash) const
Получает все файлы, измененные в коммите.
Определения RepositoryManager.cxx:947
void updateHead(const std::string &commit_hash) const
Обновляет ссылку HEAD.
Определения RepositoryManager.cxx:414
static std::string generateCommitHash(const std::string &content)
Генерирует хеш коммита из содержимого.
Определения RepositoryManager.cxx:448
bool addFileToStaging(const std::string &filePath)
Пытается добавить файл в область подготовки (индекс).
Определения RepositoryManager.cxx:336
bool initializeRepository(const std::string &path, bool force=false)
Инициализирует новый репозиторий SVCS по указанному пути.
Определения RepositoryManager.cxx:49
bool branchExists(const std::string &branch_name) const
Проверяет, существует ли ветвь.
Определения RepositoryManager.cxx:895
bool removeRepository(const std::filesystem::path &path) const
Пытается рекурсивно удалить всю структуру репозитория SVCS (например, директорию ....
Определения RepositoryManager.cxx:166
std::optional< CommitInfo > getCommitByHash(const std::string &commit_hash) const
Извлекает структуру CommitInfo для заданного хеша коммита.
Определения RepositoryManager.cxx:703
bool revertCommit(const std::string &commit_hash)
Откатывает состояние репозитория к предыдущему коммиту.
Определения RepositoryManager.cxx:628
std::string getFileContentAtCommit(const std::string &commit_hash, const std::string &file_path) const
Получает содержимое файла в конкретном коммите.
Определения RepositoryManager.cxx:928
std::vector< CommitInfo > getBranchHistory(const std::string &branch_name) const
Извлекает историю коммитов для конкретной ветви.
Определения RepositoryManager.cxx:819
Основные структуры данных СКВ и модель объектов.
Компоненты сервисного слоя и инфраструктурные сервисы.
Структура, содержащая основные метаданные для одного коммита.
Определения RepositoryManager.hxx:38
std::string message
Сообщение, предоставленное пользователем при создании коммита.
Определения RepositoryManager.hxx:47
std::string branch
Ветвь, к которой принадлежит этот коммит.
Определения RepositoryManager.hxx:67
std::string hash
Уникальный идентификатор (хеш) коммита.
Определения RepositoryManager.hxx:42
int files_count
Количество файлов, включенных в этот коммит.
Определения RepositoryManager.hxx:52
std::string author
Автор или пользователь, создавший коммит.
Определения RepositoryManager.hxx:57
std::string timestamp
Временная метка создания коммита.
Определения RepositoryManager.hxx:62