hyprland/module: optimize the code for working with filesee

parent 3ab504f2
package config
var HyprlandSkipModules = []string{
"hyprland", "hypridle", "hyprlock", "hyprpaper", "hyprsunset", "xdph",
}
...@@ -5,7 +5,6 @@ import ( ...@@ -5,7 +5,6 @@ import (
"ximperconf/ui" "ximperconf/ui"
"ximperconf/utils" "ximperconf/utils"
"bufio"
"context" "context"
"fmt" "fmt"
"os" "os"
...@@ -28,6 +27,12 @@ type HyprConfigError struct { ...@@ -28,6 +27,12 @@ type HyprConfigError struct {
Text string Text string
} }
type HyprModuleInfo struct {
Status string
Available bool
LineNumber int
}
func HyprlandCheck(configPath string) ([]HyprConfigError, error) { func HyprlandCheck(configPath string) ([]HyprConfigError, error) {
cmd := exec.Command( cmd := exec.Command(
"hyprland", "--verify-config", "hyprland", "--verify-config",
...@@ -117,23 +122,41 @@ func HyprlandGetModuleFile(module string, user bool) string { ...@@ -117,23 +122,41 @@ func HyprlandGetModuleFile(module string, user bool) string {
return filepath.Join(config.Env.Hyprland.SystemModulesDir, module+".conf") return filepath.Join(config.Env.Hyprland.SystemModulesDir, module+".conf")
} }
func hyprlandModuleStatus(module string, user bool) string { func hyprlandModuleInfo(module string, user bool) HyprModuleInfo {
sysFile, lineFull, lineTilde := hyprlandModuleLines(module, user) sysFile, lineFull, lineTilde := hyprlandModuleLines(module, user)
ModuleAvailable := true
for _, skipModule := range config.HyprlandSkipModules {
if module == skipModule {
ModuleAvailable = false
}
}
// Конфиг Hyprland отсутствует // Конфиг Hyprland отсутствует
if !utils.FileExists(config.Env.Hyprland.Config) { if !utils.FileExists(config.Env.Hyprland.Config) {
if utils.FileExists(sysFile) { if utils.FileExists(sysFile) {
return "unused" return HyprModuleInfo{
Status: "unused",
Available: ModuleAvailable,
}
}
return HyprModuleInfo{
Status: "missing",
} }
return "missing"
} }
f, err := os.Open(config.Env.Hyprland.Config) f, err := os.Open(config.Env.Hyprland.Config)
if err != nil { if err != nil {
if utils.FileExists(sysFile) { if utils.FileExists(sysFile) {
return "unused" return HyprModuleInfo{
Status: "unused",
Available: ModuleAvailable,
}
}
return HyprModuleInfo{
Status: "missing",
} }
return "missing"
} }
defer f.Close() defer f.Close()
...@@ -142,51 +165,72 @@ func hyprlandModuleStatus(module string, user bool) string { ...@@ -142,51 +165,72 @@ func hyprlandModuleStatus(module string, user bool) string {
foundActive := false foundActive := false
foundCommented := false foundCommented := false
var LineNumber int
sc := bufio.NewScanner(f) data, _ := os.ReadFile(config.Env.Hyprland.Config)
for sc.Scan() { lines := strings.Split(string(data), "\n")
line := sc.Text()
for i, line := range lines {
trim := strings.TrimSpace(line) trim := strings.TrimSpace(line)
if trim == "#"+lineFull || trim == "# "+lineFull || trim == "#"+lineTilde || trim == "# "+lineTilde { if trim == "#"+lineFull || trim == "# "+lineFull || trim == "#"+lineTilde || trim == "# "+lineTilde {
foundCommented = true foundCommented = true
LineNumber = i
continue continue
} }
if reFull.MatchString(line) || reTilde.MatchString(line) { if reFull.MatchString(line) || reTilde.MatchString(line) {
foundActive = true foundActive = true
LineNumber = i
break break
} }
} }
// подключён, но файла нет // подключён, но файла нет
if foundActive && !utils.FileExists(sysFile) { if foundActive && !utils.FileExists(sysFile) {
return "missing" return HyprModuleInfo{
Status: "missing",
Available: ModuleAvailable,
LineNumber: LineNumber,
}
} }
// подключён и файл есть // подключён и файл есть
if foundActive && utils.FileExists(sysFile) { if foundActive && utils.FileExists(sysFile) {
return "enabled" return HyprModuleInfo{
Status: "enabled",
Available: ModuleAvailable,
LineNumber: LineNumber,
}
} }
// закомментирован // закомментирован
if foundCommented { if foundCommented {
return "disabled" return HyprModuleInfo{
Status: "disabled",
Available: ModuleAvailable,
LineNumber: LineNumber,
}
} }
// файл есть, но строка отсутствует // файл есть, но строка отсутствует
if utils.FileExists(sysFile) && !foundActive && !foundCommented { if utils.FileExists(sysFile) && !foundActive && !foundCommented {
return "unused" return HyprModuleInfo{
Status: "unused",
Available: ModuleAvailable,
}
} }
// Файла нет и упоминаний нет // Файла нет и упоминаний нет
return "missing" return HyprModuleInfo{
Status: "missing",
}
} }
func hyprlandModuleStatusStruct(module string, user bool) ui.ItemStatus { func hyprlandModuleStatusStruct(module string, user bool) ui.ItemStatus {
status := hyprlandModuleStatus(module, user) info := hyprlandModuleInfo(module, user)
switch status { switch info.Status {
case "enabled": case "enabled":
return ui.StatusEnabled return ui.StatusEnabled
case "disabled": case "disabled":
...@@ -200,8 +244,12 @@ func hyprlandModuleStatusStruct(module string, user bool) ui.ItemStatus { ...@@ -200,8 +244,12 @@ func hyprlandModuleStatusStruct(module string, user bool) ui.ItemStatus {
} }
func HyprlandModuleStatusCommand(ctx context.Context, cmd *cli.Command) error { func HyprlandModuleStatusCommand(ctx context.Context, cmd *cli.Command) error {
status := hyprlandModuleStatus(cmd.Args().Get(0), cmd.Bool("user")) info := hyprlandModuleInfo(cmd.Args().Get(0), cmd.Bool("user"))
fmt.Println(status) if !info.Available {
color.Red("недопустимое название для модуля.")
return nil
}
fmt.Println(info.Status)
return nil return nil
} }
...@@ -243,6 +291,13 @@ func HyprlandModuleCheck(module string, user bool, tmp bool) ([]HyprConfigError, ...@@ -243,6 +291,13 @@ func HyprlandModuleCheck(module string, user bool, tmp bool) ([]HyprConfigError,
func HyprlandModuleCheckCommand(ctx context.Context, cmd *cli.Command) error { func HyprlandModuleCheckCommand(ctx context.Context, cmd *cli.Command) error {
moduleinfo := hyprlandModuleInfo(cmd.Args().Get(0), cmd.Bool("user"))
if !moduleinfo.Available {
color.Red("недопустимое название для модуля.")
return nil
}
info, err := HyprlandModuleCheck(cmd.Args().Get(0), cmd.Bool("user"), true) info, err := HyprlandModuleCheck(cmd.Args().Get(0), cmd.Bool("user"), true)
if err != nil { if err != nil {
...@@ -259,43 +314,44 @@ func HyprlandModuleCheckCommand(ctx context.Context, cmd *cli.Command) error { ...@@ -259,43 +314,44 @@ func HyprlandModuleCheckCommand(ctx context.Context, cmd *cli.Command) error {
func HyprlandSetModule(action string, module string, user bool, onlyNew bool) (string, error) { func HyprlandSetModule(action string, module string, user bool, onlyNew bool) (string, error) {
sysFile, lineFull, lineTilde := hyprlandModuleLines(module, user) sysFile, lineFull, lineTilde := hyprlandModuleLines(module, user)
info := hyprlandModuleInfo(module, user)
reFull := regexp.MustCompile(`^\s*#\s*` + regexp.QuoteMeta(lineFull) + `$`) reFull := regexp.MustCompile(`^\s*#\s*` + regexp.QuoteMeta(lineFull) + `$`)
reTilde := regexp.MustCompile(`^\s*#\s*` + regexp.QuoteMeta(lineTilde) + `$`) reTilde := regexp.MustCompile(`^\s*#\s*` + regexp.QuoteMeta(lineTilde) + `$`)
var out string var out string
if !utils.FileExists(sysFile) { if !info.Available {
return "", fmt.Errorf("недопустимое название для модуля.")
}
if info.Status == "missing" {
return "", fmt.Errorf("модуль '%s' не найден: %s", module, sysFile) return "", fmt.Errorf("модуль '%s' не найден: %s", module, sysFile)
} }
data, _ := os.ReadFile(config.Env.Hyprland.Config) data, _ := os.ReadFile(config.Env.Hyprland.Config)
lines := strings.Split(string(data), "\n") lines := strings.Split(string(data), "\n")
changed := false changed := false
found := false
switch action { switch action {
case "enable": case "enable":
for i, l := range lines {
trim := strings.TrimSpace(l)
// Уже включён // Уже включён
if trim == lineFull || trim == lineTilde { if info.Status == "enabled" {
return "", fmt.Errorf("модуль '%s' уже включён", module) return "", fmt.Errorf("модуль '%s' уже включён", module)
} }
// Был закомментирован // Был закомментирован
if reFull.MatchString(l) || reTilde.MatchString(l) { if info.Status == "disabled" {
found = true if onlyNew {
if onlyNew { return "", fmt.Errorf("модуль '%s' уже присутствует в конфиге (закомментирован) — пропущено", module)
return "", fmt.Errorf("модуль '%s' уже присутствует в конфиге (закомментирован) — пропущено", module)
}
lines[i] = lineFull
changed = true
} }
lines[info.LineNumber] = lineFull
changed = true
} }
// Если модуль нигде не найден — добавляем новую строку // Если модуль нигде не найден — добавляем новую строку
if !found { if info.Status == "unused" {
lines = append(lines, lineFull) lines = append(lines, lineFull)
changed = true changed = true
} }
...@@ -307,20 +363,17 @@ func HyprlandSetModule(action string, module string, user bool, onlyNew bool) (s ...@@ -307,20 +363,17 @@ func HyprlandSetModule(action string, module string, user bool, onlyNew bool) (s
out = fmt.Sprintf("Модуль '%s' включён", module) out = fmt.Sprintf("Модуль '%s' включён", module)
case "disable": case "disable":
for i, l := range lines {
trim := strings.TrimSpace(l)
// Уже выключен // Уже выключен
if reFull.MatchString(l) || reTilde.MatchString(l) { if info.Status == "disabled" {
return "", fmt.Errorf("модуль '%s' уже отключён", module) return "", fmt.Errorf("модуль '%s' уже отключён", module)
} }
// Включён // Включён
if trim == lineFull || trim == lineTilde { if info.Status == "enabled" {
lines[i] = "# " + lineFull lines[info.LineNumber] = "# " + lineFull
out = fmt.Sprintf("Модуль '%s' отключён", module) out = fmt.Sprintf("Модуль '%s' отключён", module)
changed = true changed = true
}
} }
if !changed { if !changed {
...@@ -328,6 +381,7 @@ func HyprlandSetModule(action string, module string, user bool, onlyNew bool) (s ...@@ -328,6 +381,7 @@ func HyprlandSetModule(action string, module string, user bool, onlyNew bool) (s
} }
case "remove": case "remove":
// слайс для строк, которые не нужно удалять // слайс для строк, которые не нужно удалять
newLines := []string{} newLines := []string{}
...@@ -399,15 +453,15 @@ func HyprlandModuleDisableCommand(ctx context.Context, cmd *cli.Command) error { ...@@ -399,15 +453,15 @@ func HyprlandModuleDisableCommand(ctx context.Context, cmd *cli.Command) error {
func HyprlandToggleModuleCommand(ctx context.Context, cmd *cli.Command) error { func HyprlandToggleModuleCommand(ctx context.Context, cmd *cli.Command) error {
module := cmd.Args().Get(0) module := cmd.Args().Get(0)
user := cmd.Bool("user") user := cmd.Bool("user")
status := hyprlandModuleStatus(module, user) info := hyprlandModuleInfo(module, user)
var msg string var msg string
var err error var err error
switch status { switch info.Status {
case "enabled": case "enabled":
msg, err = HyprlandSetModule("disable", module, user, false) msg, err = HyprlandSetModule("disable", module, user, false)
case "disabled": case "disabled", "unused":
msg, err = HyprlandSetModule("enable", module, user, false) msg, err = HyprlandSetModule("enable", module, user, false)
} }
...@@ -432,11 +486,6 @@ func hyprlandListModules(user bool, filter string) []string { ...@@ -432,11 +486,6 @@ func hyprlandListModules(user bool, filter string) []string {
if err != nil { if err != nil {
return nil return nil
} }
skip := map[string]bool{
"hyprland": true, "hypridle": true,
"hyprlock": true, "hyprpaper": true,
"hyprsunset": true, "xdph": true,
}
var modules []string var modules []string
for _, e := range entries { for _, e := range entries {
...@@ -444,17 +493,18 @@ func hyprlandListModules(user bool, filter string) []string { ...@@ -444,17 +493,18 @@ func hyprlandListModules(user bool, filter string) []string {
continue continue
} }
module := strings.TrimSuffix(e.Name(), ".conf") module := strings.TrimSuffix(e.Name(), ".conf")
if skip[module] { info := hyprlandModuleInfo(module, user)
if !info.Available {
continue continue
} }
status := hyprlandModuleStatus(module, user)
if filter == "" || filter == "all" { if filter == "" || filter == "all" {
modules = append(modules, module) modules = append(modules, module)
continue continue
} }
if status == filter { if info.Status == filter {
modules = append(modules, module) modules = append(modules, module)
} }
} }
...@@ -508,6 +558,12 @@ func HyprlandModuleEditCommand(ctx context.Context, cmd *cli.Command) error { ...@@ -508,6 +558,12 @@ func HyprlandModuleEditCommand(ctx context.Context, cmd *cli.Command) error {
module := cmd.Args().Get(0) module := cmd.Args().Get(0)
user := cmd.Bool("user") user := cmd.Bool("user")
modulefile := HyprlandGetModuleFile(module, user) modulefile := HyprlandGetModuleFile(module, user)
info := hyprlandModuleInfo(module, user)
if !info.Available {
color.Red("недопустимое название для модуля.")
return nil
}
if !utils.FileExists(modulefile) { if !utils.FileExists(modulefile) {
color.Red("Модуль '%s' не найден: %s", module, modulefile) color.Red("Модуль '%s' не найден: %s", module, modulefile)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment