2016-03-06 13:14:05 +00:00
|
|
|
package git
|
|
|
|
|
|
|
|
import (
|
2016-03-06 14:23:37 +00:00
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2016-03-06 13:14:05 +00:00
|
|
|
"net/http"
|
2016-03-06 14:23:37 +00:00
|
|
|
"os/exec"
|
|
|
|
"strings"
|
2016-03-06 13:14:05 +00:00
|
|
|
|
|
|
|
"github.com/hacdias/caddy-hugo/config"
|
2016-03-06 20:37:49 +00:00
|
|
|
"github.com/hacdias/caddy-hugo/tools/server"
|
2016-03-06 13:14:05 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// POST handles the POST method on GIT page which is only an API.
|
|
|
|
func POST(w http.ResponseWriter, r *http.Request, c *config.Config) (int, error) {
|
2016-03-06 15:39:03 +00:00
|
|
|
// Check if git is installed on the computer
|
2016-03-06 14:23:37 +00:00
|
|
|
if _, err := exec.LookPath("git"); err != nil {
|
2016-03-06 20:37:49 +00:00
|
|
|
return server.RespondJSON(w, map[string]string{
|
2016-03-06 15:56:53 +00:00
|
|
|
"message": "Git is not installed on your computer.",
|
|
|
|
}, 400, nil)
|
2016-03-06 14:23:37 +00:00
|
|
|
}
|
2016-03-06 13:14:05 +00:00
|
|
|
|
2016-03-06 14:23:37 +00:00
|
|
|
// Get the JSON information sent using a buffer
|
|
|
|
buff := new(bytes.Buffer)
|
|
|
|
buff.ReadFrom(r.Body)
|
|
|
|
|
|
|
|
// Creates the raw file "map" using the JSON
|
|
|
|
var info map[string]interface{}
|
|
|
|
json.Unmarshal(buff.Bytes(), &info)
|
|
|
|
|
2016-03-06 15:39:03 +00:00
|
|
|
// Check if command was sent
|
2016-03-06 14:23:37 +00:00
|
|
|
if _, ok := info["command"]; !ok {
|
2016-03-06 20:37:49 +00:00
|
|
|
return server.RespondJSON(w, map[string]string{
|
2016-03-06 15:56:53 +00:00
|
|
|
"message": "Command not specified.",
|
|
|
|
}, 400, nil)
|
2016-03-06 14:23:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
command := info["command"].(string)
|
|
|
|
args := strings.Split(command, " ")
|
|
|
|
|
|
|
|
if len(args) > 0 && args[0] == "git" {
|
|
|
|
args = append(args[:0], args[1:]...)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(args) == 0 {
|
2016-03-06 20:37:49 +00:00
|
|
|
return server.RespondJSON(w, map[string]string{
|
2016-03-06 15:56:53 +00:00
|
|
|
"message": "Command not specified.",
|
|
|
|
}, 400, nil)
|
2016-03-06 14:23:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
cmd := exec.Command("git", args...)
|
|
|
|
cmd.Dir = c.Path
|
|
|
|
output, err := cmd.CombinedOutput()
|
|
|
|
|
|
|
|
if err != nil {
|
2016-03-06 20:37:49 +00:00
|
|
|
return server.RespondJSON(w, map[string]string{
|
2016-03-06 15:56:53 +00:00
|
|
|
"message": err.Error(),
|
|
|
|
}, 500, err)
|
2016-03-06 14:23:37 +00:00
|
|
|
}
|
|
|
|
|
2016-03-06 20:37:49 +00:00
|
|
|
return server.RespondJSON(w, map[string]string{
|
2016-03-06 15:56:53 +00:00
|
|
|
"message": string(output),
|
|
|
|
}, 200, nil)
|
2016-03-06 14:23:37 +00:00
|
|
|
}
|