add hyprland var subcommands

parent f65678f8
......@@ -60,6 +60,37 @@ func CommandList() *cli.Command {
},
},
},
{
Name: "var",
Usage: "Hyprland vars",
Commands: []*cli.Command{
{
Name: "list",
Usage: "vars list",
Action: HyprlandVarListCommand,
},
{
Name: "info",
Usage: "vars info",
Action: HyprlandVarInfoCommand,
},
{
Name: "get",
Usage: "get var value",
Action: HyprlandVarGetCommand,
},
{
Name: "set",
Usage: "set var value",
Action: HyprlandVarSetCommand,
},
{
Name: "unset",
Usage: "unset var",
Action: HyprlandVarUnsetCommand,
},
},
},
},
}
}
package hyprland
import (
"context"
"ximperconf/config"
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/fatih/color"
"github.com/urfave/cli/v3"
)
var (
reVarLine = regexp.MustCompile(`^\s*\$([A-Za-z0-9_]+)\s*=\s*(.*)`)
)
func hyprlandVarList() ([]string, error) {
if !fileExists(config.Env.Hyprland.Config) {
color.Red("Конфигурация не найдена: %s", config.Env.Hyprland.Config)
return nil, nil
}
f, err := os.Open(config.Env.Hyprland.Config)
if err != nil {
return nil, err
}
defer f.Close()
var vars []string
sc := bufio.NewScanner(f)
for sc.Scan() {
line := sc.Text()
if m := reVarLine.FindStringSubmatch(line); m != nil {
vars = append(vars, m[1])
}
}
return vars, nil
}
func HyprlandVarListCommand(ctx context.Context, cmd *cli.Command) error {
vars, _ := hyprlandVarList()
fmt.Println(strings.Join(vars, "\n"))
return nil
}
func hyprlandVarInfo() (map[string]string, error) {
if !fileExists(config.Env.Hyprland.Config) {
color.Red("Конфигурация не найдена: %s", config.Env.Hyprland.Config)
os.Exit(1)
}
f, err := os.Open(config.Env.Hyprland.Config)
if err != nil {
return nil, err
}
defer f.Close()
vars := make(map[string]string)
sc := bufio.NewScanner(f)
for sc.Scan() {
line := sc.Text()
if m := reVarLine.FindStringSubmatch(line); m != nil {
name := m[1]
value := strings.TrimSpace(m[2])
if idx := strings.Index(value, "#"); idx != -1 {
value = strings.TrimSpace(value[:idx])
}
vars[name] = value
}
}
return vars, nil
}
func HyprlandVarInfoCommand(ctx context.Context, cmd *cli.Command) error {
info, _ := hyprlandVarInfo()
for k, v := range info {
fmt.Printf("%s = %s\n", k, v)
}
return nil
}
func hyprlandVarGet(name string) (string, error) {
if name == "" {
color.Red("Укажите имя переменной")
os.Exit(1)
}
if !regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`).MatchString(name) {
color.Red("Недопустимое имя переменной: %s", name)
os.Exit(1)
}
if !fileExists(config.Env.Hyprland.Config) {
color.Red("Конфигурация не найдена: %s", config.Env.Hyprland.Config)
os.Exit(1)
}
f, _ := os.Open(config.Env.Hyprland.Config)
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
line := sc.Text()
if m := reVarLine.FindStringSubmatch(line); m != nil && m[1] == name {
value := strings.TrimSpace(m[2])
if idx := strings.Index(value, "#"); idx != -1 {
value = strings.TrimSpace(value[:idx])
}
return value, nil
}
}
color.Red("Переменная %s не найдена", name)
os.Exit(1)
return "", nil
}
func HyprlandVarGetCommand(ctx context.Context, cmd *cli.Command) error {
info, _ := hyprlandVarGet(cmd.Args().Get(0))
fmt.Println(info)
return nil
}
func hyprlandVarSet(name, newValue string) error {
if name == "" {
color.Red("Укажите имя переменной")
os.Exit(1)
}
if newValue == "" {
color.Red("Укажите новое значение")
os.Exit(1)
}
if !regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`).MatchString(name) {
color.Red("Недопустимое имя переменной: %s", name)
os.Exit(1)
}
path := config.Env.Hyprland.Config
if !fileExists(path) {
_ = os.MkdirAll(filepath.Dir(path), 0755)
_ = os.WriteFile(path, []byte{}, 0644)
}
data, _ := os.ReadFile(path)
lines := strings.Split(string(data), "\n")
changed := false
re := regexp.MustCompile(`^\s*\$` + regexp.QuoteMeta(name) + `\s*=`)
for i, l := range lines {
if re.MatchString(l) {
lines[i] = fmt.Sprintf("$%s = %s", name, newValue)
changed = true
}
}
if !changed {
var insertAt = -1
for i, l := range lines {
if strings.Contains(l, "ПЕРЕМЕННЫЕ") && strings.Contains(l, "VARS") {
insertAt = i + 1
break
}
}
if insertAt >= 0 {
// вставим после блока
before := append([]string{}, lines[:insertAt]...)
after := append([]string{fmt.Sprintf("$%s = %s", name, newValue)}, lines[insertAt:]...)
lines = append(before, after...)
color.Green("Переменная %s добавлена: %s", name, newValue)
} else {
// создаём блок VARS
lines = append(lines,
"",
"#---------- ПЕРЕМЕННЫЕ ---- VARS",
fmt.Sprintf("$%s = %s", name, newValue),
)
color.Green("Блок VARS создан, переменная %s добавлена: %s", name, newValue)
}
} else {
color.Green("Переменная %s обновлена: %s", name, newValue)
}
return os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0644)
}
func HyprlandVarSetCommand(ctx context.Context, cmd *cli.Command) error {
hyprlandVarSet(cmd.Args().Get(0), cmd.Args().Get(1))
return nil
}
func hyprlandVarUnset(name string) error {
if name == "" {
color.Red("Укажите имя переменной")
os.Exit(1)
}
if !regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`).MatchString(name) {
color.Red("Недопустимое имя переменной: %s", name)
os.Exit(1)
}
if !fileExists(config.Env.Hyprland.Config) {
color.Red("Конфигурация не найдена: %s", config.Env.Hyprland.Config)
os.Exit(1)
}
data, _ := os.ReadFile(config.Env.Hyprland.Config)
lines := strings.Split(string(data), "\n")
re := regexp.MustCompile(`^\s*\$` + regexp.QuoteMeta(name) + `\s*=`)
newLines := make([]string, 0, len(lines))
removed := false
for _, l := range lines {
if re.MatchString(l) {
removed = true
continue
}
newLines = append(newLines, l)
}
if !removed {
color.Red("Переменная %s не найдена", name)
os.Exit(1)
}
color.Green("Переменная %s удалена", name)
return os.WriteFile(config.Env.Hyprland.Config, []byte(strings.Join(newLines, "\n")), 0644)
}
func HyprlandVarUnsetCommand(ctx context.Context, cmd *cli.Command) error {
hyprlandVarUnset(cmd.Args().Get(0))
return nil
}
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