pgm/cmd/add.go

296 lines
6.5 KiB
Go

/*
Copyright © 2020 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"encoding/json"
"io/ioutil"
//"encoding/json"
"fmt"
input "github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
te "github.com/muesli/termenv"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"log"
"pgm/data"
"pgm/logger"
//"io/ioutil"
//"log"
"os"
//"pgm/logger"
)
const focusedTextColor = "212"
var (
focusedPrompt = te.String("> ").Foreground(color("205")).String()
blurredPrompt = "> "
color = te.ColorProfile().Color
focusedSubmitButton = "[ " + te.String("Submit").Foreground(color("205")).String() + " ]"
blurredSubmitButton = "[ " + te.String("Submit").Foreground(color("240")).String() + " ]"
)
type dupeFileMsg string
type dbCfg struct {
index int
dbFileName input.Model
hostName input.Model
dbName input.Model
userName input.Model
secret input.Model
submitButton string
}
// addCmd represents the add command
var addCmd = &cobra.Command{
Use: "add",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
result := make(chan string, 1)
if err := tea.NewProgram(initialModel()).Start(); err != nil {
fmt.Printf("could not start program: %s\n", err)
os.Exit(1)
}
// Print out the final choice.
if r := <-result; r != "" {
fmt.Printf("\n---\nYou chose %s!\n", r)
}
},
}
func init() {
rootCmd.AddCommand(addCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// addCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func (m dbCfg) Init() tea.Cmd {
return tea.Batch(
input.Blink(m.dbFileName),
input.Blink(m.hostName),
input.Blink(m.dbName),
input.Blink(m.userName),
input.Blink(m.secret),
)
}
func (m dbCfg) View() string {
s := "\n"
inputs := []string{
input.View(m.dbFileName),
input.View(m.hostName),
input.View(m.dbName),
input.View(m.userName),
input.View(m.secret),
}
for i := 0; i < len(inputs); i++ {
s += inputs[i]
if i < len(inputs)-1 {
s += "\n"
}
}
s += "\n\n" + m.submitButton + "\n"
return s
}
func (m dbCfg) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
// Cycle between inputs
case "tab", "shift+tab", "enter", "up", "down":
inputs := []input.Model{
m.dbFileName,
m.hostName,
m.dbName,
m.userName,
m.secret,
}
s := msg.String()
// Did the user press enter while the submit button was focused?
// If so, exit.
if s == "enter" && m.index == len(inputs) {
return m, tea.Quit
}
// Cycle indexes
if s == "up" || s == "shift+tab" {
m.index--
} else {
m.index++
}
if m.index > len(inputs) {
m.index = 0
} else if m.index < 0 {
m.index = len(inputs)
}
for i := 0; i <= len(inputs)-1; i++ {
if i == m.index {
// Set focused state
inputs[i].Focus()
inputs[i].Prompt = focusedPrompt
inputs[i].TextColor = focusedTextColor
continue
}
// Remove focused state
inputs[i].Blur()
inputs[i].Prompt = blurredPrompt
inputs[i].TextColor = ""
}
m.dbFileName = inputs[0]
m.hostName = inputs[1]
m.dbName = inputs[2]
m.userName = inputs[3]
m.secret = inputs[4]
if m.index == len(inputs) {
m.submitButton = focusedSubmitButton
} else {
m.submitButton = blurredSubmitButton
}
return m, nil
}
}
// Handle character input and blinks
m, cmd = updateInputs(msg, m)
return m, cmd
}
func updateInputs(msg tea.Msg, m dbCfg) (dbCfg, tea.Cmd) {
var (
cmd tea.Cmd
cmds []tea.Cmd
)
m.dbFileName, cmd = input.Update(msg, m.dbFileName)
cmds = append(cmds, cmd)
m.hostName, cmd = input.Update(msg, m.hostName)
cmds = append(cmds, cmd)
m.dbName, cmd = input.Update(msg, m.dbName)
cmds = append(cmds, cmd)
m.userName, cmd = input.Update(msg, m.userName)
cmds = append(cmds, cmd)
m.secret, cmd = input.Update(msg, m.secret)
return m, tea.Batch(cmds...)
}
func initialModel() dbCfg {
dbFileName := input.NewModel()
dbFileName.Placeholder = "database file name (no spaces)"
dbFileName.Focus()
hostName := input.NewModel()
hostName.Placeholder = "hostname"
dbName := input.NewModel()
dbName.Placeholder = "database name on host"
userName := input.NewModel()
userName.Placeholder = "username"
secret := input.NewModel()
secret.Placeholder = "secret"
return dbCfg{0, dbFileName, hostName, dbName, userName, secret, blurredSubmitButton}
}
// Writes configs to .pgm/hosts directory
func configWriter(t []input.Model){
h := viper.GetString("hostsDir")
var c data.HostDetails
var fp string
var cfg []byte
c = data.HostDetails{t[4].Value(), t[1].Value(), t[2].Value(), t[3].Value()}
cfgFileName := t[0].Value()
if _, err := os.Stat(h + "/" + cfgFileName); os.IsNotExist(err) {
fp = h + "/" + cfgFileName
} else {
e := "dupe"
return dupeFileMsg(e)
}
_ = cfg
f, err := os.Create(fp)
if err != nil {
log.Fatal("unable to create file: " + fp)
}
defer f.Close()
if err != nil {
log.Fatal("error writing to file: " + err.Error())
}
cfg, err = json.MarshalIndent(c, "", " ")
if err != nil {
log.Fatal(err)
}
logger.Logger("[LOG] writing file to: " + fp)
_ = ioutil.WriteFile(fp, cfg, 0644)
lgd := logger.Logger("[LOG] configuration file written: dbname::" + c.DatabaseName + "::hostname::" + c.Hostname)
if lgd != true {
fmt.Println("failed to log")
}
}