Scafold

The following is a Bash script I've created to bootstrap small C projects. I'm trying to (re)learn C programming:

#!/bin/bash

GIT=`which git`
MSG="initial commit from $USER on $(date)"
CURRENT_DIRECTORY=`pwd`
PROJECT_NAME=$1
EXECUTABLE_NAME="${2:-clap}"

if [[ -z "${PROJECT_NAME}" ]]; then
  echo "Please add the name of the project"
  exit
fi

if [[ -d "${CURRENT_DIRECTORY}/${PROJECT_NAME}" ]]; then
  echo "The folder exists. Choose another name"
  exit
fi

# project tree
mkdir -p "${CURRENT_DIRECTORY}/${PROJECT_NAME}"/{build,src,docs,include,lib,tests,data}

# clang format config
clang-format --style=llvm -dump-config > "${CURRENT_DIRECTORY}/${PROJECT_NAME}"/.clang-format

# Makefile header
cat <<EOF >> "${CURRENT_DIRECTORY}/${PROJECT_NAME}"/Makefile
SHELL := /bin/sh
EXECUTABLE := $EXECUTABLE_NAME

EOF

# Makefile body
cat <<"EOF" >> "${CURRENT_DIRECTORY}/${PROJECT_NAME}"/Makefile
BIN_DIR = $(shell echo $${HOME})/bin

BUILD_DIR ?= build
SRC_DIRS ?= src

SRCS := $(shell find $(SRC_DIRS) -name *.c)
OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)
DEPS := $(OBJS:.o=.d)

INC_DIRS := $(shell find $(SRC_DIRS) -type d)
INC_FLAGS := $(addprefix -I,$(INC_DIRS))
CFLAGS ?= $(INC_FLAGS) -g -Wall -Wfatal-errors -pedantic -Wextra -std=c99 -MMD -MP

install: $(BUILD_DIR)/$(EXECUTABLE) ## install prog
	@echo "installing..."
	$(CP) $(BUILD_DIR)/$(EXECUTABLE) $(BIN_DIR)

$(BUILD_DIR)/$(EXECUTABLE): $(OBJS) ## build executable
	@echo "building executable file..."
	$(CC) $(OBJS) -o $@ $(LDFLAGS)

$(BUILD_DIR)/%.c.o: %.c clean ## build object files
	@echo "building object files..."
	@$(MKDIR_P) $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

format:
	@echo "reformatting..."
	find . -iname *.h -o -iname *.c | xargs clang-format -style=file -i -fallback-style=none

clean: ## delete build files
	@echo "deleting old build..."
	@$(RM) -r $(BUILD_DIR)
	@$(RM) -r $(BIN_DIR)/$(EXECUTABLE)

-include $(DEPS)

MKDIR_P ?= mkdir -p
CP ?= cp -r

.PHONY: clean install help format
EOF


# main source file
cat <<EOF > "${CURRENT_DIRECTORY}/${PROJECT_NAME}"/src/main.c
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>


int main (int argc, char **argv) {
    printf("Hello World.\n");
    exit(EXIT_SUCCESS);
}

EOF

# git it
cd ${PROJECT_NAME}
${GIT} init -q .
${GIT} add --all .
${GIT} commit -m "$MSG"