From a87c36268b10558d54ba9bcb2081f57e8c6a7973 Mon Sep 17 00:00:00 2001 From: xucong053 Date: Thu, 9 Jun 2022 11:03:53 +0800 Subject: [PATCH] fix: ensure all dependencies in debugtalk.go are installed --- hrp/build.go | 21 +++++++++++++++++++++ hrp/internal/builtin/utils.go | 5 +++++ 2 files changed, 26 insertions(+) diff --git a/hrp/build.go b/hrp/build.go index 4c5cb940..3184fa3c 100644 --- a/hrp/build.go +++ b/hrp/build.go @@ -44,6 +44,7 @@ type TemplateContent struct { FromImports []string // python from...import... Functions []string // python/go function FunctionNames []string // function name set by user + Packages []string // python packages } type Regexps struct { @@ -127,8 +128,15 @@ func (t *TemplateContent) parsePyContent(path string) error { if strings.HasPrefix(line, "import") { t.Imports = append(t.Imports, strings.Trim(line, " ")) + // e.g. import module as md + // import package.module + t.Packages = append(t.Packages, strings.Split(strings.Split(line, " ")[1], ".")[0]) } else if strings.HasPrefix(line, "from") { t.FromImports = append(t.FromImports, strings.Trim(line, " ")) + // e.g. from package.module import function + // from module import function + // from package import module + t.Packages = append(t.Packages, strings.Split(strings.Split(line, " ")[1], ".")[0]) } else { // no parse content at under of `if __name__ == "__main__"` if strings.HasPrefix(line, "if __name__") { @@ -257,11 +265,24 @@ func buildPy(path string, output string) error { FunctionName: regexp.MustCompile(regexPythonFunctionName), }, } + err := templateContent.parsePyContent(path) if err != nil { return err } + // ensure installation of packages + _, err = builtin.EnsurePython3Venv(templateContent.Packages...) + if err != nil { + return err + } + + // check the syntax of debugtalk.py + err = builtin.CheckPythonScriptSyntax(path) + if err != nil { + return err + } + // generate .debugtalk_gen.py if output == "" { dir, _ := os.Getwd() diff --git a/hrp/internal/builtin/utils.go b/hrp/internal/builtin/utils.go index 8f3ca391..93a4b64b 100644 --- a/hrp/internal/builtin/utils.go +++ b/hrp/internal/builtin/utils.go @@ -103,6 +103,11 @@ func EnsurePython3Venv(packages ...string) (string, error) { return python3, nil } +func CheckPythonScriptSyntax(path string) error { + err := ExecCommand("python3", "-m", "py_compile", path) + return err +} + func ExecCommandInDir(cmd *exec.Cmd, dir string) error { log.Info().Str("cmd", cmd.String()).Str("dir", dir).Msg("exec command") cmd.Dir = dir