You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

128 lines
2.2 KiB
Go

package operators
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/user"
"path/filepath"
)
const (
packageListURL string = "https://git.rawtext.club/slope-lang/packages/raw/branch/master/packages.json"
)
func ExpandedAbsFilepath(p string) string {
if strings.HasPrefix(p, "~") {
if p == "~" || strings.HasPrefix(p, "~/") {
homedir, _ := os.UserHomeDir()
if len(p) <= 2 {
p = homedir
} else if len(p) > 2 {
p = filepath.Join(homedir, p[2:])
}
} else {
i := strings.IndexRune(p, '/')
var u string
var remainder string
if i < 0 {
u = p[1:]
remainder = ""
} else {
u = p[1:i]
remainder = p[i:]
}
usr, err := user.Lookup(u)
if err != nil {
p = filepath.Join("/home", u, remainder)
} else {
p = filepath.Join(usr.HomeDir, remainder)
}
}
} else if !strings.HasPrefix(p, "/") {
wd, _ := os.Getwd()
p = filepath.Join(wd, p)
}
path, _ := filepath.Abs(p)
return path
}
func getModBaseDir() string {
p := os.Getenv("SLOPE_MOD_PATH")
if p == "" {
x := os.Getenv("XDG_DATA_HOME")
if x == "" {
return ExpandedAbsFilepath("~/.local/share/slope/modules/")
}
return filepath.Join(x, "slope", "modules")
}
return p
}
func downloadTheDirectory() error {
modDir, err := getModBaseDir()
if err != nil {
return err
}
out, err := os.Create(filepath.Join(modDir, "packages.json"))
if err != nil {
return err
}
defer out.Close()
resp, err := http.Get(packageListURL)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func getPackages() (map[string]string, error) {
modDir, err := getModBaseDir()
if err != nil {
return nil, err
}
data, err := ioutil.ReadFile(filepath.Join(modDir, "packages.json"))
if err != nil {
return nil, err
}
weak := map[string]interface{}{}
err = json.Unmarshal(data, &weak)
if err != nil {
return nil, err
}
packages := map[string]string{}
for pkg, v := range weak {
repo, ok := v.(string)
if !ok {
return nil, fmt.Errorf("packages.json: invalid repository for %s. submit an issue to get it fixed", pkg)
}
packages[pkg] = repo
}
return packages, nil
}