Debian Codegraph @

userdirs/userdirs.go

raw
1 // Package userdirs provides easy access to "well known" user
2 // directories. For more information, see:
3 // https://www.freedesktop.org/wiki/Software/xdg-user-dirs/
4 package userdirs
5
6 import (
7 "github.com/rkoesters/xdg/basedir"
8 "github.com/rkoesters/xdg/keyfile"
9 "io"
10 "os"
11 "path/filepath"
12 "strings"
13 )
14
15 // The default set of userdirs. Most people will only need to use this.
16 var (
17 Desktop string
18 Documents string
19 Download string
20 Music string
21 Pictures string
22 PublicShare string
23 Templates string
24 Videos string
25 )
26
27 func init() {
28 f, err := os.Open(filepath.Join(basedir.ConfigHome, "user-dirs.dirs"))
29 if err != nil {
30 return
31 }
32 defer f.Close()
33
34 dirs, err := New(f)
35 if err != nil {
36 return
37 }
38
39 Desktop = dirs.Desktop
40 Documents = dirs.Documents
41 Download = dirs.Download
42 Music = dirs.Music
43 Pictures = dirs.Pictures
44 PublicShare = dirs.PublicShare
45 Templates = dirs.Templates
46 Videos = dirs.Videos
47 }
48
49 // UserDirs is a set of user directories that are common in graphical
50 // environments.
51 type UserDirs struct {
52 Desktop string
53 Documents string
54 Download string
55 Music string
56 Pictures string
57 PublicShare string
58 Templates string
59 Videos string
60 }
61
62 // New creates a new UserDirs struct by reading from the given
63 // io.Reader.
64 func New(r io.Reader) (*UserDirs, error) {
65 kf, err := keyfile.New(r)
66 if err != nil {
67 return nil, err
68 }
69
70 dirs := new(UserDirs)
71
72 dirs.Desktop, err = parse(kf.String("", "XDG_DESKTOP_DIR"))
73 if err != nil {
74 return nil, err
75 }
76 dirs.Documents, err = parse(kf.String("", "XDG_DOCUMENTS_DIR"))
77 if err != nil {
78 return nil, err
79 }
80 dirs.Download, err = parse(kf.String("", "XDG_DOWNLOAD_DIR"))
81 if err != nil {
82 return nil, err
83 }
84 dirs.Music, err = parse(kf.String("", "XDG_MUSIC_DIR"))
85 if err != nil {
86 return nil, err
87 }
88 dirs.Pictures, err = parse(kf.String("", "XDG_PICTURES_DIR"))
89 if err != nil {
90 return nil, err
91 }
92 dirs.PublicShare, err = parse(kf.String("", "XDG_PUBLICSHARE_DIR"))
93 if err != nil {
94 return nil, err
95 }
96 dirs.Templates, err = parse(kf.String("", "XDG_TEMPLATES_DIR"))
97 if err != nil {
98 return nil, err
99 }
100 dirs.Videos, err = parse(kf.String("", "XDG_VIDEOS_DIR"))
101 if err != nil {
102 return nil, err
103 }
104
105 return dirs, nil
106 }
107
108 // parse takes a given string and returns it as a path.
109 func parse(s string, err error) (string, error) {
110 if err != nil {
111 return "", err
112 }
113 s = strings.Trim(s, "\"")
114 if strings.HasPrefix(s, "$HOME") {
115 s = filepath.Join(basedir.Home, strings.TrimPrefix(s, "$HOME"))
116 }
117 if s == "" {
118 s = basedir.Home
119 }
120 return s, nil
121 }