summaryrefslogtreecommitdiff
path: root/build.sh
blob: 339b19afa42eb00cbaf115b0d0d5b6e8cbd4a4d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#!/usr/bin/env bash
# build.sh - Professional build script for BoltDBG (improved)
#
# Usage:
#   ./build.sh                          # Debug build (preset: debug)
#   ./build.sh --preset release         # Release build
#   ./build.sh --preset debug-asan      # Debug with ASAN
#   ./build.sh --clean                  # Clean build
#   ./build.sh --install                # Build and install
#   ./build.sh --format                 # Format code before build
#   ./build.sh --help                   # Show help
#
# Environment variables:
#   CMAKE_PRESET     - CMake preset to use (default: debug)
#   JOBS             - Number of parallel jobs (default: auto -> detected)
#   BUILD_DIR        - Build directory (default: build/<preset>)
#   INSTALL_PREFIX   - Install prefix (default: /usr/local)

set -euo pipefail

# ============================================================================
# Configuration
# ============================================================================

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="${SCRIPT_DIR}"

# Defaults (can be overridden by env)
: "${CMAKE_PRESET:=debug}"
: "${JOBS:=auto}"
: "${INSTALL_PREFIX:=/usr/local}"
: "${VERBOSE:=0}"

# Flags
CLEAN_BUILD=1
RUN_INSTALL=0
RUN_TESTS=0
RUN_FORMAT=0
SHOW_HELP=0

# ============================================================================
# Colors and Formatting
# ============================================================================

if [[ -t 1 ]]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    BLUE='\033[0;34m'
    BOLD='\033[1m'
    NC='\033[0m' # No Color
else
    RED=''
    GREEN=''
    YELLOW=''
    BLUE=''
    BOLD=''
    NC=''
fi

# ============================================================================
# Helper Functions
# ============================================================================

log_info()    { echo -e "${BLUE}[INFO]${NC} $*"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $*"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $*"; }
log_error()   { echo -e "${RED}[ERROR]${NC} $*" >&2; }
log_header()  {
    echo
    echo -e "${BOLD}========================================${NC}"
    echo -e "${BOLD}$*${NC}"
    echo -e "${BOLD}========================================${NC}"
}

require_cmd() {
    if ! command -v "$1" >/dev/null 2>&1; then
        log_error "Required command '$1' not found. Please install it."
        exit 2
    fi
}

detect_jobs() {
    if [[ "${JOBS}" == "auto" ]]; then
        if command -v nproc >/dev/null 2>&1; then
            JOBS="$(nproc)"
        elif [[ "$(uname)" == "Darwin" ]] && command -v sysctl >/dev/null 2>&1; then
            JOBS="$(sysctl -n hw.ncpu)"
        else
            JOBS=2
        fi
    fi
    # ensure integer
    if ! [[ "${JOBS}" =~ ^[0-9]+$ ]]; then
        JOBS=2
    fi
}

show_help() {
    cat << EOF
${BOLD}BoltDBG Build Script${NC}

USAGE:
    $0 [OPTIONS]

OPTIONS:
    --preset PRESET       CMake preset (debug, release, debug-asan, etc.)
    --clean               Remove build directory before building
    --install             Install after building
    --no-tests            Skip running tests
    --format              Run code formatter before building
    --jobs N              Number of parallel build jobs (default: auto)
    --prefix PATH         Installation prefix (default: /usr/local)
    --verbose             Enable verbose output
    --help                Show this help message

PRESETS:
    debug                 Debug build with symbols
    release               Optimized release build
    debug-asan            Debug with Address Sanitizer
    debug-ubsan           Debug with UB Sanitizer
    debug-tsan            Debug with Thread Sanitizer
    ci                    CI/CD build configuration

EXAMPLES:
    $0                              # Basic debug build
    $0 --preset release             # Release build
    $0 --preset debug-asan --clean  # Clean ASAN build
    $0 --install --prefix ~/local   # Build and install to ~/local
    $0 --format --preset release    # Format then build release

EOF
    exit 0
}

# ============================================================================
# Argument Parsing
# ============================================================================

