Beispiel #1
0
func TestDemo(ot *testing.T) {
	importPath := "github.com/bronze1man/kmg/kmgGoSource"
	kmgCmd.MustRun("kmg go test -i " + importPath)
	pkgDir := kmgConfig.DefaultEnv().MustGetPathFromImportPath(importPath)
	fset := token.NewFileSet()
	astPkgMap, err := parser.ParseDir(fset, pkgDir, nil, 0)
	if err != nil {
		panic(err)
	}
	astPkg := astPkgMap["kmgGoSource_test"]
	astFileList := []*ast.File{}
	for _, file := range astPkg.Files {
		astFileList = append(astFileList, file)
	}
	//os.Chdir(kmgConfig.DefaultEnv().ProjectPath)
	pkg, err := types.Check(pkgDir, fset, astFileList)
	if err != nil {
		panic(err)
	}
	funcA := pkg.Scope().Lookup("FuncA")
	recvPkg := types.NewPackage("github.com/bronze1man/kmg/kmgGoSource", "kmgGoSource")
	kmgDebug.Println(types.TypeString(recvPkg, funcA.Type()))
	funTypParams := funcA.Type().(*types.Signature).Params()
	for i := 0; i < funTypParams.Len(); i++ {
		kmgDebug.Println(funTypParams.At(i).Name())
		kmgDebug.Println(funTypParams.At(i).Type().String())
	}
	//for _,p:=range funcA.Type().(*types.Signature).Params().
	//kmgDebug.Println(funcA.Type().(*types.Signature).Params().String())
}
Beispiel #2
0
// 此处路径表示 项目里面的一个路径
func MustBuildTplInDirWithCache(root string) {
	root = kmgConfig.DefaultEnv().PathInProject(root)
	cachedFileList := cacheFileFilter(root)
	kmgCache.MustMd5FileChangeCache("kmgGoTpl_"+root, cachedFileList, func() {
		MustBuildTplInPathList(cachedFileList)
	})
}
Beispiel #3
0
func mustLoadConfigByFilename(filename string) {
	conf := TestDbConf{}
	err := kmgYaml.ReadFile(kmgConfig.DefaultEnv().PathInConfig(filename), &conf)
	if err != nil {
		panic(err)
	}
	SetDefaultDbConfig(conf.Db)
}
Beispiel #4
0
// 如果没有数据会返回nil
func MustKvdbGetBytes(s string) (b []byte) {
	key := kmgCrypto.Md5Hex([]byte(s))
	content, err := kmgFile.ReadFile(kmgConfig.DefaultEnv().PathInTmp("kvdb/" + key))
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		panic(err)
	}
	return content
}
Beispiel #5
0
func main() {
	kmgCmd.MustRun(`kmg GoCrossCompile -platform linux_amd64 github.com/bronze1man/kmg/kmg`)
	kmgCmd.MustRun(`kmg GoCrossCompile -platform linux_amd64 github.com/bronze1man/kmg/kmg/SubCommand/serviceCmd/testBin`)
	kmgFile.MustCopyFile(filepath.Join(kmgConfig.DefaultEnv().ProjectPath, "bin/kmg_linux_amd64"), filepath.Join(dockerPath, "kmg"))
	kmgFile.MustCopyFile(filepath.Join(kmgConfig.DefaultEnv().ProjectPath, "bin/testBin_linux_amd64"), filepath.Join(dockerPath, "testBin"))
	kmgFile.MustWriteFile(filepath.Join(dockerPath, "Dockerfile"), []byte(`FROM ubuntu
WORKDIR /
COPY kmg /bin/
COPY testBin /bin/
RUN chmod +x /bin/kmg
RUN chmod +x /bin/testBin
CMD testBin
`))
	//CMD kmg service setandrestart t testBin && kmg service stop t && kmg service start t && kmg service restart t
	kmgCmd.MustRunAndReturnOutput("docker build -t kmgtest " + dockerPath)
	for i := 0; i < 20; i++ {
		time.Sleep(time.Second)
		kmgCmd.MustRunAndReturnOutput("docker run kmgtest")
	}
}
Beispiel #6
0
func ResourceBuild(req *ResourceUploadRequest) {
	if req.Name == "" {
		panic(`[ResourceBuild] req.Name == ""`)
	}
	tmpDirPath := kmgConfig.DefaultEnv().PathInTmp("kmgViewResource_build/" + req.Name)
	kmgFile.MustDelete(tmpDirPath)
	response := resourceBuildToDir(req.ImportPathList, tmpDirPath)
	req.Qiniu.MustUploadFromFile(tmpDirPath, req.QiniuPrefix)

	packageName := filepath.Base(filepath.Dir(req.OutGoFilePath))

	urlPrefix := req.Qiniu.GetSchemeAndDomain() + "/" + req.QiniuPrefix
	//jsUrl:=urlPrefix+"/"+response.JsFileName
	//cssUrl:=urlPrefix+"/"+response.CssFileName

	// 不可以使用 fmt.Sprintf("%#v",generated) 会导出私有变量.
	//generated:=&Generated{
	//	Name: req.Name,
	//	GeneratedJsFileUrl: jsUrl,
	//	GeneratedCssFileUrl: cssUrl,
	//	GeneratedUrlPrefix: urlPrefix,
	//	RequestImportList: req.ImportPathList,
	//}
	outGoContent := []byte(`package ` + packageName + `
import (
	"github.com/bronze1man/kmg/kmgView/kmgViewResource"
	"sync"
)
var ` + req.Name + `Once sync.Once
var ` + req.Name + `generated *kmgViewResource.Generated
func get` + req.Name + `ViewResource() *kmgViewResource.Generated{
	` + req.Name + `Once.Do(func(){
		` + req.Name + `generated = &kmgViewResource.Generated{
			Name: ` + fmt.Sprintf("%#v", req.Name) + `,
			GeneratedJsFileName: ` + fmt.Sprintf("%#v", response.JsFileName) + `,
			GeneratedCssFileName: ` + fmt.Sprintf("%#v", response.CssFileName) + `,
			GeneratedUrlPrefix: ` + fmt.Sprintf("%#v", urlPrefix) + `,
			RequestImportList: ` + fmt.Sprintf("%#v", req.ImportPathList) + `,
		}
		` + req.Name + `generated.Init()
	})
	return ` + req.Name + `generated
}
`)
	outGoContent, err := kmgFormat.Source(outGoContent)
	if err != nil {
		panic(err)
	}
	kmgFile.MustWriteFile(req.OutGoFilePath, outGoContent)
}
Beispiel #7
0
func TestParseCurrentProject(ot *testing.T) {
	gopath := kmgConfig.DefaultEnv().GOPATHToString()
	goSourcePath := filepath.Join(gopath, "src")
	dirList := kmgFile.MustGetAllDir(goSourcePath)
	for _, dir := range dirList {
		if strings.Contains(dir, "go/loader/testdata") {
			continue
		}
		dir, err := filepath.Rel(goSourcePath, dir)
		if err != nil {
			panic(err)
		}
		MustParsePackage(gopath, dir)
	}
}
Beispiel #8
0
func (b *tBuilder) parsePkg(packageName string) *pkg {
	thisPkg := &pkg{
		PackageName: packageName,
	}
	thisPkg.Dirpath = path.Join(kmgConfig.DefaultEnv().GetFirstGOPATH(), "src", packageName)
	if !kmgFile.MustDirectoryExist(thisPkg.Dirpath) {
		panic("[kmgViewResource] can not found dir " + thisPkg.Dirpath)
	}
	fileList := kmgFile.MustGetAllFileOneLevel(thisPkg.Dirpath)
	for _, file := range fileList {
		ext := kmgFile.GetExt(file)
		if ext == ".js" {
			thisPkg.JsFilePathList = append(thisPkg.JsFilePathList, file)

			importPathList := parseImportPath(file, kmgFile.MustReadFile(file))
			thisPkg.ImportPathList = kmgStrings.SliceNoRepeatMerge(thisPkg.ImportPathList, importPathList)
		} else if ext == ".css" {
			thisPkg.CssFilePathList = append(thisPkg.CssFilePathList, file)

			importPathList := parseImportPath(file, kmgFile.MustReadFile(file))
			thisPkg.ImportPathList = kmgStrings.SliceNoRepeatMerge(thisPkg.ImportPathList, importPathList)
		} else if kmgStrings.IsInSlice(allowResourceExt, ext) {
			name := filepath.Base(file)
			if b.ResourceFileNameMap[name] {
				panic("[kmgViewResource] resource file name " + name + " repeat path " + file)
			}
			thisPkg.ResourceFilePathList = append(thisPkg.ResourceFilePathList, file)
		}
	}
	sort.Strings(thisPkg.JsFilePathList)
	sort.Strings(thisPkg.CssFilePathList)

	for _, file := range thisPkg.JsFilePathList {
		// 这个泄漏信息比较严重.暂时关掉吧.
		//thisPkg.JsContent = append(thisPkg.JsContent, []byte("\n/* "+file+" */\n\n")...)
		thisPkg.JsContent = append(thisPkg.JsContent, kmgFile.MustReadFile(file)...)
		thisPkg.JsContent = append(thisPkg.JsContent, byte('\n'))
	}

	for _, file := range thisPkg.CssFilePathList {
		//thisPkg.CssContent = append(thisPkg.CssContent, []byte("\n/* "+file+"*/\n\n")...)
		thisPkg.CssContent = append(thisPkg.CssContent, kmgFile.MustReadFile(file)...)
		thisPkg.CssContent = append(thisPkg.CssContent, byte('\n'))
	}

	return thisPkg
}
Beispiel #9
0
func HasProdConfig() bool {
	return kmgFile.MustFileExist(kmgConfig.DefaultEnv().PathInConfig("Prod.yml"))
}
Beispiel #10
0
func TestMustParsePackageFunc(ot *testing.T) {
	pkg := MustParsePackage(kmgConfig.DefaultEnv().GOPATHToString(), "github.com/bronze1man/kmg/kmgGoSource/kmgGoParser/testPackage/testFunc")
	kmgTest.Equal(len(pkg.FuncList), 7)
}
Beispiel #11
0
func TestGoRunFile(ot *testing.T) {
	wd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	defer os.Chdir(wd)
	root := kmgConfig.DefaultEnv().ProjectPath
	os.Chdir(root)
	kmgPath := filepath.Join(root, "bin/kmg")
	kmgFile.MustDelete(kmgPath)
	//kmgCmd.MustRun("kmg go install github.com/bronze1man/kmg/kmg")
	gopath := filepath.Join(wd, "testWorkspace")
	os.Chdir(gopath)
	kmgFile.MustDelete(filepath.Join(gopath, "bin"))
	kmgFile.MustDelete(filepath.Join(gopath, "pkg"))
	kmgFile.MustDelete(filepath.Join(gopath, "tmp"))
	kmgFile.MustDelete(filepath.Join(gopath, "src", "kmgTestMain", "other.go"))
	goRunInstall(gopath, "kmgTestMain")
	output := kmgCmd.MustRunAndReturnOutput(filepath.Join(gopath, "bin", "kmgTestMain"))
	kmgTest.Equal(string(output), "1\n")
	kmgFile.MustWriteFile(filepath.Join(wd, "testWorkspace", "src", "kmgTestMain", "other.go"), []byte(`
package main

func init(){
	a=2
}
`))

	goRunInstall(gopath, "kmgTestMain")
	output = kmgCmd.MustRunAndReturnOutput(filepath.Join(gopath, "bin", "kmgTestMain"))
	kmgTest.Equal(string(output), "2\n")
	kmgFile.MustDelete(filepath.Join(wd, "testWorkspace", "src", "kmgTestMain", "other.go"))

	goRunInstall(gopath, "kmgTestMain")
	output = kmgCmd.MustRunAndReturnOutput(filepath.Join(gopath, "bin", "kmgTestMain"))
	kmgTest.Equal(string(output), "1\n")

	goRunInstall(gopath, "kmgTestMain/l2Main")
	output = kmgCmd.MustRunAndReturnOutput(filepath.Join(gopath, "bin", "l2Main"))
	kmgTest.Equal(string(output), "l2Main\n")

	kmgFile.MustWriteFile(filepath.Join(gopath, "src", "replaceBin", "replaceBin.go"), []byte(`
package main

import "fmt"

func main(){
	fmt.Println("replaceBin")
}
`))
	goRunInstall(gopath, "replaceBin")
	output = kmgCmd.MustRunAndReturnOutput(filepath.Join(gopath, "bin", "replaceBin"))
	kmgTest.Equal(string(output), "replaceBin\n")

	kmgFile.MustWriteFile(filepath.Join(gopath, "src", "replaceBin", "replaceBin.go"), []byte(`
package replaceBin

var A = "1"
`))
	goRunInstall(gopath, "replaceBin")
	// 应该会说这个不是main的package
}
Beispiel #12
0
func TestMustParsePackage(ot *testing.T) {
	pkg := MustParsePackage(kmgConfig.DefaultEnv().GOPATHToString(), "github.com/bronze1man/kmg/kmgGoSource/kmgGoParser/testPackage")
	kmgTest.Equal(pkg.GetImportList(), []string{"errors", "bytes"})
}
Beispiel #13
0
func NewProgramFromDefault() *Program {
	return &Program{
		PackageLookupPathList: append(kmgConfig.DefaultEnv().GOPATH, kmgConfig.DefaultEnv().GetGOROOT()),
		CachedPackageMap:      map[string]*Package{},
	}
}
Beispiel #14
0
func getFileTtlCachePath(key string) string {
	return filepath.Join(kmgConfig.DefaultEnv().TmpPath, "FileTtlCache", hex.EncodeToString([]byte(key)))
}
Beispiel #15
0
//这个测试要用到.
func getFileChangeCachePath(key string) string {
	// 此处key长度不可控,所以用md5.
	return filepath.Join(kmgConfig.DefaultEnv().TmpPath, "FileChangeCache", kmgCrypto.Md5HexFromString(key))
}
Beispiel #16
0
func HasTestConfig() bool {
	return kmgFile.MustFileExist(kmgConfig.DefaultEnv().PathInConfig("Test.yml"))
}
Beispiel #17
0
package main

