Compare commits

..

No commits in common. "d58ab81fd83b0f052759855014d74d5e6c3734f3" and "2ad04b46039d8cc10f0e53eea15fd5a73b633e52" have entirely different histories.

10 changed files with 48 additions and 79 deletions

View file

@ -1,15 +1,18 @@
cmake_minimum_required(VERSION 3.14) cmake_minimum_required(VERSION 3.14)
project(snag) project(snag)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") set(PROJECT_VERSION_MAJOR 0)
include(snag_version) set(PROJECT_VERSION_MINOR 1)
set(PROJECT_VERSION_PATCH 0)
string(TIMESTAMP PROJECT_VERSION_BUILD "%y%j.%H%M") string(TIMESTAMP PROJECT_VERSION_BUILD "%y%j.%H%M")
if(GIT_HASH_VERSION)
message(STATUS "GIT_HASH_VERSION is set")
include(snag_git)
endif()
include(snag_platforms)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
include(snag_git)
include(snag_platforms)
set(PROJECT_VERSION_SUFFIX "-${GIT_VERSION_SUFFIX}")
# Overwrite suffix for Release or Release Candidate builds
set(PROJECT_VERSION_SUFFIX "-alpha.1")
set(CMAKE_BUILD_TYPE "Release") set(CMAKE_BUILD_TYPE "Release")
if(CMAKE_BUILD_TYPE) if(CMAKE_BUILD_TYPE)
set(BUILD_TYPE ${CMAKE_BUILD_TYPE}) set(BUILD_TYPE ${CMAKE_BUILD_TYPE})
@ -24,7 +27,7 @@ message(STATUS "PROJECT_VERSION_DISPLAY: ${PROJECT_VERSION_DISPLAY}")
message(STATUS "") message(STATUS "")
# Deb package # Deb package
set(DEB_PACKAGE_VERSION "${PROJECT_VERSION_DISPLAY}${PROJECT_VERSION_SUFFIX}${GIT_VERSION_SUFFIX}") set(DEB_PACKAGE_VERSION "${PROJECT_VERSION_DISPLAY}${PROJECT_VERSION_SUFFIX}")
if(PROJECT_VERSION_CODENAME) if(PROJECT_VERSION_CODENAME)
set(DEB_PACKAGE_VERSION "${DEB_PACKAGE_VERSION}-${PROJECT_VERSION_CODENAME}") set(DEB_PACKAGE_VERSION "${DEB_PACKAGE_VERSION}-${PROJECT_VERSION_CODENAME}")
endif() endif()

View file

@ -1,20 +1,24 @@
cmake_minimum_required(VERSION 3.6) cmake_minimum_required(VERSION 3.6)
find_package(Git) if(DEFINED ENV{CI_COMMIT_BRANCH})
string(REGEX REPLACE ".*/" "" GIT_BRANCH $ENV{CI_COMMIT_BRANCH})
if(GIT_FOUND) string(REPLACE "_" "-" GIT_BRANCH ${GIT_BRANCH})
# Получаем короткий хэш текущего коммита if(NOT GIT_BRANCH STREQUAL "stable")
execute_process( set(GIT_VERSION_SUFFIX "${GIT_BRANCH}-")
COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_SHORT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# Проверяем, успешно ли получен хэш
if(GIT_SHORT_HASH)
message(STATUS "Git short hash: ${GIT_SHORT_HASH}")
set(GIT_VERSION_SUFFIX "-${GIT_SHORT_HASH}")
else() else()
message(WARNING "Failed to retrieve Git short hash") set(GIT_VERSION_SUFFIX "")
endif() endif()
else()
set(GIT_BRANCH "dev")
set(GIT_VERSION_SUFFIX "${GIT_BRANCH}-")
endif() endif()
if(DEFINED ENV{CI_COMMIT_SHORT_SHA})
set(GIT_TAG $ENV{CI_COMMIT_SHORT_SHA})
else()
set(GIT_TAG "0000000")
endif()
set(GIT_VERSION_SUFFIX "${GIT_VERSION_SUFFIX}${GIT_TAG}")
MESSAGE(STATUS "GIT_VERSION_SUFFIX: ${GIT_VERSION_SUFFIX}")
MESSAGE(STATUS "")

View file

@ -1,28 +0,0 @@
cmake_minimum_required (VERSION 3.6)
# Сохраняем копию файла с версией программы и каждый раз обновляем при конфигуре через Cmake
if(EXISTS "${CMAKE_SOURCE_DIR}/source/snag/version_.d.bak")
configure_file(
"${CMAKE_SOURCE_DIR}/source/snag/version_.d.bak"
"${CMAKE_SOURCE_DIR}/source/snag/version_.d"
COPYONLY
)
else()
configure_file(
"${CMAKE_SOURCE_DIR}/source/snag/version_.d"
"${CMAKE_SOURCE_DIR}/source/snag/version_.d.bak"
COPYONLY
)
endif()
# Чтение файла version_.d
file(READ "${CMAKE_SOURCE_DIR}/source/snag/version_.d" VERSION_FILE_CONTENT)
# Извлечение строки версии (например, "0.1.0-alpha.1")
string(REGEX MATCH "snagVersion = \"([0-9]+)\\.([0-9]+)\\.([0-9]+)([^\"]*)\"" _ ${VERSION_FILE_CONTENT})
# Установка переменных для мажорной, минорной, патч-версии и суффикса
set(PROJECT_VERSION_MAJOR ${CMAKE_MATCH_1})
set(PROJECT_VERSION_MINOR ${CMAKE_MATCH_2})
set(PROJECT_VERSION_PATCH ${CMAKE_MATCH_3})
set(PROJECT_VERSION_SUFFIX ${CMAKE_MATCH_4})

View file

@ -1,6 +1,6 @@
# Сборка из под Debian # Сборка из под Debian
``` ```
cmake . -DGIT_HASH_VERSION=ON cmake .
dpkg-buildpackage -us -uc -nc dpkg-buildpackage -us -uc -nc
``` ```

2
debian/rules vendored
View file

@ -8,7 +8,7 @@ DEST_DIR = $(DEBIAN_DIR)/snag
dh $@ $(BUILD_SYSTEM) dh $@ $(BUILD_SYSTEM)
override_dh_auto_configure: override_dh_auto_configure:
cmake -S . -B build -DCMAKE_INSTALL_PREFIX=/usr -DGIT_HASH_VERSION=ON cmake -S . -B build -DCMAKE_INSTALL_PREFIX=/usr
override_dh_auto_build: override_dh_auto_build:
cmake --build build cmake --build build

View file

@ -237,9 +237,7 @@ int main(string[] args)
return EXIT_FAILURE; return EXIT_FAILURE;
} catch (Exception e) { } catch (Exception e) {
writeln( writeln(
"AN UNEXPECTED ERROR HAS OCCURRED!\n", "AN UNEXPECTED ERROR HAS OCCURRED! PLEASE REPORT IT TO THE AUTHOR OF THE SNAG!\n\n",
"PLEASE REPORT IT TO THE AUTHOR OF THE SNAG: ",
"alexander@zhirov.kz (Alexander Zhirov)\n\n",
e e
); );
return EXIT_FAILURE; return EXIT_FAILURE;

View file

@ -22,8 +22,8 @@ class Snag {
this(SnagConfig config) { this(SnagConfig config) {
_baseCommand = format( _baseCommand = format(
"git -C %s --git-dir=%s --work-tree=%s", "git --git-dir=%s --work-tree=%s",
config.project, config.git, config.project config.git, config.project
).split(); ).split();
_config = config; _config = config;
@ -131,7 +131,7 @@ class Snag {
} }
writeln("The following list of files requires backup:"); writeln("The following list of files requires backup:");
result.output.split('\n')[0..$-1].map!(e => result.output.split('\n')[0..$-1].map!(e =>
e.strip.splitByFirstSpace e.strip.split
).each!(e => ).each!(e =>
writefln("\t%s\t/%s", gitStatus(e[0], true), e[1]) writefln("\t%s\t/%s", gitStatus(e[0], true), e[1])
); );
@ -158,7 +158,7 @@ class Snag {
result = execute(_baseCommand ~ ["rev-parse", "--short", "HEAD"]); result = execute(_baseCommand ~ ["rev-parse", "--short", "HEAD"]);
if (result.status == 128) { if (result.status == 128) {
// Если это самый первый коммит после инициализации репозитория // Если это самый первый коммит после инициализации репозитория
git(["add", _config.project], "Failed to prepare files for archiving"); git(["add", "."], "Failed to prepare files for archiving");
git(["commit", "-m"] ~ message, "Failed to create a snapshot"); git(["commit", "-m"] ~ message, "Failed to create a snapshot");
newSnapshot = git( newSnapshot = git(
["rev-parse", "--short", "HEAD"], ["rev-parse", "--short", "HEAD"],
@ -197,7 +197,7 @@ class Snag {
"Failed to create a branch from the current state" "Failed to create a branch from the current state"
); );
git( git(
["add", _config.project], ["add", "."],
"Failed to prepare files for archiving" "Failed to prepare files for archiving"
); );
git( git(
@ -211,7 +211,7 @@ class Snag {
} else { } else {
// Если коммит является посленим в ветке // Если коммит является посленим в ветке
git( git(
["add", _config.project], ["add", "."],
"Failed to prepare files for archiving" "Failed to prepare files for archiving"
); );
git( git(
@ -250,7 +250,7 @@ class Snag {
[ [
"log", "log",
"--all", "--all",
"--date=format:%Y.%m.%d %H:%M:%S", "--date=format:%Y.%m.%d %H:%M",
"--pretty=" ~ format "--pretty=" ~ format
], ],
"Failed to retrieve the list of snapshots" "Failed to retrieve the list of snapshots"
@ -273,7 +273,7 @@ class Snag {
); );
if (result.output.length) { if (result.output.length) {
git( git(
["restore", _config.project], ["restore", "."],
"Failed to reset file changes state" "Failed to reset file changes state"
); );
git( git(
@ -381,8 +381,8 @@ class Snag {
// Выполнение git команд относительно распакованного архива // Выполнение git команд относительно распакованного архива
string[] customCommand = format( string[] customCommand = format(
"git -C %s --git-dir=%s --work-tree=%s", "git --git-dir=%s --work-tree=%s",
tempDirectory, _config.git, tempDirectory _config.git, tempDirectory
).split(); ).split();
// Необходимо проверить, что текущее состояние файлов не идентично файлам распакованного архива // Необходимо проверить, что текущее состояние файлов не идентично файлам распакованного архива
@ -406,7 +406,7 @@ class Snag {
); );
// Создание нового снимка на основе состояния файлов из распакованного архива // Создание нового снимка на основе состояния файлов из распакованного архива
result = execute(customCommand ~ ["add", tempDirectory]); result = execute(customCommand ~ ["add", "."]);
result.status && result.status &&
throw new SnagException( throw new SnagException(
"Failed to prepare files for archiving:\n" "Failed to prepare files for archiving:\n"
@ -427,7 +427,7 @@ class Snag {
// Сброс состояния файлов // Сброс состояния файлов
git( git(
["restore", _config.project], ["restore", "."],
"Failed to reset file changes state" "Failed to reset file changes state"
); );
git( git(

View file

@ -75,8 +75,8 @@ class SnagRules {
_gitignoreBak = _gitignore ~ ".bak"; _gitignoreBak = _gitignore ~ ".bak";
_baseCommand = format( _baseCommand = format(
"git -C %s --git-dir=%s --work-tree=%s", "git --git-dir=%s --work-tree=%s",
config.project, config.git, config.project config.git, config.project
).split(); ).split();
generate(); generate();

View file

@ -2,8 +2,6 @@ module snag.lib.lib;
import std.regex; import std.regex;
import std.process; import std.process;
import std.algorithm;
import std.string;
bool isValidHash(string hash) { bool isValidHash(string hash) {
auto hashPattern = ctRegex!r"^[a-fA-F0-9]{7}$"; auto hashPattern = ctRegex!r"^[a-fA-F0-9]{7}$";
@ -19,9 +17,3 @@ bool checkGit() {
auto result = execute(["which", "git"]); auto result = execute(["which", "git"]);
return !result.status; return !result.status;
} }
string[] splitByFirstSpace(string line) {
auto spaceIndex = line.indexOf(' ');
return spaceIndex == -1 ?
[line] : [line[0 .. spaceIndex], line[spaceIndex + 1..$]];
}

View file

@ -1,3 +1,3 @@
module snag.version_; module snag.version_;
enum snagVersion = "${PROJECT_VERSION_DISPLAY}${PROJECT_VERSION_SUFFIX}${GIT_VERSION_SUFFIX}"; enum snagVersion = "${PROJECT_VERSION_DISPLAY}";