PLT-6471 Properly panic when translations can't be loaded (#6414)

* PLT-6471 Properly panic when translations can't be loaded

* Print usage messages when errors occur during CLI initialization

* Reverted behaviour of FindDir and added second return value to it

* Fixed merge conflict
This commit is contained in:
Harrison Healey
2017-05-23 11:06:25 -04:00
committed by GitHub
parent 69f3f2fdce
commit 5c1049054e
23 changed files with 189 additions and 73 deletions

View File

@@ -805,7 +805,7 @@ func TestGetInfoForFilename(t *testing.T) {
}
func readTestFile(name string) ([]byte, error) {
path := utils.FindDir("tests")
path, _ := utils.FindDir("tests")
file, err := os.Open(path + "/" + name)
if err != nil {
return nil, err

View File

@@ -747,7 +747,7 @@ func TestUserUploadProfileImage(t *testing.T) {
t.Fatal(err)
}
path := utils.FindDir("tests")
path, _ := utils.FindDir("tests")
file, err := os.Open(path + "/test.png")
if err != nil {
t.Fatal(err)

View File

@@ -611,7 +611,7 @@ func CheckPayLoadTooLargeStatus(t *testing.T, resp *model.Response) {
}
func readTestFile(name string) ([]byte, error) {
path := utils.FindDir("tests")
path, _ := utils.FindDir("tests")
file, err := os.Open(path + "/" + name)
if err != nil {
return nil, err

View File

@@ -323,7 +323,9 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'")
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Cache-Control", "no-cache, max-age=31556926, public")
http.ServeFile(w, r, utils.FindDir(model.CLIENT_DIR)+"root.html")
staticDir, _ := utils.FindDir(model.CLIENT_DIR)
http.ServeFile(w, r, staticDir+"root.html")
}
func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {

View File

@@ -41,7 +41,7 @@ func NewAutoPostCreator(client *model.Client, channelid string) *AutoPostCreator
func (cfg *AutoPostCreator) UploadTestFile() ([]string, bool) {
filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})]
path := utils.FindDir("web/static/images")
path, _ := utils.FindDir("web/static/images")
file, err := os.Open(path + "/" + filename)
defer file.Close()

View File

@@ -42,7 +42,8 @@ func WriteSamlFile(fileData *multipart.FileHeader) *model.AppError {
return model.NewLocAppError("AddSamlCertificate", "api.admin.add_certificate.open.app_error", nil, err.Error())
}
out, err := os.Create(utils.FindDir("config") + filename)
configDir, _ := utils.FindDir("config")
out, err := os.Create(configDir + filename)
if err != nil {
return model.NewLocAppError("AddSamlCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error())
}

View File

@@ -709,7 +709,8 @@ func CreateProfileImage(username string, userId string) ([]byte, *model.AppError
initial := string(strings.ToUpper(username)[0])
fontBytes, err := ioutil.ReadFile(utils.FindDir("fonts") + utils.Cfg.FileSettings.InitialFont)
fontDir, _ := utils.FindDir("fonts")
fontBytes, err := ioutil.ReadFile(fontDir + utils.Cfg.FileSettings.InitialFont)
if err != nil {
return nil, model.NewLocAppError("CreateProfileImage", "api.user.create_profile_image.default_font.app_error", nil, err.Error())
}

View File

@@ -102,7 +102,9 @@ func init() {
}
func createChannelCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if !utils.IsLicensed {
return errors.New(utils.T("cli.license.critical"))
@@ -152,7 +154,9 @@ func createChannelCmdF(cmd *cobra.Command, args []string) error {
}
func removeChannelUsersCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if !utils.IsLicensed {
return errors.New(utils.T("cli.license.critical"))
@@ -186,7 +190,9 @@ func removeUserFromChannel(channel *model.Channel, user *model.User, userArg str
}
func addChannelUsersCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if !utils.IsLicensed {
return errors.New(utils.T("cli.license.critical"))
@@ -220,7 +226,9 @@ func addUserToChannel(channel *model.Channel, user *model.User, userArg string)
}
func archiveChannelsCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one channel to delete.")
@@ -241,7 +249,9 @@ func archiveChannelsCmdF(cmd *cobra.Command, args []string) error {
}
func deleteChannelsCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one channel to delete.")
@@ -278,7 +288,9 @@ func deleteChannel(channel *model.Channel) *model.AppError {
}
func listChannelsCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if !utils.IsLicensed {
return errors.New(utils.T("cli.license.critical"))
@@ -313,7 +325,9 @@ func listChannelsCmdF(cmd *cobra.Command, args []string) error {
}
func restoreChannelsCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if !utils.IsLicensed {
return errors.New(utils.T("cli.license.critical"))

View File

@@ -44,7 +44,9 @@ func init() {
}
func slackImportCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) != 2 {
return errors.New("Incorrect number of arguments.")
@@ -76,7 +78,9 @@ func slackImportCmdF(cmd *cobra.Command, args []string) error {
}
func bulkImportCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
apply, err := cmd.Flags().GetBool("apply")
if err != nil {

View File

@@ -12,14 +12,18 @@ func initDBCommandContextCobra(cmd *cobra.Command) error {
if err != nil {
return err
}
initDBCommandContext(config)
if err := initDBCommandContext(config); err != nil {
// Returning an error just prints the usage message, so actually panic
panic(err)
}
return nil
}
func initDBCommandContext(configFileLocation string) {
if errstr := utils.InitAndLoadConfig(configFileLocation); errstr != "" {
return
func initDBCommandContext(configFileLocation string) error {
if err := utils.InitAndLoadConfig(configFileLocation); err != nil {
return err
}
utils.ConfigureCmdLineLog()
@@ -29,4 +33,6 @@ func initDBCommandContext(configFileLocation string) {
if model.BuildEnterpriseReady == "true" {
app.LoadLicense()
}
return nil
}

View File

@@ -28,7 +28,9 @@ func init() {
}
func uploadLicenseCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) != 1 {
return errors.New("Enter one license file to upload")

View File

@@ -59,7 +59,9 @@ var resetCmd = &cobra.Command{
}
func resetCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
confirmFlag, _ := cmd.Flags().GetBool("confirm")
if !confirmFlag {

View File

@@ -38,7 +38,10 @@ func init() {
}
func makeSystemAdminCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one user.")
}
@@ -58,7 +61,10 @@ func makeSystemAdminCmdF(cmd *cobra.Command, args []string) error {
}
func makeMemberCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one user.")
}

View File

@@ -44,12 +44,16 @@ func runServerCmd(cmd *cobra.Command, args []string) error {
}
func runServer(configFileLocation string) {
if errstr := utils.InitAndLoadConfig(configFileLocation); errstr != "" {
l4g.Exit("Unable to load mattermost configuration file: ", errstr)
if err := utils.InitAndLoadConfig(configFileLocation); err != nil {
l4g.Exit("Unable to load Mattermost configuration file: ", err)
return
}
if err := utils.InitTranslations(utils.Cfg.LocalizationSettings); err != nil {
l4g.Exit("Unable to load Mattermost translation files: %v", err)
return
}
utils.InitTranslations(utils.Cfg.LocalizationSettings)
utils.TestConnection(utils.Cfg)
pwd, _ := os.Getwd()

View File

@@ -67,7 +67,9 @@ func init() {
}
func createTeamCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
name, errn := cmd.Flags().GetString("name")
if errn != nil || name == "" {
@@ -100,7 +102,9 @@ func createTeamCmdF(cmd *cobra.Command, args []string) error {
}
func removeUsersCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 2 {
return errors.New("Not enough arguments.")
@@ -130,7 +134,9 @@ func removeUserFromTeam(team *model.Team, user *model.User, userArg string) {
}
func addUsersCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 2 {
return errors.New("Not enough arguments.")
@@ -160,7 +166,9 @@ func addUserToTeam(team *model.Team, user *model.User, userArg string) {
}
func deleteTeamsCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Not enough arguments.")

View File

@@ -45,7 +45,10 @@ func init() {
}
func webClientTestsCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
utils.InitTranslations(utils.Cfg.LocalizationSettings)
api.InitRouter()
wsapi.InitRouter()
@@ -61,7 +64,10 @@ func webClientTestsCmdF(cmd *cobra.Command, args []string) error {
}
func serverForWebClientTestsCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
utils.InitTranslations(utils.Cfg.LocalizationSettings)
api.InitRouter()
wsapi.InitRouter()

View File

@@ -157,7 +157,9 @@ func init() {
}
func userActivateCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter user(s) to activate.")
@@ -193,7 +195,9 @@ func changeUserActiveStatus(user *model.User, userArg string, activate bool) err
}
func userDeactivateCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter user(s) to deactivate.")
@@ -204,7 +208,10 @@ func userDeactivateCmdF(cmd *cobra.Command, args []string) error {
}
func userCreateCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
username, erru := cmd.Flags().GetString("username")
if erru != nil || username == "" {
return errors.New("Username is required")
@@ -248,7 +255,10 @@ func userCreateCmdF(cmd *cobra.Command, args []string) error {
}
func userInviteCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
utils.InitHTML()
if len(args) < 2 {
@@ -285,7 +295,10 @@ func inviteUser(email string, team *model.Team, teamArg string) error {
}
func resetUserPasswordCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) != 2 {
return errors.New("Incorect number of arguments.")
}
@@ -304,7 +317,10 @@ func resetUserPasswordCmdF(cmd *cobra.Command, args []string) error {
}
func resetUserMfaCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one user.")
}
@@ -325,7 +341,10 @@ func resetUserMfaCmdF(cmd *cobra.Command, args []string) error {
}
func deleteUserCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one user.")
}
@@ -362,7 +381,10 @@ func deleteUserCmdF(cmd *cobra.Command, args []string) error {
}
func deleteAllUsersCommandF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) > 0 {
return errors.New("Don't enter any agruments.")
}
@@ -393,7 +415,10 @@ func deleteAllUsersCommandF(cmd *cobra.Command, args []string) error {
}
func migrateAuthCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) != 3 {
return errors.New("Enter the correct number of arguments.")
}
@@ -431,7 +456,10 @@ func migrateAuthCmdF(cmd *cobra.Command, args []string) error {
}
func verifyUserCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one user.")
}
@@ -452,7 +480,10 @@ func verifyUserCmdF(cmd *cobra.Command, args []string) error {
}
func searchUserCmdF(cmd *cobra.Command, args []string) error {
initDBCommandContextCobra(cmd)
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
if len(args) < 1 {
return errors.New("Enter at least one query.")
}

View File

@@ -12,12 +12,17 @@ import (
var versionCmd = &cobra.Command{
Use: "version",
Short: "Display version information",
Run: versionCmdF,
RunE: versionCmdF,
}
func versionCmdF(cmd *cobra.Command, args []string) {
initDBCommandContextCobra(cmd)
func versionCmdF(cmd *cobra.Command, args []string) error {
if err := initDBCommandContextCobra(cmd); err != nil {
return err
}
printVersion()
return nil
}
func printVersion() {

View File

@@ -78,17 +78,21 @@ func FindConfigFile(fileName string) string {
return fileName
}
func FindDir(dir string) string {
func FindDir(dir string) (string, bool) {
fileName := "."
found := false
if _, err := os.Stat("./" + dir + "/"); err == nil {
fileName, _ = filepath.Abs("./" + dir + "/")
found = true
} else if _, err := os.Stat("../" + dir + "/"); err == nil {
fileName, _ = filepath.Abs("../" + dir + "/")
found = true
} else if _, err := os.Stat("../../" + dir + "/"); err == nil {
fileName, _ = filepath.Abs("../../" + dir + "/")
found = true
}
return fileName + "/"
return fileName + "/", found
}
func DisableDebugLogForTest() {
@@ -161,7 +165,8 @@ func configureLog(s *model.LogSettings) {
func GetLogFileLocation(fileLocation string) string {
if fileLocation == "" {
return FindDir("logs") + LOG_FILENAME
logDir, _ := FindDir("logs")
return logDir + LOG_FILENAME
} else {
return fileLocation + LOG_FILENAME
}
@@ -258,19 +263,17 @@ func DisableConfigWatch() {
}
}
func InitAndLoadConfig(filename string) (err string) {
defer func() {
if r := recover(); r != nil {
err = fmt.Sprintf("%v", r)
}
}()
TranslationsPreInit()
func InitAndLoadConfig(filename string) error {
if err := TranslationsPreInit(); err != nil {
return err
}
EnableConfigFromEnviromentVars()
LoadConfig(filename)
InitializeConfigWatch()
EnableConfigWatch()
return ""
return nil
}
// LoadConfig will try to search around for the corresponding config file.

View File

@@ -33,7 +33,7 @@ func InitHTMLWithDir(dir string) {
return
}
templatesDir := FindDir(dir)
templatesDir, _ := FindDir(dir)
l4g.Debug(T("api.api.init.parsing_templates.debug"), templatesDir)
var err error
if htmlTemplates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {

View File

@@ -1,6 +1,7 @@
package utils
import (
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
@@ -18,30 +19,47 @@ var settings model.LocalizationSettings
// this functions loads translations from filesystem
// and assign english while loading server config
func TranslationsPreInit() {
InitTranslationsWithDir("i18n")
func TranslationsPreInit() error {
if err := InitTranslationsWithDir("i18n"); err != nil {
return err
}
T = TfuncWithFallback("en")
TDefault = TfuncWithFallback("en")
return nil
}
func InitTranslations(localizationSettings model.LocalizationSettings) {
func InitTranslations(localizationSettings model.LocalizationSettings) error {
settings = localizationSettings
T = GetTranslationsBySystemLocale()
var err error
T, err = GetTranslationsBySystemLocale()
return err
}
func InitTranslationsWithDir(dir string) {
i18nDirectory := FindDir(dir)
func InitTranslationsWithDir(dir string) error {
i18nDirectory, found := FindDir(dir)
if !found {
return fmt.Errorf("Unable to find i18n directory")
}
files, _ := ioutil.ReadDir(i18nDirectory)
for _, f := range files {
if filepath.Ext(f.Name()) == ".json" {
filename := f.Name()
locales[strings.Split(filename, ".")[0]] = i18nDirectory + filename
i18n.MustLoadTranslationFile(i18nDirectory + filename)
if err := i18n.LoadTranslationFile(i18nDirectory + filename); err != nil {
return err
}
}
}
return nil
}
func GetTranslationsBySystemLocale() i18n.TranslateFunc {
func GetTranslationsBySystemLocale() (i18n.TranslateFunc, error) {
locale := *settings.DefaultServerLocale
if _, ok := locales[locale]; !ok {
l4g.Error("Failed to load system translations for '%v' attempting to fall back to '%v'", locale, model.DEFAULT_LOCALE)
@@ -49,16 +67,16 @@ func GetTranslationsBySystemLocale() i18n.TranslateFunc {
}
if locales[locale] == "" {
panic("Failed to load system translations for '" + model.DEFAULT_LOCALE + "'")
return nil, fmt.Errorf("Failed to load system translations for '%v'", model.DEFAULT_LOCALE)
}
translations := TfuncWithFallback(locale)
if translations == nil {
panic("Failed to load system translations")
return nil, fmt.Errorf("Failed to load system translations")
}
l4g.Info(translations("utils.i18n.loaded"), locale, locales[locale])
return translations
return translations, nil
}
func GetUserTranslations(locale string) i18n.TranslateFunc {

View File

@@ -152,7 +152,8 @@ func GetLicenseFileFromDisk(fileName string) []byte {
func GetLicenseFileLocation(fileLocation string) string {
if fileLocation == "" {
return FindDir("config") + "mattermost.mattermost-license"
configDir, _ := FindDir("config")
return configDir + "mattermost.mattermost-license"
} else {
return fileLocation
}

View File

@@ -23,7 +23,7 @@ func InitWeb() {
mainrouter := app.Srv.Router
if *utils.Cfg.ServiceSettings.WebserverMode != "disabled" {
staticDir := utils.FindDir(model.CLIENT_DIR)
staticDir, _ := utils.FindDir(model.CLIENT_DIR)
l4g.Debug("Using client directory at %v", staticDir)
if *utils.Cfg.ServiceSettings.WebserverMode == "gzip" {
mainrouter.PathPrefix("/static/").Handler(gziphandler.GzipHandler(staticHandler(http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir))))))
@@ -79,5 +79,7 @@ func root(c *api.Context, w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("Cache-Control", "no-cache, max-age=31556926, public")
http.ServeFile(w, r, utils.FindDir(model.CLIENT_DIR)+"root.html")
staticDir, _ := utils.FindDir(model.CLIENT_DIR)
http.ServeFile(w, r, staticDir+"root.html")
}