Debian Codegraph @

trash/info.go

raw
1 package trash
2
3 import (
4 "fmt"
5 "github.com/rkoesters/xdg/keyfile"
6 "io"
7 "net/url"
8 "strings"
9 "time"
10 )
11
12 const (
13 trashInfo = "Trash Info"
14
15 timeFormat = "2006-01-02T15:04:05"
16 )
17
18 // Info represents a .trashinfo file.
19 type Info struct {
20 Path string
21 DeletionDate time.Time
22 }
23
24 // NewInfo creates a new Info using the given io.Reader.
25 func NewInfo(r io.Reader) (*Info, error) {
26 kf, err := keyfile.New(r)
27 if err != nil {
28 return nil, err
29 }
30
31 info := new(Info)
32 tmp, err := kf.String(trashInfo, "Path")
33 if err != nil {
34 return nil, err
35 }
36 info.Path, err = url.QueryUnescape(tmp)
37 if err != nil {
38 return nil, err
39 }
40 tmp, err = kf.String(trashInfo, "DeletionDate")
41 if err != nil {
42 return nil, err
43 }
44 info.DeletionDate, err = time.ParseInLocation(timeFormat, tmp, time.Local)
45 if err != nil {
46 return nil, err
47 }
48 return info, nil
49 }
50
51 // String returns Info as a string in the INI format.
52 func (i *Info) String() string {
53 return fmt.Sprintf(
54 "[Trash Info]\nPath=%v\nDeletionDate=%v\n",
55 queryEscape(i.Path),
56 i.DeletionDate.Format(timeFormat),
57 )
58 }
59
60 // queryEscape is a wrapper function around url.QueryEscape that doesn't
61 // escape '/'.
62 func queryEscape(s string) string {
63 // The first for loop is the workaround for "/".
64 a := strings.Split(s, "/")
65 for i := 0; i < len(a); i++ {
66 // The second for loop is the workaround for " ".
67 b := strings.Split(a[i], " ")
68 for j := 0; j < len(b); j++ {
69 b[j] = url.QueryEscape(b[j])
70 }
71 a[i] = strings.Join(b, "%20")
72 }
73 return strings.Join(a, "/")
74 }