gosimplenpm/internal/handler/tagdelete.go

85 lines
2.1 KiB
Go
Raw Normal View History

package handler
import (
"encoding/json"
"fmt"
2023-11-25 02:17:09 +00:00
"gosimplenpm/internal/config"
"gosimplenpm/internal/serviceidos"
"gosimplenpm/internal/storage"
"net/http"
"net/url"
"strconv"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"golang.org/x/mod/semver"
)
2023-12-25 08:56:48 +00:00
func DistTagDelete(lg *logrus.Logger, cfg config.Config, stg storage.Storage) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
escapedName := mux.Vars(r)["name"]
packageName, _ := url.PathUnescape(escapedName)
2023-06-30 19:06:46 +00:00
lg.WithFields(logrus.Fields{
"function": "dist-tags-delete",
}).Debugf("Package name => %s\n", packageName)
escapedName = mux.Vars(r)["tag"]
tag, _ := url.PathUnescape(escapedName)
2023-06-30 19:06:46 +00:00
lg.WithFields(logrus.Fields{
"function": "dist-tags-delete",
}).Debugf("Tag => %s\n", tag)
if semver.IsValid(tag) {
2023-12-25 08:56:48 +00:00
http.Error(w, fmt.Sprintf("Tag %s cannot be a semver version", tag), http.StatusBadRequest)
return
}
if tag == "latest" {
http.Error(w, "Cannot delete the latest tag", http.StatusBadRequest)
return
}
2023-12-25 08:56:48 +00:00
fileToServe, found, err := stg.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
2023-12-25 08:56:48 +00:00
err = stg.ReadIndexJson(fileToServe, &jsonFile, lg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
delete(jsonFile.DistTags, tag)
// Write index.json
2023-12-25 08:56:48 +00:00
err = stg.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)
}
}