Files
2026-11-04 04:58:48 -08:00

116 lines
2.7 KiB
Go

package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/luciochen233/luphoto/internal/app"
"github.com/luciochen233/luphoto/internal/build"
"github.com/luciochen233/luphoto/internal/config"
)
var version = "dev"
const usage = `usage: luphoto [-config path] <command>
commands:
build process albums once and publish a new build
serve build, watch and serve over HTTP on server.listen
export build into the output folder and keep watching
run serve or export, as server.mode says
version print the version
flags:
-config path config file (default /etc/luphoto/config.toml; a missing file means all defaults)
signals:
SIGHUP re-read the config and rebuild
SIGINT/SIGTERM stop gracefully
`
func main() {
os.Exit(run(os.Args[1:]))
}
func run(args []string) int {
logger := log.New(os.Stderr, "", 0)
global := flag.NewFlagSet("luphoto", flag.ContinueOnError)
global.SetOutput(os.Stderr)
global.Usage = func() { fmt.Fprint(os.Stderr, usage) }
configPath := global.String("config", config.DefaultPath, "config file")
if err := global.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2
}
rest := global.Args()
if len(rest) == 0 {
fmt.Fprint(os.Stderr, usage)
return 2
}
command := rest[0]
sub := flag.NewFlagSet("luphoto "+command, flag.ContinueOnError)
sub.SetOutput(os.Stderr)
sub.Usage = global.Usage
sub.StringVar(configPath, "config", *configPath, "config file")
if err := sub.Parse(rest[1:]); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2
}
if sub.NArg() > 0 {
fmt.Fprintf(os.Stderr, "luphoto %s: unexpected arguments %v\n", command, sub.Args())
return 2
}
switch command {
case "version":
fmt.Println("luphoto " + version)
return 0
case "build", "serve", "export", "run":
default:
fmt.Fprintf(os.Stderr, "luphoto: unknown command %q\n\n%s", command, usage)
return 2
}
cfg, err := config.Load(*configPath)
if err != nil {
logger.Printf("luphoto: %v", err)
return 1
}
if cfg.Source == "" {
logger.Printf("luphoto: config %s not found, using defaults", *configPath)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if command == "build" {
summary, err := build.Run(ctx, cfg, logger)
if err != nil {
logger.Printf("luphoto: build failed: %v", err)
return 1
}
logger.Print(summary.String())
return 0
}
mode := command
if mode == "run" {
mode = cfg.Server.Mode
}
logger.Printf("luphoto %s: %s mode, config %s", version, mode, *configPath)
if err := app.Run(ctx, mode, *configPath, cfg, logger); err != nil {
logger.Printf("luphoto: %v", err)
return 1
}
return 0
}