gitdeploy/main.go

298 lines
7.6 KiB
Go
Raw Normal View History

package main
import (
"compress/flate"
2020-09-29 10:40:09 +00:00
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"git.rootprojects.org/root/gitdeploy/assets/examples"
"git.rootprojects.org/root/gitdeploy/assets/public"
2020-11-21 12:41:01 +00:00
"git.rootprojects.org/root/gitdeploy/internal/api"
2020-12-01 00:48:09 +00:00
"git.rootprojects.org/root/gitdeploy/internal/log"
2020-10-09 09:22:06 +00:00
"git.rootprojects.org/root/gitdeploy/internal/options"
"git.rootprojects.org/root/gitdeploy/internal/webhooks"
"git.rootprojects.org/root/vfscopy"
2020-09-28 09:56:51 +00:00
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
2020-11-21 12:41:01 +00:00
2020-09-28 09:56:51 +00:00
_ "github.com/joho/godotenv/autoload"
)
var (
name = "gitdeploy"
version = "0.0.0"
date = "0001-01-01T00:00:00Z"
commit = "0000000"
)
func usage() {
2020-10-20 23:05:01 +00:00
fmt.Println(ver())
fmt.Println("")
2020-10-20 23:05:01 +00:00
fmt.Printf("Use '%s help <command>'\n", name)
fmt.Println(" init")
fmt.Println(" run")
}
2020-10-20 23:05:01 +00:00
func ver() string {
return fmt.Sprintf("%s v%s (%s) %s", name, version, commit[:7], date)
}
2020-09-28 23:39:05 +00:00
var runOpts *options.ServerConfig
var runFlags *flag.FlagSet
var initFlags *flag.FlagSet
var promotions []string
var promotionList string
var defaultPromotionList = "production,staging,master"
var oldScripts string
func init() {
2020-09-28 23:39:05 +00:00
runOpts = options.Server
2020-09-28 23:39:05 +00:00
initFlags = options.InitFlags
_ = initFlags.Bool("TODO", false, "init will eventually copy default assets into a local directory")
runFlags = options.ServerFlags
2020-10-09 08:15:39 +00:00
runFlags.StringVar(&runOpts.Addr, "listen", "", "the address and port on which to listen (default :4483)")
2020-09-28 23:39:05 +00:00
runFlags.BoolVar(&runOpts.TrustProxy, "trust-proxy", false, "trust X-Forwarded-For header")
runFlags.StringVar(&runOpts.RepoList, "trust-repos", "",
"list of repos (ex: 'github.com/org/repo', or '*' for all) for which to run '.gitdeploy/deploy.sh'")
2020-09-28 23:39:05 +00:00
runFlags.BoolVar(&runOpts.Compress, "compress", true, "enable compression for text,html,js,css,etc")
2020-09-29 03:15:30 +00:00
runFlags.StringVar(
&runOpts.ServePath, "serve-path", "",
"path to serve, falls back to built-in web app")
runFlags.StringVar(
&oldScripts, "exec", "",
"old alias for --scripts")
runFlags.StringVar(
&runOpts.ScriptsPath, "scripts", "",
2020-09-29 10:40:09 +00:00
"path to ./scripts/{deploy.sh,promote.sh,etc}")
//"path to bash script to run with git info as arguments")
runFlags.StringVar(&promotionList, "promotions", "",
"a list of promotable branches in descending order (default '"+defaultPromotionList+"')")
}
func main() {
2020-10-20 23:05:01 +00:00
// Support [--]version and -V
if len(os.Args) > 1 {
if "version" == strings.TrimLeft(os.Args[1], "-") || "-V" == os.Args[1] {
fmt.Println(ver())
os.Exit(0)
return
}
}
args := os.Args[:]
if 1 == len(args) {
// "run" should be the default
args = append(args, "run")
}
2020-10-20 23:05:01 +00:00
if "help" == strings.TrimLeft(args[1], "-") {
// top-level help
if 2 == len(args) {
usage()
os.Exit(0)
return
}
// move help to subcommand argument
self := args[0]
args = append([]string{self}, args[2:]...)
args = append(args, "--help")
}
switch args[1] {
case "version":
2020-10-20 23:05:01 +00:00
fmt.Println(ver())
os.Exit(0)
return
case "init":
2020-09-29 08:08:35 +00:00
_ = initFlags.Parse(args[2:])
gdInit()
os.Exit(0)
return
case "run":
2020-09-29 08:08:35 +00:00
_ = runFlags.Parse(args[2:])
if "" == runOpts.ScriptsPath {
if "" != oldScripts {
fmt.Fprintf(os.Stderr, "--exec is deprecated and will be removed. Please use --scripts instead.\n")
runOpts.ScriptsPath = oldScripts
}
}
if "" == runOpts.ScriptsPath {
runOpts.ScriptsPath = "./scripts"
pathname, _ := filepath.Abs("./scripts")
if info, _ := os.Stat("./scripts/deploy.sh"); nil == info || !info.Mode().IsRegular() {
fmt.Printf(
"%q not found.\nPlease provide --scripts ./scripts/ as a path where \"deploy.sh\" can be found\n",
pathname,
)
os.Exit(1)
}
2020-09-29 03:15:30 +00:00
}
2020-10-09 08:15:39 +00:00
if 0 == len(runOpts.Addr) {
runOpts.Addr = os.Getenv("LISTEN")
}
if 0 == len(runOpts.Addr) {
port := os.Getenv("PORT")
if len(port) > 0 {
runOpts.Addr = "localhost:" + port
}
}
2020-10-09 08:15:39 +00:00
if 0 == len(runOpts.Addr) {
runOpts.Addr = "localhost:4483"
2020-10-09 08:15:39 +00:00
}
if 0 == len(runOpts.Addr) {
fmt.Printf("--listen <[addr]:port> is a required flag")
os.Exit(1)
return
}
if 0 == len(runOpts.RepoList) {
runOpts.RepoList = os.Getenv("TRUST_REPOS")
}
if len(runOpts.RepoList) > 0 {
runOpts.RepoList = strings.ReplaceAll(runOpts.RepoList, ",", " ")
runOpts.RepoList = strings.ReplaceAll(runOpts.RepoList, " ", " ")
2020-10-26 20:12:43 +00:00
runOpts.RepoList = strings.ToLower(runOpts.RepoList)
}
2020-11-21 12:41:01 +00:00
cwd, _ := os.Getwd()
log.Printf("WORK_DIR=%s", cwd)
log.Printf("TRUST_REPOS=%s", runOpts.RepoList)
if 0 == len(promotionList) {
promotionList = os.Getenv("PROMOTIONS")
}
if 0 == len(promotionList) {
promotionList = defaultPromotionList
}
2020-11-21 12:41:01 +00:00
runOpts.Promotions = strings.Fields(
strings.ReplaceAll(promotionList, ",", " "),
)
2020-09-28 23:39:05 +00:00
webhooks.MustRegisterAll()
serve()
default:
usage()
os.Exit(1)
return
}
}
func gdInit() {
vfs := vfscopy.NewVFS(examples.Assets)
_, err := os.Open("scripts")
fmt.Println("Initiazing ...")
if !os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, " skip: ./scripts already exists\n")
} else {
if err := vfscopy.CopyAll(vfs, ".", "./scripts", vfscopy.Options{
AddPermission: os.FileMode(0600),
Skip: func(path string) (bool, error) {
if strings.HasSuffix(path, "/dotenv") {
return true, nil
}
f, _ := vfs.Open(path)
fi, _ := f.Stat()
if !fi.IsDir() {
fmt.Println(" copy: scripts/" + path)
}
return false, nil
},
}); nil != err {
fmt.Fprintf(os.Stderr, "error initializing ./scripts directory: %v\n", err)
os.Exit(1)
return
}
}
_, err = os.Open(".env")
if !os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, " skip: ./.env already exists\n")
} else {
if err := vfscopy.CopyAll(vfs, "dotenv", ".env", vfscopy.Options{
AddPermission: os.FileMode(0600),
}); nil != err {
fmt.Fprintf(os.Stderr, "error initializing ./.env file: %v\n", err)
os.Exit(1)
return
}
_ = os.Chmod(".env", 0600)
fmt.Println(" copy: .env")
}
fmt.Println("Done.")
}
func serve() {
r := chi.NewRouter()
// A good base middleware stack
2020-09-28 23:39:05 +00:00
if runOpts.TrustProxy {
r.Use(middleware.RealIP)
}
2020-09-28 23:39:05 +00:00
if runOpts.Compress {
r.Use(middleware.Compress(flate.DefaultCompression))
}
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
2020-09-28 09:43:30 +00:00
2020-10-20 23:05:01 +00:00
r.Get("/version", func(w http.ResponseWriter, r *http.Request) {
w.Write(append([]byte(ver()), '\n'))
})
r.Get("/api/version", func(w http.ResponseWriter, r *http.Request) {
b, _ := json.MarshalIndent(struct {
Name string `json:"name"`
Version string `json:"version"`
Date string `json:"date"`
Commit string `json:"commit"`
}{
Name: name,
Version: version,
Date: date,
Commit: commit,
}, "", " ")
w.Write(append(b, '\n'))
})
2020-11-21 12:41:01 +00:00
api.Route(r, runOpts)
2020-09-29 10:40:09 +00:00
2020-11-21 12:41:01 +00:00
var staticHandler http.HandlerFunc
pub := http.FileServer(public.Assets)
2020-09-29 10:40:09 +00:00
2020-11-21 12:41:01 +00:00
if len(runOpts.ServePath) > 0 {
// try the user-provided directory first, then fallback to the built-in
devFS := http.Dir(runOpts.ServePath)
dev := http.FileServer(devFS)
staticHandler = func(w http.ResponseWriter, r *http.Request) {
if _, err := devFS.Open(r.URL.Path); nil != err {
pub.ServeHTTP(w, r)
2020-09-29 10:40:09 +00:00
return
}
2020-11-21 12:41:01 +00:00
dev.ServeHTTP(w, r)
}
} else {
staticHandler = func(w http.ResponseWriter, r *http.Request) {
pub.ServeHTTP(w, r)
}
}
r.Get("/*", staticHandler)
2020-09-28 23:39:05 +00:00
fmt.Println("Listening for http (with reasonable timeouts) on", runOpts.Addr)
srv := &http.Server{
2020-09-28 23:39:05 +00:00
Addr: runOpts.Addr,
Handler: r,
ReadHeaderTimeout: 2 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 20 * time.Second,
MaxHeaderBytes: 1024 * 1024, // 1MiB
}
if err := srv.ListenAndServe(); nil != err {
fmt.Fprintf(os.Stderr, "%s", err)
os.Exit(1)
return
}
}