Files
futriix/vendor_build.sh

413 lines
12 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# Copyright 2026 Safronov Grigorii
#
# Licensed under the CDDL, Version 1.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at
# https://opensource.org/licenses/CDDL-1.0
#
# Скрипт сборки futriis с использованием vendoring зависимостей
# Поддерживает Linux и Illumos (OpenIndiana)
# После внеснения изменения(й) в файл "go.mod" требует ручного обновления зависимостей командой "go mod vendor"
# Ключевые отличия от исходного build.sh:
# Использование -mod=vendor - сборка из локальной копии зависимостей
# Автоматическое создание vendor - если директория отсутствует
# Проверка актуальности vendor - сравнение времени изменения go.mod и vendor/
# Дополнительные флаги - очистка, обновление, информация
# Кросс-компиляция - поддержка сборки для других ОС
# Улучшенный вывод - цветной, информативный
#########################################
# Как использовать скрипт
########################################
# Полная сборка для всех платформ
# ./vendoring_build.sh
# Сборка только для Linux
# ./vendoring_build.sh -l
# Сборка только для Illumos
# ./vendoring_build.sh -m
# Сборка только для текущей ОС
# ./vendoring_build.sh -o
# Очистка бинарников
# ./vendoring_build.sh -c
# Полная очистка (бинарники + vendor)
# ./vendoring_build.sh -C
# Обновление зависимостей
# ./vendoring_build.sh -u
# Показать информацию о зависимостях
# ./vendoring_build.sh -i
# Показать справку
# ./vendoring_build.sh -h
set -e
# Цвета для вывода
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Функции для вывода сообщений
error_msg() {
echo -e "${RED}$1${NC}"
}
success_msg() {
echo -e "${GREEN}$1${NC}"
}
info_msg() {
echo -e "${BLUE}📋 $1${NC}"
}
warning_msg() {
echo -e "${YELLOW}⚠️ $1${NC}"
}
print_separator() {
echo "================================================"
}
# Проверка наличия Go
check_go() {
info_msg "Checking Go installation..."
if ! command -v go &> /dev/null; then
error_msg "Go is not installed or not in PATH"
exit 1
fi
GO_VERSION=$(go version | awk '{print $3}')
success_msg "Go found: $GO_VERSION"
}
# Проверка и создание vendor директории
setup_vendor() {
info_msg "Checking vendor directory..."
if [ ! -d "vendor" ]; then
warning_msg "Vendor directory not found. Creating vendor dependencies..."
info_msg "Running: go mod vendor"
if go mod vendor; then
success_msg "Vendor dependencies created successfully"
else
error_msg "Failed to create vendor dependencies"
exit 1
fi
else
info_msg "Vendor directory already exists"
# Проверяем, не изменился ли go.mod
if [ -f "go.mod" ] && [ -f "vendor/modules.txt" ]; then
GO_MOD_TIME=$(stat -c %Y "go.mod" 2>/dev/null || stat -f %m "go.mod" 2>/dev/null)
VENDOR_TIME=$(stat -c %Y "vendor/modules.txt" 2>/dev/null || stat -f %m "vendor/modules.txt" 2>/dev/null)
if [ "$GO_MOD_TIME" -gt "$VENDOR_TIME" ] 2>/dev/null; then
warning_msg "go.mod is newer than vendor directory"
warning_msg "Consider running: go mod vendor"
fi
fi
fi
}
# Создание директории bin
create_bin_dir() {
if [ ! -d "bin" ]; then
info_msg "Creating bin directory..."
mkdir -p bin
success_msg "Bin directory created"
fi
}
# Сборка для Linux
build_linux() {
info_msg "Building for Linux..."
OUTPUT="bin/futriis-linux-vendor"
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -mod=vendor \
-ldflags="-s -w -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
-o "$OUTPUT" ./cmd/futriis
if [ $? -eq 0 ]; then
success_msg "Linux build successful: $OUTPUT"
# Копируем в корень для удобства
cp "$OUTPUT" ./futriis-linux-vendor 2>/dev/null || true
info_msg "Binary copied to: ./futriis-linux-vendor"
# Показываем размер бинарника
SIZE=$(ls -lh "$OUTPUT" | awk '{print $5}')
info_msg "Binary size: $SIZE"
else
error_msg "Linux build failed"
return 1
fi
}
# Сборка для Illumos (OpenIndiana)
build_illumos() {
info_msg "Building for Illumos (OpenIndiana)..."
OUTPUT="bin/futriis-illumos-vendor"
# Для Illumos используем теги и включаем CGO
GOOS=illumos GOARCH=amd64 CGO_ENABLED=1 go build -mod=vendor \
-tags=illumos \
-ldflags="-s -w -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
-o "$OUTPUT" ./cmd/futriis
if [ $? -eq 0 ]; then
success_msg "Illumos build successful: $OUTPUT"
# Копируем в корень для удобства
cp "$OUTPUT" ./futriis-illumos-vendor 2>/dev/null || true
info_msg "Binary copied to: ./futriis-illumos-vendor"
# Показываем размер бинарника
SIZE=$(ls -lh "$OUTPUT" | awk '{print $5}')
info_msg "Binary size: $SIZE"
else
error_msg "Illumos build failed"
return 1
fi
}
# Сборка для текущей ОС (для разработки)
build_current() {
info_msg "Building for current OS ($(uname -s))..."
OUTPUT="bin/futriis-current-vendor"
go build -mod=vendor \
-ldflags="-s -w -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
-o "$OUTPUT" ./cmd/futriis
if [ $? -eq 0 ]; then
success_msg "Current OS build successful: $OUTPUT"
# Копируем в корень для удобства
cp "$OUTPUT" ./futriis-current-vendor 2>/dev/null || true
info_msg "Binary copied to: ./futriis-current-vendor"
SIZE=$(ls -lh "$OUTPUT" | awk '{print $5}')
info_msg "Binary size: $SIZE"
else
error_msg "Current OS build failed"
return 1
fi
}
# Очистка бинарных файлов
clean() {
info_msg "Cleaning binary files..."
rm -f bin/futriis-*-vendor
rm -f ./futriis-*-vendor
success_msg "Clean completed"
}
# Очистка vendor директории
clean_vendor() {
info_msg "Cleaning vendor directory..."
rm -rf vendor
success_msg "Vendor directory removed"
}
# Обновление зависимостей
update_deps() {
info_msg "Updating dependencies..."
info_msg "Running: go get -u ./..."
go get -u ./...
info_msg "Running: go mod tidy"
go mod tidy
info_msg "Running: go mod vendor"
go mod vendor
success_msg "Dependencies updated"
}
# Показать информацию о зависимостях
show_deps() {
info_msg "Project dependencies:"
echo ""
if [ -f "go.mod" ]; then
echo "Direct dependencies:"
go list -m all | head -20
echo ""
fi
if [ -d "vendor" ]; then
echo "Vendor directory size:"
du -sh vendor 2>/dev/null || echo "Cannot determine size"
echo ""
echo "Number of packages in vendor:"
find vendor -name "*.go" 2>/dev/null | wc -l
fi
}
# Показать справку
show_help() {
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -h, --help Show this help message"
echo " -c, --clean Clean build artifacts"
echo " -C, --clean-all Clean build artifacts and vendor directory"
echo " -u, --update Update dependencies and rebuild vendor"
echo " -i, --info Show dependency information"
echo " -l, --linux Build only for Linux"
echo " -m, --illumos Build only for Illumos"
echo " -o, --only-os Build only for current OS"
echo ""
echo "Examples:"
echo " $0 # Build for all supported platforms"
echo " $0 -l # Build only for Linux"
echo " $0 -c # Clean build artifacts"
echo " $0 -u # Update dependencies and rebuild"
}
# Основная функция
main() {
print_separator
echo -e "${GREEN}🔨 Building futriis database with vendoring${NC}"
print_separator
# Определяем ОС
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
info_msg "Detected OS: $OS"
# Обработка аргументов командной строки
BUILD_LINUX=true
BUILD_ILLUMOS=true
BUILD_CURRENT=false
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
show_help
exit 0
;;
-c|--clean)
clean
exit 0
;;
-C|--clean-all)
clean
clean_vendor
exit 0
;;
-u|--update)
update_deps
exit 0
;;
-i|--info)
show_deps
exit 0
;;
-l|--linux)
BUILD_LINUX=true
BUILD_ILLUMOS=false
BUILD_CURRENT=false
shift
;;
-m|--illumos)
BUILD_LINUX=false
BUILD_ILLUMOS=true
BUILD_CURRENT=false
shift
;;
-o|--only-os)
BUILD_LINUX=false
BUILD_ILLUMOS=false
BUILD_CURRENT=true
shift
;;
*)
error_msg "Unknown option: $1"
show_help
exit 1
;;
esac
done
# Проверяем Go
check_go
# Создаём vendor зависимости
setup_vendor
# Создаём bin директорию
create_bin_dir
print_separator
# Сборка
BUILD_FAILED=0
if [ "$BUILD_CURRENT" = true ]; then
if ! build_current; then
BUILD_FAILED=1
fi
else
if [ "$BUILD_LINUX" = true ] && [ "$OS" != "linux" ]; then
info_msg "Cross-compiling for Linux..."
if ! build_linux; then
BUILD_FAILED=1
fi
elif [ "$BUILD_LINUX" = true ] && [ "$OS" = "linux" ]; then
if ! build_current; then
BUILD_FAILED=1
fi
fi
if [ "$BUILD_ILLUMOS" = true ] && [ "$OS" != "sunos" ] && [ "$OS" != "illumos" ]; then
info_msg "Cross-compiling for Illumos..."
if ! build_illumos; then
BUILD_FAILED=1
fi
elif [ "$BUILD_ILLUMOS" = true ] && ([ "$OS" = "sunos" ] || [ "$OS" = "illumos" ]); then
if ! build_current; then
BUILD_FAILED=1
fi
fi
fi
print_separator
if [ $BUILD_FAILED -eq 0 ]; then
success_msg "All builds completed successfully!"
# Показываем список созданных бинарников
echo ""
info_msg "Generated binaries:"
ls -lh bin/futriis-*-vendor 2>/dev/null || echo " No binaries in bin/"
echo ""
info_msg "To run the database:"
echo " ./futriis-linux-vendor # On Linux"
echo " ./futriis-illumos-vendor # On Illumos/OpenIndiana"
else
error_msg "Some builds failed"
exit 1
fi
}
# Запуск основной функции
main "$@"