MCPcopy Create free account
hub / github.com/SolarLune/masterplan / NewResource

Function NewResource

resources.go:77–147  ·  view source on GitHub ↗
(resourcePath string)

Source from the content-addressed store, hash-verified

75}
76
77func NewResource(resourcePath string) (*Resource, error) {
78
79 resource := &Resource{
80 Name: resourcePath,
81 Destructible: true,
82 }
83
84 if _, err := os.ReadFile(resourcePath); err == nil {
85
86 resource.LocalFilepath = resourcePath
87 resource.Extension = filepath.Ext(resourcePath)
88 resource.Parse()
89
90 } else {
91
92 log.Println("possible online resource: ", resourcePath)
93
94 project := globals.Project
95
96 if globals.NextProject != nil {
97 project = globals.NextProject
98 }
99
100 destDir := project.Properties.Get(ProjectCacheDirectory).AsString()
101
102 if destDir == "" || !FolderExists(destDir) {
103 destDir = filepath.Join(os.TempDir(), "masterplan")
104 resource.TempFile = true
105 // It's online, so we don't need to save it
106 }
107
108 if req, err := grab.NewRequest("", resourcePath); err != nil {
109 return nil, err
110 } else {
111 unescapedPath, _ := url.QueryUnescape(req.URL().Path)
112 req.Filename = filepath.Join(destDir, filepath.FromSlash(req.URL().Hostname()+"/"+unescapedPath))
113
114 // It's already been downloaded
115 if FileExists(req.Filename) {
116 resource.LocalFilepath = req.Filename
117 resource.Extension = filepath.Ext(resource.LocalFilepath)
118 resource.Parse()
119 return resource, nil
120 }
121
122 resource.LocalFilepath = req.Filename
123 resource.Extension = filepath.Ext(resourcePath)
124 resource.Response = globals.GrabClient.Do(req) // This can take time, up to and including seconds to execute
125
126 if resource.Response.IsComplete() && resource.Response.Err() != nil {
127 return nil, resource.Response.Err()
128 } else if site, err := http.Get(resourcePath); err == nil {
129
130 // We're going to get what the Mime data is by downloading the first 5kb of a link, and then passing
131 // it into mimetype.Detect().
132
133 r := bufio.NewScanner(site.Body)
134 r.Buffer([]byte{}, 5000)

Callers 1

GetMethod · 0.85

Calls 7

ParseMethod · 0.95
FolderExistsFunction · 0.85
FileExistsFunction · 0.85
AsStringMethod · 0.80
DoMethod · 0.80
GetMethod · 0.45
StringMethod · 0.45

Tested by

no test coverage detected