2019-08-16 09:55:03 -04:00
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"strings"
|
|
|
|
|
2020-12-18 12:20:12 -05:00
|
|
|
"github.com/cli/safeexec"
|
|
|
|
"github.com/gohugoio/hugo/common/hexec"
|
|
|
|
|
2019-08-16 09:55:03 -04:00
|
|
|
"github.com/gohugoio/hugo/markup/converter"
|
|
|
|
)
|
|
|
|
|
|
|
|
func ExternallyRenderContent(
|
|
|
|
cfg converter.ProviderConfig,
|
|
|
|
ctx converter.DocumentContext,
|
|
|
|
content []byte, path string, args []string) []byte {
|
|
|
|
logger := cfg.Logger
|
2020-12-18 12:20:12 -05:00
|
|
|
cmd, err := hexec.SafeCommand(path, args...)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("%s rendering %s: %v", path, ctx.DocumentName, err)
|
|
|
|
return nil
|
|
|
|
}
|
2019-08-16 09:55:03 -04:00
|
|
|
cmd.Stdin = bytes.NewReader(content)
|
|
|
|
var out, cmderr bytes.Buffer
|
|
|
|
cmd.Stdout = &out
|
|
|
|
cmd.Stderr = &cmderr
|
2020-12-18 12:20:12 -05:00
|
|
|
err = cmd.Run()
|
2019-08-16 09:55:03 -04:00
|
|
|
// Most external helpers exit w/ non-zero exit code only if severe, i.e.
|
|
|
|
// halting errors occurred. -> log stderr output regardless of state of err
|
|
|
|
for _, item := range strings.Split(cmderr.String(), "\n") {
|
|
|
|
item := strings.TrimSpace(item)
|
|
|
|
if item != "" {
|
2020-10-21 05:17:48 -04:00
|
|
|
logger.Errorf("%s: %s", ctx.DocumentName, item)
|
2019-08-16 09:55:03 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if err != nil {
|
2020-10-21 05:17:48 -04:00
|
|
|
logger.Errorf("%s rendering %s: %v", path, ctx.DocumentName, err)
|
2019-08-16 09:55:03 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return normalizeExternalHelperLineFeeds(out.Bytes())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Strips carriage returns from third-party / external processes (useful for Windows)
|
|
|
|
func normalizeExternalHelperLineFeeds(content []byte) []byte {
|
|
|
|
return bytes.Replace(content, []byte("\r"), []byte(""), -1)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetPythonExecPath() string {
|
2020-12-18 12:20:12 -05:00
|
|
|
path, err := safeexec.LookPath("python")
|
2019-08-16 09:55:03 -04:00
|
|
|
if err != nil {
|
2020-12-18 12:20:12 -05:00
|
|
|
path, err = safeexec.LookPath("python.exe")
|
2019-08-16 09:55:03 -04:00
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return path
|
|
|
|
}
|