my-log/cmd/drop.go
2024-02-11 13:50:27 -06:00

92 lines
2.3 KiB
Go

/*
Copyright © 2024 Dan Jones <danjones@goodevilgenius.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"encoding/json"
"fmt"
"time"
"codeberg.org/danjones000/my-log/files"
"codeberg.org/danjones000/my-log/models"
"codeberg.org/danjones000/my-log/tools"
"github.com/spf13/cobra"
)
var dateStr string
var fields map[string]string
var j Json
// dropCmd represents the drop command
var dropCmd = &cobra.Command{
Use: "drop log title",
Short: "Add a new log entry",
// Long: ``,
Args: cobra.ExactArgs(2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
log := args[0]
title := args[1]
e := models.PartialEntry()
if len(j.RawMessage) > 8 {
err := json.Unmarshal([]byte(j.RawMessage), &e)
if err != nil {
return err
}
}
for k, v := range fields {
e.Fields = append(e.Fields, models.Meta{k, tools.ParseString(v)})
}
e.Title = title
e.Date = time.Now().Local() // @todo parse date
l := models.Log{log, []models.Entry{e}}
err := files.Append(l)
if err != nil {
return err
}
by, err := e.MarshalText()
if err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "%s\n", by)
return nil
},
}
func init() {
rootCmd.AddCommand(dropCmd)
dropCmd.Flags().StringVarP(&dateStr, "date", "d", time.Now().Local().Format(time.RFC3339), "Date for log entry")
dropCmd.Flags().StringToStringVarP(&fields, "fields", "f", nil, "Fields you add to entry")
dropCmd.Flags().VarP(&j, "json", "j", "Entire entry as json")
}
type Json struct {
json.RawMessage
}
func (j *Json) String() string {
return string(j.RawMessage)
}
func (j *Json) Set(in string) error {
return json.Unmarshal([]byte(in), &j.RawMessage)
}
func (j *Json) Type() string {
return "json"
}