Skip to content

Instantly share code, notes, and snippets.

@pszponder
Created December 18, 2023 04:00
Show Gist options
  • Save pszponder/7b10359092e79c6086e393b8cf6bf187 to your computer and use it in GitHub Desktop.
Save pszponder/7b10359092e79c6086e393b8cf6bf187 to your computer and use it in GitHub Desktop.
Shell script to initialize a go project. To run, type chmod + x init.sh && ./init.sh
#!/usr/bin/env bash
# This script will create a new Golang project with a Makefile and some basic directories and files.
# It will also initialize a Git repository and make an initial commit.
# Use this script by running the following command: chmod +x init.sh && ./init.sh
# Get user input for the module path
read -p "Enter the module path (e.g., github.com/<username>/<project-name>): " module_path
# Create project directories
project_name=$(basename "$module_path")
project_root=$(pwd)
directories=("bin" "cmd" "tests" "internal" "pkg" "cmd/$project_name")
for dir in "${directories[@]}"; do
mkdir -p "$project_root/$dir"
done
# Create main.go using a here document
main_file="cmd/$project_name/main.go"
cat <<EOT >"$main_file"
package main
import "fmt"
func main() {
fmt.Println("It works!")
}
EOT
# Create .gitignore using a here document
gitignore_file="$project_root/.gitignore"
cat <<EOT >"$gitignore_file"
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
bin
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
EOT
# Create README.md using a here document
readme_file="$project_root/README.md"
cat <<EOT >"$readme_file"
# $project_name
This is a new Golang project.
## Getting Started
Reference the [Makefile](Makefile) for available commands.
\`\`\`bash
make help
\`\`\`
EOT
# Download and add Makefile from my Gist
makefile_url="https://gist.githubusercontent.com/pszponder/28ed7553b5d6d0847edd4c65cad880de/raw/9c7074436829ed4f7f3d41c2f0dfee68652bc5e7/Makefile"
echo "Downloading Makefile from $makefile_url"
curl -sSL "$makefile_url" > "$project_root/Makefile"
# Create go.mod using a here document
go mod init "$module_path"
# Initialize a Git repository
git init
# Add all files to the repository
git add .
# Commit everything as an initial commit
git commit -m "Initial commit"
# Delete the script
rm -- "$0"
echo "Golang Project setup complete! You can find your project in $project_root"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment