浏览代码

refactor!(config): use os.OpenFile() instead

ayntgl 4 年之前
父节点
当前提交
39923074f2
共有 9 个文件被更改,包括 114 次插入129 次删除
  1. 101 23
      config/config.go
  2. 0 49
      config/general.go
  3. 0 33
      config/keys.go
  4. 0 15
      config/theme.go
  5. 6 2
      main.go
  6. 4 4
      ui/app.go
  7. 1 1
      ui/builder.go
  8. 1 1
      ui/channels.go
  9. 1 1
      ui/messages.go

+ 101 - 23
config/config.go

@@ -1,56 +1,134 @@
 package config
 
 import (
+	"log"
 	"os"
 	"path/filepath"
+	"runtime"
 
 	"github.com/BurntSushi/toml"
 )
 
+type IdentifyConfig struct {
+	UserAgent string `toml:"user_agent"`
+	Os        string `toml:"os"`
+	Browser   string `toml:"browser"`
+}
+
+type KeysConfig struct {
+	ToggleGuildsList        string `toml:"toggle_guilds_list"`
+	ToggleChannelsTreeView  string `toml:"toggle_channels_tree_view"`
+	ToggleMessagesTextView  string `toml:"toggle_messages_text_view"`
+	ToggleMessageInputField string `toml:"toggle_message_input_field"`
+
+	OpenMessageActionsList string `toml:"open_message_actions_list"`
+	OpenExternalEditor     string `toml:"open_external_editor"`
+
+	SelectPreviousMessage string `toml:"select_previous_message"`
+	SelectNextMessage     string `toml:"select_next_message"`
+	SelectFirstMessage    string `toml:"select_first_message"`
+	SelectLastMessage     string `toml:"select_last_message"`
+}
+
+type ThemeConfig struct {
+	Background string `toml:"background"`
+	Border     string `toml:"border"`
+	Title      string `toml:"title"`
+}
+
 type Config struct {
-	General GeneralConfig `toml:"general"`
-	Theme   ThemeConfig   `toml:"theme"`
-	Keys    KeysConfig    `toml:"keys"`
+	Mouse                  bool           `toml:"mouse"`
+	Timestamps             bool           `toml:"timestamps"`
+	MessagesLimit          int            `toml:"messages_limit"`
+	AttachmentDownloadsDir string         `toml:"attachment_downloads_dir"`
+	Identify               IdentifyConfig `toml:"identify"`
+	Theme                  ThemeConfig    `toml:"theme"`
+	Keys                   KeysConfig     `toml:"keys"`
 }
 
 func New() *Config {
 	return &Config{
-		General: newGeneralConfig(),
-		Theme:   newThemeConfig(),
-		Keys:    newKeysConfig(),
+		Mouse:                  true,
+		Timestamps:             false,
+		MessagesLimit:          50,
+		AttachmentDownloadsDir: UserDownloadsDir(),
+		Identify: IdentifyConfig{
+			UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36",
+			Os:        "Linux",
+			Browser:   "Chrome",
+		},
+		Theme: ThemeConfig{
+			Background: "black",
+			Border:     "white",
+			Title:      "white",
+		},
+		Keys: KeysConfig{
+			ToggleGuildsList:        "Rune[g]",
+			ToggleChannelsTreeView:  "Rune[c]",
+			ToggleMessagesTextView:  "Rune[m]",
+			ToggleMessageInputField: "Rune[i]",
+
+			OpenMessageActionsList: "Rune[a]",
+			OpenExternalEditor:     "Ctrl+E",
+
+			SelectPreviousMessage: "Up",
+			SelectNextMessage:     "Down",
+			SelectFirstMessage:    "Home",
+			SelectLastMessage:     "End",
+		},
 	}
 }
 
-func (c *Config) Load(path string) {
+func (c *Config) Load(path string) error {
+	// Create directories that do not exist and are mentioned in the path recursively.
 	err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
 	if err != nil {
-		panic(err)
+		return err
+	}
+
+	// If the configuration file does not exist already, create a new file; otherwwise, open the existing file with read-write flag.
+	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModePerm)
+	if err != nil {
+		return err
 	}
+	defer f.Close()
 
-	if _, err = os.Stat(path); os.IsNotExist(err) {
-		f, err := os.Create(path)
-		if err != nil {
-			panic(err)
-		}
+	fi, err := f.Stat()
+	if err != nil {
+		return err
+	}
 
-		err = toml.NewEncoder(f).Encode(c)
-		if err != nil {
-			panic(err)
-		}
-	} else {
-		_, err = toml.DecodeFile(path, &c)
-		if err != nil {
-			panic(err)
-		}
+	// If the file is empty (the size of the file is zero), write the dedfault configuration to the file.
+	if fi.Size() == 0 {
+		return toml.NewEncoder(f).Encode(c)
 	}
+
+	_, err = toml.NewDecoder(f).Decode(&c)
+	return err
 }
 
 func DefaultPath() string {
 	path, err := os.UserConfigDir()
 	if err != nil {
-		panic(err)
+		log.Fatal(err)
 	}
 
 	path += "/discordo/config.toml"
 	return path
 }
+
+func UserDownloadsDir() string {
+	// We try to set the download folder location to the default Downloads folder
+	var dlloc string
+	if runtime.GOOS == "windows" {
+		h, _ := os.UserHomeDir()
+		dlloc = h + "\\Downloads"
+	} else if runtime.GOOS == "linux" || runtime.GOOS == "darwin" {
+		h, _ := os.UserHomeDir()
+		dlloc = h + "/Downloads"
+	} else {
+		dlloc = os.TempDir() // Very lame fallback, I know
+	}
+
+	return dlloc
+}

+ 0 - 49
config/general.go

@@ -1,49 +0,0 @@
-package config
-
-import (
-	"os"
-	"runtime"
-)
-
-type IdentifyConfig struct {
-	Os      string `toml:"os"`
-	Browser string `toml:"browser"`
-}
-
-type GeneralConfig struct {
-	UserAgent              string         `toml:"user_agent"`
-	FetchMessagesLimit     int            `toml:"fetch_messages_limit"`
-	Mouse                  bool           `toml:"mouse"`
-	Timestamps             bool           `toml:"timestamps"`
-	Identify               IdentifyConfig `toml:"identify"`
-	AttachmentDownloadsDir string         `toml:"attachment_downloads_dir"`
-}
-
-func newGeneralConfig() GeneralConfig {
-	return GeneralConfig{
-		UserAgent:              "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0",
-		FetchMessagesLimit:     50,
-		Mouse:                  true,
-		Timestamps:             false,
-		AttachmentDownloadsDir: UserDownloadsDir(),
-		Identify: IdentifyConfig{
-			Os:      "Linux",
-			Browser: "Firefox",
-		},
-	}
-}
-
-func UserDownloadsDir() string {
-	// We try to set the download folder location to the default Downloads folder
-	var dlloc string
-	if runtime.GOOS == "windows" {
-		h, _ := os.UserHomeDir()
-		dlloc = h + "\\Downloads"
-	} else if runtime.GOOS == "linux" || runtime.GOOS == "darwin" {
-		h, _ := os.UserHomeDir()
-		dlloc = h + "/Downloads"
-	} else {
-		dlloc = os.TempDir() // Very lame fallback, I know
-	}
-	return dlloc
-}

+ 0 - 33
config/keys.go

@@ -1,33 +0,0 @@
-package config
-
-type KeysConfig struct {
-	ToggleGuildsList        string `toml:"toggle_guilds_list"`
-	ToggleChannelsTreeView  string `toml:"toggle_channels_tree_view"`
-	ToggleMessagesTextView  string `toml:"toggle_messages_text_view"`
-	ToggleMessageInputField string `toml:"toggle_message_input_field"`
-
-	OpenMessageActionsList string `toml:"open_message_actions_list"`
-	OpenExternalEditor     string `toml:"open_external_editor"`
-
-	SelectPreviousMessage string `toml:"select_previous_message"`
-	SelectNextMessage     string `toml:"select_next_message"`
-	SelectFirstMessage    string `toml:"select_first_message"`
-	SelectLastMessage     string `toml:"select_last_message"`
-}
-
-func newKeysConfig() KeysConfig {
-	return KeysConfig{
-		ToggleGuildsList:        "Rune[g]",
-		ToggleChannelsTreeView:  "Rune[c]",
-		ToggleMessagesTextView:  "Rune[m]",
-		ToggleMessageInputField: "Rune[i]",
-
-		OpenMessageActionsList: "Rune[a]",
-		OpenExternalEditor:     "Ctrl+E",
-
-		SelectPreviousMessage: "Up",
-		SelectNextMessage:     "Down",
-		SelectFirstMessage:    "Home",
-		SelectLastMessage:     "End",
-	}
-}

+ 0 - 15
config/theme.go

@@ -1,15 +0,0 @@
-package config
-
-type ThemeConfig struct {
-	Background string `toml:"background"`
-	Border     string `toml:"border"`
-	Title      string `toml:"title"`
-}
-
-func newThemeConfig() ThemeConfig {
-	return ThemeConfig{
-		Background: "black",
-		Border:     "white",
-		Title:      "white",
-	}
-}

+ 6 - 2
main.go

@@ -1,6 +1,7 @@
 package main
 
 import (
+	"log"
 	"os"
 
 	"github.com/ayntgl/discordo/config"
@@ -42,7 +43,10 @@ func main() {
 
 	cliApp.Action = func(ctx *cli.Context) error {
 		c := config.New()
-		c.Load(ctx.String("config"))
+		err := c.Load(ctx.String("config"))
+		if err != nil {
+			log.Fatal(err)
+		}
 
 		token := ctx.String("token")
 		app := ui.NewApp(token, c)
@@ -128,7 +132,7 @@ func main() {
 		tview.Styles.BorderColor = tcell.GetColor(app.Config.Theme.Border)
 		tview.Styles.TitleColor = tcell.GetColor(app.Config.Theme.Title)
 
-		err := app.Run()
+		err = app.Run()
 		if err != nil {
 			panic(err)
 		}

+ 4 - 4
ui/app.go

@@ -37,7 +37,7 @@ func NewApp(token string, c *config.Config) *App {
 	app.MessageInputField = NewMessageInputField(app)
 
 	app.Application = tview.NewApplication()
-	app.EnableMouse(app.Config.General.Mouse)
+	app.EnableMouse(app.Config.Mouse)
 	app.SetInputCapture(app.onInputCapture)
 
 	return app
@@ -47,13 +47,13 @@ func (app *App) Connect() error {
 	// For user accounts, all of the guilds, the user is in, are dispatched in the READY gateway event.
 	// Whereas, for bot accounts, the guilds are dispatched discretely in the GUILD_CREATE gateway events.
 	if !strings.HasPrefix(app.Session.Identify.Token, "Bot") {
-		app.Session.UserAgent = app.Config.General.UserAgent
+		app.Session.UserAgent = app.Config.Identify.UserAgent
 		app.Session.Identify.Compress = false
 		app.Session.Identify.LargeThreshold = 0
 		app.Session.Identify.Intents = 0
 		app.Session.Identify.Properties = astatine.IdentifyProperties{
-			OS:      app.Config.General.Identify.Os,
-			Browser: app.Config.General.Identify.Browser,
+			OS:      app.Config.Identify.Os,
+			Browser: app.Config.Identify.Browser,
 		}
 		app.Session.AddHandlerOnce(app.onSessionReady)
 	}

+ 1 - 1
ui/builder.go

@@ -23,7 +23,7 @@ func buildMessage(app *App, m *astatine.Message) []byte {
 		// Build the message associated with crosspost, channel follow add, pin, or a reply.
 		buildReferencedMessage(&b, m.ReferencedMessage, app.Session.State.User.ID)
 
-		if app.Config.General.Timestamps {
+		if app.Config.Timestamps {
 			b.WriteString("[::d]")
 			b.WriteString(m.Timestamp.Format(time.Stamp))
 			b.WriteString("[::-]")

+ 1 - 1
ui/channels.go

@@ -55,7 +55,7 @@ func (ctv *ChannelsTreeView) onSelected(n *tview.TreeNode) {
 	ctv.app.MessagesTextView.SetTitle(title)
 
 	go func() {
-		ms, err := ctv.app.Session.ChannelMessages(c.ID, ctv.app.Config.General.FetchMessagesLimit, "", "", "")
+		ms, err := ctv.app.Session.ChannelMessages(c.ID, ctv.app.Config.MessagesLimit, "", "", "")
 		if err != nil {
 			return
 		}

+ 1 - 1
ui/messages.go

@@ -203,7 +203,7 @@ func (mtv *MessagesTextView) onInputCapture(e *tcell.EventKey) *tcell.EventKey {
 
 func (mtv *MessagesTextView) downloadAttachment(as []*astatine.MessageAttachment) error {
 	for _, a := range as {
-		f, err := os.Create(filepath.Join(mtv.app.Config.General.AttachmentDownloadsDir, a.Filename))
+		f, err := os.Create(filepath.Join(mtv.app.Config.AttachmentDownloadsDir, a.Filename))
 		if err != nil {
 			return err
 		}