while [[ $# -gt 0 ]]; do
    case $1 in
        --preset)
            CMAKE_PRESET="${2:-}"
            shift 2
            ;;
        --clean)
            CLEAN_BUILD=1
            shift
            ;;
        --install)
            RUN_INSTALL=1
            shift
            ;;
        --no-tests)
            RUN_TESTS=0
            shift
            ;;
        --format)
            RUN_FORMAT=1
            shift
            ;;
        --jobs)
            JOBS="${2:-}"
            shift 2
            ;;
        --prefix)
            INSTALL_PREFIX="${2:-}"
            shift 2
            ;;
        --verbose)
            VERBOSE=1
            shift
            ;;
        --help|-h)
            SHOW_HELP=1
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

if [[ $SHOW_HELP -eq 1 ]]; then
    show_help
fi

# ============================================================================
# Prerequisites
# ============================================================================

require_cmd cmake
require_cmd git

detect_jobs

BUILD_DIR="${ROOT_DIR}/build/${CMAKE_PRESET}"

# ============================================================================
# Main Build Process
# ============================================================================

log_header "BoltDBG Build Configuration"
log_info "Root directory:    ${ROOT_DIR}"
log_info "Build directory:   ${BUILD_DIR}"
log_info "CMake preset:      ${CMAKE_PRESET}"
log_info "Parallel jobs:     ${JOBS}"
log_info "Install prefix:    ${INSTALL_PREFIX}"
log_info "Clean build:       ${CLEAN_BUILD}"
log_info "Run tests:         ${RUN_TESTS}"
log_info "Run install:       ${RUN_INSTALL}"

# Step 1: Code formatting (optional)
if [[ $RUN_FORMAT -eq 1 ]]; then
    log_header "Step 1/6: Code Formatting"
    if [[ -f "${ROOT_DIR}/scripts/format.sh" ]]; then
        "${ROOT_DIR}/scripts/format.sh"
        log_success "Code formatted"
    else
        log_warning "scripts/format.sh not found, skipping formatting"
    fi
else
    log_info "Skipping code formatting (use --format to enable)"
fi

# Step 2: Fetch dependencies (optional helper)
# If you use submodules or have a fetch script, run it here.
if [[ -f "${ROOT_DIR}/scripts/fetch_deps.sh" ]]; then
    log_header "Step 2/6: Fetch Dependencies"
    "${ROOT_DIR}/scripts/fetch_deps.sh" || {
        log_warning "fetch_deps.sh failed or returned non-zero, continuing anyway"
    }
else
    log_info "No fetch_deps.sh found — relying on CMake FetchContent or vendored deps"
fi

# Step 3: Clean (optional)
if [[ $CLEAN_BUILD -eq 1 ]]; then
    log_header "Step 3/6: Clean Build Directory"
    if [[ -d "${BUILD_DIR}" ]]; then
        log_info "Removing ${BUILD_DIR}..."
        rm -rf "${BUILD_DIR}"
        log_success "Build directory cleaned"
    else
        log_info "Build directory does not exist, nothing to clean"
    fi
else
    log_info "Using existing build directory (use --clean for fresh build)"
fi

# Step 4: Configure
log_header "Step 4/6: CMake Configure"
mkdir -p "${BUILD_DIR}"

# If CMakePresets.json exists, prefer using presets. Otherwise fallback to manual args.
CMAKE_CONF_ARGS=()
CMAKE_CONF_ARGS+=("-DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX}")

if [[ "${VERBOSE}" -eq 1 ]]; then
    CMAKE_CONF_ARGS+=("-DCMAKE_VERBOSE_MAKEFILE=ON")
fi

if [[ -f "${ROOT_DIR}/CMakePresets.json" ]]; then
    # Use preset; need to call with -S and -B for predictable behavior
    log_info "Found CMakePresets.json — configuring with preset '${CMAKE_PRESET}'"
    cmake -S "${ROOT_DIR}" -B "${BUILD_DIR}" --preset "${CMAKE_PRESET}" "${CMAKE_CONF_ARGS[@]}"
