]> Cypherpunks.ru repositories - nncp.git/blob - src/humanizer.go
701b590d51ede2638075b4e1c0f4b761905ef632
[nncp.git] / src / humanizer.go
1 /*
2 NNCP -- Node to Node copy
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package nncp
19
20 import (
21         "fmt"
22         "strings"
23         "time"
24
25         "go.cypherpunks.ru/recfile"
26 )
27
28 func (ctx *Ctx) HumanizeRec(rec string) string {
29         r := recfile.NewReader(strings.NewReader(rec))
30         le, err := r.NextMap()
31         if err != nil {
32                 return rec
33         }
34         humanized, err := ctx.Humanize(le)
35         if err != nil {
36                 return fmt.Sprintf("Can not humanize: %s\n%s", err, rec)
37         }
38         return humanized
39 }
40
41 func (ctx *Ctx) Humanize(le map[string]string) (string, error) {
42         when, err := time.Parse(time.RFC3339Nano, le["When"])
43         if err != nil {
44                 return "", err
45         }
46         var level string
47         msg := le["Msg"]
48         if errMsg, isErr := le["Err"]; isErr {
49                 level = "ERROR "
50                 msg += ": " + errMsg
51         }
52         return fmt.Sprintf("%s %s%s", when.Format(time.RFC3339), level, msg), nil
53 }