import (
	"github.com/bronze1man/kmg/kmgCmd"
	"github.com/bronze1man/kmg/kmgConfig"
	"github.com/bronze1man/kmg/kmgFile"
	"path/filepath"
	"time"
)

var dockerPath = filepath.Join(kmgConfig.DefaultEnv().ProjectPath, "src/github.com/bronze1man/kmg/kmg/SubCommand/serviceCmd/test")

func main() {
	kmgCmd.MustRun(`kmg GoCrossCompile -platform linux_amd64 github.com/bronze1man/kmg/kmg`)
	kmgCmd.MustRun(`kmg GoCrossCompile -platform linux_amd64 github.com/bronze1man/kmg/kmg/SubCommand/serviceCmd/testBin`)
	kmgFile.MustCopyFile(filepath.Join(kmgConfig.DefaultEnv().ProjectPath, "bin/kmg_linux_amd64"), filepath.Join(dockerPath, "kmg"))
	kmgFile.MustCopyFile(filepath.Join(kmgConfig.DefaultEnv().ProjectPath, "bin/testBin_linux_amd64"), filepath.Join(dockerPath, "testBin"))
	kmgFile.MustWriteFile(filepath.Join(dockerPath, "Dockerfile"), []byte(`FROM ubuntu
WORKDIR /
COPY kmg /bin/
COPY testBin /bin/
RUN chmod +x /bin/kmg
RUN chmod +x /bin/testBin
CMD testBin
`))
	//CMD kmg service setandrestart t testBin && kmg service stop t && kmg service start t && kmg service restart t
	kmgCmd.MustRunAndReturnOutput("docker build -t kmgtest " + dockerPath)
	for i := 0; i < 20; i++ {
		time.Sleep(time.Second)
		kmgCmd.MustRunAndReturnOutput("docker run kmgtest")
	}
Beispiel #18
0
// @deprecated
func Env() *kmgConfig.Env {
	return kmgConfig.DefaultEnv()
}
Beispiel #19
0
func reflectToTplConfig(req *GenerateRequest) *tplConfig {
	config := &tplConfig{
		ObjectName:     req.ObjectName,
		OutPackageName: path.Base(req.OutPackageImportPath),
		ImportPathMap: map[string]bool{
			"encoding/json": true,
			"errors":        true,
			"fmt":           true,
			"github.com/bronze1man/kmg/kmgCrypto":      true,
			"github.com/bronze1man/kmg/kmgLog":         true,
			"github.com/bronze1man/kmg/kmgNet/kmgHttp": true,
			"net/http": true,
			"bytes":    true,
		},
	}
	if req.ApiNameFilterCb == nil {
		req.ApiNameFilterCb = func(name string) bool {
			return true
		}
	}

	pkg := kmgGoParser.MustParsePackage(kmgConfig.DefaultEnv().GOPATHToString(), req.ObjectPkgPath)
	namedTyp := pkg.LookupNamedType(req.ObjectName)
	if namedTyp == nil {
		panic(fmt.Errorf("can not find this object. [%s]", req.ObjectName))
	}
	objTyp := kmgGoParser.Type(namedTyp)
	if req.ObjectIsPointer {
		objTyp = kmgGoParser.NewPointer(objTyp)
	}
	var importPathList []string
	config.ObjectTypeStr, importPathList = kmgGoParser.MustWriteGoTypes(req.OutPackageImportPath, objTyp)
	config.mergeImportPath(importPathList)

	//获取 object的 上面所有的方法
	methodList := pkg.GetNamedTypeMethodSet(namedTyp)
	for _, methodObj := range methodList {
		if !methodObj.IsExport() {
			continue
		}
		if !req.ApiNameFilterCb(methodObj.Name) {
			continue
		}
		api := Api{
			Name: methodObj.Name,
		}
		for _, pairObj := range methodObj.InParameter {
			pair := ArgumentNameTypePair{
				Name: kmgStrings.FirstLetterToUpper(pairObj.Name),
			}
			pair.ObjectTypeStr, importPathList = kmgGoParser.MustWriteGoTypes(req.OutPackageImportPath, pairObj.Type)
			config.mergeImportPath(importPathList)
			api.InArgsList = append(api.InArgsList, pair)
		}
		for i, pairObj := range methodObj.OutParameter {
			name := kmgStrings.FirstLetterToUpper(pairObj.Name)
			if name == "" {
				builtintyp, ok := pairObj.Type.(kmgGoParser.BuiltinType)
				if ok && string(builtintyp) == "error" { //TODO 不要特例
					name = "Err"
				} else {
					name = fmt.Sprintf("Out_%d", i)
				}
			}
			pair := ArgumentNameTypePair{
				Name: name,
			}
			pair.ObjectTypeStr, importPathList = kmgGoParser.MustWriteGoTypes(req.OutPackageImportPath, pairObj.Type)
			config.mergeImportPath(importPathList)
			api.OutArgsList = append(api.OutArgsList, pair)
		}
		config.ApiList = append(config.ApiList, api)
	}
	return config
}
Beispiel #20
0
func MustKvdbSetBytes(s string, b []byte) {
	key := kmgCrypto.Md5Hex([]byte(s))
	kmgFile.MustWriteFileWithMkdir(kmgConfig.DefaultEnv().PathInTmp("kvdb/"+key), b)
}
Beispiel #21
0
// 使用缓存 生成代码
func MustGenerateCodeWithCache(req *GenerateRequest) {
	pkgFilePath := kmgConfig.DefaultEnv().PathInProject(filepath.Join("src", req.ObjectPkgPath))
	kmgCache.MustMd5FileChangeCache("kmgRpc_"+req.OutFilePath, []string{req.OutFilePath, pkgFilePath}, func() {
		MustGenerateCode(req)
	})
}