This repository has been archived by the owner on Nov 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch.go
93 lines (78 loc) · 1.95 KB
/
fetch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"fmt"
"io"
"log"
"net/url"
"os"
"path/filepath"
"github.com/nesv/pm"
"github.com/spf13/cobra"
)
var FetchCmd = &cobra.Command{
Use: "fetch [url]",
Short: "Fetch a remote package, and store it in the local cache",
Long: `
pm currently supports fetching packages with the following URL schemes:
* http
* https
* file
You can supply more than one package URL to the fetch command.
`,
Run: runFetch,
}
func runFetch(cmd *cobra.Command, args []string) {
if len(args) < 1 {
log.Fatalln("no package URLs specified")
}
for _, urlStr := range args {
if err := fetch(urlStr); err != nil {
log.Fatalln(err)
}
}
}
func fetch(urlStr string) error {
u, err := url.Parse(urlStr)
if err != nil {
log.Fatalln(err)
}
// Check to see if the package cache directory exists, and if it
// doesn't, then create it.
if fi, err := os.Stat(rootCacheDir); err != nil && os.IsNotExist(err) {
if Verbose {
log.Println("cache directory does not exist; creating it")
}
if err := os.MkdirAll(rootCacheDir, 0755); err != nil {
log.Fatalln("failed to create cache directory:", err)
}
} else if !fi.IsDir() {
log.Fatalln(rootCacheDir, "exists, but is not a directory")
}
destPath := filepath.Join(rootCacheDir, filepath.Base(u.Path))
if f, err := os.Open(destPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed while checking cache for %q", filepath.Base(u.Path))
} else if err != nil && os.IsNotExist(err) {
if Verbose {
log.Println("fetching", u.String())
}
r, err := pm.Fetch(urlStr)
if err != nil {
log.Fatalln(err)
}
defer r.Close()
dest, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create %q: %v", destPath, err)
}
defer dest.Close()
if _, err := io.Copy(dest, r); err != nil {
return fmt.Errorf("failed to write file %q", destPath)
}
} else {
f.Close()
if Verbose {
log.Printf("%s is already cached", u.Path)
}
}
return nil
}