gosimplenpm/internal/handler/tagput.go

93 lines
2.2 KiB
Go

package handler
import (
"encoding/json"
"fmt"
"gosimplenpm/internal/config"
"gosimplenpm/internal/serviceidos"
"gosimplenpm/internal/storage"
"io"
"net/http"
"net/url"
"strconv"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"golang.org/x/mod/semver"
)
func DistTagPut(lg *logrus.Logger, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
escapedName := mux.Vars(r)["name"]
packageName, _ := url.PathUnescape(escapedName)
lg.WithFields(logrus.Fields{
"function": "dist-tags-put",
}).Debugf("Package name => %s\n", packageName)
escapedName = mux.Vars(r)["tag"]
tag, _ := url.PathUnescape(escapedName)
lg.WithFields(logrus.Fields{
"function": "dist-tags-put",
}).Debugf("Tag => %s\n", tag)
if semver.IsValid(tag) {
http.Error(w, "Tag cannot be a semver version", http.StatusBadRequest)
return
}
if tag == "latest" {
http.Error(w, "Cannot delete the latest tag", http.StatusBadRequest)
return
}
body, _ := io.ReadAll(r.Body)
var version string
_ = json.Unmarshal(body, &version)
lg.WithFields(logrus.Fields{
"function": "dist-tags-put",
}).Debugf("Body => %s", version)
fileToServe, found, err := storage.GetIndexJsonFromStore(packageName, cfg.RepoDir, lg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found {
ret := fmt.Sprintf("Package not found: %s", packageName)
http.Error(w, ret, http.StatusNotFound)
return
}
var jsonFile serviceidos.IndexJson
err = storage.ReadIndexJson(fileToServe, &jsonFile, lg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonFile.DistTags[tag] = version
// Write index.json
err = storage.WriteIndexJson(fileToServe, &jsonFile, lg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
distTagsString, _ := json.Marshal(jsonFile.DistTags)
response := serviceidos.TagPutResponse{
Ok: true,
ID: escapedName,
DistTags: string(distTagsString),
}
jsonString, _ := json.Marshal(response)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(jsonString)))
w.Write(jsonString)
}
}