Welcome to mirror list, hosted at ThFree Co, Russian Federation.

external.go « internal « markup - github.com/gohugoio/hugo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 97cf5cc7d3cf19dd1f0af100cf43080a3d8c0142 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package internal

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/gohugoio/hugo/common/collections"
	"github.com/gohugoio/hugo/common/hexec"
	"github.com/gohugoio/hugo/markup/converter"
)

func ExternallyRenderContent(
	cfg converter.ProviderConfig,
	ctx converter.DocumentContext,
	content []byte, binaryName string, args []string) ([]byte, error) {
	logger := cfg.Logger

	if strings.Contains(binaryName, "/") {
		panic(fmt.Sprintf("should be no slash in %q", binaryName))
	}

	argsv := collections.StringSliceToInterfaceSlice(args)

	var out, cmderr bytes.Buffer
	argsv = append(argsv, hexec.WithStdout(&out))
	argsv = append(argsv, hexec.WithStderr(&cmderr))
	argsv = append(argsv, hexec.WithStdin(bytes.NewReader(content)))

	cmd, err := cfg.Exec.New(binaryName, argsv...)
	if err != nil {
		return nil, err
	}

	err = cmd.Run()

	// 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 != "" {
			if err == nil {
				logger.Warnf("%s: %s", ctx.DocumentName, item)
			} else {
				logger.Errorf("%s: %s", ctx.DocumentName, item)
			}
		}
	}

	if err != nil {
		logger.Errorf("%s rendering %s: %v", binaryName, ctx.DocumentName, err)
	}

	return normalizeExternalHelperLineFeeds(out.Bytes()), nil
}

// Strips carriage returns from third-party / external processes (useful for Windows)
func normalizeExternalHelperLineFeeds(content []byte) []byte {
	return bytes.Replace(content, []byte("\r"), []byte(""), -1)
}

var pythonBinaryCandidates = []string{"python", "python.exe"}

func GetPythonBinaryAndExecPath() (string, string) {
	for _, p := range pythonBinaryCandidates {
		if pth := hexec.LookPath(p); pth != "" {
			return p, pth
		}
	}
	return "", ""
}