Изменение вызова действий, проверка наличия действий секции, отображение счетчика выполнения действий в модальном окне, работа над подключением привязки горячих клавиш
This commit is contained in:
parent
91b1eea1d4
commit
c69a7ae84b
14 changed files with 886 additions and 706 deletions
213
setup/main.go
213
setup/main.go
|
|
@ -2,23 +2,25 @@ package setup
|
|||
|
||||
import (
|
||||
"bubble/bootstrap"
|
||||
"bubble/setup/utils"
|
||||
"bubble/types"
|
||||
"fmt"
|
||||
"github.com/charmbracelet/bubbles/help"
|
||||
"github.com/charmbracelet/bubbles/key"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/sirupsen/logrus"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func Start() {
|
||||
//Создаем новый объект Main для настройки.
|
||||
m := NewMain()
|
||||
p := tea.NewProgram(m, tea.WithAltScreen())
|
||||
m.p = p
|
||||
p := tea.NewProgram(m, tea.WithAltScreen()) //Запускаем через bubble tea программу
|
||||
m.Program = p //Указываем объекту настроек, программу в которой запущен, чтобы передавать туда сигналы
|
||||
if _, err := p.Run(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// todo подсказка горячие клавиши
|
||||
// Main структура описывающая объект настроек
|
||||
type Main struct {
|
||||
current tea.Model //Текущая модель для отображения
|
||||
|
|
@ -31,7 +33,9 @@ type Main struct {
|
|||
CurrentSectionIdx int //Индекс текущей секции
|
||||
Width int //Ширина окна
|
||||
Height int //Высота окна
|
||||
p *tea.Program
|
||||
Program *tea.Program //Программа для отправки данных между собой
|
||||
Keys BaseKeyMap
|
||||
help help.Model
|
||||
}
|
||||
|
||||
// NewMain создаем новый объект настройки
|
||||
|
|
@ -41,7 +45,10 @@ func NewMain() *Main {
|
|||
m := &Main{
|
||||
Applications: apps,
|
||||
CurrentSectionIdx: 0,
|
||||
Keys: keys,
|
||||
help: help.New(),
|
||||
}
|
||||
m.help.ShowAll = false
|
||||
//Записываем в текущую модель список приложений
|
||||
m.current = NewListApplicationsModel(m.Applications, m.Width, m.Height)
|
||||
m.log = NewLogModel(m.Width, m.Height)
|
||||
|
|
@ -56,8 +63,9 @@ func (m *Main) Init() tea.Cmd {
|
|||
func (m *Main) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
var cmds []tea.Cmd
|
||||
var cmd tea.Cmd
|
||||
//Если у нас установлен модель модального окна, то передаем сообщение в его функцию обновления,
|
||||
//Если у нас установлена модель модального окна, то передаем сообщение в его функцию обновления,
|
||||
//при возврате команды модального окна записываем её в массив команд.
|
||||
//Если у нас сейчас показывается окно логирования, то обновляем его модель.
|
||||
//В противном случае передаем сообщение в функцию обновления текущей модели,
|
||||
//при возврате команды также записываем её в массив команд.
|
||||
if m.overlay != nil {
|
||||
|
|
@ -65,7 +73,7 @@ func (m *Main) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
if cmd != nil {
|
||||
cmds = append(cmds, cmd)
|
||||
}
|
||||
} else if m.showLog { //todo комментарии
|
||||
} else if m.showLog {
|
||||
m.log, cmd = m.log.Update(msg)
|
||||
if cmd != nil {
|
||||
cmds = append(cmds, cmd)
|
||||
|
|
@ -92,12 +100,15 @@ func (m *Main) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
}
|
||||
case tea.KeyMsg:
|
||||
//Отслеживаем нажатие клавиш приложения
|
||||
switch msg.String() {
|
||||
case "ctrl+l":
|
||||
//Обработчик клавиш ctrl+l показывает/скрывает окно логирования действий
|
||||
switch {
|
||||
case key.Matches(msg, m.Keys.Help):
|
||||
//Обработчик клавиш помощи, показывает/скрывает полное меню подсказок
|
||||
m.help.ShowAll = !m.help.ShowAll
|
||||
case key.Matches(msg, m.Keys.Log):
|
||||
//Обработчик клавиш логов показывает/скрывает окно логирования действий
|
||||
m.showLog = !m.showLog
|
||||
case "ctrl+c":
|
||||
//Обработчик клавиш ctrl+c у приложения нужен для его закрытия.
|
||||
case key.Matches(msg, m.Keys.Quit):
|
||||
//Обработчик клавиш закрытия приложения.
|
||||
//Возвращаем команду по возврату сообщения о показе модального окна
|
||||
return m, func() tea.Msg {
|
||||
return types.ShowModalMsg{
|
||||
|
|
@ -119,19 +130,28 @@ func (m *Main) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
}
|
||||
case types.NextSectionMsg:
|
||||
//Получаем сообщение о переходе на следующую секцию настраиваемого приложения.
|
||||
//Добавляем команду для возврата сообщения показа модального окна о выполнении действий секции
|
||||
//todo добавить проверку на наличие действий, если действий нет, просто переходить к следующей секции, выдавать сообщение "Действий секции нет"
|
||||
cmds = append(cmds, func() tea.Msg {
|
||||
return types.ShowModalMsg{
|
||||
Type: types.ModalInfo,
|
||||
Title: "Выполнение действий",
|
||||
Message: "Ожидайте завершения действий секции",
|
||||
ModalButtons: nil,
|
||||
OnResult: nil,
|
||||
//Если у текущей секции есть действия, то добавляем в массив команд функцию возврата сообщения показа модального окна с информацией о запуске действий.
|
||||
//Запускаем функцию выполнения действий секции в горутине.
|
||||
//Если действий у текущей секции нет, то просто меняем секцию на следующую
|
||||
if len(m.CurrentSection.Actions) > 0 {
|
||||
cmds = append(cmds, func() tea.Msg {
|
||||
return types.ShowModalMsg{
|
||||
Type: types.ModalLoading,
|
||||
Title: "Выполнение действий",
|
||||
Message: "Ожидайте завершения действий секции",
|
||||
ModalButtons: nil,
|
||||
OnResult: nil,
|
||||
}
|
||||
})
|
||||
//Запуск функции выполнения действий в горутине
|
||||
go m.executeSectionActions()
|
||||
} else {
|
||||
if ok, modalMsg := m.NextSectionProcess(); !ok {
|
||||
return m, func() tea.Msg {
|
||||
return modalMsg
|
||||
}
|
||||
}
|
||||
})
|
||||
//Запуск функции выполнения действий в горутине
|
||||
go m.executeSectionActions()
|
||||
}
|
||||
case types.ActionsCompleteMsg:
|
||||
//Команда закрытия модального окна
|
||||
cmds = append(cmds, func() tea.Msg {
|
||||
|
|
@ -142,45 +162,12 @@ func (m *Main) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
logModel.logs = append(logModel.logs, msg.Log...)
|
||||
m.log, cmd = logModel.Update(msg)
|
||||
if msg.Success {
|
||||
//Если действие успешно, переходим к следующей секции.
|
||||
//Ищем индекс следующей секции, если он остался 0, то следующие секции недоступны.
|
||||
//Возвращаем модальное окно с выходом к списку приложений
|
||||
nextSectionIndex := 0
|
||||
for sectionIdx := m.CurrentSectionIdx + 1; sectionIdx < len(m.CurrentApplication.Sections); sectionIdx++ {
|
||||
section := m.CurrentApplication.Sections[sectionIdx]
|
||||
if CheckCondition(section.Condition, m.CurrentApplication) {
|
||||
nextSectionIndex = sectionIdx
|
||||
break
|
||||
}
|
||||
}
|
||||
if nextSectionIndex == 0 {
|
||||
//Если действие успешно, то запускаем функцию перехода на следующую секцию.
|
||||
if ok, modalMsg := m.NextSectionProcess(); !ok {
|
||||
return m, func() tea.Msg {
|
||||
return types.ShowModalMsg{
|
||||
Type: types.ModalWarning,
|
||||
Title: "Ошибка секций приложения",
|
||||
Message: "Указанное приложение не имеет больше доступных секций для обработки",
|
||||
ModalButtons: []types.ModalButton{{
|
||||
Text: "Вернутся",
|
||||
Value: true,
|
||||
}},
|
||||
OnResult: func(result any) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return types.BackToListMsg{}
|
||||
}
|
||||
},
|
||||
}
|
||||
return modalMsg
|
||||
}
|
||||
}
|
||||
|
||||
//Если следующая секция доступна записываем секцию и её индекс.
|
||||
//Выводим либо финальную форму, если секция последняя и её тип SectionFinal, либо следующую простую секцию.
|
||||
m.CurrentSectionIdx = nextSectionIndex
|
||||
m.CurrentSection = &m.CurrentApplication.Sections[nextSectionIndex]
|
||||
if nextSectionIndex == len(m.CurrentApplication.Sections)-1 && m.CurrentSection.Type == types.SectionFinal {
|
||||
m.current = NewFinalModel(m.CurrentApplication.Variables, m.Width, m.Height)
|
||||
} else {
|
||||
m.current = NewFormModel(m.CurrentApplication, m.CurrentSectionIdx, 0, m.Width, m.Height)
|
||||
}
|
||||
} else {
|
||||
//Если действие не удалось выполнить показываем модель логов принудительно,
|
||||
//также возвращаем команду возврата сообщения показа модального окна
|
||||
|
|
@ -207,7 +194,7 @@ func (m *Main) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
//ищем доступную секцию
|
||||
for sectionIdx := 0; sectionIdx < len(m.CurrentApplication.Sections); sectionIdx++ {
|
||||
section := m.CurrentApplication.Sections[sectionIdx]
|
||||
if CheckCondition(section.Condition, m.CurrentApplication) {
|
||||
if utils.CheckCondition(section.Condition, m.CurrentApplication) {
|
||||
m.CurrentSectionIdx = sectionIdx
|
||||
m.CurrentSection = §ion
|
||||
break
|
||||
|
|
@ -243,19 +230,24 @@ func (m *Main) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
case types.ShowModalMsg:
|
||||
//Получаем сообщение о показе модального окна.
|
||||
//В поле модального окна записываем новый объект модального окна на основе сообщений.
|
||||
//Инициализируем модальное окно, если оно вернуло команду, добавляем её в массив.
|
||||
//НЕ СТИРАЕМ ТЕКУЩЕЕ ПРИЛОЖЕНИЕ
|
||||
m.overlay = NewModalModel(msg, m.Width, m.Height)
|
||||
return m, nil
|
||||
initModalCmd := m.overlay.Init()
|
||||
if initModalCmd != nil {
|
||||
cmds = append(cmds, initModalCmd)
|
||||
}
|
||||
return m, tea.Sequence(cmds...)
|
||||
case types.CloseModalMsg:
|
||||
//Получаем сообщение о закрытии модального окна.
|
||||
//Стираем модальное окно.
|
||||
m.overlay = nil
|
||||
return m, nil
|
||||
//предохранитель
|
||||
//return m,tea.Batch(cmds...)
|
||||
//return m,tea.Sequence(cmds...)
|
||||
}
|
||||
//Возвращаем команду собранную из массива команд текущей модели
|
||||
return m, tea.Batch(cmds...)
|
||||
return m, tea.Sequence(cmds...)
|
||||
}
|
||||
|
||||
// View формирует строку на основе модального окна или текущей модели
|
||||
|
|
@ -267,55 +259,22 @@ func (m *Main) View() string {
|
|||
if m.overlay != nil {
|
||||
view = m.overlay.View()
|
||||
}
|
||||
return view
|
||||
return view + "\n\n" + m.help.View(m.Keys)
|
||||
}
|
||||
|
||||
// Sugar проверяет поле указанное в сообщение на важность в форме и приложении.
|
||||
func (m *Main) Sugar(sugar types.SugarMsg) {
|
||||
//Если полей с указанной переменной несколько, то выключаем все прочие поля кроме, указанного в сообщении
|
||||
if m.IsMultiField(sugar.VariableName) {
|
||||
if utils.IsMultiField(sugar.VariableName, m.CurrentApplication.Sections) {
|
||||
m.DeactivateField(sugar.VariableName, sugar.FieldName)
|
||||
}
|
||||
//Если от переменной поля зависит секции или поля,
|
||||
//то формируем новую форму с учетом прошлого фокуса
|
||||
if IsParent(sugar.VariableName, m.CurrentApplication.Sections) {
|
||||
if utils.IsParent(sugar.VariableName, m.CurrentApplication.Sections) {
|
||||
m.current = NewFormModel(m.CurrentApplication, m.CurrentSectionIdx, sugar.Focus, m.Width, m.Height)
|
||||
}
|
||||
}
|
||||
|
||||
// IsParent проверяет, является ли указанная переменная условием для поля или секции
|
||||
func IsParent(variableName string, sections []types.Section) bool {
|
||||
for _, section := range sections {
|
||||
for _, parent := range section.Parent {
|
||||
if parent == variableName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, field := range section.Fields {
|
||||
for _, parent := range field.Parent {
|
||||
if parent == variableName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsMultiField проверяет переменную на использование несколькими полями.
|
||||
func (m *Main) IsMultiField(variableName string) bool {
|
||||
var count int
|
||||
for _, section := range m.CurrentApplication.Sections {
|
||||
for _, field := range section.Fields {
|
||||
if field.Name == variableName {
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
return count > 1
|
||||
}
|
||||
|
||||
// DeactivateField отключает все поля использующие указанную переменную, кроме поля с указанным именем
|
||||
func (m *Main) DeactivateField(variableName, fieldName string) {
|
||||
for sectionIdx, section := range m.CurrentApplication.Sections {
|
||||
|
|
@ -340,14 +299,14 @@ func (m *Main) executeSectionActions() {
|
|||
logBuffer = append(logBuffer, sectionLog)
|
||||
for _, action := range m.CurrentSection.Actions {
|
||||
//Если условие для действия не выполняется, то пропускаем
|
||||
if !CheckCondition(action.Condition, m.CurrentApplication) {
|
||||
if !utils.CheckCondition(action.Condition, m.CurrentApplication) {
|
||||
return
|
||||
}
|
||||
sectionActionLog := fmt.Sprintf("Выполнение действия: %s", action.Name)
|
||||
logrus.Infof(sectionActionLog)
|
||||
logBuffer = append(logBuffer, sectionActionLog)
|
||||
//Проверяем, что все нужные пакеты для действия установлены
|
||||
if err := m.InstallPackage(action.RequirePackages); err != nil {
|
||||
if err := utils.InstallPackages(action.RequirePackages); err != nil {
|
||||
errLog := fmt.Sprintf("Ошибка установки пакета: %v", err)
|
||||
logrus.Errorf(errLog)
|
||||
logBuffer = append(logBuffer, errLog)
|
||||
|
|
@ -355,7 +314,7 @@ func (m *Main) executeSectionActions() {
|
|||
break
|
||||
}
|
||||
//Выполняем действие
|
||||
if err := ExecuteAction(&action, m.CurrentApplication); err != nil {
|
||||
if err := utils.ExecuteAction(&action, m.CurrentApplication); err != nil {
|
||||
errLog := fmt.Sprintf("Ошибка выполнения действия: %v", err)
|
||||
logrus.Errorf(errLog)
|
||||
logBuffer = append(logBuffer, errLog)
|
||||
|
|
@ -367,23 +326,47 @@ func (m *Main) executeSectionActions() {
|
|||
logrus.Infof(successMsg)
|
||||
}
|
||||
//Отправляем в программу сигнал об успешном завершении действия
|
||||
m.p.Send(types.ActionsCompleteMsg{
|
||||
m.Program.Send(types.ActionsCompleteMsg{
|
||||
Success: success,
|
||||
Log: logBuffer,
|
||||
})
|
||||
}
|
||||
|
||||
// InstallPackage проверяет установлен ли пакет, устанавливает при отсутствии
|
||||
func (m *Main) InstallPackage(packages []string) error {
|
||||
for _, pkg := range packages {
|
||||
cmd := exec.Command("dpkg", "-s", pkg)
|
||||
if err := cmd.Run(); err != nil {
|
||||
installCmd := exec.Command("apt", "install", "-y", pkg)
|
||||
out, err := installCmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("пакет %s: %v\nOutput: %s", pkg, err, out)
|
||||
}
|
||||
// NextSectionProcess проверяет доступность следующей секции для настройки
|
||||
func (m *Main) NextSectionProcess() (bool, types.ShowModalMsg) {
|
||||
//Ищем индекс следующей секции, если он остался 0, то следующие секции недоступны.
|
||||
//Возвращаем модальное окно с выходом к списку приложений
|
||||
nextSectionIndex := 0
|
||||
for sectionIDx := m.CurrentSectionIdx + 1; sectionIDx < len(m.CurrentApplication.Sections); sectionIDx++ {
|
||||
section := m.CurrentApplication.Sections[sectionIDx]
|
||||
if utils.CheckCondition(section.Condition, m.CurrentApplication) {
|
||||
nextSectionIndex = sectionIDx
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
if nextSectionIndex == 0 {
|
||||
return false, types.ShowModalMsg{
|
||||
Type: types.ModalWarning,
|
||||
Title: "Ошибка секций приложения",
|
||||
Message: "Указанное приложение не имеет больше доступных секций для обработки",
|
||||
ModalButtons: []types.ModalButton{
|
||||
{Text: "Вернуться", Value: true},
|
||||
},
|
||||
OnResult: func(result any) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return types.BackToListMsg{}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
//Если следующая секция доступна записываем секцию и её индекс.
|
||||
//Выводим либо финальную форму, если секция последняя и её тип SectionFinal, либо следующую простую секцию.
|
||||
m.CurrentSectionIdx = nextSectionIndex
|
||||
m.CurrentSection = &m.CurrentApplication.Sections[nextSectionIndex]
|
||||
if nextSectionIndex == len(m.CurrentApplication.Sections)-1 && m.CurrentSection.Type == types.SectionFinal {
|
||||
m.current = NewFinalModel(m.CurrentApplication.Variables, m.Width, m.Height)
|
||||
} else {
|
||||
m.current = NewFormModel(m.CurrentApplication, m.CurrentSectionIdx, 0, m.Width, m.Height)
|
||||
}
|
||||
return true, types.ShowModalMsg{}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue