diff --git a/.gitignore b/.gitignore
index 3986dde..ccba2bf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,15 +2,16 @@
docs.json
__dummy.html
docs/
-/snapd
-snapd.so
-snapd.dylib
-snapd.dll
-snapd.a
-snapd.lib
-snapd-test-*
+/snag
+snag.so
+snag.dylib
+snag.dll
+snag.a
+snag.lib
+snag-test-*
*.exe
*.pdb
*.o
*.obj
*.lst
+bin
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 0000000..03d6784
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,17 @@
+{
+ // Используйте IntelliSense, чтобы узнать о возможных атрибутах.
+ // Наведите указатель мыши, чтобы просмотреть описания существующих атрибутов.
+ // Для получения дополнительной информации посетите: https://go.microsoft.com/fwlink/?linkid=830387
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "type": "code-d",
+ "request": "launch",
+ "dubBuild": true,
+ "name": "Build & Debug DUB project",
+ "cwd": "${command:dubWorkingDirectory}",
+ "program": "bin/${command:dubTarget}",
+ "args": ["list"]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..9efa6fb
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,338 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Moe Ghoul, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/README.md b/README.md
index e91f5bd..fc0c46a 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,263 @@
-# snapd
+# snag
-Snapshot D - система резервного копирования на основе фиксации состояния файлов с помощью Git.
+`snag` (snapshot git) — это утилита командной строки для создания, управления и восстановления снимков данных. Она позволяет импортировать, экспортировать, создавать и восстанавливать снимки, а также управлять правилами отслеживания файлов.
+
+## Сборка
+
+Для сборки необходим предустановленный комплятор языка D (dmd/ldc/gdc), для удобства использовать пакетный менеджер dub:
+
+```sh
+dub build --build=release
+```
+
+## Использование
+
+Основной формат команды:
+
+```bash
+snag [флаги] [опции] команда
+```
+
+### Флаги
+- `-h, --help` — Выводит справку.
+- `--version` — Выводит версию утилиты.
+
+### Опции
+- `-c, --config <путь>` — Указывает путь к файлу конфигурации.
+
+### Команды
+- `init` — Инициализация репозитория для хранения снимков.
+- `create` — Создание нового снимка.
+- `import` — Импорт снимка из архива tar.gz.
+- `export` — Экспорт снимка в архив tar.gz.
+- `restore` — Восстановление состояния из указанного снимка.
+- `list` — Вывод списка снимков.
+- `diff` — Показ изменённых данных.
+- `status` — Проверка статуса отслеживаемых файлов.
+- `rules` — Управление правилами отслеживания.
+- `size` — Отображение размера снимков.
+
+## Подробное описание команд
+
+### `snag init`
+Инициализирует репозиторий для хранения снимков.
+
+```bash
+snag init [-h] [-f]
+```
+
+- `-f, --force` — Перезаписывает существующий репозиторий.
+
+### `snag create`
+Создаёт новый снимок.
+
+```bash
+snag create [-h] [--no-pre] [--no-post] [-c <комментарий>] [-a <автор>] [-e ]
+```
+
+- `--no-pre` — Выполнение без предкоманд.
+- `--no-post` — Выполнение без посткоманд.
+- `-c, --comment <значение>` — Указывает комментарий к снимку.
+- `-a, --author <значение>` — Указывает автора снимка.
+- `-e, --email <значение>` — Указывает email автора.
+
+### `snag import`
+Импортирует снимок из архива tar.gz.
+
+```bash
+snag import [-h] [--no-pre] [--no-post] [-c <комментарий>] [-a <автор>] [-e ] <путь_к_архиву>
+```
+
+- `--no-pre` — Без выполнения предкоманд.
+- `--no-post` — Без выполнения посткоманд.
+- `-c, --comment <значение>` — Комментарий к снимку.
+- `-a, --author <значение>` — Автор снимка.
+- `-e, --email <значение>` — Email автора.
+- `<путь_к_архиву>` — Путь к файлу tar.gz.
+
+### `snag export`
+Экспортирует снимок в архив tar.gz.
+
+```bash
+snag export [-h] [-s <хэш_снимка>] <путь_к_папке>
+```
+
+- `-s, --snapshot <хэш>` — Указывает хэш снимка.
+- `<путь_к_папке>` — Путь к папке для сохранения архива.
+
+### `snag restore`
+Восстанавливает состояние из указанного снимка.
+
+```bash
+snag restore [-h] [--no-pre] [--no-post] <хэш_снимка>
+```
+
+- `--no-pre` — Без выполнения предкоманд.
+- `--no-post` — Без выполнения посткоманд.
+- `<хэш_снимка>` — Хэш восстанавливаемого снимка.
+
+### `snag list`
+Выводит список снимков.
+
+```bash
+snag list [-h] [-c] [-a] [-e]
+```
+
+- `-c, --comment` — Показать комментарии к снимкам.
+- `-a, --author` — Показать авторов снимков.
+- `-e, --email` — Показать email авторов.
+
+### `snag diff`
+Показывает изменённые данные.
+
+```bash
+snag diff
+```
+
+### `snag status`
+Проверяет статус отслеживаемых файлов.
+
+```bash
+snag status
+```
+
+### `snag size`
+Отображает размер снимков.
+
+```bash
+snag size
+```
+
+### `snag rules`
+Управление правилами отслеживания.
+
+```bash
+snag rules [-h] save|show|update|reset|clear
+```
+
+- `save` — Сохраняет правила.
+- `show` — Показывает правила.
+ ```bash
+ snag rules show [-h] [-c]
+ ```
+ - `-c, --config` — Показать правила из файла конфигурации.
+- `update` — Обновляет правила.
+ ```bash
+ snag rules update [-h] [-r]
+ ```
+ - `-r, --remove` — Удаляет игнорируемые файлы из отслеживания (Требуется повышенная осторожность!).
+- `reset` — Сбрасывает правила до состояния внесенных изменений.
+- `clear` — Очищает правила.
+
+## Примеры использования
+
+1. **Инициализация репозитория:**
+ ```bash
+ snag init
+ ```
+
+2. **Создание снимка с комментарием:**
+ ```bash
+ snag create -c "Начальный снимок" -a "Иван Иванов" -e "ivan@example.com"
+ ```
+
+3. **Импорт снимка из архива:**
+ ```bash
+ snag import archive.tar.gz
+ ```
+
+4. **Экспорт снимка:**
+ ```bash
+ snag export -s abc123 /path/to/output
+ ```
+
+5. **Восстановление снимка:**
+ ```bash
+ snag restore abc123
+ ```
+
+6. **Просмотр списка снимков с комментариями:**
+ ```bash
+ snag list -c
+ ```
+
+7. **Обновление правил отслеживания:**
+ ```bash
+ snag rules update
+ ```
+
+## Конфигурация
+
+Утилита `snag` поддерживает настройку через конфигурационный файл в формате JSON, который задаётся с помощью опции `-c` или `--config`. Этот файл определяет параметры работы утилиты, включая пути, автора, команды для выполнения до и после создания снимков, а также правила отслеживания файлов.
+
+Пример использования конфигурационного файла:
+
+```bash
+snag -c /path/to/config.json create
+```
+
+### Пример конфигурационного файла
+
+```json
+{
+ "git": "/path/to/git/repository/dir",
+ "project": "/path/to/project",
+ "email": "user@site.domain",
+ "author": "snag",
+ "presnag": [
+ "systemctl stop my.service"
+ ],
+ "postsnag": [
+ "systemctl start my.service"
+ ],
+ "rules": {
+ "tracking": [
+ "/first_dir/",
+ "/second_dir/*.conf",
+ "/second_dir/more/"
+ ],
+ "ignore": [
+ "/second_dir/more/*.so"
+ ]
+ }
+}
+```
+
+### Описание полей конфигурационного файла
+
+- **`git`** (`string`): Путь к репозиторию для хранения снимков. В примере: `/path/to/git/repository/dir`. Этот путь используется при инициализации репозитория (`snag init`) для определения места хранения метаданных и снимков.
+
+- **`project`** (`string`): Путь к проекту или директории, файлы которой отслеживаются утилитой. В примере: `/path/to/project`. Указывает корневую папку, в которой `snag` будет создавать, импортировать или восстанавливать снимки.
+
+- **`email`** (`string`): Email автора снимков. Используется для метаданных снимков при выполнении команд, таких как `snag create` или `snag import`. В примере: `user@site.domain`. Может переопределяться опцией `-e` или `--email`.
+
+- **`author`** (`string`): Имя автора снимков. Используется для метаданных снимков. В примере: `snag`. Может переопределяться опцией `-a` или `--author`.
+
+- **`presnag`** (`array of strings`): Список команд, выполняемых перед созданием или импортом снимка (если не указан флаг `--no-pre`). В примере:
+ - `systemctl stop my.service` — останавливает сервис `my.service` перед выполнением операции. Это может быть полезно для временной остановки сервиса, чтобы обеспечить целостность данных во время создания снимка.
+
+- **`postsnag`** (`array of strings`): Список команд, выполняемых после создания или импорта снимка (если не указан флаг `--no-post`). В примере:
+ - `systemctl start my.service` — запускает сервис `my.service` после завершения операции. Это может использоваться для восстановления работы сервиса после создания или импорта снимка.
+
+- **`rules`** (`object`): Определяет правила отслеживания файлов.
+ - **`tracking`** (`array of strings`): Список шаблонов файлов или директорий, которые отслеживаются утилитой. В примере:
+ - `/first_dir/` — отслеживается вся директория `/first_dir` и её содержимое.
+ - `/second_dir/*.conf` — отслеживаются все файлы с расширением `.conf` в директории `/second_dir`.
+ - `/second_dir/more/` — отслеживается вся директория `/second_dir/more` и её содержимое.
+ - **`ignore`** (`array of strings`): Список файлов или директорий, которые исключаются из отслеживания. В примере:
+ - `/second_dir/more/*.so` — игнорируются все файлы с расширением `.so` в директории `/second_dir/more`.
+
+### Примечания
+
+- Правила в разделе `rules` можно обновлять с помощью команды `snag rules update` или просматривать с помощью `snag rules show -c`.
+- Если параметры, такие как `email` или `author`, указаны в командной строке (например, через `-e` или `-a`), они имеют приоритет над значениями из конфигурационного файла.
+- Убедитесь, что пути, указанные в `git` и `project`, существуют и доступны для записи/чтения перед выполнением операций.
+- Команды в `presnag` и `postsnag` должны быть корректными и доступными в системе, иначе выполнение операции может завершиться ошибкой.
+
+## Лицензия
+
+Лицензия GPL-2.0. Подробности см. в файле `LICENSE`.
+
+## Контакты
+
+Для вопросов и предложений: alexander@zhirov.kz
diff --git a/dub.json b/dub.json
index 798e277..f63ef25 100644
--- a/dub.json
+++ b/dub.json
@@ -5,7 +5,7 @@
"copyright": "Copyright © 2025, Alexander Zhirov",
"description": "A backup system based on tracking file states using Git",
"license": "GPL-2.0-or-later",
- "name": "snapd",
+ "name": "snag",
"targetPath": "bin",
"targetType": "executable",
"dependencies": {
diff --git a/snag.json b/snag.json
new file mode 100644
index 0000000..518738f
--- /dev/null
+++ b/snag.json
@@ -0,0 +1,23 @@
+{
+ "git": "/tmp/testgit",
+ "project": "/tmp/test",
+ "email": "user@site.domain",
+ "author": "snag",
+ "presnag": [
+ "echo $(which ls)",
+ "pwd"
+ ],
+ "postsnag": [
+ "/usr/bin/ls"
+ ],
+ "rules": {
+ "tracking": [
+ "/etc/*.conf"
+ ],
+ "ignore": [
+ "/usr/exit/.gitignore",
+ "/usr/exit/dd",
+ "/file1"
+ ]
+ }
+}
diff --git a/source/app.d b/source/app.d
index 497c1a8..a79b3f8 100644
--- a/source/app.d
+++ b/source/app.d
@@ -1,14 +1,247 @@
-import snapd;
+import snag;
import commandr;
+import std.file;
+import std.stdio : writeln;
-import core.stdc.stdlib : EXIT_SUCCESS;
+import core.stdc.stdlib : EXIT_SUCCESS, EXIT_FAILURE;
-private string programName = "snapd";
+private string programName = "snag";
int main(string[] args)
{
- auto argumets = new Program(programName, snapdVersion)
+ if (!checkGit()) {
+ "Using snag requires Git to be installed".writeln;
+ return EXIT_FAILURE;
+ }
+
+ auto argumets = new Program(programName, snagVersion)
+ .add(new Command("init", "Initializing the repository for storing snapshots")
+ .add(new Flag("f", "force", "Initializing a repository with overwriting the existing one")
+ .name("force")
+ .optional
+ )
+ )
+ .add(new Command("rules", "Tracking rules")
+ .add(new Command("update", "Update rules")
+ .add(new Flag("r", "remove", "Removing from tracking the found ignored files")
+ .name("remove")
+ .optional
+ )
+ )
+ .add(new Command("reset", "Reset rules (restores rules to pre-change state)"))
+ .add(new Command("clear", "Clear rules"))
+ .add(new Command("save", "Save rules"))
+ .add(new Command("show", "Show rules")
+ .add(new Flag("c", "config", "Show rules from the configuration file")
+ .name("config")
+ .optional
+ )
+ )
+ )
+ .add(new Command("status", "Checking the status of tracked files"))
+ .add(new Command("diff", "Show changed data"))
+ .add(new Command("size", "Size of snapshots"))
+ .add(new Command("import", "Import snapshot from a tar.gz archive")
+ .add(new Argument("archive", "The path to the tar.gz archive file").required)
+ .add(new Option("c", "comment", "Specify comment")
+ .optional
+ .validateEachWith(
+ opt => opt.length > 0,
+ "cannot be empty"
+ )
+ )
+ .add(new Option("a", "author", "Specify author")
+ .optional
+ .validateEachWith(
+ opt => opt.length > 0,
+ "cannot be empty"
+ )
+ )
+ .add(new Option("e", "email", "Specify email")
+ .optional
+ .validateEachWith(
+ opt => opt.isValidEmail,
+ "must contain an email address"
+ )
+ )
+ .add(new Flag(null, "no-pre", "Execution without running pre-execution commands")
+ .name("nopre")
+ .optional
+ )
+ .add(new Flag(null, "no-post", "Execution without running post-execution commands")
+ .name("nopost")
+ .optional
+ )
+ )
+ .add(new Command("export", "Export snapshot to a tar.gz archive")
+ .add(new Argument("path", "Output directory path for the archive").required)
+ .add(new Option("s", "snapshot", "Specify snapshot hash")
+ .optional
+ .validateEachWith(
+ opt => opt.isValidHash,
+ "must contain snapshot hash provided"
+ )
+ )
+ )
+ .add(new Command("create", "Create a new snapshot")
+ .add(new Option("c", "comment", "Specify comment")
+ .optional
+ .validateEachWith(
+ opt => opt.length > 0,
+ "cannot be empty"
+ )
+ )
+ .add(new Option("a", "author", "Specify author")
+ .optional
+ .validateEachWith(
+ opt => opt.length > 0,
+ "cannot be empty"
+ )
+ )
+ .add(new Option("e", "email", "Specify email")
+ .optional
+ .validateEachWith(
+ opt => opt.isValidEmail,
+ "must contain an email address"
+ )
+ )
+ .add(new Flag(null, "no-pre", "Execution without running pre-execution commands")
+ .name("nopre")
+ .optional
+ )
+ .add(new Flag(null, "no-post", "Execution without running post-execution commands")
+ .name("nopost")
+ .optional
+ )
+ )
+ .add(new Command("list", "List of snapshots")
+ .add(new Flag("c", "comment", "Show comment")
+ .name("comment")
+ .optional
+ )
+ .add(new Flag("a", "author", "Show author")
+ .name("author")
+ .optional
+ )
+ .add(new Flag("e", "email", "Show email")
+ .name("email")
+ .optional
+ )
+ )
+ .add(new Command("restore", "Restore to the specified snapshot state")
+ .add(new Argument("snapshot", "Specify snapshot hash").required)
+ .add(new Flag(null, "no-pre", "Execution without running pre-execution commands")
+ .name("nopre")
+ .optional
+ )
+ .add(new Flag(null, "no-post", "Execution without running post-execution commands")
+ .name("nopost")
+ .optional
+ )
+ )
+ .add(new Option("c", "config", "Configuration file path")
+ .optional
+ .validateEachWith(
+ opt => opt.exists && opt.isFile,
+ "must specify the path to the JSON file"
+ )
+ )
.parse(args);
+ string configFile = argumets.option("config", "snag.json");
+
+ SnagConfig config;
+
+ try {
+ config = new SnagConfig(configFile);
+ } catch (SnagConfigException e) {
+ e.print();
+ return EXIT_FAILURE;
+ }
+
+ auto snag = new Snag(config);
+
+ try {
+ argumets
+ .on("init", init =>
+ snag.initialize(init.flag("force"))
+ )
+ .on("diff", diff =>
+ snag.diff()
+ )
+ .on("size", size =>
+ snag.size()
+ )
+ .on("status", status =>
+ snag.status()
+ )
+ .on("create", (create) {
+ create.flag("nopre") || snag.executePreSnag();
+ snag.create(
+ create.option("comment", ""),
+ create.option("author", ""),
+ create.option("email", "")
+ );
+ create.flag("nopost") || snag.executePostSnag();
+ })
+ .on("list", list =>
+ snag.list(
+ list.flag("comment"),
+ list.flag("author"),
+ list.flag("email")
+ )
+ )
+ .on("restore", (restore) {
+ restore.flag("nopre") || snag.executePreSnag();
+ snag.restore(restore.arg("snapshot"));
+ restore.flag("nopost") || snag.executePostSnag();
+ })
+ .on("export", e =>
+ snag.exportSnapshot(
+ e.arg("path"),
+ e.option("snapshot", ""),
+ )
+ )
+ .on("import", (i) {
+ i.flag("nopre") || snag.executePreSnag();
+ snag.importSnapshot(
+ i.arg("archive"),
+ i.option("comment", ""),
+ i.option("author", ""),
+ i.option("email", "")
+ );
+ i.flag("nopost") || snag.executePostSnag();
+ })
+ .on("rules", (r) {
+ auto rules = new SnagRules(config);
+ r
+ .on("update", update =>
+ rules.update(update.flag("remove"))
+ )
+ .on("reset", reset =>
+ rules.reset()
+ )
+ .on("clear", clear =>
+ rules.clear()
+ )
+ .on("save", clear =>
+ rules.save()
+ )
+ .on("show", show =>
+ rules.show(show.flag("config"))
+ );
+ }
+ );
+ } catch (SnagException e) {
+ e.print();
+ return EXIT_FAILURE;
+ } catch (Exception e) {
+ writeln(
+ "AN UNEXPECTED ERROR HAS OCCURRED! PLEASE REPORT IT TO THE AUTHOR OF THE SNAG!\n\n",
+ e
+ );
+ return EXIT_FAILURE;
+ }
+
return EXIT_SUCCESS;
}
diff --git a/source/snag/config/config.d b/source/snag/config/config.d
new file mode 100644
index 0000000..e9e0ca2
--- /dev/null
+++ b/source/snag/config/config.d
@@ -0,0 +1,150 @@
+module snag.config.config;
+
+import std.json;
+import std.file;
+import std.path;
+import std.string;
+import snag.lib;
+import std.algorithm;
+import std.array;
+
+import snag.config.exception;
+
+class SnagConfig {
+ private string _git;
+ private string _project;
+ private string _email;
+ private string _author;
+ private string[] _tracking;
+ private string[] _ignore;
+ private string[] _presnag;
+ private string[] _postsnag;
+
+ this(string configFile) {
+ string jsonText;
+ JSONValue jsonData;
+
+ try {
+ jsonText = readText(configFile);
+ jsonData = parseJSON(jsonText);
+ } catch (Exception e) {
+ throw new SnagConfigException(
+ "An error occurred while reading the configuration file:\n\t"
+ ~ e.msg
+ );
+ }
+
+ if ("git" !in jsonData)
+ throw new SnagConfigException(
+ "The configuration file is missing the \"git\" parameter"
+ );
+
+ _git = jsonData["git"].str;
+
+ if (!_git.length)
+ throw new SnagConfigException(
+ "The \"git\" parameter must contain the path to the directory"
+ );
+
+ if (!_git.isAbsolute)
+ throw new SnagConfigException(
+ "The \"git\" parameter must be an absolute path to the directory:\n\t"
+ ~ _git
+ );
+
+ if ("project" !in jsonData)
+ throw new SnagConfigException(
+ "The configuration file is missing the \"project\" parameter"
+ );
+
+ _project = jsonData["project"].str;
+
+ if (!_project.length)
+ throw new SnagConfigException(
+ "The \"project\" parameter must contain the path to the directory"
+ );
+
+ if (!_project.isAbsolute)
+ throw new SnagConfigException(
+ "The \"project\" parameter must be an absolute path to the directory:\n\t"
+ ~ _project
+ );
+
+ if ("email" !in jsonData)
+ throw new SnagConfigException(
+ "The configuration file is missing the \"email\" parameter"
+ );
+
+ _email = jsonData["email"].str;
+
+ if (!_email.length)
+ throw new SnagConfigException(
+ "The \"email\" parameter must contain an email address"
+ );
+
+ if (!isValidEmail(_email))
+ throw new SnagConfigException(
+ "Invalid email address provided in the \"email\" parameter:\n\t"
+ ~ _email
+ );
+
+ if ("author" !in jsonData)
+ throw new SnagConfigException(
+ "The configuration file is missing the \"author\" parameter"
+ );
+
+ _author = jsonData["author"].str;
+
+ if (!_author.length)
+ throw new SnagConfigException(
+ "The \"author\" parameter must contain an author name"
+ );
+
+ if ("rules" in jsonData) {
+ if (jsonData["rules"].type != JSONType.object)
+ throw new SnagConfigException(
+ "The \"rules\" parameter must be an object"
+ );
+ auto rules = jsonData["rules"];
+ if ("tracking" in rules) {
+ if (rules["tracking"].type != JSONType.array)
+ throw new SnagConfigException(
+ "The \"tracking\" parameter must be an array containing a set of paths to tracked files"
+ );
+ _tracking = rules["tracking"].array.map!(item => item.str).array;
+ }
+ if ("ignore" in rules) {
+ if (rules["ignore"].type != JSONType.array)
+ throw new SnagConfigException(
+ "The \"ignore\" parameter must contain a gitignore rule"
+ );
+ _ignore = rules["ignore"].array.map!(item => item.str).array;
+ }
+ }
+
+ if ("presnag" in jsonData) {
+ if (jsonData["presnag"].type != JSONType.array)
+ throw new SnagConfigException(
+ "The \"presnag\" parameter must be an array containing a set of commands"
+ );
+ _presnag = jsonData["presnag"].array.map!(item => item.str).array;
+ }
+
+ if ("postsnag" in jsonData) {
+ if (jsonData["postsnag"].type != JSONType.array)
+ throw new SnagConfigException(
+ "The \"postsnag\" parameter must be an array containing a set of commands"
+ );
+ _postsnag = jsonData["postsnag"].array.map!(item => item.str).array;
+ }
+ }
+
+ @property string git() const { return _git; }
+ @property string project() const { return _project; }
+ @property string email() const { return _email; }
+ @property string author() const { return _author; }
+ @property const(string[]) tracking() const { return _tracking; }
+ @property const(string[]) ignore() const { return _ignore; }
+ @property const(string[]) presnag() const { return _presnag; }
+ @property const(string[]) postsnag() const { return _postsnag; }
+}
diff --git a/source/snag/config/exception.d b/source/snag/config/exception.d
new file mode 100644
index 0000000..fc21ee1
--- /dev/null
+++ b/source/snag/config/exception.d
@@ -0,0 +1,14 @@
+module snag.config.exception;
+
+import std.exception;
+import std.stdio : writeln;
+
+class SnagConfigException : Exception {
+ this(string msg, string file = __FILE__, size_t line = __LINE__) {
+ super(msg, file, line);
+ }
+
+ void print() {
+ writeln(msg);
+ }
+}
diff --git a/source/snag/config/package.d b/source/snag/config/package.d
new file mode 100644
index 0000000..09c7b1d
--- /dev/null
+++ b/source/snag/config/package.d
@@ -0,0 +1,4 @@
+module snag.config;
+
+public import snag.config.exception;
+public import snag.config.config;
diff --git a/source/snag/core/core.d b/source/snag/core/core.d
new file mode 100644
index 0000000..9917240
--- /dev/null
+++ b/source/snag/core/core.d
@@ -0,0 +1,462 @@
+module snag.core.core;
+
+import snag.config;
+import std.format;
+import std.datetime : Clock;
+import std.stdio;
+import std.array;
+import std.process;
+import std.algorithm;
+import std.string;
+import std.file;
+import std.path;
+
+import snag.lib;
+import snag.core.exception;
+import snag.core.rules;
+
+class Snag {
+ private string[] _baseCommand;
+ private SnagConfig _config;
+ private string _date;
+
+ this(SnagConfig config) {
+ _baseCommand = format(
+ "git --git-dir=%s --work-tree=%s",
+ config.git, config.project
+ ).split();
+
+ _config = config;
+ auto currentTime = Clock.currTime();
+ _date = format("%02d%03d%02d%02d%02d",
+ currentTime.year % 100,
+ currentTime.dayOfYear,
+ currentTime.hour,
+ currentTime.minute,
+ currentTime.second);
+ }
+
+ private auto git(string[] command, string message, string separator = ":\n\t") {
+ auto result = execute(_baseCommand ~ command);
+ if (result.status)
+ throw new SnagException(
+ message ~ separator ~ result.output.split('\n')[0]
+ );
+ return result;
+ }
+
+ private string gitStatus(string shortStatus, bool formatted = false) {
+ immutable string[string] statusMap = [
+ "??": "Untracked",
+ "A": "Added",
+ "M": "Modified",
+ "D": "Deleted",
+ "R": "Renamed",
+ "C": "Copied",
+ "U": "Unmerged",
+ "T": "Type changed",
+ "!": "Ignored"
+ ];
+ string fullStatus = statusMap.get(shortStatus, shortStatus);
+ return formatted && fullStatus.length < 8 ? fullStatus ~ "\t" : fullStatus;
+ }
+
+ void executePreSnag() {
+ _config.presnag().each!((command) {
+ auto result = executeShell(command);
+ result.status && throw new SnagException(
+ "%s:\n\t%s\n\n%s".format(
+ "An error occurred during presnag-command execution",
+ command,
+ result.output
+ )
+ );
+ });
+ }
+
+ void executePostSnag() {
+ _config.postsnag().each!((command) {
+ auto result = executeShell(command);
+ result.status && throw new SnagException(
+ "%s:\n\t%s\n\n%s".format(
+ "An error occurred during postsnag-command execution",
+ command,
+ result.output
+ )
+ );
+ });
+ }
+
+ void initialize(bool force) {
+ auto result = execute(_baseCommand ~ ["rev-parse", "--git-dir"]);
+ !force && !result.status &&
+ throw new SnagException(
+ "The Git repository has already been initialized: "
+ ~ result.output.strip('\n')
+ );
+
+ force && _config.git.exists
+ && _config.git.isDir
+ && _config.git.rmdirRecurse;
+
+ git(
+ ["init", "--initial-branch=default"],
+ "A Git repository initialization error occurred"
+ );
+ git(
+ ["config", "user.email", _config.email],
+ "A Git repository initialization error occurred"
+ );
+ git(
+ ["config", "user.name", _config.author],
+ "A Git repository initialization error occurred"
+ );
+
+ (new SnagRules(_config)).create();
+
+ writeln(
+ "The Git repository has been initialized successfully: ",
+ _config.git
+ );
+ }
+
+ void status() {
+ auto result = git(
+ ["status", "--porcelain"],
+ "An error occurred while checking the file tracking status"
+ );
+ if (!result.output.length) {
+ writeln("The current state of the files is up to date as of the latest snapshot");
+ return;
+ }
+ writeln("The following list of files requires backup:");
+ result.output.split('\n')[0..$-1].map!(e =>
+ e.strip.split
+ ).each!(e =>
+ writefln("\t%s\t/%s", gitStatus(e[0], true), e[1])
+ );
+ }
+
+ void create(string comment, string author, string email) {
+ auto result = git(
+ ["status", "--porcelain"],
+ "An error occurred while checking the file tracking status"
+ );
+
+ // Если нечего коммитить, то выходим
+ if (!result.output.length)
+ throw new SnagException(
+ "Current file state doesn't need to be archived again"
+ );
+
+ author.length && (environment["GIT_AUTHOR_NAME"] = author);
+ email.length && (environment["GIT_AUTHOR_EMAIL"] = email);
+
+ string message = comment.length ? comment : "Standard snapshot creation";
+ string newSnapshot;
+
+ result = execute(_baseCommand ~ ["rev-parse", "--short", "HEAD"]);
+ if (result.status == 128) {
+ // Если это самый первый коммит после инициализации репозитория
+ git(["add", "."], "Failed to prepare files for archiving");
+ git(["commit", "-m"] ~ message, "Failed to create a snapshot");
+ newSnapshot = git(
+ ["rev-parse", "--short", "HEAD"],
+ "Failed to retrieve current snapshot information"
+ ).output.strip('\n');
+ writeln("Snapshot was created successfully: ", newSnapshot);
+ return;
+ } else if (result.status != 0)
+ throw new SnagException(
+ "Failed to retrieve current snapshot information:\n"
+ ~ result.output
+ );
+
+ // Текущий коммит, который был изменен
+ string currentSnapshot = result.output.strip('\n');
+
+ // Если текущий измененный коммит является последним в ветке - то продолжить коммиты в этой ветке
+ // При разбивке по '\n' присутствует последний пустой элемент, поэтому нужный элемент 2-ой с конца
+ string currentBranch = git(
+ ["for-each-ref", "--format='%(refname:short)'", "--contains", currentSnapshot],
+ "Error while getting the current branch"
+ ).output.split('\n')[$-2].strip('\'');
+
+ // Получение списка коммитов между текущим и веткой
+ result = git(
+ ["log", "--oneline", "HEAD.." ~ currentBranch],
+ "Failed to get the commit list between HEAD and " ~ currentBranch
+ );
+
+ // Если список существует
+ if (result.output.length) {
+ // Если коммит не является последним, то необходимо ответвление
+ string newBranch = "%s-%s".format(_date, currentSnapshot);
+ git(
+ ["checkout", "-b", newBranch, currentSnapshot ],
+ "Failed to create a branch from the current state"
+ );
+ git(
+ ["add", "."],
+ "Failed to prepare files for archiving"
+ );
+ git(
+ ["commit", "-m"] ~ message,
+ "Failed to create a snapshot"
+ );
+ newSnapshot = git(
+ ["rev-parse", "--short", "HEAD"],
+ "Failed to retrieve current snapshot information"
+ ).output.strip('\n');
+ } else {
+ // Если коммит является посленим в ветке
+ git(
+ ["add", "."],
+ "Failed to prepare files for archiving"
+ );
+ git(
+ ["commit", "-m"] ~ message,
+ "Failed to create a snapshot"
+ );
+ newSnapshot = git(
+ ["rev-parse", "--short", "HEAD"],
+ "Failed to retrieve current snapshot information"
+ ).output.strip('\n');
+ git(
+ ["checkout", currentBranch],
+ "Failed to perform intermediate state switching"
+ );
+ git(
+ ["merge", newSnapshot],
+ "Issue with including the commit into the branch " ~ currentBranch
+ );
+ }
+ writeln("Snapshot was created successfully: ", newSnapshot);
+ }
+
+ void list(bool comment, bool author, bool email) {
+ string currentSnapshot = git(
+ ["rev-parse", "--short", "HEAD"],
+ "Failed to retrieve current snapshot information"
+ ).output.strip('\n');
+
+ string format = "format:%h\t%ad";
+
+ comment && (format ~= "\t%s");
+ author && (format ~= "\t%an");
+ email && (format ~= "\t%ae");
+
+ git(
+ [
+ "log",
+ "--all",
+ "--date=format:%Y.%m.%d %H:%M",
+ "--pretty=" ~ format
+ ],
+ "Failed to retrieve the list of snapshots"
+ ).output.split('\n').map!(line => line.split('\t')).array.each!(e =>
+ writefln("%s\t%s",
+ currentSnapshot == e[0] ? " >" : "",
+ e.join("\t")
+ )
+ );
+ }
+
+ void restore(string hash) {
+ if (!isValidHash(hash))
+ throw new SnagException(
+ "Invalid snapshot hash provided"
+ );
+ auto result = git(
+ ["status", "--porcelain"],
+ "An error occurred while checking the file tracking status"
+ );
+ if (result.output.length) {
+ git(
+ ["restore", "."],
+ "Failed to reset file changes state"
+ );
+ git(
+ ["clean", "-fd"],
+ "Failed to clean untracked files"
+ );
+ }
+ git(
+ ["rev-parse", hash],
+ "This snapshot is not available in the archive"
+ );
+ git(
+ ["checkout", hash],
+ "Failed to restore the snapshot state " ~ hash
+ );
+ writeln("Backup was restored successfully: ", hash);
+ }
+
+ void diff() {
+ auto result = git(
+ ["diff"],
+ "Failed to retrieve changes"
+ );
+ if (result.output.length) {
+ result.output.write;
+ return;
+ }
+ writeln("No changes at the moment");
+ }
+
+ void exportSnapshot(string path, string hash) {
+ try {
+ !path.isDir &&
+ throw new SnagException(
+ "Path is not a directory"
+ );
+ } catch (Exception e) {
+ throw new SnagException(
+ "Failed to verify the archive output directory:\n\t"
+ ~ e.msg
+ );
+ }
+ if (hash.length) {
+ !isValidHash(hash) &&
+ throw new SnagException(
+ "Invalid snapshot hash provided"
+ );
+ git(
+ ["rev-parse", hash],
+ "This snapshot is not available in the archive"
+ );
+ } else {
+ hash = git(
+ ["rev-parse", "--short", "HEAD"],
+ "Failed to retrieve current snapshot information"
+ ).output.strip('\n');
+ }
+ string file = buildPath(
+ path.absolutePath.buildNormalizedPath,
+ "%s-%s.tar.gz".format(_date, hash)
+ );
+ git(
+ [
+ "archive",
+ "--format=tar.gz",
+ hash,
+ "-o",
+ file
+ ],
+ "Failed to export snapshot to archive"
+ );
+ writeln("Export to archive completed successfully: ", file);
+ }
+
+ void importSnapshot(string path, string comment, string author, string email) {
+ try {
+ (!path.isFile || !path.endsWith("tar.gz")) &&
+ throw new SnagException(
+ "Path is not an archive file"
+ );
+ } catch (Exception e) {
+ throw new SnagException(
+ "Failed to verify the archive file:\n\t"
+ ~ e.msg
+ );
+ }
+
+ string newBranch = _date ~ "-import";
+ string tempDirectory = tempDir().buildPath(newBranch);
+
+ mkdir(tempDirectory);
+
+ scope(exit) tempDirectory.exists
+ && tempDirectory.isDir
+ && tempDirectory.rmdirRecurse;
+
+ auto result = execute([
+ "tar", "xf", path, "-C", tempDirectory
+ ]);
+ result.status &&
+ throw new SnagException(
+ "The error occurred during decompression (or unpacking) of the archive:\n\t"
+ ~ result.output.split('\n')[0]
+ );
+
+ // Выполнение git команд относительно распакованного архива
+ string[] customCommand = format(
+ "git --git-dir=%s --work-tree=%s",
+ _config.git, tempDirectory
+ ).split();
+
+ // Необходимо проверить, что текущее состояние файлов не идентично файлам распакованного архива
+ result = execute(customCommand ~ ["status", "--porcelain"]);
+ result.status &&
+ throw new SnagException(
+ "An error occurred while checking the file tracking status:\n"
+ ~ result.output.split('\n')[0]
+ );
+
+ // Если текущее состояние файлов идентично файлам распакованного архива
+ !result.output.length &&
+ throw new SnagException(
+ "Import aborted:\n\t"
+ ~ "The new state of the files is up to date as of the current snapshot"
+ );
+
+ git(
+ ["checkout", "--orphan", newBranch ],
+ "Failed to create a branch from the new state"
+ );
+
+ // Создание нового снимка на основе состояния файлов из распакованного архива
+ result = execute(customCommand ~ ["add", "."]);
+ result.status &&
+ throw new SnagException(
+ "Failed to prepare files for archiving:\n"
+ ~ result.output.split('\n')[0]
+ );
+
+ author.length && (environment["GIT_AUTHOR_NAME"] = author);
+ email.length && (environment["GIT_AUTHOR_EMAIL"] = email);
+
+ string message = comment.length ? comment : "Creating a snapshot from import";
+
+ result = execute(customCommand ~ ["commit", "-m"] ~ message);
+ result.status &&
+ throw new SnagException(
+ "Failed to create a snapshot:\n"
+ ~ result.output.split('\n')[0]
+ );
+
+ // Сброс состояния файлов
+ git(
+ ["restore", "."],
+ "Failed to reset file changes state"
+ );
+ git(
+ ["clean", "-fd"],
+ "Failed to clean untracked files"
+ );
+
+ string newSnapshot = git(
+ ["rev-parse", "--short", "HEAD"],
+ "Failed to retrieve current snapshot information"
+ ).output.strip('\n');
+
+ writeln("Import completed successfully: ", newSnapshot);
+ }
+
+ void size() {
+ try {
+ "Total size of the snapshots is: %.2f MB".writefln(
+ dirEntries(_config.git, SpanMode.depth)
+ .filter!(path => path.isFile)
+ .array
+ .map!(path => path.getSize)
+ .sum / (1024.0 * 1024.0)
+ );
+ } catch (Exception e) {
+ throw new SnagException(
+ "Error while checking the snapshots size:\n\t"
+ ~ e.msg
+ );
+ }
+ }
+}
diff --git a/source/snag/core/exception.d b/source/snag/core/exception.d
new file mode 100644
index 0000000..1b79433
--- /dev/null
+++ b/source/snag/core/exception.d
@@ -0,0 +1,14 @@
+module snag.core.exception;
+
+import std.exception;
+import std.stdio;
+
+class SnagException : Exception {
+ this(string msg, string file = __FILE__, size_t line = __LINE__) {
+ super(msg, file, line);
+ }
+
+ void print() {
+ writeln(msg);
+ }
+}
diff --git a/source/snag/core/package.d b/source/snag/core/package.d
new file mode 100644
index 0000000..6ae1164
--- /dev/null
+++ b/source/snag/core/package.d
@@ -0,0 +1,5 @@
+module snag.core;
+
+public import snag.core.core;
+public import snag.core.exception;
+public import snag.core.rules;
diff --git a/source/snag/core/rules.d b/source/snag/core/rules.d
new file mode 100644
index 0000000..d8a2c9c
--- /dev/null
+++ b/source/snag/core/rules.d
@@ -0,0 +1,164 @@
+module snag.core.rules;
+
+import snag.config;
+import snag.core.exception;
+import std.algorithm;
+import std.array;
+import std.path;
+import std.stdio;
+import std.string;
+import std.conv;
+import std.container;
+import std.process;
+import std.file;
+
+class SnagRules {
+ private string[] _rules;
+ private SnagConfig _config;
+ private string[] _baseCommand;
+ private string _gitignore;
+ private string _gitignoreBak;
+
+ private auto git(string[] command, string message, string separator = ":\n\t") {
+ auto result = execute(_baseCommand ~ command);
+ if (result.status)
+ throw new SnagException(
+ message ~ separator ~ result.output.split('\n')[0]
+ );
+ return result;
+ }
+
+ private string[] generateGitignoreRules(string finalPath) {
+ string[] rules;
+ string[] parts = finalPath.split("/").filter!(p => !p.empty).array;
+
+ if (parts.length == 0) return rules;
+
+ rules ~= "/*";
+ rules ~= "!/" ~ parts[0];
+ rules ~= "/" ~ parts[0] ~ "/*";
+
+ if (parts.length > 1) {
+ string currentPath = "/" ~ parts[0];
+ foreach (i; 1 .. parts.length) {
+ currentPath ~= "/" ~ parts[i];
+ rules ~= "!" ~ currentPath;
+ if (i < parts.length.to!int - 1) {
+ rules ~= currentPath ~ "/*";
+ }
+ }
+ }
+
+ return rules;
+ }
+
+ private void generate() {
+ string[] rules;
+ auto tempRules = new RedBlackTree!string;
+
+ _config.tracking.each!(
+ track => rules ~= generateGitignoreRules(track)
+ );
+
+ rules.each!((rule) {
+ if (rule in tempRules) return;
+ tempRules.insert(rule);
+ _rules ~= rule;
+ });
+
+ _rules ~= _config.ignore;
+ }
+
+ this(SnagConfig config) {
+ _config = config;
+ _gitignore = config.git.buildPath("info/exclude");
+ _gitignoreBak = _gitignore ~ ".bak";
+
+ _baseCommand = format(
+ "git --git-dir=%s --work-tree=%s",
+ config.git, config.project
+ ).split();
+
+ generate();
+ }
+
+ private void restoreUntracked() {
+ git(
+ ["diff", "--cached", "--name-only"],
+ "Failed to retrieve the list of files removed from tracking"
+ ).output.split('\n').filter!(e => !e.strip.empty).each!(
+ file => git(
+ ["add", "-f", file],
+ "Failed to restore the file to tracking"
+ )
+ );
+ }
+
+ private void removeUntracked() {
+ git(
+ ["ls-files", "-i", "-c", "--exclude-standard"],
+ "Failed to get the list of files to remove from tracking"
+ ).output.split('\n').filter!(e => !e.strip.empty).each!(
+ file => git(
+ ["rm", "--cached", file],
+ "Failed to remove file from tracking"
+ )
+ );
+ }
+
+ void create() {
+ auto file = File(_gitignore, "w");
+ _rules.each!(rule => file.writeln(rule));
+ file.close();
+ }
+
+ void update(bool remove) {
+ if (!_gitignoreBak.exists) {
+ readText(_gitignore).splitLines().equal(_rules) &&
+ throw new SnagException(
+ "Rule configuration is up-to-date and doesn't require updating"
+ );
+ copy(_gitignore, _gitignoreBak);
+ }
+
+ restoreUntracked();
+ create();
+
+ remove && removeUntracked();
+ }
+
+ void reset() {
+ !_gitignoreBak.exists &&
+ throw new SnagException(
+ "No rule changes to reset"
+ );
+ restoreUntracked();
+ rename(_gitignoreBak, _gitignore);
+ }
+
+ void clear() {
+ !readText(_gitignore).splitLines().length &&
+ throw new SnagException(
+ "The configuration has no rules"
+ );
+ !_gitignoreBak.exists && copy(_gitignore, _gitignoreBak);
+ restoreUntracked();
+ File(_gitignore, "w").close();
+ }
+
+ void show(bool config) {
+ if (config)
+ _rules.join('\n').writeln;
+ else
+ readText(_gitignore).write;
+ }
+
+ void save() {
+ if (!_gitignoreBak.exists) {
+ writeln("The rules are up to date");
+ return;
+ }
+ remove(_gitignoreBak);
+ writeln("The rules have been saved");
+ }
+}
diff --git a/source/snag/lib/lib.d b/source/snag/lib/lib.d
new file mode 100644
index 0000000..902691d
--- /dev/null
+++ b/source/snag/lib/lib.d
@@ -0,0 +1,19 @@
+module snag.lib.lib;
+
+import std.regex;
+import std.process;
+
+bool isValidHash(string hash) {
+ auto hashPattern = ctRegex!r"^[a-fA-F0-9]{7}$";
+ return !matchFirst(hash, hashPattern).empty;
+}
+
+bool isValidEmail(string email) {
+ auto emailPattern = ctRegex!r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
+ return !matchFirst(email, emailPattern).empty;
+}
+
+bool checkGit() {
+ auto result = execute(["which", "git"]);
+ return !result.status;
+}
diff --git a/source/snag/lib/package.d b/source/snag/lib/package.d
new file mode 100644
index 0000000..46fa21c
--- /dev/null
+++ b/source/snag/lib/package.d
@@ -0,0 +1,3 @@
+module snag.lib;
+
+public import snag.lib.lib;
diff --git a/source/snag/package.d b/source/snag/package.d
new file mode 100644
index 0000000..ae8b15d
--- /dev/null
+++ b/source/snag/package.d
@@ -0,0 +1,6 @@
+module snag;
+
+public import snag.version_;
+public import snag.lib;
+public import snag.config;
+public import snag.core;
diff --git a/source/snag/version_.d b/source/snag/version_.d
new file mode 100644
index 0000000..b4f3fd3
--- /dev/null
+++ b/source/snag/version_.d
@@ -0,0 +1,3 @@
+module snag.version_;
+
+enum snagVersion = "0.0.13";
diff --git a/source/snapd/package.d b/source/snapd/package.d
deleted file mode 100644
index 45456d4..0000000
--- a/source/snapd/package.d
+++ /dev/null
@@ -1,3 +0,0 @@
-module snapd;
-
-public import snapd.version_;
diff --git a/source/snapd/version_.d b/source/snapd/version_.d
deleted file mode 100644
index e09faec..0000000
--- a/source/snapd/version_.d
+++ /dev/null
@@ -1,3 +0,0 @@
-module snapd.version_;
-
-enum snapdVersion = "0.0.1";