common.go (2648B)
1 // GoToSocial 2 // Copyright (C) GoToSocial Authors admin@gotosocial.org 3 // SPDX-License-Identifier: AGPL-3.0-or-later 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package main 19 20 import ( 21 "context" 22 "fmt" 23 24 "github.com/spf13/cobra" 25 "github.com/superseriousbusiness/gotosocial/cmd/gotosocial/action" 26 "github.com/superseriousbusiness/gotosocial/internal/config" 27 "github.com/superseriousbusiness/gotosocial/internal/log" 28 ) 29 30 type preRunArgs struct { 31 cmd *cobra.Command 32 skipValidation bool 33 } 34 35 // preRun should be run in the pre-run stage of every cobra command. 36 // The goal here is to initialize the viper config store, and also read in 37 // the config file (if present). 38 // 39 // Config then undergoes basic validation if 'skipValidation' is not true. 40 // 41 // The order of these is important: the init-config function reads the location 42 // of the config file from the viper store so that it can be picked up by either 43 // env vars or cli flag. 44 func preRun(a preRunArgs) error { 45 if err := config.BindFlags(a.cmd); err != nil { 46 return fmt.Errorf("error binding flags: %s", err) 47 } 48 49 if err := config.Reload(); err != nil { 50 return fmt.Errorf("error reloading config: %s", err) 51 } 52 53 if !a.skipValidation { 54 if err := config.Validate(); err != nil { 55 return fmt.Errorf("invalid config: %s", err) 56 } 57 } 58 59 return nil 60 } 61 62 // run should be used during the run stage of every cobra command. 63 // The idea here is to take a GTSAction and run it with the given 64 // context, after initializing any last-minute things like loggers etc. 65 func run(ctx context.Context, action action.GTSAction) error { 66 // Set the global log level from configuration 67 if err := log.ParseLevel(config.GetLogLevel()); err != nil { 68 return fmt.Errorf("error parsing log level: %w", err) 69 } 70 71 if config.GetSyslogEnabled() { 72 // Enable logging to syslog 73 if err := log.EnableSyslog( 74 config.GetSyslogProtocol(), 75 config.GetSyslogAddress(), 76 ); err != nil { 77 return fmt.Errorf("error enabling syslogging: %w", err) 78 } 79 } 80 81 return action(ctx) 82 }