| 1 |
package internal |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"github.com/gohugoio/hugo/common/collections" |
| 9 |
"github.com/gohugoio/hugo/common/hexec" |
| 10 |
"github.com/gohugoio/hugo/markup/converter" |
| 11 |
) |
| 12 |
|
| 13 |
func ExternallyRenderContent( |
| 14 |
cfg converter.ProviderConfig, |
| 15 |
ctx converter.DocumentContext, |
| 16 |
content []byte, binaryName string, args []string, |
| 17 |
) ([]byte, error) { |
| 18 |
logger := cfg.Logger |
| 19 |
|
| 20 |
if strings.Contains(binaryName, "/") { |
| 21 |
panic(fmt.Sprintf("should be no slash in %q", binaryName)) |
| 22 |
} |
| 23 |
|
| 24 |
argsv := collections.StringSliceToInterfaceSlice(args) |
| 25 |
|
| 26 |
var out, cmderr bytes.Buffer |
| 27 |
argsv = append(argsv, hexec.WithStdout(&out)) |
| 28 |
argsv = append(argsv, hexec.WithStderr(&cmderr)) |
| 29 |
argsv = append(argsv, hexec.WithStdin(bytes.NewReader(content))) |
| 30 |
|
| 31 |
cmd, err := cfg.Exec.New(binaryName, argsv...) |
| 32 |
if err != nil { |
| 33 |
return nil, err |
| 34 |
} |
| 35 |
|
| 36 |
err = cmd.Run() |
| 37 |
|
| 38 |
// Most external helpers exit w/ non-zero exit code only if severe, i.e. |
| 39 |
// halting errors occurred. -> log stderr output regardless of state of err |
| 40 |
for item := range strings.SplitSeq(cmderr.String(), "\n") { |
| 41 |
item := strings.TrimSpace(item) |
| 42 |
if item != "" { |
| 43 |
if err == nil { |
| 44 |
logger.Warnf("%s: %s", ctx.DocumentName, item) |
| 45 |
} else { |
| 46 |
logger.Errorf("%s: %s", ctx.DocumentName, item) |
| 47 |
} |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
if err != nil { |
| 52 |
logger.Errorf("%s rendering %s: %v", binaryName, ctx.DocumentName, err) |
| 53 |
} |
| 54 |
|
| 55 |
return normalizeExternalHelperLineFeeds(out.Bytes()), nil |
| 56 |
} |
| 57 |
|
| 58 |
// Strips carriage returns from third-party / external processes (useful for Windows) |
| 59 |
func normalizeExternalHelperLineFeeds(content []byte) []byte { |
| 60 |
return bytes.Replace(content, []byte("\r"), []byte(""), -1) |
| 61 |
} |
| 62 |
|
| 63 |
var pythonBinaryCandidates = []string{"python", "python.exe"} |
| 64 |
|
| 65 |
func GetPythonBinaryAndExecPath() (string, string) { |
| 66 |
for _, p := range pythonBinaryCandidates { |
| 67 |
if pth := hexec.LookPath(p); pth != "" { |
| 68 |
return p, pth |
| 69 |
} |
| 70 |
} |
| 71 |
return "", "" |
| 72 |
} |