From 2a6d5408bdbf2f5a9884ee1c45e10f4203d35a27 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Wed, 27 Nov 2024 02:03:33 +0200 Subject: [PATCH] main: move version info to separate package and refactor other things --- .gitlab-ci.yml | 4 +- build.sh | 2 +- cmd/gomuks/main.go | 75 ++++----------------------------- pkg/gomuks/config.go | 2 +- pkg/gomuks/gomuks.go | 3 +- pkg/gomuks/server.go | 20 ++++++--- pkg/hicli/database/database.go | 2 + pkg/hicli/json.go | 20 +++++---- version/version.go | 76 ++++++++++++++++++++++++++++++++++ 9 files changed, 118 insertions(+), 86 deletions(-) create mode 100644 version/version.go diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 5d137b6..c95356f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -37,7 +37,7 @@ frontend: - export GOPATH="$CI_PROJECT_DIR/.cache" - export GOCACHE="$CI_PROJECT_DIR/.cache/build" - export MAUTRIX_VERSION=$(cat go.mod | grep 'maunium.net/go/mautrix ' | awk '{ print $2 }') - - export GO_LDFLAGS="-s -w -linkmode external -extldflags -static -X main.Tag=$CI_COMMIT_TAG -X main.Commit=$CI_COMMIT_SHA -X 'main.BuildTime=`date -Iseconds`' -X 'maunium.net/go/mautrix.GoModVersion=$MAUTRIX_VERSION'" + - export GO_LDFLAGS="-s -w -linkmode external -extldflags -static -X go.mau.fi/gomuks/version.Tag=$CI_COMMIT_TAG -X go.mau.fi/gomuks/version.Commit=$CI_COMMIT_SHA -X 'go.mau.fi/gomuks/version.BuildTime=`date -Iseconds`' -X 'maunium.net/go/mautrix.GoModVersion=$MAUTRIX_VERSION'" script: - go build -ldflags "$GO_LDFLAGS" -o gomuks ./cmd/gomuks artifacts: @@ -89,7 +89,7 @@ macos/arm64: before_script: - export PATH=/opt/homebrew/bin:$PATH - export MAUTRIX_VERSION=$(cat go.mod | grep 'maunium.net/go/mautrix ' | awk '{ print $2 }') - - export GO_LDFLAGS="-X main.Tag=$CI_COMMIT_TAG -X main.Commit=$CI_COMMIT_SHA -X 'main.BuildTime=`date -Iseconds`' -X 'maunium.net/go/mautrix.GoModVersion=$MAUTRIX_VERSION'" + - export GO_LDFLAGS="-X go.mau.fi/gomuks/version.Tag=$CI_COMMIT_TAG -X go.mau.fi/gomuks/version.Commit=$CI_COMMIT_SHA -X 'go.mau.fi/gomuks/version.BuildTime=`date -Iseconds`' -X 'maunium.net/go/mautrix.GoModVersion=$MAUTRIX_VERSION'" - export LIBRARY_PATH=$(brew --prefix)/lib - export CPATH=$(brew --prefix)/include script: diff --git a/build.sh b/build.sh index a5822f6..031cc2b 100755 --- a/build.sh +++ b/build.sh @@ -1,4 +1,4 @@ #!/usr/bin/env bash go generate ./web export MAUTRIX_VERSION=$(cat go.mod | grep 'maunium.net/go/mautrix ' | head -n1 | awk '{ print $2 }') -go build -ldflags "-X main.Tag=$(git describe --exact-match --tags 2>/dev/null) -X main.Commit=$(git rev-parse HEAD) -X 'main.BuildTime=`date -Iseconds`' -X 'maunium.net/go/mautrix.GoModVersion=$MAUTRIX_VERSION'" ./cmd/gomuks "$@" || exit 2 +go build -ldflags "-X go.mau.fi/gomuks/version.Tag=$(git describe --exact-match --tags 2>/dev/null) -X go.mau.fi/gomuks/version.Commit=$(git rev-parse HEAD) -X 'go.mau.fi/gomuks/version.BuildTime=`date -Iseconds`' -X 'maunium.net/go/mautrix.GoModVersion=$MAUTRIX_VERSION'" ./cmd/gomuks "$@" || exit 2 diff --git a/cmd/gomuks/main.go b/cmd/gomuks/main.go index 692bde1..6dc7d85 100644 --- a/cmd/gomuks/main.go +++ b/cmd/gomuks/main.go @@ -19,42 +19,20 @@ package main import ( "fmt" "os" - "runtime" - "strings" - "time" - _ "github.com/mattn/go-sqlite3" - _ "go.mau.fi/util/dbutil/litestream" flag "maunium.net/go/mauflag" - "maunium.net/go/mautrix" "go.mau.fi/gomuks/pkg/gomuks" "go.mau.fi/gomuks/pkg/hicli" + "go.mau.fi/gomuks/version" "go.mau.fi/gomuks/web" ) -var ( - Tag = "unknown" - Commit = "unknown" - BuildTime = "unknown" -) - -const StaticVersion = "0.4.0" -const URL = "https://github.com/tulir/gomuks" - -var ( - Version string - VersionDesc string - LinkifiedVersion string - ParsedBuildTime time.Time -) - var wantHelp, _ = flag.MakeHelpFlag() -var version = flag.MakeFull("v", "version", "View gomuks version and quit.", "false").Bool() +var wantVersion = flag.MakeFull("v", "version", "View gomuks version and quit.", "false").Bool() func main() { hicli.InitialDeviceDisplayName = "gomuks web" - initVersion(Tag, Commit, BuildTime) flag.SetHelpTitles( "gomuks - A Matrix client written in Go.", "gomuks [-hv]", @@ -68,53 +46,16 @@ func main() { } else if *wantHelp { flag.PrintHelp() os.Exit(0) - } else if *version { - fmt.Println(VersionDesc) + } else if *wantVersion { + fmt.Println(version.Description) os.Exit(0) } gmx := gomuks.NewGomuks() - gmx.Version = Version - gmx.Commit = Commit - gmx.LinkifiedVersion = LinkifiedVersion - gmx.BuildTime = ParsedBuildTime + gmx.Version = version.Version + gmx.Commit = version.Commit + gmx.LinkifiedVersion = version.LinkifiedVersion + gmx.BuildTime = version.ParsedBuildTime gmx.FrontendFS = web.Frontend gmx.Run() } - -func initVersion(tag, commit, rawBuildTime string) { - if len(tag) > 0 && tag[0] == 'v' { - tag = tag[1:] - } - if tag != StaticVersion { - suffix := "+dev" - if len(commit) > 8 { - Version = fmt.Sprintf("%s%s.%s", StaticVersion, suffix, commit[:8]) - } else { - Version = fmt.Sprintf("%s%s.unknown", StaticVersion, suffix) - } - } else { - Version = StaticVersion - } - - LinkifiedVersion = fmt.Sprintf("v%s", Version) - if tag == Version { - LinkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, tag) - } else if len(commit) > 8 { - LinkifiedVersion = strings.Replace(LinkifiedVersion, commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", commit[:8], URL, commit), 1) - } - if rawBuildTime != "unknown" { - ParsedBuildTime, _ = time.Parse(time.RFC3339, rawBuildTime) - } - var builtWith string - if ParsedBuildTime.IsZero() { - rawBuildTime = "unknown" - builtWith = runtime.Version() - } else { - rawBuildTime = ParsedBuildTime.Format(time.RFC1123) - builtWith = fmt.Sprintf("built at %s with %s", rawBuildTime, runtime.Version()) - } - mautrix.DefaultUserAgent = fmt.Sprintf("gomuks/%s %s", Version, mautrix.DefaultUserAgent) - VersionDesc = fmt.Sprintf("gomuks %s (%s)", Version, builtWith) - BuildTime = rawBuildTime -} diff --git a/pkg/gomuks/config.go b/pkg/gomuks/config.go index 421f08e..7916ee3 100644 --- a/pkg/gomuks/config.go +++ b/pkg/gomuks/config.go @@ -96,7 +96,7 @@ func (gmx *Gomuks) LoadConfig() error { gmx.Config.Web.TokenKey = random.String(64) changed = true } - if gmx.Config.Web.Username == "" || gmx.Config.Web.PasswordHash == "" { + if !gmx.DisableAuth && (gmx.Config.Web.Username == "" || gmx.Config.Web.PasswordHash == "") { fmt.Println("Please create a username and password for authenticating the web app") gmx.Config.Web.Username, err = readline.Line("Username: ") if err != nil { diff --git a/pkg/gomuks/gomuks.go b/pkg/gomuks/gomuks.go index 4329977..1b32847 100644 --- a/pkg/gomuks/gomuks.go +++ b/pkg/gomuks/gomuks.go @@ -59,7 +59,8 @@ type Gomuks struct { FrontendFS embed.FS - Config Config + Config Config + DisableAuth bool stopOnce sync.Once stopChan chan struct{} diff --git a/pkg/gomuks/server.go b/pkg/gomuks/server.go index abbd2e4..a317020 100644 --- a/pkg/gomuks/server.go +++ b/pkg/gomuks/server.go @@ -41,7 +41,7 @@ import ( "go.mau.fi/gomuks/pkg/hicli" ) -func (gmx *Gomuks) StartServer() { +func (gmx *Gomuks) CreateAPIRouter() http.Handler { api := http.NewServeMux() api.HandleFunc("GET /websocket", gmx.HandleWebsocket) api.HandleFunc("POST /auth", gmx.Authenticate) @@ -50,19 +50,25 @@ func (gmx *Gomuks) StartServer() { api.HandleFunc("POST /sso", gmx.PrepareSSO) api.HandleFunc("GET /media/{server}/{media_id}", gmx.DownloadMedia) api.HandleFunc("GET /codeblock/{style}", gmx.GetCodeblockCSS) - apiHandler := exhttp.ApplyMiddleware( + return exhttp.ApplyMiddleware( api, hlog.NewHandler(*gmx.Log), hlog.RequestIDHandler("request_id", "Request-ID"), requestlog.AccessLogger(false), - exhttp.StripPrefix("/_gomuks"), - gmx.AuthMiddleware, ) +} + +func (gmx *Gomuks) StartServer() { + api := gmx.CreateAPIRouter() router := http.NewServeMux() if gmx.Config.Web.DebugEndpoints { router.Handle("/debug/", http.DefaultServeMux) } - router.Handle("/_gomuks/", apiHandler) + router.Handle("/_gomuks/", exhttp.ApplyMiddleware( + api, + exhttp.StripPrefix("/_gomuks"), + gmx.AuthMiddleware, + )) if frontend, err := fs.Sub(gmx.FrontendFS, "dist"); err != nil { gmx.Log.Warn().Msg("Frontend not found") } else { @@ -187,6 +193,10 @@ func (gmx *Gomuks) writeTokenCookie(w http.ResponseWriter) { } func (gmx *Gomuks) Authenticate(w http.ResponseWriter, r *http.Request) { + if gmx.DisableAuth { + w.WriteHeader(http.StatusOK) + return + } authCookie, err := r.Cookie("gomuks_auth") if err == nil && gmx.validateAuth(authCookie.Value, false) { hlog.FromRequest(r).Debug().Msg("Authentication successful with existing cookie") diff --git a/pkg/hicli/database/database.go b/pkg/hicli/database/database.go index fa43a3e..95e28a7 100644 --- a/pkg/hicli/database/database.go +++ b/pkg/hicli/database/database.go @@ -7,7 +7,9 @@ package database import ( + _ "github.com/mattn/go-sqlite3" "go.mau.fi/util/dbutil" + _ "go.mau.fi/util/dbutil/litestream" "go.mau.fi/gomuks/pkg/hicli/database/upgrades" ) diff --git a/pkg/hicli/json.go b/pkg/hicli/json.go index 2d74eae..8f7346c 100644 --- a/pkg/hicli/json.go +++ b/pkg/hicli/json.go @@ -28,30 +28,32 @@ type JSONEventHandler func(*JSONCommand) var outgoingEventCounter atomic.Int64 -func (jeh JSONEventHandler) HandleEvent(evt any) { - var command string +func EventTypeName(evt any) string { switch evt.(type) { case *SyncComplete: - command = "sync_complete" + return "sync_complete" case *SyncStatus: - command = "sync_status" + return "sync_status" case *EventsDecrypted: - command = "events_decrypted" + return "events_decrypted" case *Typing: - command = "typing" + return "typing" case *SendComplete: - command = "send_complete" + return "send_complete" case *ClientState: - command = "client_state" + return "client_state" default: panic(fmt.Errorf("unknown event type %T", evt)) } +} + +func (jeh JSONEventHandler) HandleEvent(evt any) { data, err := json.Marshal(evt) if err != nil { panic(fmt.Errorf("failed to marshal event %T: %w", evt, err)) } jeh(&JSONCommand{ - Command: command, + Command: EventTypeName(evt), RequestID: -outgoingEventCounter.Add(1), Data: data, }) diff --git a/version/version.go b/version/version.go new file mode 100644 index 0000000..feecfb8 --- /dev/null +++ b/version/version.go @@ -0,0 +1,76 @@ +// gomuks - A Matrix client written in Go. +// Copyright (C) 2024 Tulir Asokan +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +package version + +import ( + "fmt" + "runtime" + "strings" + "time" + + "maunium.net/go/mautrix" +) + +const StaticVersion = "0.4.0" +const URL = "https://github.com/tulir/gomuks" + +var ( + Tag = "unknown" + Commit = "unknown" + BuildTime = "unknown" +) + +var ( + Version string + Description string + LinkifiedVersion string + ParsedBuildTime time.Time +) + +func init() { + tagWithoutV := strings.TrimPrefix(Tag, "v") + if tagWithoutV != StaticVersion { + suffix := "+dev" + if len(Commit) > 8 { + Version = fmt.Sprintf("%s%s.%s", StaticVersion, suffix, Commit[:8]) + } else { + Version = fmt.Sprintf("%s%s.unknown", StaticVersion, suffix) + } + } else { + Version = StaticVersion + } + + LinkifiedVersion = fmt.Sprintf("v%s", Version) + if tagWithoutV == Version { + LinkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, tagWithoutV) + } else if len(Commit) > 8 { + LinkifiedVersion = strings.Replace(LinkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1) + } + if BuildTime != "unknown" { + ParsedBuildTime, _ = time.Parse(time.RFC3339, BuildTime) + } + var builtWith string + if ParsedBuildTime.IsZero() { + BuildTime = "unknown" + builtWith = runtime.Version() + } else { + BuildTime = ParsedBuildTime.Format(time.RFC1123) + builtWith = fmt.Sprintf("built at %s with %s", BuildTime, runtime.Version()) + } + mautrix.DefaultUserAgent = fmt.Sprintf("gomuks/%s %s", Version, mautrix.DefaultUserAgent) + Description = fmt.Sprintf("gomuks %s (%s)", Version, builtWith) +}