wide/output/build.go

310 lines
6.2 KiB
Go
Raw Normal View History

2019-05-17 06:28:50 +03:00
// Copyright (c) 2014-present, b3log.org
//
// 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
//
2018-03-12 07:28:33 +03:00
// https://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 output
import (
"bufio"
"encoding/json"
2017-03-27 05:04:34 +03:00
"fmt"
2019-05-24 16:04:25 +03:00
"github.com/b3log/gulu"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/b3log/wide/conf"
"github.com/b3log/wide/i18n"
"github.com/b3log/wide/session"
)
// BuildHandler handles request of building.
func BuildHandler(w http.ResponseWriter, r *http.Request) {
2019-05-24 16:04:25 +03:00
result := gulu.Ret.NewResult()
defer gulu.Ret.RetResult(w, r, result)
2019-05-16 19:41:52 +03:00
httpSession, _ := session.HTTPSession.Get(r, session.CookieName)
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
2019-05-16 18:17:25 +03:00
uid := httpSession.Values["uid"].(string)
user := conf.GetUser(uid)
locale := user.Locale
var args map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
return
}
sid := args["sid"].(string)
filePath := args["file"].(string)
2019-05-24 16:04:25 +03:00
if gulu.Go.IsAPI(filePath) || !session.CanAccess(uid, filePath) {
2015-07-23 11:31:37 +03:00
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
curDir := filepath.Dir(filePath)
fout, err := os.Create(filePath)
if nil != err {
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
return
}
code := args["code"].(string)
2019-05-23 06:26:33 +03:00
if _, err := fout.WriteString(code); nil != err {
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
return
}
2019-05-23 06:26:33 +03:00
fout.Close()
2019-05-23 06:26:33 +03:00
channelRet := map[string]interface{}{}
if nil != session.OutputWS[sid] {
// display "START [go build]" in front-end browser
msg := i18n.Get(locale, "start-build").(string)
msg = strings.Replace(msg, "build]", "build "+fmt.Sprint(user.BuildArgs(runtime.GOOS))+"]", 1)
channelRet["output"] = "<span class='start-build'>" + msg + "</span>\n"
channelRet["cmd"] = "start-build"
wsChannel := session.OutputWS[sid]
wsChannel.WriteJSON(&channelRet)
wsChannel.Refresh()
}
var goModCmd *exec.Cmd
2019-05-24 16:04:25 +03:00
if !gulu.File.IsExist(filepath.Join(curDir, "go.mod")) {
2019-05-23 06:26:33 +03:00
curDirName := filepath.Base(curDir)
goModCmd = exec.Command("go", "mod", "init", curDirName)
} else {
goModCmd = exec.Command("go", "mod", "tidy")
}
goModCmd.Dir = curDir
setCmdEnv(goModCmd, uid)
outputBytes, err := goModCmd.CombinedOutput()
output := string(outputBytes)
if nil != err && strings.Contains(output, "go.mod already exists") {
logger.Error(err.Error() + ": " + output)
2019-05-24 16:52:17 +03:00
result.Code = -1
2019-05-23 06:26:33 +03:00
return
}
2019-05-23 06:22:42 +03:00
var goBuildArgs []string
goBuildArgs = append(goBuildArgs, "build")
2017-05-05 08:35:09 +03:00
goBuildArgs = append(goBuildArgs, user.BuildArgs(runtime.GOOS)...)
2019-05-24 16:04:25 +03:00
if !gulu.Str.Contains("-i", goBuildArgs) {
2019-05-23 06:22:42 +03:00
goBuildArgs = append(goBuildArgs, "-i")
}
cmd := exec.Command("go", goBuildArgs...)
cmd.Dir = curDir
2019-05-16 18:17:25 +03:00
setCmdEnv(cmd, uid)
2019-05-23 06:26:33 +03:00
suffix := ""
2019-05-24 16:04:25 +03:00
if gulu.OS.IsWindows() {
2019-05-23 06:26:33 +03:00
suffix = ".exe"
}
executable := filepath.Base(curDir) + suffix
executable = filepath.Join(curDir, executable)
stdout, err := cmd.StdoutPipe()
if nil != err {
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
return
}
stderr, err := cmd.StderrPipe()
if nil != err {
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
return
}
2019-05-24 16:52:17 +03:00
if 0 != result.Code {
return
}
if err := cmd.Start(); nil != err {
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
return
}
channelRet["cmd"] = "build"
channelRet["executable"] = executable
outReader := bufio.NewReader(stdout)
/////////
go func() {
2019-05-24 16:04:25 +03:00
defer gulu.Panic.Recover()
for {
wsChannel := session.OutputWS[sid]
if nil == wsChannel {
break
}
line, err := outReader.ReadString('\n')
2019-05-24 06:36:42 +03:00
if io.EOF == err {
break
}
_, ok := err.(*os.PathError)
if ok {
// 构建时报 “read |0: file already closed” https://github.com/b3log/wide/issues/363
break
}
if nil != err {
2019-05-24 03:43:07 +03:00
logger.Warnf("%#v", err)
break
}
channelRet["output"] = line
err = wsChannel.WriteJSON(&channelRet)
if nil != err {
logger.Warn(err)
2019-05-16 13:10:44 +03:00
break
}
2015-03-16 06:24:55 +03:00
wsChannel.Refresh()
}
}()
errReader := bufio.NewReader(stderr)
2019-05-16 05:53:03 +03:00
var lines []string
for {
wsChannel := session.OutputWS[sid]
if nil == wsChannel {
break
}
line, err := errReader.ReadString('\n')
if io.EOF == err {
break
}
lines = append(lines, line)
if nil != err {
logger.Warn(err)
break
}
// path process
errOutWithPath := parsePath(curDir, line)
channelRet["output"] = "<span class='stderr'>" + errOutWithPath + "</span>"
err = wsChannel.WriteJSON(&channelRet)
if nil != err {
logger.Warn(err)
break
}
wsChannel.Refresh()
}
if nil == cmd.Wait() {
channelRet["nextCmd"] = args["nextCmd"]
channelRet["output"] = "<span class='build-succ'>" + i18n.Get(locale, "build-succ").(string) + "</span>\n"
} else {
channelRet["output"] = "<span class='build-error'>" + i18n.Get(locale, "build-error").(string) + "</span>\n"
// lint process
if lines[0][0] == '#' {
lines = lines[1:] // skip the first line
}
lints := []*Lint{}
for _, line := range lines {
if len(line) < 1 || !strings.Contains(line, ":") {
continue
}
if line[0] == '\t' {
// append to the last lint
last := len(lints)
msg := lints[last-1].Msg
msg += line
lints[last-1].Msg = msg
continue
}
file := line[:strings.Index(line, ":")]
left := line[strings.Index(line, ":")+1:]
index := strings.Index(left, ":")
lineNo := 0
msg := left
if index >= 0 {
lineNo, err = strconv.Atoi(left[:index])
if nil != err {
continue
}
msg = left[index+2:]
}
lint := &Lint{
File: filepath.ToSlash(filepath.Join(curDir, file)),
LineNo: lineNo - 1,
Severity: lintSeverityError,
Msg: msg,
}
lints = append(lints, lint)
}
channelRet["lints"] = lints
}
wsChannel := session.OutputWS[sid]
if nil == wsChannel {
return
}
err = wsChannel.WriteJSON(&channelRet)
if nil != err {
logger.Warn(err)
}
wsChannel.Refresh()
}