else
    # Fallback: map simple preset names to CMAKE_BUILD_TYPE and sanitizer flags
    log_info "No CMakePresets.json — using fallback configure for preset '${CMAKE_PRESET}'"
    case "${CMAKE_PRESET}" in
        debug)
            CMAKE_CONF_ARGS+=("-DCMAKE_BUILD_TYPE=Debug")
            ;;
        release)
            CMAKE_CONF_ARGS+=("-DCMAKE_BUILD_TYPE=Release")
            ;;
        debug-asan)
            CMAKE_CONF_ARGS+=("-DCMAKE_BUILD_TYPE=Debug" "-DBOLTDBG_ENABLE_ASAN=ON")
            ;;
        debug-ubsan)
            CMAKE_CONF_ARGS+=("-DCMAKE_BUILD_TYPE=Debug" "-DBOLTDBG_ENABLE_UBSAN=ON")
            ;;
        debug-tsan)
            CMAKE_CONF_ARGS+=("-DCMAKE_BUILD_TYPE=Debug" "-DBOLTDBG_ENABLE_TSAN=ON")
            ;;
        ci)
            CMAKE_CONF_ARGS+=("-DCMAKE_BUILD_TYPE=RelWithDebInfo")
            ;;
        *)
            # default fallback
            CMAKE_CONF_ARGS+=("-DCMAKE_BUILD_TYPE=Debug")
            log_warning "Unknown preset '${CMAKE_PRESET}', falling back to Debug build type"
            ;;
    esac

    # Run configure explicitly with -S and -B
    log_info "Running: cmake -S ${ROOT_DIR} -B ${BUILD_DIR} ${CMAKE_CONF_ARGS[*]}"
    cmake -S "${ROOT_DIR}" -B "${BUILD_DIR}" "${CMAKE_CONF_ARGS[@]}"
fi

log_success "Configuration complete"

# Step 5: Build
log_header "Step 5/6: Build"

# Build args for cmake --build
CMAKE_BUILD_ARGS=(--build "${BUILD_DIR}" --parallel "${JOBS}")
if [[ "${VERBOSE}" -eq 1 ]]; then
    CMAKE_BUILD_ARGS+=(--verbose)
fi

log_info "Running: cmake ${CMAKE_BUILD_ARGS[*]}"
cmake "${CMAKE_BUILD_ARGS[@]}"
log_success "Build complete"

# Step 6: Tests
if [[ $RUN_TESTS -eq 1 ]]; then
    log_header "Step 6/6: Run Tests"
    if command -v ctest >/dev/null 2>&1; then
        (
            cd "${BUILD_DIR}"
            if ! ctest --output-on-failure --parallel "${JOBS}"; then
                log_error "Some tests failed"
                exit 1
            fi
        )
        log_success "All tests passed"
    else
        log_warning "ctest not found, skipping tests"
    fi
else
    log_info "Skipping tests (use --no-tests to enable)"
fi

# Optional: Install
if [[ $RUN_INSTALL -eq 1 ]]; then
    log_header "Installing"
    cmake --install "${BUILD_DIR}" --prefix "${INSTALL_PREFIX}"
    log_success "Installation complete to ${INSTALL_PREFIX}"
fi

# ============================================================================
# Summary
# ============================================================================

log_header "Build Complete"

# Try to guess executable path, but don't assume too much
POSSIBLE_BIN="${BUILD_DIR}/src/boltdbg"
if [[ -x "${POSSIBLE_BIN}" ]]; then
    log_success "Executable: ${POSSIBLE_BIN}"
else
    log_info "Executable not found at ${POSSIBLE_BIN}. Check your targets inside ${BUILD_DIR}"
    log_info "You can inspect build tree or run: cmake --build ${BUILD_DIR} --target <your-target>"
fi

if [[ $RUN_INSTALL -eq 1 ]]; then
    log_success "Installed to: ${INSTALL_PREFIX}/bin/ (if install step created it)"
fi

echo
log_info "To run the application (if present):"
echo "  ${POSSIBLE_BIN}"
echo
log_info "To run tests manually:"
echo "  cd ${BUILD_DIR} && ctest --output-on-failure"
echo
log_info "To install manually:"
echo "  cmake --install ${BUILD_DIR} --prefix ${INSTALL_PREFIX}"
echo

exit 0