many change

This commit is contained in:
Star 2024-03-16 22:54:11 +08:00
parent 5dfeef91a2
commit e5f5626d46
4 changed files with 113 additions and 34 deletions

73
main.go
View File

@ -8,6 +8,7 @@ import (
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"text/template"
@ -48,12 +49,13 @@ type Command struct {
Func func([]string)
}
// TODO js 缓存 & 开发模式检测自动gowatch 不再监听 js
var commands = []Command{
{"new", "+", "[name]", "create a new project, will create in the current directory if no name is specified", newProject},
{"new plugin", "+p", "[name]", "create a new plugin project, will create in the current directory if no name is specified", newPluginProject},
//{"new server", "+s", "[name]", "create a new server project, will create in the current directory if no name is specified", newServerProject},
//{"new api", "+a", "[path] [method]", "create a new api for server project, will use restful api if specified http method", newServerAPI},
//{"new game", "+g", "[name]", "create a new game project, will create in the current directory if no name is specified", newServerProject},
//{"new webkit", "+w", "[name]", "create a new webkit project, will create in the current directory if no name is specified", newServerProject},
{"run", "r", "[...more gowatch args]", "run project use gowatch, if project files changed will restart auto, gowatch args help see: https://github.com/ssgo/tool", runProject},
{"test", "t", "[...more gowatch args]", "test project use gowatch, if project files changed will restart auto, gowatch args help see: https://github.com/ssgo/tool", testProject},
{"export plugins", "ep", "", "export typescript code for used plugins into \"plugins/\"", makePluginCode},
@ -64,6 +66,15 @@ var commands = []Command{
//{"git list", "/l", "", "list current repository tags from apigo.cloud/git", },
//{"git commit", "/c", "comment", "commit current repository to apigo.cloud/git", },
//{"git tag", "/t", "tag", "create new tag for current repository and push to apigo.cloud/git", },
//{"build", "b", "[-m]", "build for current os, output to build/, -m will mix js files into exec file", },
//{"build mac", "bm", "", "build", },
//{"build macarm", "bma", "", "build", },
//{"build win", "bw", "", "build", },
//{"build win32", "bw32", "", "build", },
//{"build linux", "bl", "", "build", },
//{"build linuxarm", "bla", "", "build", },
//{"build all", "ba", "", "build", },
//{"deploy", "d", "", "deploy", },
}
func findTool() (gowatchPath string, logvPath string) {
@ -160,17 +171,19 @@ func newServerAPI(args []string) {
func runProject(args []string) {
gowatchPath, logvPath := findTool()
_ = runCommandPipe(logvPath, gowatchPath, "-pt", ".go,.json,.yml,.js,.ts", "run", ".")
_ = runCommand("go", "mod", "tidy")
_ = runCommandPipe(logvPath, gowatchPath, "-pt", ".go,.yml,.js", "run", ".")
//_ = runCommandPipe(logvPath, gowatchPath, "-pt", ".go,.yml,.js", "-ig", "api", "run", ".")
}
func testProject(args []string) {
gowatchPath, logvPath := findTool()
if u.FileExists("tests") {
_ = os.Chdir("tests")
fmt.Println(logvPath, gowatchPath)
_ = runCommandPipe(logvPath, gowatchPath, "-p", ".,..", "-pt", ".go,.yml,.js,.ts", "test", "-v", ".")
_ = runCommand("go", "mod", "tidy")
_ = runCommandPipe(logvPath, gowatchPath, "-p", ".,..", "-pt", ".go,.yml,.js", "test", "-v", ".")
} else {
_ = runCommandPipe(logvPath, gowatchPath, "-pt", ".go,.yml,.js,.ts", "test", "-v", ".")
_ = runCommandPipe(logvPath, gowatchPath, "-pt", ".go,.yml,.js", "test", "-v", ".")
}
}
@ -187,6 +200,7 @@ func makePluginCodeImports(from string, imports *[]string) {
if strings.HasSuffix(f.Name(), ".go") && !strings.HasPrefix(f.Name(), ".") && f.Name() != "makePluginCode.go" {
if code, err := u.ReadFile(path.Join(from, f.Name())); err == nil {
for _, m := range pkgMatcher.FindAllStringSubmatch(code, 1024) {
if m[1] != "current-plugin" {
*imports = u.AppendUniqueString(*imports, m[1])
}
}
@ -194,6 +208,7 @@ func makePluginCodeImports(from string, imports *[]string) {
}
}
}
}
}
func writeFile(filename string, fileContent string, data any) {
@ -208,18 +223,52 @@ func writeFile(filename string, fileContent string, data any) {
}
}
var replaceMatcher = regexp.MustCompile(`([a-zA-Z0-9._\-/]+)\s+(v[0-9.]+)\s+=>\s+([a-zA-Z0-9._\-/\\]+)`)
func makePluginCode(args []string) {
// 判断是否可执行项目(不创建指向项目本身的 import _
isMainProject := false
if files, err := os.ReadDir("."); err == nil {
for _, f := range files {
if !f.IsDir() && strings.HasSuffix(f.Name(), ".go") {
code, _ := u.ReadFile(f.Name())
if strings.Contains(code, "package main") || strings.Contains(code, "func main(") {
isMainProject = true
break
}
}
}
}
// 扫描用到的插件import _
imports := make([]string, 0)
makePluginCodeImports(".", &imports)
if len(imports) > 0 {
writeFile("makePluginCode.go", makePluginCodeTPL, map[string]any{"imports": imports})
if err := runCommand("go", "run", "makePluginCode.go"); err != nil {
goModCode := "module main\ngo 1.18\n"
if !isMainProject {
imports = append(imports, "current-project")
goModCode += "require current-project v0.0.0 // indirect\nreplace current-project v0.0.0 => ../\n"
}
// 扫描 replace处理路径后加入到 _makePluginCode/go.mod
findGoModCode, _ := u.ReadFile("go.mod")
for _, m := range replaceMatcher.FindAllStringSubmatch(findGoModCode, 100) {
replacePath := m[3]
if absPath, err := filepath.Abs(m[3]); err == nil {
replacePath = absPath
}
goModCode += fmt.Sprintln("replace", m[1], m[2], "=>", replacePath)
}
_ = u.WriteFile("_makePluginCode/go.mod", goModCode)
writeFile("_makePluginCode/main.go", makePluginCodeTPL, map[string]any{"imports": imports})
_ = os.Chdir("_makePluginCode")
_ = runCommand("go", "mod", "tidy")
if err := runCommand("go", "run", "."); err != nil {
fmt.Println(u.Red(err.Error()))
}
_ = os.Remove("makePluginCode.go")
} else {
fmt.Println(u.Red("no plugin imported"))
}
_ = os.Chdir("..")
_ = os.RemoveAll("_makePluginCode")
}
func runCommand(name string, args ...string) error {

View File

@ -1,4 +1,6 @@
// import file from 'plugins/file';
import console from '_/console'
import logger from '_/logger'
import file from '_/apigo.cloud/git/apigo/plguins/file'
// console.info(file.read('test.txt'))
setWorldName('gojs')

View File

@ -3,27 +3,54 @@ package main
import (
"apigo.cloud/git/apigo/gojs"
"apigo.cloud/git/apigo/plugin"
{{- range .imports}}
_ "{{.}}"
{{- end}}
"fmt"
"github.com/ssgo/u"
"path"
"strings"
{{- range.imports}}
_ "{{.}}"
{{- end}}
)
func main() {
for _, plg := range plugin.List() {
code := gojs.MakePluginCode(&plg)
errStr := "no code"
if code != "" {
err := u.WriteFile(path.Join("plugins", plg.Id+".ts"), code)
if err == nil {
fmt.Println(u.Cyan(plg.Id), "-", plg.Name, u.BGreen("OK"), ">>", u.Magenta(path.Join("plugins", plg.Id+".ts")))
continue
const consoleModuleCode = `export default {
"log": function (...args: any): void {return},
"info": function (...args: any): void {return},
"warn": function (...args: any): void {return},
"error": function (...args: any): void {return},
"input": function (): string {return},
}`
const loggerModuleCode = `export default {
"debug": function (message: string, ext?: Object): void {return},
"info": function (message: string, ext?: Object): void {return},
"warn": function (message: string, ext?: Object): void {return},
"error": function (message: string, ext?: Object): void {return},
}`
func writeModule(id, name, code string, modules *[]string, imports *[]string) {
idParts := strings.Split(id, "/")
filename := path.Join("node_modules", path.Join(idParts...)+u.StringIf(len(idParts) == 1, "/index.ts", ".ts"))
if err := u.WriteFile("../"+filename, code); err != nil {
fmt.Println(u.Cyan(id), "-", name, u.BRed(err.Error()))
} else {
errStr = err.Error()
}
}
fmt.Println(u.Cyan(plg.Id), "-", plg.Name, u.BGreen(errStr))
fmt.Println(u.Cyan(id), "-", name, u.BGreen("OK"), u.Dim(">> "+filename))
(*modules) = u.AppendUniqueString(*modules, fmt.Sprint("\"", idParts[0], "\": \"v0.0.0\""))
(*imports) = u.AppendUniqueString(*imports, fmt.Sprint("import ", idParts[len(idParts)-1], " from '"+id+"'"))
}
}
func main() {
modules := make([]string, 0)
imports := make([]string, 0)
writeModule("console", "终端工具", consoleModuleCode, &modules, &imports)
writeModule("logger", "日志工具", loggerModuleCode, &modules, &imports)
for _, plg := range plugin.List() {
if code := gojs.MakePluginCode(&plg); code != "" {
writeModule(plg.Id, plg.Name, code, &modules, &imports)
}
}
_ = u.WriteFile("../package.json", "{\n \"devDependencies\": {\n "+strings.Join(modules, ",\n ")+"\n }\n}")
fmt.Println()
fmt.Println("Usage:")
fmt.Println(" " + u.Magenta(strings.Join(imports, "\n ")))
}

View File

@ -1,6 +1,7 @@
// run "ag export plugins" to make plugins code
import logger from 'plugins/logger';
import {{.name}} from 'plugins/{{.name}}';
import logger from 'logger'
import console from 'console'
import {{.name}} from '{{.name}}'
{{.name}}.set('aaa', 111)
let aaa = {{.name}}.get('aaa')