mirror of
https://github.com/caddyserver/xcaddy.git
synced 2025-01-22 08:36:28 +01:00
Initial commit
This commit is contained in:
commit
6004fc79b2
7 changed files with 706 additions and 0 deletions
202
LICENSE
Normal file
202
LICENSE
Normal file
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
54
README.md
Normal file
54
README.md
Normal file
|
@ -0,0 +1,54 @@
|
|||
Custom Caddy Builder
|
||||
====================
|
||||
|
||||
This package and associated CLI tool make it easy to perform custom builds of the [Caddy Web Server](https://github.com/caddyserver/caddy).
|
||||
|
||||
Supports Caddy 2 and up.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Go installed
|
||||
- Go modules enabled
|
||||
|
||||
|
||||
## Library usage
|
||||
|
||||
```go
|
||||
caddyVersion := "v2.0.0-beta.19"
|
||||
plugins := []builder.CaddyPlugin{
|
||||
ModulePath: "github.com/caddyserver/nginx-adapter",
|
||||
Version: "6c484552e630ccac384d2d9c43c9d14c4e8d2e56",
|
||||
}
|
||||
output := "./caddy"
|
||||
|
||||
err := builder.Build(caddyVersion, plugins, output)
|
||||
```
|
||||
|
||||
Versions can be anything compatible with `go get`.
|
||||
|
||||
|
||||
## CLI usage
|
||||
|
||||
Syntax:
|
||||
|
||||
```
|
||||
builder --version <version> [--output <file>] [<plugins...>]
|
||||
```
|
||||
|
||||
Where:
|
||||
|
||||
- `--version` is the core Caddy version to build (required).
|
||||
- `--output` changes the output file.
|
||||
- `<plugins...>` are extra plugins and their versions, in `go get` module syntax: `module@version`
|
||||
|
||||
For example:
|
||||
|
||||
```bash
|
||||
$ builder --version v2.0.0-beta.19 \
|
||||
github.com/caddyserver/nginx-adapter@6c484552e630ccac384d2d9c43c9d14c4e8d2e56
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
© 2020 Matthew Holt
|
163
builder.go
Normal file
163
builder.go
Normal file
|
@ -0,0 +1,163 @@
|
|||
// Copyright 2020 Matthew Holt
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/semver/v3"
|
||||
)
|
||||
|
||||
// Build builds Caddy at the given version with the given plugins and plops
|
||||
// binary down at outputFile.
|
||||
func Build(caddyVersion string, plugins []CaddyPlugin, outputFile string) error {
|
||||
if caddyVersion == "" {
|
||||
return fmt.Errorf("caddy version is required")
|
||||
}
|
||||
if outputFile == "" {
|
||||
return fmt.Errorf("output file path is required")
|
||||
}
|
||||
// the user's specified output file might be relative, and
|
||||
// because the `go build` command is executed in a different,
|
||||
// temporary folder, we convert the user's input to an
|
||||
// absolute path so it goes the expected place
|
||||
absOutputFile, err := filepath.Abs(outputFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
env, err := newEnvironment(caddyVersion, plugins)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer env.Close()
|
||||
|
||||
log.Println("[INFO] Building Caddy")
|
||||
|
||||
cmd := env.newCommand("go", "build",
|
||||
"-o", absOutputFile,
|
||||
"-ldflags", "-w -s", // trim debug symbols
|
||||
"-trimpath",
|
||||
)
|
||||
err = env.runCommand(cmd, 1*time.Minute)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("[INFO] Build complete: %s", outputFile)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CaddyPlugin pairs a Go module path with a version.
|
||||
type CaddyPlugin struct {
|
||||
ModulePath string
|
||||
Version string
|
||||
}
|
||||
|
||||
// newTempFolder creates a new folder in a temporary location.
|
||||
// It is the caller's responsibility to remove the folder when finished.
|
||||
func newTempFolder() (string, error) {
|
||||
var parentDir string
|
||||
if runtime.GOOS == "darwin" {
|
||||
// After upgrading to macOS High Sierra, Caddy builds mysteriously
|
||||
// started missing the embedded version information that -ldflags
|
||||
// was supposed to produce. But it only happened on macOS after
|
||||
// upgrading to High Sierra, and it didn't happen with the usual
|
||||
// `go run build.go` -- only when using a buildenv. Bug in git?
|
||||
// Nope. Not a bug in Go 1.10 either. Turns out it's a breaking
|
||||
// change in macOS High Sierra. When the GOPATH of the buildenv
|
||||
// was set to some other folder, like in the $HOME dir, it worked
|
||||
// fine. Only within $TMPDIR it broke. The $TMPDIR folder is inside
|
||||
// /var, which is symlinked to /private/var, which is mounted
|
||||
// with noexec. I don't understand why, but evidently that
|
||||
// makes -ldflags of `go build` not work. Bizarre.
|
||||
// The solution, I guess, is to just use our own "temp" dir
|
||||
// outside of /var. Sigh... as long as it still gets cleaned up,
|
||||
// I guess it doesn't matter too much.
|
||||
// See: https://github.com/caddyserver/caddy/issues/2036
|
||||
// and https://twitter.com/mholt6/status/978345803365273600 (thread)
|
||||
// (using an absolute path prevents problems later when removing this
|
||||
// folder if the CWD changes)
|
||||
var err error
|
||||
parentDir, err = filepath.Abs(".")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
ts := time.Now().Format(YearMonthDayHourMin)
|
||||
return ioutil.TempDir(parentDir, fmt.Sprintf("buildenv_%s.", ts))
|
||||
}
|
||||
|
||||
// versionedModulePath helps enforce Go Module's Semantic Import Versioning (SIV) by
|
||||
// returning the form of modulePath with the major component of moduleVersion added,
|
||||
// if > 1. For example, inputs of "foo" and "v1.0.0" will return "foo", but inputs
|
||||
// of "foo" and "v2.0.0" will return "foo/v2", for use in Go imports and go commands.
|
||||
// Inputs that conflict, like "foo/v2" and "v3.1.0" are an error. This function
|
||||
// returns the input if the moduleVersion is not a valid semantic version string.
|
||||
func versionedModulePath(modulePath, moduleVersion string) (string, error) {
|
||||
ver, err := semver.StrictNewVersion(strings.TrimPrefix(moduleVersion, "v"))
|
||||
if err != nil {
|
||||
// only return the error if we know they were trying to use a semantic version
|
||||
// (could have been a commit SHA or something)
|
||||
if strings.HasPrefix(moduleVersion, "v") {
|
||||
return "", err
|
||||
}
|
||||
return modulePath, nil
|
||||
}
|
||||
major := ver.Major()
|
||||
|
||||
// see if the module path has a major version at the end (SIV)
|
||||
matches := moduleVersionRegexp.FindStringSubmatch(modulePath)
|
||||
if len(matches) == 2 {
|
||||
modPathVer, err := strconv.Atoi(matches[1])
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("this error should be impossible, but module path %s has bad version: %v", modulePath, err)
|
||||
}
|
||||
if modPathVer != int(major) {
|
||||
return "", fmt.Errorf("versioned module path (%s) and requested module major version (%d) diverge", modulePath, major)
|
||||
}
|
||||
} else if major > 1 {
|
||||
modulePath += fmt.Sprintf("/v%d", major)
|
||||
}
|
||||
|
||||
return path.Clean(modulePath), nil
|
||||
}
|
||||
|
||||
var moduleVersionRegexp = regexp.MustCompile(`.+/v(\d+)$`)
|
||||
|
||||
const (
|
||||
// YearMonthDayHourMin is the date format
|
||||
// used for temporary folder paths.
|
||||
YearMonthDayHourMin = "2006-01-02-1504"
|
||||
|
||||
// // ParallelBuildOps is how many build operations
|
||||
// // to perform in parallel (`go build -p` value)
|
||||
// ParallelBuildOps = 4
|
||||
|
||||
// CaddyRepo is the repository path of the Caddy package.
|
||||
CaddyRepo = "https://github.com/caddyserver/caddy.git"
|
||||
|
||||
defaultCaddyModulePath = "github.com/caddyserver/caddy"
|
||||
)
|
89
cmd/builder/main.go
Normal file
89
cmd/builder/main.go
Normal file
|
@ -0,0 +1,89 @@
|
|||
// Copyright 2020 Matthew Holt
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/caddyserver/builder"
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&caddyVersion, "version", "", "The version of Caddy core")
|
||||
flag.StringVar(&output, "output", "", "Where to save the resulting binary")
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
if caddyVersion == "" {
|
||||
log.Fatal("[FATAL] Caddy version is required (use --version)")
|
||||
}
|
||||
|
||||
// assemble list of plugins and their versions
|
||||
var plugins []builder.CaddyPlugin
|
||||
for _, arg := range flag.Args() {
|
||||
parts := strings.SplitN(arg, "@", 2)
|
||||
if len(parts) != 2 {
|
||||
log.Fatalf("[FATAL] %s: Plugins must be defined using 'module@version' format, similar to the `go get` command", arg)
|
||||
}
|
||||
plugins = append(plugins, builder.CaddyPlugin{
|
||||
ModulePath: parts[0],
|
||||
Version: parts[1],
|
||||
})
|
||||
}
|
||||
|
||||
// ensure an output file is always specified
|
||||
if output == "" {
|
||||
if runtime.GOOS == "windows" {
|
||||
output = "caddy.exe"
|
||||
} else {
|
||||
output = "caddy"
|
||||
}
|
||||
}
|
||||
|
||||
// perform the build
|
||||
err := builder.Build(caddyVersion, plugins, output)
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] %v", err)
|
||||
}
|
||||
|
||||
// prove the build is working by printing the version
|
||||
if !filepath.IsAbs(output) {
|
||||
output = "." + string(filepath.Separator) + output
|
||||
}
|
||||
fmt.Println()
|
||||
fmt.Printf("%s version\n", output)
|
||||
cmd := exec.Command(output, "version")
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
err = cmd.Run()
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
caddyVersion string
|
||||
plugins []string
|
||||
output string
|
||||
)
|
191
environment.go
Normal file
191
environment.go
Normal file
|
@ -0,0 +1,191 @@
|
|||
// Copyright 2020 Matthew Holt
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package builder
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newEnvironment(caddyVersion string, plugins []CaddyPlugin) (*environment, error) {
|
||||
caddyModulePath, err := versionedModulePath(defaultCaddyModulePath, caddyVersion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// clean up any SIV-incompatible module paths real quick
|
||||
for i, p := range plugins {
|
||||
plugins[i].ModulePath, err = versionedModulePath(p.ModulePath, p.Version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// create the context for the main module template
|
||||
ctx := moduleTemplateContext{
|
||||
CaddyModule: caddyModulePath,
|
||||
}
|
||||
for _, p := range plugins {
|
||||
ctx.Plugins = append(ctx.Plugins, p.ModulePath)
|
||||
}
|
||||
|
||||
// evaluate the template for the main module
|
||||
var buf bytes.Buffer
|
||||
tpl, err := template.New("main").Parse(mainModuleTemplate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tpl.Execute(&buf, ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// create the folder in which the build environment will operate
|
||||
tempFolder, err := newTempFolder()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
err2 := os.RemoveAll(tempFolder)
|
||||
if err2 != nil {
|
||||
err = fmt.Errorf("%w; additionally, cleaning up folder: %v", err, err2)
|
||||
}
|
||||
}
|
||||
}()
|
||||
log.Printf("[INFO] Temporary folder: %s", tempFolder)
|
||||
|
||||
// write the main module file to temporary folder
|
||||
mainPath := filepath.Join(tempFolder, "main.go")
|
||||
log.Printf("[INFO] Writing main module: %s", mainPath)
|
||||
err = ioutil.WriteFile(mainPath, buf.Bytes(), 0644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
env := &environment{
|
||||
caddyVersion: caddyVersion,
|
||||
plugins: plugins,
|
||||
caddyModulePath: caddyModulePath,
|
||||
tempFolder: tempFolder,
|
||||
}
|
||||
|
||||
// initialize the go module
|
||||
log.Println("[INFO] Initializing Go module")
|
||||
cmd := env.newCommand("go", "mod", "init", "caddy")
|
||||
err = env.runCommand(cmd, 10*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// pin versions by populating go.mod, first for Caddy itself and then plugins
|
||||
log.Println("[INFO] Pinning versions")
|
||||
err = env.execGoGet(caddyModulePath, caddyVersion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, p := range plugins {
|
||||
err = env.execGoGet(p.ModulePath, p.Version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("[INFO] Build environment ready")
|
||||
|
||||
return env, nil
|
||||
}
|
||||
|
||||
type environment struct {
|
||||
caddyVersion string
|
||||
plugins []CaddyPlugin
|
||||
caddyModulePath string
|
||||
tempFolder string
|
||||
}
|
||||
|
||||
// Close cleans up the build environment, including deleting
|
||||
// the temporary folder from the disk.
|
||||
func (env environment) Close() error {
|
||||
log.Printf("[INFO] Cleaning up temporary folder: %s", env.tempFolder)
|
||||
return os.RemoveAll(env.tempFolder)
|
||||
}
|
||||
|
||||
func (env environment) newCommand(command string, args ...string) *exec.Cmd {
|
||||
cmd := exec.Command(command, args...)
|
||||
cmd.Dir = env.tempFolder
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (env environment) runCommand(cmd *exec.Cmd, timeout time.Duration) error {
|
||||
log.Printf("[INFO] exec (timeout=%s): %+v ", timeout, cmd)
|
||||
|
||||
// no timeout? this is easy; just run it
|
||||
if timeout == 0 {
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
// otherwise start it and use a timer
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
timer := time.AfterFunc(timeout, func() {
|
||||
err = fmt.Errorf("timed out (builder-enforced)")
|
||||
cmd.Process.Kill()
|
||||
})
|
||||
waitErr := cmd.Wait()
|
||||
timer.Stop()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return waitErr
|
||||
}
|
||||
|
||||
func (env environment) execGoGet(modulePath, moduleVersion string) error {
|
||||
mod := modulePath + "@" + moduleVersion
|
||||
cmd := env.newCommand("go", "get", "-d", "-v", mod)
|
||||
return env.runCommand(cmd, 30*time.Second)
|
||||
}
|
||||
|
||||
type moduleTemplateContext struct {
|
||||
CaddyModule string
|
||||
Plugins []string
|
||||
}
|
||||
|
||||
const mainModuleTemplate = `package main
|
||||
|
||||
import (
|
||||
caddycmd "{{.CaddyModule}}/cmd"
|
||||
|
||||
// plug in Caddy modules here
|
||||
_ "{{.CaddyModule}}/modules/standard"
|
||||
{{- range .Plugins}}
|
||||
_ "{{.}}"
|
||||
{{- end}}
|
||||
)
|
||||
|
||||
func main() {
|
||||
caddycmd.Main()
|
||||
}
|
||||
`
|
5
go.mod
Normal file
5
go.mod
Normal file
|
@ -0,0 +1,5 @@
|
|||
module github.com/caddyserver/builder
|
||||
|
||||
go 1.14
|
||||
|
||||
require github.com/Masterminds/semver/v3 v3.0.3
|
2
go.sum
Normal file
2
go.sum
Normal file
|
@ -0,0 +1,2 @@
|
|||
github.com/Masterminds/semver/v3 v3.0.3 h1:znjIyLfpXEDQjOIEWh+ehwpTU14UzUPub3c3sm36u14=
|
||||
github.com/Masterminds/semver/v3 v3.0.3/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=
|
Loading…
Reference in a new issue