yay/pkg/completion/completion.go

110 lines
2.3 KiB
Go
Raw Normal View History

2019-10-05 03:02:30 +02:00
package completion
import (
"bufio"
2020-07-25 00:55:46 +02:00
"fmt"
2019-10-05 03:02:30 +02:00
"io"
"net/http"
"net/url"
2019-10-05 03:02:30 +02:00
"os"
"path"
2019-10-05 03:02:30 +02:00
"path/filepath"
2020-07-25 00:55:46 +02:00
"strings"
2019-10-05 03:02:30 +02:00
"time"
alpm "github.com/Jguer/go-alpm"
)
// Show provides completion info for shells
func Show(alpmHandle *alpm.Handle, aurURL, completionPath string, interval int, force bool) error {
err := Update(alpmHandle, aurURL, completionPath, interval, force)
2019-10-05 03:02:30 +02:00
if err != nil {
return err
}
in, err := os.OpenFile(completionPath, os.O_RDWR|os.O_CREATE, 0o644)
2019-10-05 03:02:30 +02:00
if err != nil {
return err
}
defer in.Close()
_, err = io.Copy(os.Stdout, in)
return err
}
// Update updates completion cache to be used by Complete
func Update(alpmHandle *alpm.Handle, aurURL, completionPath string, interval int, force bool) error {
info, err := os.Stat(completionPath)
2019-10-05 03:02:30 +02:00
if os.IsNotExist(err) || (interval != -1 && time.Since(info.ModTime()).Hours() >= float64(interval*24)) || force {
errd := os.MkdirAll(filepath.Dir(completionPath), 0o755)
if errd != nil {
return errd
}
out, errf := os.Create(completionPath)
2019-10-05 03:02:30 +02:00
if errf != nil {
return errf
}
if createAURList(aurURL, out) != nil {
defer os.Remove(completionPath)
2019-10-05 03:02:30 +02:00
}
2020-07-25 00:55:46 +02:00
dbList, err := alpmHandle.SyncDBs()
if err != nil {
return err
}
erra := createRepoList(&dbList, out)
2019-10-05 03:02:30 +02:00
out.Close()
return erra
}
return nil
}
// CreateAURList creates a new completion file
2019-10-16 01:03:58 +02:00
func createAURList(aurURL string, out io.Writer) error {
u, err := url.Parse(aurURL)
if err != nil {
return err
}
u.Path = path.Join(u.Path, "packages.gz")
resp, err := http.Get(u.String())
2019-10-05 03:02:30 +02:00
if err != nil {
return err
}
defer resp.Body.Close()
2020-07-25 00:55:46 +02:00
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("invalid status code: %d", resp.StatusCode)
}
2019-10-05 03:02:30 +02:00
scanner := bufio.NewScanner(resp.Body)
scanner.Scan()
for scanner.Scan() {
2020-07-25 00:55:46 +02:00
text := scanner.Text()
if strings.HasPrefix(text, "#") {
continue
}
_, err = io.WriteString(out, text+"\tAUR\n")
2019-10-05 03:02:30 +02:00
if err != nil {
return err
}
}
return nil
}
// CreatePackageList appends Repo packages to completion cache
2020-07-25 00:55:46 +02:00
func createRepoList(dbList *alpm.DBList, out io.Writer) error {
2019-10-05 03:02:30 +02:00
_ = dbList.ForEach(func(db alpm.DB) error {
_ = db.PkgCache().ForEach(func(pkg alpm.Package) error {
2020-07-25 00:55:46 +02:00
_, err := io.WriteString(out, pkg.Name()+"\t"+pkg.DB().Name()+"\n")
2019-10-05 03:02:30 +02:00
return err
})
return nil
})
return nil
}