Skip to content

Commit

Permalink
feat: following #4
Browse files Browse the repository at this point in the history
* Create an empty config yaml file when config file not exists.

* Enables the http module to use the configured proxy as well.
  • Loading branch information
aooohan committed Jan 22, 2024
1 parent 215ea52 commit c4f6d44
Show file tree
Hide file tree
Showing 7 changed files with 120 additions and 65 deletions.
16 changes: 15 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,33 @@
package config

import (
"github.com/version-fox/vfox/internal/util"
"gopkg.in/yaml.v3"
"os"
"path/filepath"
)

type Config struct {
Proxy Proxy `yaml:"proxy"`
Proxy *Proxy `yaml:"proxy"`
}

const filename = "config.yaml"

var (
defaultConfig = &Config{
Proxy: EmptyProxy,
}
)

func NewConfig(path string) (*Config, error) {
p := filepath.Join(path, filename)
if !util.FileExists(p) {
content, err := yaml.Marshal(defaultConfig)
if err != nil {
_ = os.WriteFile(p, content, 0644)
return defaultConfig, nil
}
}
content, err := os.ReadFile(p)
if err != nil {
return nil, err
Expand Down
7 changes: 7 additions & 0 deletions internal/config/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,10 @@ type Proxy struct {
Url string `yaml:"url"`
Enable bool `yaml:"enable"`
}

var (
EmptyProxy = &Proxy{
Url: "",
Enable: false,
}
)
59 changes: 27 additions & 32 deletions internal/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ type Manager struct {
Record env.Record
osType util.OSType
archType util.ArchType
config *config.Config
Config *config.Config
}

func (m *Manager) EnvKeys() env.Envs {
Expand Down Expand Up @@ -92,7 +92,7 @@ func (m *Manager) LookupSdk(name string) (*Sdk, error) {
if err != nil {
return nil, err
}
luaPlugin, err := NewLuaPlugin(content, pluginPath, m.osType, m.archType)
luaPlugin, err := NewLuaPlugin(content, pluginPath, m)
if err != nil {
return nil, err
}
Expand All @@ -115,7 +115,7 @@ func (m *Manager) LoadAllSdk() (map[string]*Sdk, error) {
// filename first as sdk name
path := filepath.Join(m.PathMeta.PluginPath, d.Name())
content, _ := m.loadLuaFromFileOrUrl(path)
source, err := NewLuaPlugin(content, path, m.osType, m.archType)
source, err := NewLuaPlugin(content, path, m)
if err != nil {
pterm.Printf("Failed to load %s plugin, err: %s\n", path, err)
continue
Expand Down Expand Up @@ -168,7 +168,7 @@ func (m *Manager) Update(pluginName string) error {
if err != nil {
return fmt.Errorf("fetch plugin failed, err: %w", err)
}
source, err := NewLuaPlugin(content, updateUrl, m.osType, m.archType)
source, err := NewLuaPlugin(content, updateUrl, m)
if err != nil {
return fmt.Errorf("check %s plugin failed, err: %w", updateUrl, err)
}
Expand Down Expand Up @@ -229,7 +229,7 @@ func (m *Manager) Add(pluginName, url, alias string) error {
return fmt.Errorf("failed to load plugin: %w", err)
}
pterm.Println("Checking plugin...")
source, err := NewLuaPlugin(content, url, m.osType, m.archType)
source, err := NewLuaPlugin(content, url, m)
if err != nil {
return fmt.Errorf("check plugin error: %w", err)
}
Expand Down Expand Up @@ -258,23 +258,30 @@ func (m *Manager) Add(pluginName, url, alias string) error {
return nil
}

func (m *Manager) httpClient() *http.Client {
var client *http.Client
if m.Config.Proxy.Enable {
if uri, err := url.Parse(m.Config.Proxy.Url); err == nil {
transPort := &http.Transport{
Proxy: http.ProxyURL(uri),
}
client = &http.Client{
Transport: transPort,
}
}
} else {
client = http.DefaultClient
}

return client
}

func (m *Manager) loadLuaFromFileOrUrl(path string) (string, error) {
if !strings.HasSuffix(path, ".lua") {
return "", fmt.Errorf("%s not a lua file", path)
}
if strings.HasPrefix(path, "https://") || strings.HasPrefix(path, "http://") {
client := http.Client{}
if m.config.Proxy.Enable {
uri, err := url.Parse(m.config.Proxy.Url)
if err == nil {
transPort := &http.Transport{
Proxy: http.ProxyURL(uri),
}
client = http.Client{
Transport: transPort,
}
}
}
client := m.httpClient()
resp, err := client.Get(path)
if err != nil {
return "", err
Expand Down Expand Up @@ -312,19 +319,7 @@ func (m *Manager) loadLuaFromFileOrUrl(path string) (string, error) {
}

func (m *Manager) Available() ([]*Category, error) {
// FIX proxy
client := http.Client{}
if m.config.Proxy.Enable {
uri, err := url.Parse(m.config.Proxy.Url)
if err == nil {
transPort := &http.Transport{
Proxy: http.ProxyURL(uri),
}
client = http.Client{
Transport: transPort,
}
}
}
client := m.httpClient()
resp, err := client.Get(pluginIndexUrl)
if err != nil {
return nil, fmt.Errorf("get plugin index error: %w", err)
Expand Down Expand Up @@ -410,7 +405,7 @@ func newSdkManager(record env.Record, meta *PathMeta) *Manager {
}
c, err := config.NewConfig(meta.ConfigPath)
if err != nil {
panic(fmt.Errorf("init config error: %w", err))
panic(fmt.Errorf("init Config error: %w", err))
}
manager := &Manager{
PathMeta: meta,
Expand All @@ -419,7 +414,7 @@ func newSdkManager(record env.Record, meta *PathMeta) *Manager {
openSdks: make(map[string]*Sdk),
osType: util.GetOSType(),
archType: util.GetArchType(),
config: c,
Config: c,
}
return manager
}
61 changes: 37 additions & 24 deletions internal/module/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,33 +17,18 @@
package http

import (
"github.com/version-fox/vfox/internal/config"
lua "github.com/yuin/gopher-lua"
"io"
"net/http"
"net/url"
)

// Preload adds json to the given Lua state's package.preload table. After it
// has been preloaded, it can be loaded using require:
//
// local json = require("http")
func Preload(L *lua.LState) {
L.PreloadModule("http", loader)
}

// loader is the module loader function.
func loader(L *lua.LState) int {
t := L.NewTable()
L.SetFuncs(t, api)
L.Push(t)
return 1
type Module struct {
proxy *config.Proxy
}

var api = map[string]lua.LGFunction{
"get": getRequest,
// TODO wait to extend
}

// getRequest performs a http get request
// Get performs a http get request
// @param url string
// @param headers table
// @return resp table
Expand All @@ -59,15 +44,27 @@ var api = map[string]lua.LGFunction{
// status_code = 200,
// headers = table
// }
func getRequest(L *lua.LState) int {
func (m *Module) Get(L *lua.LState) int {
param := L.CheckTable(1)
url := param.RawGetString("url")
if url == lua.LNil {
urlStr := param.RawGetString("url")
if urlStr == lua.LNil {
L.Push(lua.LNil)
L.Push(lua.LString("url is required"))
}

client := &http.Client{}
req, err := http.NewRequest("GET", url.String(), nil)
if m.proxy.Enable {
uri, err := url.Parse(m.proxy.Url)
if err == nil {
transPort := &http.Transport{
Proxy: http.ProxyURL(uri),
}
client = &http.Client{
Transport: transPort,
}
}
}
req, err := http.NewRequest("GET", urlStr.String(), nil)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
Expand Down Expand Up @@ -108,3 +105,19 @@ func getRequest(L *lua.LState) int {
L.Push(result)
return 1
}

func (m *Module) luaMap() map[string]lua.LGFunction {
return map[string]lua.LGFunction{
"get": m.Get,
}
}

func NewModule(proxy *config.Proxy) lua.LGFunction {
return func(L *lua.LState) int {
m := &Module{proxy: proxy}
t := L.NewTable()
L.SetFuncs(t, m.luaMap())
L.Push(t)
return 1
}
}
28 changes: 27 additions & 1 deletion internal/module/http/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,32 @@
package http

import (
"github.com/version-fox/vfox/internal/config"
lua "github.com/yuin/gopher-lua"
"testing"
)

func TestWithConfig(t *testing.T) {
const str = `
local http = require("http")
assert(type(http) == "table")
assert(type(http.get) == "function")
local resp, err = http.get({
url = "http://ip.jsontest.com/"
})
assert(err == 'Get "http://ip.jsontest.com/": proxyconnect tcp: dial tcp 127.0.0.1:80: connect: connection refused')
`
s := lua.NewState()
defer s.Close()

s.PreloadModule("http", NewModule(&config.Proxy{
Enable: true,
Url: "http://localhost",
}))
if err := s.DoString(str); err != nil {
t.Error(err)
}
}
func TestGetRequest(t *testing.T) {
const str = `
local http = require("http")
Expand All @@ -33,10 +55,14 @@ func TestGetRequest(t *testing.T) {
assert(resp.status_code == 200)
assert(resp.headers['Content-Type'] == 'application/json')
`
eval(str, t)
}

func eval(str string, t *testing.T) {
s := lua.NewState()
defer s.Close()

Preload(s)
s.PreloadModule("http", NewModule(config.EmptyProxy))
if err := s.DoString(str); err != nil {
t.Error(err)
}
Expand Down
5 changes: 3 additions & 2 deletions internal/module/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@
package module

import (
"github.com/version-fox/vfox/internal/config"
"github.com/version-fox/vfox/internal/module/html"
"github.com/version-fox/vfox/internal/module/http"
"github.com/version-fox/vfox/internal/module/json"
lua "github.com/yuin/gopher-lua"
)

func Preload(L *lua.LState) {
http.Preload(L)
func Preload(L *lua.LState, config *config.Config) {
L.PreloadModule("http", http.NewModule(config.Proxy))
json.Preload(L)
html.Preload(L)
}
9 changes: 4 additions & 5 deletions internal/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"fmt"
"github.com/version-fox/vfox/internal/env"
"github.com/version-fox/vfox/internal/module"
"github.com/version-fox/vfox/internal/util"
lua "github.com/yuin/gopher-lua"
"regexp"
)
Expand Down Expand Up @@ -318,16 +317,16 @@ func (l *LuaPlugin) Label(version string) string {
return fmt.Sprintf("%s@%s", l.Name, version)
}

func NewLuaPlugin(content, path string, osType util.OSType, archType util.ArchType) (*LuaPlugin, error) {
func NewLuaPlugin(content, path string, manager *Manager) (*LuaPlugin, error) {
luaVMInstance := lua.NewState()
module.Preload(luaVMInstance)
module.Preload(luaVMInstance, manager.Config)
if err := luaVMInstance.DoString(content); err != nil {
return nil, err
}

// set OS_TYPE and ARCH_TYPE
luaVMInstance.SetGlobal(OsType, lua.LString(osType))
luaVMInstance.SetGlobal(ArchType, lua.LString(archType))
luaVMInstance.SetGlobal(OsType, lua.LString(manager.osType))
luaVMInstance.SetGlobal(ArchType, lua.LString(manager.archType))

pluginObj := luaVMInstance.GetGlobal(LuaPluginObjKey)
if pluginObj.Type() == lua.LTNil {
Expand Down

0 comments on commit c4f6d44

Please sign in to comment.