Пример #1
0
//由于bash过度难用,直接安装kmg的时候又会遇到很复杂的情况,此处用于处理某些复杂情况
func selfInstallCmd() {
	//迁移代码,从/bin/kmg迁移到/usr/local/bin/kmg
	if kmgFile.MustFileExist("/bin/kmg") {
		kmgCmd.MustRunInBash("sudo rm /bin/kmg;hash -r")
	}
	kmgFile.MustEnsureBinPath("/usr/local/bin/kmg")
}
Пример #2
0
func (fm *FileMutex) isLock() bool {
	time.Sleep(time.Duration(kmgRand.IntBetween(0, 1000)) * time.Millisecond)
	if kmgFile.MustFileExist(fm.filePath) {
		return true
	}
	return false
}
Пример #3
0
func (prog *Program) mustParsePackage(pkgPath string) *Package {
	var dirPath string
	var found bool
	for _, lookupPath := range prog.PackageLookupPathList {
		dirPath = filepath.Join(lookupPath, "src", pkgPath)
		if kmgFile.MustFileExist(dirPath) {
			found = true
			break
		}
	}
	if !found {
		panic(fmt.Errorf("can not found pkgPath %s %#v", pkgPath, prog.PackageLookupPathList))
	}

	pkg := &Package{
		ImportMap: map[string]bool{},
		PkgPath:   pkgPath,
	}
	for _, path := range kmgFile.MustReadDirFileOneLevel(dirPath) {
		if strings.HasSuffix(path, ".go") {
			pkg.mustAddFile(filepath.Join(dirPath, path))
		}
	}
	pkg.Program = prog
	return pkg
}
Пример #4
0
func (context *Env) GetGOROOT() string {
	if context.GOROOT != "" {
		return context.GOROOT
	}
	context.GOROOT = os.Getenv("GOROOT")
	if context.GOROOT != "" {
		return context.GOROOT
	}
	if kmgFile.MustFileExist("/usr/local/go") {
		context.GOROOT = "/usr/local/go"
	}
	return context.GOROOT
}
Пример #5
0
func goRunPackageName(goPath string, pathOrPkg string) {
	//goRunInstall(goPath, pathOrPkg)
	goRunInstallSimple(goPath, pathOrPkg)
	//run
	outPath := filepath.Join(goPath, "bin", filepath.Base(pathOrPkg))
	p := kmgPlatform.GetCompiledPlatform()
	if p.Compatible(kmgPlatform.WindowsAmd64) {
		outPath += ".exe"
	}
	if !kmgFile.MustFileExist(outPath) {
		kmgConsole.ExitOnErr(fmt.Errorf("please make sure you are kmg gorun a main package. (binary file not exist. %s)", outPath))
	}
	runCmdSliceWithGoPath(goPath, append([]string{outPath}, os.Args[2:]...))
}
Пример #6
0
func installGolangWithUrlMap(urlMap map[string]string) {
	p := kmgPlatform.GetCompiledPlatform()
	if p.Compatible(kmgPlatform.WindowsAmd64) {
		contentB, err := kmgHttp.UrlGetContent(urlMap["windows_amd64"])
		kmgConsole.ExitOnErr(err)
		kmgFile.MustDelete(`c:\go`)
		err = kmgCompress.ZipUncompressFromBytesToDir(contentB, `c:\go`, "go")
		kmgConsole.ExitOnErr(err)
		err = kmgFile.CopyFile(`c:\go\bin\go.exe`, `c:\windows\system32\go.exe`)
		kmgConsole.ExitOnErr(err)
		err = kmgFile.CopyFile(`c:\go\bin\godoc.exe`, `c:\windows\system32\godoc.exe`)
		kmgConsole.ExitOnErr(err)
		err = kmgFile.CopyFile(`c:\go\bin\gofmt.exe`, `c:\windows\system32\gofmt.exe`)
		kmgConsole.ExitOnErr(err)
		return
	}
	tmpPath := kmgFile.MustChangeToTmpPath()
	defer kmgFile.MustDelete(tmpPath)
	if !kmgSys.MustIsRoot() {
		fmt.Println("you need to be root to install golang")
		return
	}

	url, ok := urlMap[p.String()]
	if !ok {
		kmgConsole.ExitOnErr(fmt.Errorf("not support platform [%s]", p))
	}
	packageName := path.Base(url)
	contentB := kmgHttp.MustUrlGetContentProcess(url)

	kmgFile.MustWriteFile(packageName, contentB)
	kmgCmd.ProxyRun("tar -xf " + packageName)
	if kmgFile.MustFileExist("/usr/local/go") {
		kmgCmd.ProxyRun("mv /usr/local/go /usr/local/go.bak." + time.Now().Format(kmgTime.FormatFileNameV2))
	}
	kmgCmd.ProxyRun("cp -rf go /usr/local")
	kmgFile.MustDeleteFile("/bin/go")
	kmgCmd.ProxyRun("ln -s /usr/local/go/bin/go /bin/go")
	kmgFile.MustDeleteFile("/bin/godoc")
	kmgCmd.ProxyRun("ln -s /usr/local/go/bin/godoc /bin/godoc")
	kmgFile.MustDeleteFile("/bin/gofmt")
	kmgCmd.ProxyRun("ln -s /usr/local/go/bin/gofmt /bin/gofmt")
	kmgFile.MustEnsureBinPath("/bin/go")
	kmgFile.MustEnsureBinPath("/bin/godoc")
	kmgFile.MustEnsureBinPath("/bin/gofmt")
}
Пример #7
0
func runCommand(kmgc *kmgConfig.Env, args []string) {
	os.Chdir(kmgc.ProjectPath)
	logDir := filepath.Join(kmgc.LogPath, "run")
	kmgFile.MustMkdirAll(logDir)
	thisLogFilePath := filepath.Join(logDir, time.Now().Format(kmgTime.FormatFileName)+".log")
	kmgFile.MustWriteFile(thisLogFilePath, []byte{})
	if !kmgPlatform.GetCompiledPlatform().Compatible(kmgPlatform.WindowsAmd64) {
		lastLogPath := filepath.Join(logDir, "last.log")
		if kmgFile.MustFileExist(lastLogPath) {
			kmgFile.MustSymlink(kmgFile.MustReadSymbolLink(lastLogPath), filepath.Join(logDir, "last2.log"))
		}
		kmgFile.MustSymlink(filepath.Base(thisLogFilePath), lastLogPath)
	}
	//TODO 大部分命令是 kmg gorun xxx 在这个地方可以直接调用gorun解决问题,这样可以少开一个进程加快了一些速度
	// 问题: 上述做法不靠谱,会导致last.log没有用处.
	//if len(args) >= 2 && args[0] == "kmg" && strings.EqualFold(args[1], "gorun") {
	//	os.Args = append(args[1:], os.Args[1:]...)
	//	goCmd.GoRunCmd()
	//	return
	//}
	// 下面的做法不靠谱,会让signle无法传递
	//err := kmgCmd.CmdSlice(append(args, os.Args[1:]...)).
	//	SetDir(kmgc.ProjectPath).
	//	RunAndTeeOutputToFile(thisLogFilePath)
	// TODO bash转义
	bashCmd := strings.Join(append(args, os.Args[1:]...), " ")
	bashCmdStr := bashCmd + " 2>&1 | tee -i " + thisLogFilePath + " ; test ${PIPESTATUS[0]} -eq 0"
	if kmgPlatform.IsWindows() {
		err := kmgCmd.CmdString(bashCmdStr).SetDir(kmgc.ProjectPath).StdioRun()
		if err != nil {
			err = fmt.Errorf("kmg make: %s", err)
			kmgConsole.ExitOnErr(err)
		}
		return
	} else {
		err := kmgCmd.CmdBash(bashCmdStr).SetDir(kmgc.ProjectPath).StdioRun()
		if err != nil {
			err = fmt.Errorf("kmg make: %s", err)
			kmgConsole.ExitOnErr(err)
		}
		return
	}
}
Пример #8
0
func (ctx *goRunInstallContext) goRunInstallIsValidAndInvalidCache(goPath string, pathOrPkg string) bool {
	err := kmgGob.ReadFile(ctx.targetCachePath, &ctx.targetPkgMapCache)
	if err != nil { //此处故意忽略错误 没有缓存文件 TODO 此处需要折腾其他东西吗?
		return false
	}
	err = kmgGob.ReadFile(ctx.pkgCachePath, &ctx.pkgMapCache)
	if err != nil { //此处故意忽略错误 没有缓存文件
		return false
	}
	//kmgDebug.Println(info)
	isValid := true
	task := kmgTask.NewLimitThreadTaskManager(runtime.NumCPU())
	for pkgName := range ctx.targetPkgMapCache {
		pkgName := pkgName
		task.AddFunc(func() {
			pkgInfo, ok := ctx.pkgMapCache[pkgName]
			if !ok {
				// 缓存不一致,删文件?
				pkgPath := filepath.Join("pkg", ctx.platform, pkgName+".a")
				if debug {
					fmt.Println("pkgname not found in pkgMapCache delete ", pkgPath)
				}
				kmgFile.MustDelete(pkgPath)
				isValid = false
				return
			}
			pkgPath := pkgInfo.getPkgBinPath(goPath, ctx.platform)
			if !checkFileWithMd5(pkgPath, pkgInfo.PkgMd5) {
				if debug {
					oldMd5 := uint64(0)
					if kmgFile.MustFileExist(pkgPath) {
						oldMd5 = mustCheckSumFile(pkgPath)
					}
					fmt.Println("pkgBinFile md5 not equal delete ", pkgPath, pkgInfo.PkgMd5, oldMd5)
				}
				kmgFile.MustDelete(pkgPath)
				isValid = false
				return
			}
			srcpkgPath := filepath.Join(goPath, "src", pkgName)
			fileList, err := kmgFile.ReadDirFileOneLevel(srcpkgPath)
			if err != nil {
				if !os.IsNotExist(err) {
					panic(err)
				}
				kmgFile.MustDelete(pkgPath)
				if debug {
					fmt.Println("dir not exist File delete ", pkgPath, srcpkgPath)
				}
				isValid = false
				return
			}
			isThisPkgValid := true
			for _, file := range fileList {
				ext := filepath.Ext(file)
				if ext == ".go" {
					// 多了一个文件
					_, ok := pkgInfo.GoFileMap[file]
					if !ok {
						kmgFile.MustDelete(pkgPath)
						if debug {
							fmt.Println("more file ", file, " delete ", pkgPath)
						}
						isValid = false
						isThisPkgValid = false
						break
					}
				}
			}
			if !isThisPkgValid {
				return
			}
			for name, md5 := range pkgInfo.GoFileMap {
				goFilePath := filepath.Join(srcpkgPath, name)
				if !checkFileWithMd5(goFilePath, md5) {
					kmgFile.MustDelete(pkgPath)
					if debug {
						fmt.Println("gofile not match ", name, " delete ", pkgPath)
					}
					isValid = false
					break
				}
			}
		})
	}
	task.Close()
	return isValid
}
Пример #9
0
func runFileHttpServer() {
	listenAddr := ""
	path := ""
	key := ""
	flag.StringVar(&listenAddr, "l", ":80", "listen address")
	flag.StringVar(&path, "path", "", "root path of the file server")
	flag.StringVar(&key, "key", "", "crypto key use to encrypt all request of this server")
	flag.Parse()
	var err error
	if path == "" {
		path, err = os.Getwd()
		if err != nil {
			fmt.Printf("os.Getwd() fail %s", err)
			return
		}
	} else {
		kmgErr.PanicIfError(os.Chdir(path))
	}
	if key == "" {
		http.Handle("/", http.FileServer(http.Dir(path)))
	}
	if key != "" {
		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			realPath := filepath.Join(path, r.URL.Path)
			if !kmgFile.MustFileExist(realPath) {
				w.Write([]byte("File Not Exist"))
				return
			}
			if !kmgStrings.IsInSlice(cacheFilePathSlice, realPath) {
				cacheFilePathSlice = append(cacheFilePathSlice, realPath)
			}
			updateCache := func() {
				cacheFilePathEncryptMap[realPath] = kmgCrypto.CompressAndEncryptBytesEncodeV2(
					kmgCrypto.Get32PskFromString(key),
					kmgFile.MustReadFile(realPath),
				)
			}
			checkCache := func() {
				lock.Lock()
				defer lock.Unlock()
				kmgCache.MustMd5FileChangeCache(realPath, []string{realPath}, func() {
					updateCache()
				})
			}
			checkCache()
			//进程重启后,内存中的缓存掉了,但是文件系统的缓存还在
			_, exist := cacheFilePathEncryptMap[realPath]
			if !exist {
				updateCache()
			}
			w.Write(cacheFilePathEncryptMap[realPath])
		})
	}
	fmt.Println("start server at", listenAddr)
	err = http.ListenAndServe(listenAddr, nil)
	if err != nil {
		fmt.Printf("http.ListenAndServe() fail %s", err)
		return
	}
	return
}
Пример #10
0
func HasProdConfig() bool {
	return kmgFile.MustFileExist(kmgConfig.DefaultEnv().PathInConfig("Prod.yml"))
}
Пример #11
0
func HasTestConfig() bool {
	return kmgFile.MustFileExist(kmgConfig.DefaultEnv().PathInConfig("Test.yml"))
}
Пример #12
0
func MustIsRepositoryAtPath(path string) bool {
	return kmgFile.MustFileExist(filepath.Join(path, ".git"))
}