wide/editor/editors.go

400 lines
9.4 KiB
Go
Raw Normal View History

2019-05-17 06:28:50 +03:00
// Copyright (c) 2014-present, b3log.org
2014-11-20 06:30:18 +03:00
//
2014-11-12 18:13:14 +03:00
// 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
2014-11-20 06:30:18 +03:00
//
2018-03-12 07:28:33 +03:00
// https://www.apache.org/licenses/LICENSE-2.0
2014-11-20 06:30:18 +03:00
//
2014-11-12 18:13:14 +03:00
// 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.
2014-12-07 06:14:10 +03:00
// Package editor includes editor related manipulations.
2014-08-18 17:45:43 +04:00
package editor
import (
"bytes"
"encoding/json"
"net/http"
"os"
"os/exec"
2014-10-28 08:22:39 +03:00
"path/filepath"
2014-09-04 19:09:51 +04:00
"runtime"
2014-08-18 17:45:43 +04:00
"strconv"
2014-09-01 16:50:51 +04:00
"strings"
2014-09-07 13:07:25 +04:00
2019-12-01 15:21:00 +03:00
"github.com/88250/gulu"
"github.com/88250/wide/conf"
"github.com/88250/wide/file"
"github.com/88250/wide/session"
2014-08-18 17:45:43 +04:00
)
2014-12-13 13:47:41 +03:00
// Logger.
2019-05-24 16:04:25 +03:00
var logger = gulu.Log.NewLogger(os.Stdout)
2014-12-13 13:47:41 +03:00
2014-10-29 13:15:18 +03:00
// AutocompleteHandler handles request of code autocompletion.
2014-08-18 17:45:43 +04:00
func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
2022-08-09 05:11:53 +03:00
if conf.Wide.ReadOnly {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
2014-08-18 17:45:43 +04:00
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-08-18 17:45:43 +04:00
return
}
2019-05-16 19:41:52 +03:00
session, _ := session.HTTPSession.Get(r, session.CookieName)
2014-11-26 08:49:27 +03:00
if session.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
2019-05-16 18:17:25 +03:00
uid := session.Values["uid"].(string)
2014-09-02 20:26:10 +04:00
2014-09-16 18:39:22 +04:00
path := args["path"].(string)
fout, err := os.Create(path)
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-09-16 18:39:22 +04:00
return
}
2014-08-18 17:45:43 +04:00
code := args["code"].(string)
2014-09-16 18:39:22 +04:00
fout.WriteString(code)
if err := fout.Close(); nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-09-16 18:39:22 +04:00
return
}
2014-09-15 06:08:49 +04:00
2014-08-18 17:45:43 +04:00
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
2014-09-01 16:50:51 +04:00
offset := getCursorOffset(code, line, ch)
2015-01-11 07:12:06 +03:00
logger.Tracef("offset: %d", offset)
2014-08-18 17:45:43 +04:00
2019-05-16 18:17:25 +03:00
userWorkspace := conf.GetUserWorkspace(uid)
2014-10-28 08:22:39 +03:00
workspaces := filepath.SplitList(userWorkspace)
2014-10-26 09:46:15 +03:00
libPath := ""
for _, workspace := range workspaces {
userLib := workspace + conf.PathSeparator + "pkg" + conf.PathSeparator +
runtime.GOOS + "_" + runtime.GOARCH
libPath += userLib + conf.PathListSeparator
}
2014-09-05 07:07:29 +04:00
2014-12-18 10:54:58 +03:00
logger.Tracef("gocode set lib-path [%s]", libPath)
2014-09-04 19:09:51 +04:00
2019-05-24 16:04:25 +03:00
gocode := gulu.Go.GetExecutableInGOBIN("gocode")
// FIXME: using gocode set lib-path has some issues while accrossing workspaces
2015-03-10 06:49:38 +03:00
exec.Command(gocode, []string{"set", "lib-path", libPath}...).Run()
2014-09-02 20:26:10 +04:00
2015-03-10 06:49:38 +03:00
argv := []string{"-f=json", "--in=" + path, "autocomplete", strconv.Itoa(offset)}
2014-09-17 12:13:00 +04:00
cmd := exec.Command(gocode, argv...)
2014-08-18 17:45:43 +04:00
2014-09-03 10:53:42 +04:00
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-09-03 10:53:42 +04:00
return
}
2014-08-18 17:45:43 +04:00
w.Header().Set("Content-Type", "application/json")
2014-09-03 10:53:42 +04:00
w.Write(output)
2014-08-18 17:45:43 +04:00
}
2014-09-01 16:50:51 +04:00
2014-10-29 13:15:18 +03:00
// GetExprInfoHandler handles request of getting expression infomation.
2014-10-10 07:18:52 +04:00
func GetExprInfoHandler(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)
2014-10-10 07:18:52 +04:00
2019-05-16 19:41:52 +03:00
session, _ := session.HTTPSession.Get(r, session.CookieName)
2019-05-16 18:17:25 +03:00
uid := session.Values["uid"].(string)
2014-10-10 07:18:52 +04:00
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-10-10 07:18:52 +04:00
return
}
path := args["path"].(string)
2015-08-05 06:09:52 +03:00
curDir := filepath.Dir(path)
filename := filepath.Base(path)
2014-10-10 07:18:52 +04:00
fout, err := os.Create(path)
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-10-10 07:18:52 +04:00
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-10-10 07:18:52 +04:00
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
2014-10-12 18:58:08 +04:00
2015-01-11 07:12:06 +03:00
logger.Tracef("offset [%d]", offset)
2014-10-10 07:18:52 +04:00
2019-05-24 16:04:25 +03:00
ideStub := gulu.Go.GetExecutableInGOBIN("gotools")
2015-08-05 06:09:52 +03:00
argv := []string{"types", "-pos", filename + ":" + strconv.Itoa(offset), "-info", "."}
2014-12-07 06:14:10 +03:00
cmd := exec.Command(ideStub, argv...)
2014-10-10 07:18:52 +04:00
cmd.Dir = curDir
2019-05-16 18:17:25 +03:00
setCmdEnv(cmd, uid)
2014-10-10 07:18:52 +04:00
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-10-10 07:18:52 +04:00
return
}
exprInfo := strings.TrimSpace(string(output))
if "" == exprInfo {
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-10-10 07:18:52 +04:00
return
}
2015-11-24 10:42:28 +03:00
result.Data = exprInfo
2014-10-10 07:18:52 +04:00
}
2014-10-29 13:15:18 +03:00
// FindDeclarationHandler handles request of finding declaration.
2014-09-11 20:22:24 +04:00
func FindDeclarationHandler(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)
2014-09-11 20:22:24 +04:00
2019-05-16 19:41:52 +03:00
session, _ := session.HTTPSession.Get(r, session.CookieName)
2014-11-26 08:49:27 +03:00
if session.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
2019-05-16 18:17:25 +03:00
uid := session.Values["uid"].(string)
2014-09-11 20:22:24 +04:00
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-09-11 20:22:24 +04:00
return
}
2014-09-13 09:05:50 +04:00
path := args["path"].(string)
2015-08-05 06:09:52 +03:00
curDir := filepath.Dir(path)
filename := filepath.Base(path)
2014-09-11 20:22:24 +04:00
2014-09-13 09:05:50 +04:00
fout, err := os.Create(path)
2014-09-11 20:22:24 +04:00
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-09-11 20:22:24 +04:00
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-09-11 20:22:24 +04:00
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
2014-10-13 08:22:50 +04:00
2015-01-11 07:12:06 +03:00
logger.Tracef("offset [%d]", offset)
2014-09-11 20:22:24 +04:00
2019-05-24 16:04:25 +03:00
ideStub := gulu.Go.GetExecutableInGOBIN("gotools")
2015-08-05 06:09:52 +03:00
argv := []string{"types", "-pos", filename + ":" + strconv.Itoa(offset), "-def", "."}
2014-12-07 06:14:10 +03:00
cmd := exec.Command(ideStub, argv...)
2014-09-11 20:22:24 +04:00
cmd.Dir = curDir
2019-05-16 18:17:25 +03:00
setCmdEnv(cmd, uid)
2014-09-11 20:22:24 +04:00
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-09-11 20:22:24 +04:00
return
}
2014-09-12 06:10:21 +04:00
found := strings.TrimSpace(string(output))
if "" == found {
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-09-12 06:10:21 +04:00
return
}
part := found[:strings.LastIndex(found, ":")]
cursorSep := strings.LastIndex(part, ":")
2014-09-13 09:05:50 +04:00
path = found[:cursorSep]
2015-08-05 06:09:52 +03:00
2014-11-04 19:27:43 +03:00
cursorLine, _ := strconv.Atoi(found[cursorSep+1 : strings.LastIndex(found, ":")])
cursorCh, _ := strconv.Atoi(found[strings.LastIndex(found, ":")+1:])
2014-09-12 06:10:21 +04:00
2015-11-24 10:42:28 +03:00
data := map[string]interface{}{}
2015-11-27 11:55:28 +03:00
result.Data = &data
2015-11-24 10:42:28 +03:00
2015-08-05 06:09:52 +03:00
data["path"] = filepath.ToSlash(path)
2014-09-12 06:10:21 +04:00
data["cursorLine"] = cursorLine
data["cursorCh"] = cursorCh
2014-09-11 20:22:24 +04:00
}
2014-10-29 13:15:18 +03:00
// FindUsagesHandler handles request of finding usages.
2014-09-12 11:55:52 +04:00
func FindUsagesHandler(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)
2014-09-12 11:55:52 +04:00
2019-05-16 19:41:52 +03:00
session, _ := session.HTTPSession.Get(r, session.CookieName)
2014-11-26 08:49:27 +03:00
if session.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
2019-05-16 18:17:25 +03:00
uid := session.Values["uid"].(string)
2014-09-12 11:55:52 +04:00
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-09-12 11:55:52 +04:00
return
}
2014-10-10 07:18:52 +04:00
filePath := args["path"].(string)
2015-08-05 06:09:52 +03:00
curDir := filepath.Dir(filePath)
filename := filepath.Base(filePath)
2014-09-12 11:55:52 +04:00
fout, err := os.Create(filePath)
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-09-12 11:55:52 +04:00
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-09-12 11:55:52 +04:00
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
2015-01-11 07:12:06 +03:00
logger.Tracef("offset [%d]", offset)
2014-09-12 11:55:52 +04:00
2019-05-24 16:04:25 +03:00
ideStub := gulu.Go.GetExecutableInGOBIN("gotools")
2015-08-05 06:09:52 +03:00
argv := []string{"types", "-pos", filename + ":" + strconv.Itoa(offset), "-use", "."}
2014-12-07 06:14:10 +03:00
cmd := exec.Command(ideStub, argv...)
2014-09-12 11:55:52 +04:00
cmd.Dir = curDir
2019-05-16 18:17:25 +03:00
setCmdEnv(cmd, uid)
2014-09-12 11:55:52 +04:00
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2019-05-17 05:34:09 +03:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2014-09-12 11:55:52 +04:00
return
}
2015-11-24 10:42:28 +03:00
out := strings.TrimSpace(string(output))
if "" == out {
2019-05-24 16:52:17 +03:00
result.Code = -1
2014-09-12 11:55:52 +04:00
return
}
2015-11-24 10:42:28 +03:00
founds := strings.Split(out, "\n")
2014-10-11 10:08:29 +04:00
usages := []*file.Snippet{}
2014-09-12 11:55:52 +04:00
for _, found := range founds {
found = strings.TrimSpace(found)
part := found[:strings.LastIndex(found, ":")]
cursorSep := strings.LastIndex(part, ":")
2015-08-05 06:09:52 +03:00
path := filepath.ToSlash(found[:cursorSep])
2014-09-12 12:50:04 +04:00
cursorLine, _ := strconv.Atoi(found[cursorSep+1 : strings.LastIndex(found, ":")])
cursorCh, _ := strconv.Atoi(found[strings.LastIndex(found, ":")+1:])
2014-09-12 11:55:52 +04:00
2014-10-12 18:00:26 +04:00
usage := &file.Snippet{Path: path, Line: cursorLine, Ch: cursorCh, Contents: []string{""}}
2014-09-12 11:55:52 +04:00
usages = append(usages, usage)
}
2015-11-24 10:42:28 +03:00
result.Data = usages
2014-09-12 11:55:52 +04:00
}
2014-10-29 13:15:18 +03:00
// getCursorOffset calculates the cursor offset.
2014-09-25 09:37:59 +04:00
//
2014-10-29 13:15:18 +03:00
// line is the line number, starts with 0 that means the first line
// ch is the column number, starts with 0 that means the first column
2014-09-01 16:50:51 +04:00
func getCursorOffset(code string, line, ch int) (offset int) {
lines := strings.Split(code, "\n")
2014-10-29 13:15:18 +03:00
// calculate sum length of lines before
2014-09-01 16:50:51 +04:00
for i := 0; i < line; i++ {
offset += len(lines[i])
}
2014-10-29 13:15:18 +03:00
// calculate length of the current line and column
2014-09-13 09:05:50 +04:00
curLine := lines[line]
var buffer bytes.Buffer
r := []rune(curLine)
for i := 0; i < ch; i++ {
buffer.WriteString(string(r[i]))
}
2014-10-29 13:15:18 +03:00
offset += len(buffer.String()) // append length of current line
offset += line // append number of '\n'
2014-09-01 16:50:51 +04:00
2014-09-13 09:05:50 +04:00
return offset
2014-09-01 16:50:51 +04:00
}
2014-09-11 20:22:24 +04:00
2019-05-16 18:17:25 +03:00
func setCmdEnv(cmd *exec.Cmd, userId string) {
userWorkspace := conf.GetUserWorkspace(userId)
2014-09-11 20:22:24 +04:00
cmd.Env = append(cmd.Env,
"GOPATH="+userWorkspace,
"GOOS="+runtime.GOOS,
"GOARCH="+runtime.GOARCH,
"GOROOT="+runtime.GOROOT(),
"PATH="+os.Getenv("PATH"))
}