From dd217f623c1f7adf2730033e115114e6539a1c72 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Sun, 4 Feb 2024 17:04:20 +0800 Subject: [PATCH 001/618] =?UTF-8?q?service=E3=80=81dao=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E6=8A=BD=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/collect/collect.go | 20 +- taskman-server/api/v1/form/form_template.go | 18 +- taskman-server/api/v1/request/request.go | 96 +++--- .../api/v1/request/request_template.go | 78 ++--- taskman-server/api/v1/task/task.go | 38 +-- taskman-server/api/v1/task/task_template.go | 14 +- taskman-server/api/v2/request/request.go | 24 +- .../api/v2/request/request_template.go | 4 +- taskman-server/common/log/log.go | 2 +- taskman-server/dao/attach_file_dao.go | 7 + taskman-server/dao/collect_template_dao.go | 7 + taskman-server/{services/db => dao}/db.go | 42 ++- taskman-server/dao/form_dao.go | 7 + taskman-server/dao/form_item_dao.go | 7 + taskman-server/dao/form_item_templdate_dao.go | 7 + taskman-server/dao/form_template_dao.go | 7 + taskman-server/dao/operation_log_dao.go | 7 + taskman-server/dao/request_dao.go | 7 + taskman-server/dao/request_template_dao.go | 7 + .../dao/request_template_group_dao.go | 7 + .../dao/request_template_role_dao.go | 7 + taskman-server/dao/task_dao.go | 7 + taskman-server/dao/task_template_dao.go | 7 + taskman-server/dao/task_template_role.go | 7 + taskman-server/main.go | 8 +- taskman-server/models/request.go | 4 + .../attach_file_service.go} | 71 ++++- .../collect_template_service.go} | 31 +- .../{services/db => service}/cron.go | 7 +- .../form_template_service.go} | 41 +-- .../ref_select_service.go} | 14 +- .../request.go => service/request_service.go} | 201 ++++++------ .../request_template_service.go} | 287 +++++++++--------- taskman-server/service/service.go | 60 ++++ .../db/task.go => service/task_service.go} | 117 +++---- .../task_template_service.go} | 39 +-- .../{services/db => service}/validate.go | 5 +- 37 files changed, 777 insertions(+), 542 deletions(-) create mode 100644 taskman-server/dao/attach_file_dao.go create mode 100644 taskman-server/dao/collect_template_dao.go rename taskman-server/{services/db => dao}/db.go (91%) create mode 100644 taskman-server/dao/form_dao.go create mode 100644 taskman-server/dao/form_item_dao.go create mode 100644 taskman-server/dao/form_item_templdate_dao.go create mode 100644 taskman-server/dao/form_template_dao.go create mode 100644 taskman-server/dao/operation_log_dao.go create mode 100644 taskman-server/dao/request_dao.go create mode 100644 taskman-server/dao/request_template_dao.go create mode 100644 taskman-server/dao/request_template_group_dao.go create mode 100644 taskman-server/dao/request_template_role_dao.go create mode 100644 taskman-server/dao/task_dao.go create mode 100644 taskman-server/dao/task_template_dao.go create mode 100644 taskman-server/dao/task_template_role.go rename taskman-server/{services/db/attach_file.go => service/attach_file_service.go} (50%) rename taskman-server/{services/db/collect.go => service/collect_template_service.go} (84%) rename taskman-server/{services/db => service}/cron.go (78%) rename taskman-server/{services/db/form_template.go => service/form_template_service.go} (71%) rename taskman-server/{services/db/ref_select.go => service/ref_select_service.go} (94%) rename taskman-server/{services/db/request.go => service/request_service.go} (89%) rename taskman-server/{services/db/request_template.go => service/request_template_service.go} (74%) create mode 100644 taskman-server/service/service.go rename taskman-server/{services/db/task.go => service/task_service.go} (77%) rename taskman-server/{services/db/task_template.go => service/task_template_service.go} (66%) rename taskman-server/{services/db => service}/validate.go (92%) diff --git a/taskman-server/api/v1/collect/collect.go b/taskman-server/api/v1/collect/collect.go index 1b646035..b6ed5483 100644 --- a/taskman-server/api/v1/collect/collect.go +++ b/taskman-server/api/v1/collect/collect.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + service "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" "strings" ) @@ -22,7 +22,7 @@ func AddTemplateCollect(c *gin.Context) { return } var parentId string - requestTemplate, err := db.GetSimpleRequestTemplate(param.TemplateId) + requestTemplate, err := service.GetSimpleRequestTemplate(param.TemplateId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -30,11 +30,11 @@ func AddTemplateCollect(c *gin.Context) { parentId = strings.TrimSpace(requestTemplate.ParentId) if parentId == "" { // parentId为空说明 模板为老数据,需要更新该名称的模板 - parentId = db.UpdateRequestTemplateParentId(requestTemplate) + parentId = service.UpdateRequestTemplateParentId(requestTemplate) // 可能由于到导入到模板,模板的 recordId值是错误的,导致parentId 还是空,此处直接更新当前模板parentId值 if parentId == "" { parentId = param.TemplateId - err = db.UpdateRequestTemplateParentIdById(param.TemplateId, parentId) + err = service.UpdateRequestTemplateParentIdById(param.TemplateId, parentId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -42,7 +42,7 @@ func AddTemplateCollect(c *gin.Context) { } } // 判断模板是否已经收藏 - if db.CheckUserCollectExist(parentId, middleware.GetRequestUser(c)) { + if service.CheckUserCollectExist(parentId, middleware.GetRequestUser(c)) { middleware.ReturnTemplateAlreadyCollectError(c) return } @@ -52,7 +52,7 @@ func AddTemplateCollect(c *gin.Context) { Role: param.Role, Type: requestTemplate.Type, } - err = db.AddTemplateCollect(collectTemplate) + err = service.AddTemplateCollect(collectTemplate) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -68,7 +68,7 @@ func CancelTemplateCollect(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - err = db.DeleteTemplateCollect(parentId, middleware.GetRequestUser(c)) + err = service.DeleteTemplateCollect(parentId, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -86,7 +86,7 @@ func QueryTemplateCollect(c *gin.Context) { if param.PageSize == 0 { param.PageSize = 10 } - pageInfo, rowData, err := db.QueryTemplateCollect(¶m, middleware.GetRequestUser(c), c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) + pageInfo, rowData, err := service.QueryTemplateCollect(¶m, middleware.GetRequestUser(c), c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -101,7 +101,7 @@ func FilterItem(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - data, err := db.GetCollectFilterItem(¶m, middleware.GetRequestUser(c)) + data, err := service.GetCollectFilterItem(¶m, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -112,7 +112,7 @@ func FilterItem(c *gin.Context) { // getRequestTemplateParentId 根据模板id查找 最开始版本模板id func getRequestTemplateParentId(templateId string) (string, error) { // 根据 templateId 查找parent_id,模板会变更产生多个版本,只需要关联最开始版本 - requestTemplate, err := db.GetSimpleRequestTemplate(templateId) + requestTemplate, err := service.GetSimpleRequestTemplate(templateId) if err != nil { return "", err } diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index ea628f8d..37df3106 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -3,7 +3,7 @@ package form import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" ) @@ -13,7 +13,7 @@ func GetRequestFormTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - result, err := db.GetRequestFormTemplate(id) + result, err := service.GetRequestFormTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -35,33 +35,33 @@ func UpdateRequestFormTemplate(c *gin.Context) { var err error param.UpdatedBy = middleware.GetRequestUser(c) if param.Id != "" { - err = db.UpdateRequestFormTemplate(param) + err = service.UpdateRequestFormTemplate(param) } else { - err = db.CreateRequestFormTemplate(param, id) + err = service.CreateRequestFormTemplate(param, id) } if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) - result, _ := db.GetRequestFormTemplate(id) + service.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) + result, _ := service.GetRequestFormTemplate(id) middleware.ReturnData(c, result) } func ConfirmRequestFormTemplate(c *gin.Context) { id := c.Param("id") - err := db.ConfirmRequestTemplate(id) + err := service.ConfirmRequestTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "confirmRequestTemplate", c.Request.RequestURI, "") + service.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "confirmRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } func DeleteRequestFormTemplate(c *gin.Context) { id := c.Param("id") - err := db.DeleteRequestFormTemplate(id) + err := service.DeleteRequestFormTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) } else { diff --git a/taskman-server/api/v1/request/request.go b/taskman-server/api/v1/request/request.go index 31d7d32e..1d44696b 100644 --- a/taskman-server/api/v1/request/request.go +++ b/taskman-server/api/v1/request/request.go @@ -5,7 +5,7 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" "io/ioutil" "net/http" @@ -17,7 +17,7 @@ func GetEntityData(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("Param requestId can not empty ")) return } - result, err := db.GetEntityData(id, c.GetHeader("Authorization")) + result, err := service.GetEntityData(id, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -32,7 +32,7 @@ func ProcessDataPreview(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("Param requestTemplateId or entityDataId can not empty ")) return } - result, err := db.ProcessDataPreview(requestTemplateId, entityDataId, c.GetHeader("Authorization")) + result, err := service.ProcessDataPreview(requestTemplateId, entityDataId, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -43,7 +43,7 @@ func ProcessDataPreview(c *gin.Context) { func GetRequestPreviewData(c *gin.Context) { requestId := c.Query("requestId") entityDataId := c.Query("rootEntityId") - result, err := db.GetRequestPreData(requestId, entityDataId, c.GetHeader("Authorization")) + result, err := service.GetRequestPreData(requestId, entityDataId, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -53,7 +53,7 @@ func GetRequestPreviewData(c *gin.Context) { // CountRequest 个人工作台统计 func CountRequest(c *gin.Context) { - platformData, err := db.GetRequestCount(middleware.GetRequestUser(c), middleware.GetRequestRoles(c)) + platformData, err := service.GetRequestCount(middleware.GetRequestUser(c), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -68,7 +68,7 @@ func FilterItem(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - data, err := db.GetFilterItem(param) + data, err := service.GetFilterItem(param) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -92,7 +92,7 @@ func DataList(c *gin.Context) { if param.PageSize == 0 { param.PageSize = 10 } - pageInfo, rowData, err := db.DataList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c)) + pageInfo, rowData, err := service.DataList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -103,7 +103,7 @@ func DataList(c *gin.Context) { // RevokeRequest 撤回请求 func RevokeRequest(c *gin.Context) { requestId := c.Param("requestId") - err := db.RevokeRequest(requestId, middleware.GetRequestUser(c)) + err := service.RevokeRequest(requestId, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -121,7 +121,7 @@ func HistoryList(c *gin.Context) { if param.PageSize == 0 { param.PageSize = 10 } - pageInfo, rowData, err := db.HistoryList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c)) + pageInfo, rowData, err := service.HistoryList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -136,7 +136,7 @@ func Export(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - err := db.Export(c.Writer, ¶m, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestUser(c)) + err := service.Export(c.Writer, ¶m, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -151,7 +151,7 @@ func ListRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := db.ListRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), permission, middleware.GetRequestUser(c)) + pageInfo, rowData, err := service.ListRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), permission, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -161,7 +161,7 @@ func ListRequest(c *gin.Context) { func GetRequest(c *gin.Context) { requestId := c.Param("requestId") - result, err := db.GetRequestWithRoot(requestId) + result, err := service.GetRequestWithRoot(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -171,7 +171,7 @@ func GetRequest(c *gin.Context) { func GetRequestDetail(c *gin.Context) { requestId := c.Param("requestId") - result, err := db.GetRequestTaskList(requestId) + result, err := service.GetRequestTaskList(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -181,7 +181,7 @@ func GetRequestDetail(c *gin.Context) { func GetRequestRootForm(c *gin.Context) { requestId := c.Param("requestId") - result, err := db.GetRequestRootForm(requestId) + result, err := service.GetRequestRootForm(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -200,12 +200,12 @@ func CreateRequest(c *gin.Context) { return } param.CreatedBy = middleware.GetRequestUser(c) - err := db.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization")) + err := service.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } @@ -221,23 +221,23 @@ func UpdateRequest(c *gin.Context) { return } param.UpdatedBy = middleware.GetRequestUser(c) - err := db.UpdateRequest(¶m) + err := service.UpdateRequest(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestLog(param.Id, param.Name, param.UpdatedBy, "updateRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordRequestLog(param.Id, param.Name, param.UpdatedBy, "updateRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } func DeleteRequest(c *gin.Context) { requestId := c.Param("requestId") - err := db.DeleteRequest(requestId, middleware.GetRequestUser(c)) + err := service.DeleteRequest(requestId, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "deleteRequest", c.Request.RequestURI, "") + service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "deleteRequest", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } @@ -250,7 +250,7 @@ func SaveRequestCache(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - err := db.SaveRequestCacheNew(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization"), ¶m) + err := service.SaveRequestCacheNew(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization"), ¶m) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -262,7 +262,7 @@ func SaveRequestCache(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - err := db.SaveRequestBindCache(requestId, middleware.GetRequestUser(c), ¶m) + err := service.SaveRequestBindCache(requestId, middleware.GetRequestUser(c), ¶m) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -274,7 +274,7 @@ func SaveRequestCache(c *gin.Context) { func GetRequestCache(c *gin.Context) { requestId := c.Param("requestId") cacheType := c.Param("cacheType") - result, err := db.GetRequestCache(requestId, cacheType) + result, err := service.GetRequestCache(requestId, cacheType) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -289,12 +289,12 @@ func StartRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - instanceId, err := db.StartRequest(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization"), param) + instanceId, err := service.StartRequest(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization"), param) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, instanceId) } @@ -310,18 +310,18 @@ func UpdateRequestStatus(c *gin.Context) { if bindErr := c.ShouldBindJSON(¶m); bindErr == nil { description = param.Description } - err := db.UpdateRequestStatus(requestId, status, middleware.GetRequestUser(c), c.GetHeader("Authorization"), description) + err := service.UpdateRequestStatus(requestId, status, middleware.GetRequestUser(c), c.GetHeader("Authorization"), description) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "setRequestStatus", c.Request.RequestURI, status) + service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "setRequestStatus", c.Request.RequestURI, status) middleware.ReturnSuccess(c) } func TerminateRequest(c *gin.Context) { requestId := c.Param("requestId") - err := db.RequestTermination(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization")) + err := service.RequestTermination(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -336,7 +336,7 @@ func GetCmdbReferenceData(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - resultBytes, statusCode, err := db.GetCmdbReferenceData(attrId, c.GetHeader("Authorization"), param) + resultBytes, statusCode, err := service.GetCmdbReferenceData(attrId, c.GetHeader("Authorization"), param) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -353,11 +353,11 @@ func GetReferenceData(c *gin.Context) { return } input := models.RefSelectParam{AttrId: attrId, RequestId: requestId, Param: ¶m, UserToken: c.GetHeader("Authorization")} - result, err := db.GetCMDBRefSelectResult(&input) + result, err := service.GetCMDBRefSelectResult(&input) if err != nil { middleware.ReturnServerHandleError(c, err) } else { - result = db.FilterInSideData(result, attrId, requestId) + result = service.FilterInSideData(result, attrId, requestId) middleware.ReturnData(c, result) } } @@ -384,21 +384,21 @@ func UploadRequestAttachFile(c *gin.Context) { c.JSON(http.StatusInternalServerError, models.ResponseErrorJson{StatusCode: "PARAM_HANDLE_ERROR", StatusMessage: "Read content fail error:" + err.Error(), Data: nil}) return } - err = db.UploadAttachFile(requestId, "", file.Filename, middleware.GetRequestUser(c), b) + err = service.UploadAttachFile(requestId, "", file.Filename, middleware.GetRequestUser(c), b) if err != nil { middleware.ReturnServerHandleError(c, err) } else { - middleware.ReturnData(c, db.GetRequestAttachFileList(requestId)) + middleware.ReturnData(c, service.GetRequestAttachFileList(requestId)) } } func DownloadAttachFile(c *gin.Context) { fileId := c.Param("fileId") - if err := db.CheckAttachFilePermission(fileId, middleware.GetRequestUser(c), "download", middleware.GetRequestRoles(c)); err != nil { + if err := service.CheckAttachFilePermission(fileId, middleware.GetRequestUser(c), "download", middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionDenyError(c) return } - fileContent, fileName, err := db.DownloadAttachFile(fileId) + fileContent, fileName, err := service.DownloadAttachFile(fileId) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -411,7 +411,7 @@ func DownloadAttachFile(c *gin.Context) { func UpdateRequestHandler(c *gin.Context) { requestId := c.Param("requestId") lastedUpdateTime := c.Param("latestUpdateTime") - request, err := db.GetSimpleRequest(requestId) + request, err := service.GetSimpleRequest(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -425,7 +425,7 @@ func UpdateRequestHandler(c *gin.Context) { middleware.ReturnUpdateRequestHandlerStatusError(c) return } - err = db.UpdateRequestHandler(requestId, middleware.GetRequestUser(c)) + err = service.UpdateRequestHandler(requestId, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -435,18 +435,18 @@ func UpdateRequestHandler(c *gin.Context) { func RemoveAttachFile(c *gin.Context) { fileId := c.Param("fileId") - if err := db.CheckAttachFilePermission(fileId, middleware.GetRequestUser(c), "delete", middleware.GetRequestRoles(c)); err != nil { + if err := service.CheckAttachFilePermission(fileId, middleware.GetRequestUser(c), "delete", middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionDenyError(c) return } - fileObj, err := db.RemoveAttachFile(fileId) + fileObj, err := service.RemoveAttachFile(fileId) if err != nil { middleware.ReturnServerHandleError(c, err) } else { if fileObj.Request != "" { - middleware.ReturnData(c, db.GetRequestAttachFileList(fileObj.Request)) + middleware.ReturnData(c, service.GetRequestAttachFileList(fileObj.Request)) } else { - middleware.ReturnData(c, db.GetTaskAttachFileList(fileObj.Task)) + middleware.ReturnData(c, service.GetTaskAttachFileList(fileObj.Task)) } } } @@ -460,18 +460,18 @@ func QueryWorkflowEntity(c *gin.Context) { func CopyRequest(c *gin.Context) { requestId := c.Param("requestId") createdBy := middleware.GetRequestUser(c) - result, err := db.CopyRequest(requestId, createdBy) + result, err := service.CopyRequest(requestId, createdBy) if err != nil { middleware.ReturnServerHandleError(c, err) } else { - db.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "copyRequest", c.Request.RequestURI, "") + service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "copyRequest", c.Request.RequestURI, "") middleware.ReturnData(c, result) } } func GetRequestParent(c *gin.Context) { requestId := c.Query("requestId") - result, err := db.GetRequestParent(requestId) + result, err := service.GetRequestParent(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -488,7 +488,7 @@ func GetRequestProgress(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - rowsData, err = db.GetRequestProgress(param.RequestId, c.GetHeader("Authorization")) + rowsData, err = service.GetRequestProgress(param.RequestId, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -505,7 +505,7 @@ func GetProcessInstance(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - rowData, err = db.GetProcessInstance(instanceId, c.GetHeader("Authorization")) + rowData, err = service.GetProcessInstance(instanceId, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -522,7 +522,7 @@ func GetProcessDefinitions(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - rowData, err = db.GetProcessDefinitions(templateId, c.GetHeader("Authorization")) + rowData, err = service.GetProcessDefinitions(templateId, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -534,7 +534,7 @@ func GetProcessDefinitions(c *gin.Context) { func GetExecutionNodes(c *gin.Context) { procInstanceId := c.Param("procInstanceId") nodeInstanceId := c.Param("nodeInstanceId") - rowData, err := db.GetExecutionNodes(c.GetHeader("Authorization"), procInstanceId, nodeInstanceId) + rowData, err := service.GetExecutionNodes(c.GetHeader("Authorization"), procInstanceId, nodeInstanceId) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/api/v1/request/request_template.go b/taskman-server/api/v1/request/request_template.go index 82a1a326..30e9357d 100644 --- a/taskman-server/api/v1/request/request_template.go +++ b/taskman-server/api/v1/request/request_template.go @@ -3,6 +3,7 @@ package request import ( "encoding/json" "fmt" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "io/ioutil" "net/http" "strings" @@ -10,7 +11,6 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" "github.com/gin-gonic/gin" ) @@ -20,7 +20,7 @@ func QueryRequestTemplateGroup(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := db.QueryRequestTemplateGroup(¶m, middleware.GetRequestRoles(c)) + pageInfo, rowData, err := service.QueryRequestTemplateGroup(¶m, middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -34,7 +34,7 @@ func CreateRequestTemplateGroup(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - err := db.CreateRequestTemplateGroup(¶m) + err := service.CreateRequestTemplateGroup(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -52,12 +52,12 @@ func UpdateRequestTemplateGroup(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - err := db.CheckRequestTemplateGroupRoles(param.Id, middleware.GetRequestRoles(c)) + err := service.CheckRequestTemplateGroupRoles(param.Id, middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnDataPermissionError(c, err) return } - err = db.UpdateRequestTemplateGroup(¶m) + err = service.UpdateRequestTemplateGroup(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -71,12 +71,12 @@ func DeleteRequestTemplateGroup(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - err := db.CheckRequestTemplateGroupRoles(id, middleware.GetRequestRoles(c)) + err := service.CheckRequestTemplateGroupRoles(id, middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnDataPermissionError(c, err) return } - err = db.DeleteRequestTemplateGroup(id) + err = service.DeleteRequestTemplateGroup(id) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -85,8 +85,8 @@ func DeleteRequestTemplateGroup(c *gin.Context) { } func GetCoreProcessList(c *gin.Context) { - result, err := db.GetCoreProcessListNew(c.GetHeader("Authorization")) - //procList, err := db.GetCoreProcessListAll(c.GetHeader("Authorization"), "MGMT", models.ProcessFetchTabs) + result, err := service.GetCoreProcessListNew(c.GetHeader("Authorization")) + //procList, err := service.GetCoreProcessListAll(c.GetHeader("Authorization"), "MGMT", models.ProcessFetchTabs) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -111,7 +111,7 @@ func GetCoreProcessList(c *gin.Context) { func GetCoreProcNodes(c *gin.Context) { requestTemplateId := c.Param("id") getType := c.Param("type") - result, err := db.GetProcessNodesByProc(models.RequestTemplateTable{Id: requestTemplateId}, c.GetHeader("Authorization"), getType) + result, err := service.GetProcessNodesByProc(models.RequestTemplateTable{Id: requestTemplateId}, c.GetHeader("Authorization"), getType) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -120,8 +120,8 @@ func GetCoreProcNodes(c *gin.Context) { } func GetRoleList(c *gin.Context) { - db.SyncCoreRole() - result, err := db.GetRoleList([]string{}) + service.SyncCoreRole() + result, err := service.GetRoleList([]string{}) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -131,7 +131,7 @@ func GetRoleList(c *gin.Context) { func GetUserByRoles(c *gin.Context) { roleString := c.Query("roles") - result, err := db.QueryUserByRoles(strings.Split(roleString, ","), c.GetHeader("Authorization")) + result, err := service.QueryUserByRoles(strings.Split(roleString, ","), c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -140,8 +140,8 @@ func GetUserByRoles(c *gin.Context) { } func GetUserRoles(c *gin.Context) { - db.SyncCoreRole() - result, err := db.GetRoleList(middleware.GetRequestRoles(c)) + service.SyncCoreRole() + result, err := service.GetRoleList(middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -155,7 +155,7 @@ func QueryRequestTemplate(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := db.QueryRequestTemplate(¶m, c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) + pageInfo, rowData, err := service.QueryRequestTemplate(¶m, c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -174,12 +174,12 @@ func CreateRequestTemplate(c *gin.Context) { return } param.CreatedBy = middleware.GetRequestUser(c) - result, err := db.CreateRequestTemplate(¶m) + result, err := service.CreateRequestTemplate(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "createRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "createRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, result) } @@ -197,17 +197,17 @@ func UpdateRequestTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - if err := db.CheckRequestTemplateRoles(param.Id, middleware.GetRequestRoles(c)); err != nil { + if err := service.CheckRequestTemplateRoles(param.Id, middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionError(c, err) return } param.UpdatedBy = middleware.GetRequestUser(c) - result, err := db.UpdateRequestTemplate(¶m) + result, err := service.UpdateRequestTemplate(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "updateRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "updateRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, result) } @@ -233,11 +233,11 @@ func DeleteRequestTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - if err := db.CheckRequestTemplateRoles(id, middleware.GetRequestRoles(c)); err != nil { + if err := service.CheckRequestTemplateRoles(id, middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionError(c, err) return } - _, err := db.DeleteRequestTemplate(id, false) + _, err := service.DeleteRequestTemplate(id, false) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -247,7 +247,7 @@ func DeleteRequestTemplate(c *gin.Context) { func ListRequestTemplateEntityAttrs(c *gin.Context) { id := c.Param("id") - result, err := db.ListRequestTemplateEntityAttrs(id, c.GetHeader("Authorization")) + result, err := service.ListRequestTemplateEntityAttrs(id, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -261,7 +261,7 @@ func GetRequestTemplateEntityAttrs(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - result, err := db.GetRequestTemplateEntityAttrs(id) + result, err := service.GetRequestTemplateEntityAttrs(id) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -280,18 +280,18 @@ func UpdateRequestTemplateEntityAttrs(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - err := db.UpdateRequestTemplateEntityAttrs(id, param, middleware.GetRequestUser(c)) + err := service.UpdateRequestTemplateEntityAttrs(id, param, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) - db.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateRequestTemplateAttr", c.Request.RequestURI, c.GetString("requestBody")) + service.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) + service.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateRequestTemplateAttr", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnSuccess(c) } func GetRequestTemplateByUser(c *gin.Context) { - result, err := db.GetRequestTemplateByUser(middleware.GetRequestRoles(c)) + result, err := service.GetRequestTemplateByUser(middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -301,18 +301,18 @@ func GetRequestTemplateByUser(c *gin.Context) { func ForkConfirmRequestTemplate(c *gin.Context) { requestTemplateId := c.Param("id") - err := db.ForkConfirmRequestTemplate(requestTemplateId, middleware.GetRequestUser(c)) + err := service.ForkConfirmRequestTemplate(requestTemplateId, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "forkRequestTemplate", c.Request.RequestURI, "") + service.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "forkRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } func GetRequestTemplateTags(c *gin.Context) { group := c.Param("requestTemplateGroup") - result, err := db.GetRequestTemplateTags(group) + result, err := service.GetRequestTemplateTags(group) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -322,7 +322,7 @@ func GetRequestTemplateTags(c *gin.Context) { func ExportRequestTemplate(c *gin.Context) { requestTemplateId := c.Param("requestTemplateId") - result, err := db.RequestTemplateExport(requestTemplateId) + result, err := service.RequestTemplateExport(requestTemplateId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -359,7 +359,7 @@ func ImportRequestTemplate(c *gin.Context) { c.JSON(http.StatusInternalServerError, models.ResponseErrorJson{StatusCode: "PARAM_HANDLE_ERROR", StatusMessage: "Json unmarshal fail error:" + err.Error(), Data: nil}) return } - templateName, backToken, importErr := db.RequestTemplateImport(paramObj, c.GetHeader("Authorization"), "", middleware.GetRequestUser(c)) + templateName, backToken, importErr := service.RequestTemplateImport(paramObj, c.GetHeader("Authorization"), "", middleware.GetRequestUser(c)) if importErr != nil { middleware.ReturnServerHandleError(c, importErr) return @@ -373,7 +373,7 @@ func ImportRequestTemplate(c *gin.Context) { func ConfirmImportRequestTemplate(c *gin.Context) { confirmToken := c.Param("confirmToken") - _, _, err := db.RequestTemplateImport(models.RequestTemplateExport{}, c.GetHeader("Authorization"), confirmToken, middleware.GetRequestUser(c)) + _, _, err := service.RequestTemplateImport(models.RequestTemplateExport{}, c.GetHeader("Authorization"), confirmToken, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -383,22 +383,22 @@ func ConfirmImportRequestTemplate(c *gin.Context) { func DisableRequestTemplate(c *gin.Context) { requestTemplateId := c.Param("id") - err := db.DisableRequestTemplate(requestTemplateId, middleware.GetRequestUser(c)) + err := service.DisableRequestTemplate(requestTemplateId, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "disableRequestTemplate", c.Request.RequestURI, "") + service.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "disableRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } func EnableRequestTemplate(c *gin.Context) { requestTemplateId := c.Param("id") - err := db.EnableRequestTemplate(requestTemplateId, middleware.GetRequestUser(c)) + err := service.EnableRequestTemplate(requestTemplateId, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "enableRequestTemplate", c.Request.RequestURI, "") + service.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "enableRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } diff --git a/taskman-server/api/v1/task/task.go b/taskman-server/api/v1/task/task.go index 8ef9a078..0c6fe2f1 100644 --- a/taskman-server/api/v1/task/task.go +++ b/taskman-server/api/v1/task/task.go @@ -6,7 +6,7 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + service "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" "io/ioutil" "net/http" @@ -15,7 +15,7 @@ import ( func GetTaskFormStruct(c *gin.Context) { procInstId := c.Query("procInstId") nodeDefId := c.Query("nodeDefId") - result, err := db.GetTaskFormStruct(procInstId, nodeDefId) + result, err := service.GetTaskFormStruct(procInstId, nodeDefId) if err != nil { result.Status = "ERROR" result.Message = err.Error() @@ -43,13 +43,13 @@ func CreateTask(c *gin.Context) { return } for _, input := range param.Inputs { - output, taskId, tmpErr := db.PluginTaskCreate(input, param.RequestId, param.DueDate, param.AllowedOptions) + output, taskId, tmpErr := service.PluginTaskCreate(input, param.RequestId, param.DueDate, param.AllowedOptions) if tmpErr != nil { output.ErrorCode = "1" output.ErrorMessage = tmpErr.Error() err = tmpErr } else { - notifyErr := db.NotifyTaskMail(taskId) + notifyErr := service.NotifyTaskMail(taskId) if notifyErr != nil { log.Logger.Error("Notify task mail fail", log.Error(notifyErr)) } @@ -64,7 +64,7 @@ func ListTask(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := db.ListTask(¶m, middleware.GetRequestRoles(c), middleware.GetRequestUser(c)) + pageInfo, rowData, err := service.ListTask(¶m, middleware.GetRequestRoles(c), middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -74,7 +74,7 @@ func ListTask(c *gin.Context) { func GetTask(c *gin.Context) { taskId := c.Param("taskId") - result, err := db.GetTask(taskId) + result, err := service.GetTask(taskId) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -100,13 +100,13 @@ func SaveTaskForm(c *gin.Context) { } } if err == nil { - err = db.ValidateRequestForm(param.FormData, c.GetHeader("Authorization")) + err = service.ValidateRequestForm(param.FormData, c.GetHeader("Authorization")) } if err != nil { middleware.ReturnParamValidateError(c, err) return } - task, err = db.GetSimpleTask(taskId) + task, err = service.GetSimpleTask(taskId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -115,11 +115,11 @@ func SaveTaskForm(c *gin.Context) { middleware.ReturnTaskSaveNotPermissionError(c) return } - err = db.SaveTaskForm(taskId, operator, param) + err = service.SaveTaskForm(taskId, operator, param) if err != nil { middleware.ReturnServerHandleError(c, err) } else { - db.RecordTaskLog(taskId, task.Name, operator, "saveTask", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordTaskLog(taskId, task.Name, operator, "saveTask", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnSuccess(c) } } @@ -171,13 +171,13 @@ func ApproveTask(c *gin.Context) { } } if err == nil { - err = db.ValidateRequestForm(param.FormData, c.GetHeader("Authorization")) + err = service.ValidateRequestForm(param.FormData, c.GetHeader("Authorization")) } if err != nil { middleware.ReturnParamValidateError(c, err) return } - taskTable, err := db.GetSimpleTask(taskId) + taskTable, err := service.GetSimpleTask(taskId) if err != nil { middleware.ReturnParamValidateError(c, err) return @@ -186,11 +186,11 @@ func ApproveTask(c *gin.Context) { middleware.ReturnTaskApproveNotPermissionError(c) return } - err = db.ApproveTask(taskId, operator, c.GetHeader("Authorization"), param) + err = service.ApproveTask(taskId, operator, c.GetHeader("Authorization"), param) if err != nil { middleware.ReturnServerHandleError(c, err) } else { - db.RecordTaskLog(taskId, taskTable.Name, operator, "approveTask", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordTaskLog(taskId, taskTable.Name, operator, "approveTask", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnSuccess(c) } } @@ -203,12 +203,12 @@ func ChangeTaskStatus(c *gin.Context) { middleware.ReturnChangeTaskStatusError(c) return } - taskObj, err := db.ChangeTaskStatus(taskId, middleware.GetRequestUser(c), operation, lastedUpdateTime) + taskObj, err := service.ChangeTaskStatus(taskId, middleware.GetRequestUser(c), operation, lastedUpdateTime) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "changeTaskStatus", c.Request.RequestURI, operation) + service.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "changeTaskStatus", c.Request.RequestURI, operation) middleware.ReturnData(c, taskObj) } @@ -234,11 +234,11 @@ func UploadTaskAttachFile(c *gin.Context) { c.JSON(http.StatusInternalServerError, models.ResponseErrorJson{StatusCode: "PARAM_HANDLE_ERROR", StatusMessage: "Read content fail error:" + err.Error(), Data: nil}) return } - err = db.UploadAttachFile("", taskId, file.Filename, middleware.GetRequestUser(c), b) + err = service.UploadAttachFile("", taskId, file.Filename, middleware.GetRequestUser(c), b) if err != nil { middleware.ReturnServerHandleError(c, err) } else { - db.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "uploadTaskFile", c.Request.RequestURI, file.Filename) - middleware.ReturnData(c, db.GetTaskAttachFileList(taskId)) + service.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "uploadTaskFile", c.Request.RequestURI, file.Filename) + middleware.ReturnData(c, service.GetTaskAttachFileList(taskId)) } } diff --git a/taskman-server/api/v1/task/task_template.go b/taskman-server/api/v1/task/task_template.go index f56d06c6..8ec72d2b 100644 --- a/taskman-server/api/v1/task/task_template.go +++ b/taskman-server/api/v1/task/task_template.go @@ -4,14 +4,14 @@ import ( "fmt" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" ) func GetTaskTemplate(c *gin.Context) { requestTemplateId := c.Param("requestTemplateId") proNodeId := c.Param("proNodeId") - result, err := db.GetTaskTemplate(requestTemplateId, proNodeId, "") + result, err := service.GetTaskTemplate(requestTemplateId, proNodeId, "") if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -34,17 +34,17 @@ func UpdateTaskTemplate(c *gin.Context) { return } if param.Id != "" { - err = db.UpdateTaskTemplate(param) + err = service.UpdateTaskTemplate(param) } else { - err = db.CreateTaskTemplate(param, id) + err = service.CreateTaskTemplate(param, id) } if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) - db.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateTaskTemplate", c.Request.RequestURI, c.GetString("requestBody")) - result, _ := db.GetTaskTemplate(id, param.NodeDefId, "") + service.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) + service.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateTaskTemplate", c.Request.RequestURI, c.GetString("requestBody")) + result, _ := service.GetTaskTemplate(id, param.NodeDefId, "") middleware.ReturnData(c, result) } diff --git a/taskman-server/api/v2/request/request.go b/taskman-server/api/v2/request/request.go index 84ff90ba..7361145e 100644 --- a/taskman-server/api/v2/request/request.go +++ b/taskman-server/api/v2/request/request.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" "time" ) @@ -12,7 +12,7 @@ import ( // GetRequestDetail 新版请求详情 func GetRequestDetail(c *gin.Context) { requestId := c.Param("requestId") - result, err := db.GetRequestDetailV2(requestId, c.GetHeader("Authorization")) + result, err := service.GetRequestDetailV2(requestId, c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -34,7 +34,7 @@ func CreateRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("Param role can not empty ")) return } - template, err := db.GetSimpleRequestTemplate(param.RequestTemplate) + template, err := service.GetSimpleRequestTemplate(param.RequestTemplate) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -53,12 +53,12 @@ func CreateRequest(c *gin.Context) { } else { param.TemplateVersion = template.Version } - err = db.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization")) + err = service.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization")) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } @@ -73,7 +73,7 @@ func SaveRequestCache(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - request, err := db.GetSimpleRequest(requestId) + request, err := service.GetSimpleRequest(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -82,7 +82,7 @@ func SaveRequestCache(c *gin.Context) { middleware.ReturnReportRequestNotPermissionError(c) return } - err = db.SaveRequestCacheV2(requestId, user, c.GetHeader("Authorization"), ¶m) + err = service.SaveRequestCacheV2(requestId, user, c.GetHeader("Authorization"), ¶m) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -95,7 +95,7 @@ func SaveRequestCache(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - request, err := db.GetSimpleRequest(requestId) + request, err := service.GetSimpleRequest(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -112,7 +112,7 @@ func SaveRequestCache(c *gin.Context) { return } } - err = db.SaveRequestBindCache(requestId, operator, ¶m) + err = service.SaveRequestBindCache(requestId, operator, ¶m) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -129,7 +129,7 @@ func StartRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - request, err := db.GetSimpleRequest(requestId) + request, err := service.GetSimpleRequest(requestId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -138,11 +138,11 @@ func StartRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("request handler not permission!")) return } - instanceId, err := db.StartRequest(requestId, operator, c.GetHeader("Authorization"), param) + instanceId, err := service.StartRequest(requestId, operator, c.GetHeader("Authorization"), param) if err != nil { middleware.ReturnServerHandleError(c, err) return } - db.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, instanceId) } diff --git a/taskman-server/api/v2/request/request_template.go b/taskman-server/api/v2/request/request_template.go index b9a4d45b..52ffb8b6 100644 --- a/taskman-server/api/v2/request/request_template.go +++ b/taskman-server/api/v2/request/request_template.go @@ -2,13 +2,13 @@ package request import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" ) // GetRequestTemplateByUser 选择模板 func GetRequestTemplateByUser(c *gin.Context) { - result, err := db.GetRequestTemplateByUserV2(middleware.GetRequestUser(c), c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) + result, err := service.GetRequestTemplateByUserV2(middleware.GetRequestUser(c), c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/common/log/log.go b/taskman-server/common/log/log.go index a5f35c87..623c7a78 100644 --- a/taskman-server/common/log/log.go +++ b/taskman-server/common/log/log.go @@ -43,7 +43,7 @@ func InitLogger() { if models.Config.Log.DbLogEnable { DatabaseLogger = logger.InitArchiveZapLogger(logger.LogConfig{ Name: "database", - FilePath: fmt.Sprintf("%s/taskman-db.log", baseLogDir), + FilePath: fmt.Sprintf("%s/taskman-service.log", baseLogDir), LogLevel: models.Config.Log.Level, ArchiveMaxSize: models.Config.Log.ArchiveMaxSize, ArchiveMaxBackup: models.Config.Log.ArchiveMaxBackup, diff --git a/taskman-server/dao/attach_file_dao.go b/taskman-server/dao/attach_file_dao.go new file mode 100644 index 00000000..22785e8b --- /dev/null +++ b/taskman-server/dao/attach_file_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type AttachFileDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/collect_template_dao.go b/taskman-server/dao/collect_template_dao.go new file mode 100644 index 00000000..d3786b6d --- /dev/null +++ b/taskman-server/dao/collect_template_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type CollectTemplateDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/services/db/db.go b/taskman-server/dao/db.go similarity index 91% rename from taskman-server/services/db/db.go rename to taskman-server/dao/db.go index 91c92e2b..d78489d6 100644 --- a/taskman-server/services/db/db.go +++ b/taskman-server/dao/db.go @@ -1,4 +1,4 @@ -package db +package dao import ( "fmt" @@ -16,20 +16,18 @@ import ( xorm_log "xorm.io/xorm/log" ) -const HistoryTablePrefix = "history_" - var ( - x *xorm.Engine _ xorm_log.Logger = &dbLogger{} + X *xorm.Engine ) -func InitDatabase() error { +func InitDatabase() (engine *xorm.Engine, err error) { connStr := fmt.Sprintf("%s:%s@%s(%s)/%s?collation=utf8mb4_unicode_ci&allowNativePasswords=true", models.Config.Database.User, models.Config.Database.Password, "tcp", fmt.Sprintf("%s:%s", models.Config.Database.Server, models.Config.Database.Port), models.Config.Database.DataBase) - engine, err := xorm.NewEngine("mysql", connStr) + engine, err = xorm.NewEngine("mysql", connStr) if err != nil { log.Logger.Error("Init database connect fail", log.Error(err)) - return err + return nil, err } engine.SetMaxIdleConns(models.Config.Database.MaxIdle) engine.SetMaxOpenConns(models.Config.Database.MaxOpen) @@ -39,9 +37,9 @@ func InitDatabase() error { } // 使用驼峰式映射 engine.SetMapper(core.SnakeMapper{}) - x = engine log.Logger.Info("Success init database connect !!") - return nil + X = engine + return } type dbLogger struct { @@ -119,10 +117,10 @@ func (d *dbLogger) IsShowSQL() bool { return d.ShowSql } -func queryCount(sql string, params ...interface{}) int { +func QueryCount(sql string, params ...interface{}) int { sql = "SELECT COUNT(1) FROM ( " + sql + " ) sub_query" params = append([]interface{}{sql}, params...) - queryRows, err := x.QueryString(params...) + queryRows, err := X.QueryString(params...) if err != nil || len(queryRows) == 0 { log.Logger.Error("Query sql count message fail", log.Error(err)) return 0 @@ -134,7 +132,7 @@ func queryCount(sql string, params ...interface{}) int { return 0 } -func getJsonToXormMap(input interface{}) (resultMap map[string]string, idKeyName string) { +func GetJsonToXormMap(input interface{}) (resultMap map[string]string, idKeyName string) { resultMap = make(map[string]string) t := reflect.TypeOf(input) for i := 0; i < t.NumField(); i++ { @@ -146,12 +144,12 @@ func getJsonToXormMap(input interface{}) (resultMap map[string]string, idKeyName return resultMap, idKeyName } -func transFiltersToSQL(queryParam *models.QueryRequestParam, transParam *models.TransFiltersParam) (filterSql, queryColumn string, param []interface{}) { +func TransFiltersToSQL(queryParam *models.QueryRequestParam, transParam *models.TransFiltersParam) (filterSql, queryColumn string, param []interface{}) { if transParam.Prefix != "" && !strings.HasSuffix(transParam.Prefix, ".") { transParam.Prefix = transParam.Prefix + "." } if transParam.IsStruct { - transParam.KeyMap, transParam.PrimaryKey = getJsonToXormMap(transParam.StructObj) + transParam.KeyMap, transParam.PrimaryKey = GetJsonToXormMap(transParam.StructObj) } for _, filter := range queryParam.Filters { if transParam.KeyMap[filter.Name] == "" || transParam.KeyMap[filter.Name] == "-" { @@ -173,7 +171,7 @@ func transFiltersToSQL(queryParam *models.QueryRequestParam, transParam *models. inValueStringList = append(inValueStringList, inValueInterfaceObj.(string)) } } - tmpSpecSql, tmpListParams := createListParams(inValueStringList, "") + tmpSpecSql, tmpListParams := CreateListParams(inValueStringList, "") filterSql += fmt.Sprintf(" AND %s%s in (%s) ", transParam.Prefix, transParam.KeyMap[filter.Name], tmpSpecSql) param = append(param, tmpListParams...) } else if filter.Operator == "lt" { @@ -219,19 +217,19 @@ func transFiltersToSQL(queryParam *models.QueryRequestParam, transParam *models. return } -func transPageInfoToSQL(pageInfo models.PageInfo) (pageSql string, param []interface{}) { +func TransPageInfoToSQL(pageInfo models.PageInfo) (pageSql string, param []interface{}) { pageSql = " LIMIT ?,? " param = append(param, pageInfo.StartIndex) param = append(param, pageInfo.PageSize) return } -type execAction struct { +type ExecAction struct { Sql string Param []interface{} } -func transaction(actions []*execAction) error { +func Transaction(actions []*ExecAction) error { if len(actions) == 0 { log.Logger.Warn("Transaction is empty,nothing to do") return fmt.Errorf("SQL exec transaction is empty,nothing to do,please check server log ") @@ -241,7 +239,7 @@ func transaction(actions []*execAction) error { return fmt.Errorf("SQL exec transaction index%d is nill error,please check server log", i) } } - session := x.NewSession() + session := X.NewSession() err := session.Begin() for _, action := range actions { params := make([]interface{}, 0) @@ -286,7 +284,7 @@ func getDefaultInsertSqlByStruct(obj interface{}, tableName string, ignoreColumn return fmt.Sprintf("INSERT INTO %s(%s) VALUE (%s)", tableName, strings.Join(columnList, ","), strings.Join(valueList, ",")) } -func transactionWithoutForeignCheck(actions []*execAction) error { +func TransactionWithoutForeignCheck(actions []*ExecAction) error { if len(actions) == 0 { log.Logger.Warn("Transaction is empty,nothing to do") return fmt.Errorf("SQL exec transaction is empty,nothing to do,please check server log ") @@ -296,7 +294,7 @@ func transactionWithoutForeignCheck(actions []*execAction) error { return fmt.Errorf("SQL exec transaction index%d is nill error,please check server log", i) } } - session := x.NewSession() + session := X.NewSession() err := session.Begin() if err != nil { return err @@ -322,7 +320,7 @@ func transactionWithoutForeignCheck(actions []*execAction) error { return err } -func createListParams(inputList []string, prefix string) (specSql string, paramList []interface{}) { +func CreateListParams(inputList []string, prefix string) (specSql string, paramList []interface{}) { if len(inputList) > 0 { var specList []string for _, v := range inputList { diff --git a/taskman-server/dao/form_dao.go b/taskman-server/dao/form_dao.go new file mode 100644 index 00000000..083fbdd8 --- /dev/null +++ b/taskman-server/dao/form_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type FormDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/form_item_dao.go b/taskman-server/dao/form_item_dao.go new file mode 100644 index 00000000..ea4d07ba --- /dev/null +++ b/taskman-server/dao/form_item_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type FormItemDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/form_item_templdate_dao.go b/taskman-server/dao/form_item_templdate_dao.go new file mode 100644 index 00000000..cdbc448f --- /dev/null +++ b/taskman-server/dao/form_item_templdate_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type FormItemTemplateDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/form_template_dao.go b/taskman-server/dao/form_template_dao.go new file mode 100644 index 00000000..47bcb41a --- /dev/null +++ b/taskman-server/dao/form_template_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type FormTemplateDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/operation_log_dao.go b/taskman-server/dao/operation_log_dao.go new file mode 100644 index 00000000..fb4a80d2 --- /dev/null +++ b/taskman-server/dao/operation_log_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type OperationLogDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/request_dao.go b/taskman-server/dao/request_dao.go new file mode 100644 index 00000000..9e036306 --- /dev/null +++ b/taskman-server/dao/request_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type RequestDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go new file mode 100644 index 00000000..f09d2ec8 --- /dev/null +++ b/taskman-server/dao/request_template_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type RequestTemplateDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/request_template_group_dao.go b/taskman-server/dao/request_template_group_dao.go new file mode 100644 index 00000000..0ab40ba0 --- /dev/null +++ b/taskman-server/dao/request_template_group_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type RequestTemplateGroupDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/request_template_role_dao.go b/taskman-server/dao/request_template_role_dao.go new file mode 100644 index 00000000..f671e873 --- /dev/null +++ b/taskman-server/dao/request_template_role_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type RequestTemplateRoleDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/task_dao.go b/taskman-server/dao/task_dao.go new file mode 100644 index 00000000..55ebd63d --- /dev/null +++ b/taskman-server/dao/task_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type TaskDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/task_template_dao.go b/taskman-server/dao/task_template_dao.go new file mode 100644 index 00000000..646aeb60 --- /dev/null +++ b/taskman-server/dao/task_template_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type TaskTemplateDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/task_template_role.go b/taskman-server/dao/task_template_role.go new file mode 100644 index 00000000..1ba0dec4 --- /dev/null +++ b/taskman-server/dao/task_template_role.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type TaskTemplateRoleDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/main.go b/taskman-server/main.go index ec4d47f6..2b129fbf 100644 --- a/taskman-server/main.go +++ b/taskman-server/main.go @@ -6,7 +6,7 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/services/db" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" ) // @title Taskman Server New @@ -20,10 +20,10 @@ func main() { return } log.InitLogger() - if initDbError := db.InitDatabase(); initDbError != nil { - return + if err := service.New(); err != nil { + panic(fmt.Errorf("service new err:%+v", err)) } - go db.StartCornJob() + go service.StartCornJob() //start http api.InitHttpServer() } diff --git a/taskman-server/models/request.go b/taskman-server/models/request.go index 54fff54f..1268c6c2 100644 --- a/taskman-server/models/request.go +++ b/taskman-server/models/request.go @@ -170,6 +170,10 @@ type RequestTable struct { TemplateVersion string `json:"templateVersion" xorm:"-"` // 模板版本 } +func (RequestTable) TableName() string { + return "request" +} + type ExpireObj struct { Percent float64 `json:"percent"` ReportTime string `json:"reportTime"` diff --git a/taskman-server/services/db/attach_file.go b/taskman-server/service/attach_file_service.go similarity index 50% rename from taskman-server/services/db/attach_file.go rename to taskman-server/service/attach_file_service.go index 4c3b84ad..d62c04db 100644 --- a/taskman-server/services/db/attach_file.go +++ b/taskman-server/service/attach_file_service.go @@ -1,14 +1,19 @@ -package db +package service import ( "context" "fmt" "github.com/WeBankPartners/go-common-lib/file_server" "github.com/WeBankPartners/go-common-lib/guid" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "time" ) +type AttachFileService struct { + attachFileDao dao.AttachFileDao +} + func UploadAttachFile(requestId, taskId, fileName, operator string, fileContent []byte) error { if requestId == "" && taskId == "" { return fmt.Errorf("requestId or taskId can not empty ") @@ -34,13 +39,47 @@ func UploadAttachFile(requestId, taskId, fileName, operator string, fileContent return err } nowTime := time.Now().Format(models.DateTimeFormat) - var actions []*execAction + var actions []*dao.ExecAction + if requestId != "" { + actions = append(actions, &dao.ExecAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,request,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{fileGuid, fileName, models.Config.AttachFile.Bucket, uploadParam.ObjectName, requestId, operator, nowTime, operator, nowTime}}) + } else if taskId != "" { + actions = append(actions, &dao.ExecAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,task,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{fileGuid, fileName, models.Config.AttachFile.Bucket, uploadParam.ObjectName, taskId, operator, nowTime, operator, nowTime}}) + } + return dao.Transaction(actions) +} + +func (s AttachFileService) UploadAttachFile(requestId, taskId, fileName, operator string, fileContent []byte) error { + if requestId == "" && taskId == "" { + return fmt.Errorf("requestId or taskId can not empty ") + } + ms, err := getMinioServerObj() + if err != nil { + return err + } + fileGuid := guid.CreateGuid() + uploadParam := file_server.MinioParam{Ctx: context.Background(), Bucket: models.Config.AttachFile.Bucket} + uploadParam.FileContent = fileContent + requestTemplateId := getAttachFileRequestTemplate(requestId, taskId) + if requestTemplateId != "" { + requestTemplateId = requestTemplateId + "/" + } + if requestId != "" { + uploadParam.ObjectName = fmt.Sprintf("%s%s_%s", requestTemplateId, fileName, requestId) + } else { + uploadParam.ObjectName = fmt.Sprintf("%s%s_%s", requestTemplateId, fileName, taskId) + } + err = ms.Upload(uploadParam) + if err != nil { + return err + } + nowTime := time.Now().Format(models.DateTimeFormat) + var actions []*dao.ExecAction if requestId != "" { - actions = append(actions, &execAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,request,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{fileGuid, fileName, models.Config.AttachFile.Bucket, uploadParam.ObjectName, requestId, operator, nowTime, operator, nowTime}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,request,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{fileGuid, fileName, models.Config.AttachFile.Bucket, uploadParam.ObjectName, requestId, operator, nowTime, operator, nowTime}}) } else if taskId != "" { - actions = append(actions, &execAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,task,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{fileGuid, fileName, models.Config.AttachFile.Bucket, uploadParam.ObjectName, taskId, operator, nowTime, operator, nowTime}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,task,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{fileGuid, fileName, models.Config.AttachFile.Bucket, uploadParam.ObjectName, taskId, operator, nowTime, operator, nowTime}}) } - return transaction(actions) + return dao.Transaction(actions) } func DownloadAttachFile(fileId string) (fileContent []byte, fileName string, err error) { @@ -77,13 +116,13 @@ func RemoveAttachFile(fileId string) (fileObj models.AttachFileTable, err error) if err != nil { return } - _, err = x.Exec("delete from attach_file where id=?", fileId) + _, err = dao.X.Exec("delete from attach_file where id=?", fileId) return } func getAttachFileInfo(fileId string) (fileObj models.AttachFileTable, err error) { var attachFileTable []*models.AttachFileTable - err = x.SQL("select * from attach_file where id=?", fileId).Find(&attachFileTable) + err = dao.X.SQL("select * from attach_file where id=?", fileId).Find(&attachFileTable) if err != nil { return fileObj, err } @@ -96,13 +135,13 @@ func getAttachFileInfo(fileId string) (fileObj models.AttachFileTable, err error func GetRequestAttachFileList(requestId string) []*models.AttachFileTable { attachFileTable := []*models.AttachFileTable{} - x.SQL("select id,name from attach_file where request=?", requestId).Find(&attachFileTable) + dao.X.SQL("select id,name from attach_file where request=?", requestId).Find(&attachFileTable) return attachFileTable } func GetTaskAttachFileList(taskId string) []*models.AttachFileTable { attachFileTable := []*models.AttachFileTable{} - x.SQL("select id,name from attach_file where task=?", taskId).Find(&attachFileTable) + dao.X.SQL("select id,name from attach_file where task=?", taskId).Find(&attachFileTable) return attachFileTable } @@ -121,19 +160,19 @@ func CheckAttachFilePermission(fileId, operator, operation string, roles []strin if fileObj.Request != "" { var requestTemplateRoles []*models.RequestTemplateRoleTable if operation == "download" { - x.SQL("select distinct t1.`role` from (select `role` from task_template_role where task_template in (select id from task_template where request_template in (select request_template from request where id=?)) union select `role` from request_template_role where request_template in (select request_template from request where id=?)) t1", fileObj.Request, fileObj.Request).Find(&requestTemplateRoles) + dao.X.SQL("select distinct t1.`role` from (select `role` from task_template_role where task_template in (select id from task_template where request_template in (select request_template from request where id=?)) union select `role` from request_template_role where request_template in (select request_template from request where id=?)) t1", fileObj.Request, fileObj.Request).Find(&requestTemplateRoles) for _, v := range requestTemplateRoles { legalRoles = append(legalRoles, v.Role) } } else { var requestTable []*models.RequestTable - x.SQL("select id,created_by from request where id=?", fileObj.Request).Find(&requestTable) + dao.X.SQL("select id,created_by from request where id=?", fileObj.Request).Find(&requestTable) if len(requestTable) > 0 { if requestTable[0].CreatedBy == operator { return nil } } - x.SQL("select * from request_template_role where request_template in (select request_template from request where id=?)", fileObj.Request).Find(&requestTemplateRoles) + dao.X.SQL("select * from request_template_role where request_template in (select request_template from request where id=?)", fileObj.Request).Find(&requestTemplateRoles) for _, v := range requestTemplateRoles { if v.RoleType == "USE" { legalRoles = append(legalRoles, v.Role) @@ -144,12 +183,12 @@ func CheckAttachFilePermission(fileId, operator, operation string, roles []strin if fileObj.Task != "" { var taskTemplateRoles []*models.TaskTemplateRoleTable if operation == "download" { - x.SQL("select distinct t1.`role` from (select `role` from task_template_role where task_template in (select id from task_template where request_template in (select request_template from request where id in (select request from task where id=?))) union select `role` from request_template_role where request_template in (select request_template from request where id in (select request from task where id=?))) t1", fileObj.Task, fileObj.Task).Find(&taskTemplateRoles) + dao.X.SQL("select distinct t1.`role` from (select `role` from task_template_role where task_template in (select id from task_template where request_template in (select request_template from request where id in (select request from task where id=?))) union select `role` from request_template_role where request_template in (select request_template from request where id in (select request from task where id=?))) t1", fileObj.Task, fileObj.Task).Find(&taskTemplateRoles) for _, v := range taskTemplateRoles { legalRoles = append(legalRoles, v.Role) } } else { - x.SQL("select * from task_template_role where task_template in (select task_template from task where id=?)", fileObj.Task).Find(&taskTemplateRoles) + dao.X.SQL("select * from task_template_role where task_template in (select task_template from task where id=?)", fileObj.Task).Find(&taskTemplateRoles) for _, v := range taskTemplateRoles { legalRoles = append(legalRoles, v.Role) } @@ -176,9 +215,9 @@ func CheckAttachFilePermission(fileId, operator, operation string, roles []strin func getAttachFileRequestTemplate(requestId, taskId string) string { var requestTable []*models.RequestTable if requestId != "" { - x.SQL("select request_template from request where id=?", requestId).Find(&requestTable) + dao.X.SQL("select request_template from request where id=?", requestId).Find(&requestTable) } else { - x.SQL("select request_template from request where id in (select request from task where id=?)", taskId).Find(&requestTable) + dao.X.SQL("select request_template from request where id in (select request from task where id=?)", taskId).Find(&requestTable) } if len(requestTable) > 0 { return requestTable[0].RequestTemplate diff --git a/taskman-server/services/db/collect.go b/taskman-server/service/collect_template_service.go similarity index 84% rename from taskman-server/services/db/collect.go rename to taskman-server/service/collect_template_service.go index 91bd4258..6f1de10f 100644 --- a/taskman-server/services/db/collect.go +++ b/taskman-server/service/collect_template_service.go @@ -1,18 +1,23 @@ -package db +package service import ( "fmt" "github.com/WeBankPartners/go-common-lib/guid" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "sort" "strconv" "time" ) +type CollectTemplateService struct { + collectTemplateDao dao.CollectTemplateDao +} + func AddTemplateCollect(param *models.CollectTemplateTable) error { param.Id = guid.CreateGuid() nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("insert into collect_template(id,request_template,type,user,role,created_time) value (?,?,?,?,?,?)", + _, err := dao.X.Exec("insert into collect_template(id,request_template,type,user,role,created_time) value (?,?,?,?,?,?)", param.Id, param.RequestTemplate, param.Type, param.User, param.Role, nowTime) if err != nil { err = fmt.Errorf("Insert database error:%s ", err.Error()) @@ -21,7 +26,7 @@ func AddTemplateCollect(param *models.CollectTemplateTable) error { } func DeleteTemplateCollect(templateId, user string) error { - _, err := x.Exec("delete from collect_template where request_template = ? and user = ?", templateId, user) + _, err := dao.X.Exec("delete from collect_template where request_template = ? and user = ?", templateId, user) if err != nil { err = fmt.Errorf("Delete database error:%s ", err.Error()) } @@ -46,14 +51,14 @@ func QueryTemplateCollect(param *models.QueryCollectTemplateParam, user, userTok templateType = 0 } // 查询该用户收藏的所有模板id - err = x.SQL("select * from collect_template where user = ? and type = ?", user, templateType).Find(&collectTemplateList) + err = dao.X.SQL("select * from collect_template where user = ? and type = ?", user, templateType).Find(&collectTemplateList) if err != nil { return } // 遍历模板id,查询 当前最新的发布模板id for _, collectTemplate := range collectTemplateList { var tempList []string - x.SQL("select id from request_template where (status='confirm' or status='disable') and parent_id = ? order by created_time desc limit 0,1", collectTemplate.RequestTemplate).Find(&tempList) + dao.X.SQL("select id from request_template where (status='confirm' or status='disable') and parent_id = ? order by created_time desc limit 0,1", collectTemplate.RequestTemplate).Find(&tempList) resultList = append(resultList, tempList...) roleTemplateMap[collectTemplate.RequestTemplate] = collectTemplate.Role } @@ -65,7 +70,7 @@ func QueryTemplateCollect(param *models.QueryCollectTemplateParam, user, userTok "join request_template_group rtg on rt.group= rtg.id where rt.id in ("+getSQL(resultList)+")) t %s", transCollectConditionToSQL(param)) // 排序处理 if param.Sorting != nil { - hashMap, _ := getJsonToXormMap(models.CollectDataObj{}) + hashMap, _ := dao.GetJsonToXormMap(models.CollectDataObj{}) if len(hashMap) > 0 { if param.Sorting.Asc { sql += fmt.Sprintf(" ORDER BY %s ASC", hashMap[param.Sorting.Field]) @@ -77,8 +82,8 @@ func QueryTemplateCollect(param *models.QueryCollectTemplateParam, user, userTok // 分页处理 pageInfo.PageSize = param.PageSize pageInfo.StartIndex = param.StartIndex - pageInfo.TotalRows = queryCount(sql) - err = x.SQL(sql+" limit ?,?", param.StartIndex, param.PageSize).Find(&rowData) + pageInfo.TotalRows = dao.QueryCount(sql) + err = dao.X.SQL(sql+" limit ?,?", param.StartIndex, param.PageSize).Find(&rowData) if err != nil { return } @@ -142,7 +147,7 @@ func compare(v1, v2 string) int { func getAllDisableTemplateVersionMap() map[string]string { var hashMap = make(map[string]string) var list []*models.RequestTemplateTable - x.SQL("select * from request_template where status = 'disable'").Find(&list) + dao.X.SQL("select * from request_template where status = 'disable'").Find(&list) if len(list) > 0 { for _, requestTemplate := range list { hashMap[requestTemplate.ParentId] = requestTemplate.Version @@ -154,7 +159,7 @@ func getAllDisableTemplateVersionMap() map[string]string { func QueryAllTemplateCollect(user string) (collectMap map[string]bool, err error) { collectMap = make(map[string]bool) var idList []string - err = x.SQL("select request_template from collect_template where user = ?", user).Find(&idList) + err = dao.X.SQL("select request_template from collect_template where user = ?", user).Find(&idList) if err != nil { return } @@ -177,7 +182,7 @@ func GetCollectFilterItem(param *models.FilterRequestParam, user string) (data * var useRoleMap = make(map[string]bool) var sql = "select rt.id,rt.name,rtg.id as template_group_id,rtg.name as template_group ,rt.operator_obj_type,rt.proc_def_name,rtg.manage_role,rt.handler as owner,rt.tags,rt.created_time from request_template rt " + "join request_template_group rtg on rt.group= rtg.id where rt.id in (select request_template from collect_template where user = ?) and rt.created_time > ?" - err = x.SQL(sql, user, param.StartTime).Find(&rowsData) + err = dao.X.SQL(sql, user, param.StartTime).Find(&rowsData) if err != nil { return } @@ -190,7 +195,7 @@ func GetCollectFilterItem(param *models.FilterRequestParam, user string) (data * tagMap[row.Tags] = true manageRoleMap[row.ManageRole] = true var roleList []string - err = x.SQL("select role from request_template_role where role_type='USE' and request_template= ?", row.Id).Find(&roleList) + err = dao.X.SQL("select role from request_template_role where role_type='USE' and request_template= ?", row.Id).Find(&roleList) if err != nil || len(roleList) == 0 { continue } @@ -236,7 +241,7 @@ func GetCollectFilterItem(param *models.FilterRequestParam, user string) (data * // CheckUserCollectExist 检查用户模板id是否收藏 func CheckUserCollectExist(templateId, user string) bool { var idList []string - err := x.SQL("select id from collect_template where request_template=? and user=?", templateId, user).Find(&idList) + err := dao.X.SQL("select id from collect_template where request_template=? and user=?", templateId, user).Find(&idList) if err != nil { return true } diff --git a/taskman-server/services/db/cron.go b/taskman-server/service/cron.go similarity index 78% rename from taskman-server/services/db/cron.go rename to taskman-server/service/cron.go index b153cf38..5be01652 100644 --- a/taskman-server/services/db/cron.go +++ b/taskman-server/service/cron.go @@ -1,7 +1,8 @@ -package db +package service import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "time" ) @@ -22,7 +23,7 @@ func startNotifyCronJob() { func notifyAction() { log.Logger.Info("Start notify action") var taskTable []*models.TaskTable - err := x.SQL("select id,created_time,expire_time,notify_count from task where status<>'done'").Find(&taskTable) + err := dao.X.SQL("select id,created_time,expire_time,notify_count from task where status<>'done'").Find(&taskTable) if err != nil { log.Logger.Error("notify action fail,query task error", log.Error(err)) return @@ -41,7 +42,7 @@ func notifyAction() { if tmpErr != nil { log.Logger.Error("notify task mail fail", log.String("taskId", v.Id), log.Error(tmpErr)) } else { - x.Exec("update task set notify_count=? where id=?", v.NotifyCount+1, v.Id) + dao.X.Exec("update task set notify_count=? where id=?", v.NotifyCount+1, v.Id) } } } diff --git a/taskman-server/services/db/form_template.go b/taskman-server/service/form_template_service.go similarity index 71% rename from taskman-server/services/db/form_template.go rename to taskman-server/service/form_template_service.go index fc45390d..8f667f33 100644 --- a/taskman-server/services/db/form_template.go +++ b/taskman-server/service/form_template_service.go @@ -1,14 +1,19 @@ -package db +package service import ( "fmt" "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "strconv" "time" ) +type FormTemplateService struct { + formTemplateDao dao.FormTemplateDao +} + func GetRequestFormTemplate(id string) (result models.FormTemplateDto, err error) { result = models.FormTemplateDto{Items: []*models.FormItemTemplateTable{}} requestTemplate, getErr := GetSimpleRequestTemplate(id) @@ -17,7 +22,7 @@ func GetRequestFormTemplate(id string) (result models.FormTemplateDto, err error return } var formTemplateTable []*models.FormTemplateTable - err = x.SQL("select * from form_template where id=?", requestTemplate.FormTemplate).Find(&formTemplateTable) + err = dao.X.SQL("select * from form_template where id=?", requestTemplate.FormTemplate).Find(&formTemplateTable) if err != nil { err = fmt.Errorf("Try to query form template table fail,%s ", err.Error()) return @@ -33,7 +38,7 @@ func GetRequestFormTemplate(id string) (result models.FormTemplateDto, err error result.UpdatedTime = formTemplateTable[0].UpdatedTime result.UpdatedBy = formTemplateTable[0].UpdatedBy var formItemTemplate []*models.FormItemTemplateTable - x.SQL("select * from form_item_template where form_template=?", requestTemplate.FormTemplate).Find(&formItemTemplate) + dao.X.SQL("select * from form_item_template where form_template=?", requestTemplate.FormTemplate).Find(&formItemTemplate) result.Items = formItemTemplate return } @@ -41,19 +46,19 @@ func GetRequestFormTemplate(id string) (result models.FormTemplateDto, err error func CreateRequestFormTemplate(param models.FormTemplateDto, requestTemplateId string) error { param.NowTime = time.Now().Format(models.DateTimeFormat) insertFormActions, formId := getFormTemplateCreateActions(param) - insertFormActions = append(insertFormActions, &execAction{Sql: "update request_template set form_template=?,expire_day=?,description=? where id=?", Param: []interface{}{formId, param.ExpireDay, param.Description, requestTemplateId}}) - return transactionWithoutForeignCheck(insertFormActions) + insertFormActions = append(insertFormActions, &dao.ExecAction{Sql: "update request_template set form_template=?,expire_day=?,description=? where id=?", Param: []interface{}{formId, param.ExpireDay, param.Description, requestTemplateId}}) + return dao.TransactionWithoutForeignCheck(insertFormActions) } -func getFormTemplateCreateActions(param models.FormTemplateDto) (actions []*execAction, id string) { +func getFormTemplateCreateActions(param models.FormTemplateDto) (actions []*dao.ExecAction, id string) { param.Id = guid.CreateGuid() id = param.Id itemIds := guid.CreateGuidList(len(param.Items)) - insertAction := execAction{Sql: "insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?)"} + insertAction := dao.ExecAction{Sql: "insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?)"} insertAction.Param = []interface{}{param.Id, param.Name, param.Description, param.UpdatedBy, param.NowTime, param.UpdatedBy, param.NowTime} actions = append(actions, &insertAction) for i, item := range param.Items { - tmpAction := execAction{Sql: "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} + tmpAction := dao.ExecAction{Sql: "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} tmpAction.Param = []interface{}{itemIds[i], id, item.Name, item.Description, item.ItemGroup, item.ItemGroupName, item.DefaultValue, item.Sort, item.PackageName, item.Entity, item.AttrDefId, item.AttrDefName, item.AttrDefDataType, item.ElementType, item.Title, item.Width, item.RefPackageName, item.RefEntity, item.DataOptions, item.Required, item.Regular, item.IsEdit, item.IsView, item.IsOutput, item.InDisplayName, item.IsRefInside, item.Multiple, item.DefaultClear} actions = append(actions, &tmpAction) } @@ -66,13 +71,13 @@ func UpdateRequestFormTemplate(param models.FormTemplateDto) error { if err != nil { return err } - updateActions = append(updateActions, &execAction{Sql: "update request_template set expire_day=?,description=? where form_template=?", Param: []interface{}{param.ExpireDay, param.Description, param.Id}}) - return transaction(updateActions) + updateActions = append(updateActions, &dao.ExecAction{Sql: "update request_template set expire_day=?,description=? where form_template=?", Param: []interface{}{param.ExpireDay, param.Description, param.Id}}) + return dao.Transaction(updateActions) } -func getFormTemplateUpdateActions(param models.FormTemplateDto) (actions []*execAction, err error) { +func getFormTemplateUpdateActions(param models.FormTemplateDto) (actions []*dao.ExecAction, err error) { var formTemplateTable []*models.FormTemplateTable - err = x.SQL("select id,updated_time from form_template where id=?", param.Id).Find(&formTemplateTable) + err = dao.X.SQL("select id,updated_time from form_template where id=?", param.Id).Find(&formTemplateTable) if err != nil { err = fmt.Errorf("Try to query form template table fail,%s ", err.Error()) return @@ -85,14 +90,14 @@ func getFormTemplateUpdateActions(param models.FormTemplateDto) (actions []*exec err = fmt.Errorf("Update time validate fail,please refersh data ") return } - updateAction := execAction{Sql: "update form_template set name=?,description=?,updated_by=?,updated_time=? where id=?"} + updateAction := dao.ExecAction{Sql: "update form_template set name=?,description=?,updated_by=?,updated_time=? where id=?"} updateAction.Param = []interface{}{param.Name, param.Description, param.UpdatedBy, param.NowTime, param.Id} actions = append(actions, &updateAction) newItemGuidList := guid.CreateGuidList(len(param.Items)) var formItemTemplate []*models.FormItemTemplateTable - x.SQL("select id from form_item_template where form_template=?", param.Id).Find(&formItemTemplate) + dao.X.SQL("select id from form_item_template where form_template=?", param.Id).Find(&formItemTemplate) for i, inputItem := range param.Items { - tmpAction := execAction{} + tmpAction := dao.ExecAction{} if inputItem.Id == "" { inputItem.Id = newItemGuidList[i] tmpAction.Sql = "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" @@ -112,15 +117,15 @@ func getFormTemplateUpdateActions(param models.FormTemplateDto) (actions []*exec } } if !existFlag { - actions = append(actions, &execAction{Sql: "delete from form_item where form_item_template=?", Param: []interface{}{existItem.Id}}) - actions = append(actions, &execAction{Sql: "delete from form_item_template where id=?", Param: []interface{}{existItem.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item where form_item_template=?", Param: []interface{}{existItem.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item_template where id=?", Param: []interface{}{existItem.Id}}) } } return } func DeleteRequestFormTemplate(id string) error { - _, err := x.Exec("update form_template set del_flag=1 where id=?", id) + _, err := dao.X.Exec("update form_template set del_flag=1 where id=?", id) return err } diff --git a/taskman-server/services/db/ref_select.go b/taskman-server/service/ref_select_service.go similarity index 94% rename from taskman-server/services/db/ref_select.go rename to taskman-server/service/ref_select_service.go index e2fb7733..d9b25830 100644 --- a/taskman-server/services/db/ref_select.go +++ b/taskman-server/service/ref_select_service.go @@ -1,16 +1,20 @@ -package db +package service import ( "bytes" "encoding/json" "fmt" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "io/ioutil" "net/http" "strings" ) +type RefSelectService struct { +} + func GetCMDBRefSelectResult(input *models.RefSelectParam) (result []*models.EntityDataObj, err error) { result = []*models.EntityDataObj{} // if param map data have no new data -> get remote data + same entity new data @@ -55,7 +59,7 @@ func checkIfNeedAnalyze(input *models.RefSelectParam) (refFlag int, options []*m } var formItemTemplates []*models.FormItemTemplateTable //x.SQL("select id,name,ref_package_name,ref_entity,data_options from form_item_template where entity=? and form_template in (select form_template from request_template where id in (select request_template from request where id=?))", entity, input.RequestId).Find(&formItemTemplates) - x.SQL("select distinct name,ref_package_name,ref_entity,data_options from form_item_template where entity=? and form_template in (select form_template from request_template where id in (select request_template from request where id=?) union select form_template from task_template where id in (select task_template from task where request=?))", entity, input.RequestId, input.RequestId).Find(&formItemTemplates) + dao.X.SQL("select distinct name,ref_package_name,ref_entity,data_options from form_item_template where entity=? and form_template in (select form_template from request_template where id in (select request_template from request where id=?) union select form_template from task_template where id in (select task_template from task where request=?))", entity, input.RequestId, input.RequestId).Find(&formItemTemplates) refColumnMap := make(map[string]int) for _, v := range formItemTemplates { if v.Name == attrName { @@ -173,7 +177,7 @@ func getCMDBRefData(input *models.RefSelectParam) (result []*models.CiReferenceD func getRefSelectEntity(requestId, attrId string) (refEntity string, err error) { var formItemTemplates []*models.FormItemTemplateTable attrSplit := strings.Split(attrId, models.SysTableIdConnector) - x.SQL("select id,ref_package_name,ref_entity from form_item_template where entity=? and name=? and form_template in (select form_template from request_template where id in (select request_template from request where id=?) union select form_template from task_template where request_template in (select request_template from request where id=?))", attrSplit[0], attrSplit[1], requestId, requestId).Find(&formItemTemplates) + dao.X.SQL("select id,ref_package_name,ref_entity from form_item_template where entity=? and name=? and form_template in (select form_template from request_template where id in (select request_template from request where id=?) union select form_template from task_template where request_template in (select request_template from request where id=?))", attrSplit[0], attrSplit[1], requestId, requestId).Find(&formItemTemplates) if len(formItemTemplates) == 0 { return refEntity, fmt.Errorf("Can not find form item template with entity:%s name:%s ", attrSplit[0], attrSplit[1]) } @@ -541,7 +545,7 @@ func FilterInSideData(input []*models.EntityDataObj, attrId, requestId string) ( output = input attrSplit := strings.Split(attrId, models.SysTableIdConnector) var formItemTemplate []*models.FormItemTemplateTable - x.SQL("select * from form_item_template where entity=? and name=? and form_template in (select form_template from request_template where id in (select request_template from request where id=?))", attrSplit[0], attrSplit[1], requestId).Find(&formItemTemplate) + dao.X.SQL("select * from form_item_template where entity=? and name=? and form_template in (select form_template from request_template where id in (select request_template from request where id=?))", attrSplit[0], attrSplit[1], requestId).Find(&formItemTemplate) if len(formItemTemplate) == 0 { return output } @@ -549,7 +553,7 @@ func FilterInSideData(input []*models.EntityDataObj, attrId, requestId string) ( return output } var formItems []*models.FormItemTable - x.SQL("select distinct row_data_id from form_item where form in (select form from request where id=?)", requestId).Find(&formItems) + dao.X.SQL("select distinct row_data_id from form_item where form in (select form from request where id=?)", requestId).Find(&formItems) rowDataMap := make(map[string]int) for _, v := range formItems { tmpV := v.RowDataId diff --git a/taskman-server/services/db/request.go b/taskman-server/service/request_service.go similarity index 89% rename from taskman-server/services/db/request.go rename to taskman-server/service/request_service.go index 5b7ace9c..6df6366d 100644 --- a/taskman-server/services/db/request.go +++ b/taskman-server/service/request_service.go @@ -1,4 +1,4 @@ -package db +package service import ( "bytes" @@ -7,6 +7,7 @@ import ( "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "github.com/tealeg/xlsx" "io/ioutil" @@ -19,6 +20,10 @@ import ( "time" ) +type RequestService struct { + requestDao dao.RequestDao +} + const ( InProgress ProgressStatus = 1 // 进行中 NotStart ProgressStatus = 2 // 未开始 @@ -122,7 +127,7 @@ func GetRequestCount(user string, userRoles []string) (platformData models.Platf // GetPendingCount 统计待处理,包括:(1)待定版 (2)任务待审批 分配给本组、本人的所有请求,此处按照角色去统计 func GetPendingCount(userRoles []string) (resultArr []string) { - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") var requestQueryParam, taskQueryParam []interface{} var roleFilterList []string var requestSQL, taskSQL string @@ -136,7 +141,7 @@ func GetPendingCount(userRoles []string) (resultArr []string) { for i := 0; i < len(templateTypeArr); i++ { requestSQL, requestQueryParam = pendingRequestSQL(templateTypeArr[i], userRolesFilterSql, userRolesFilterParam) taskSQL, taskQueryParam = pendingTaskSQL(templateTypeArr[i], userRolesFilterSql, userRolesFilterParam, roleFilterSql) - resultArr = append(resultArr, strconv.Itoa(queryCount(requestSQL, requestQueryParam...)+queryCount(taskSQL, taskQueryParam...))) + resultArr = append(resultArr, strconv.Itoa(dao.QueryCount(requestSQL, requestQueryParam...)+dao.QueryCount(taskSQL, taskQueryParam...))) } return } @@ -164,7 +169,7 @@ func GetHasProcessedCount(user string) (resultArr []string) { for i := 0; i < len(templateTypeArr); i++ { requestSQL, requestQueryParam = hasProcessedRequestSQL(templateTypeArr[i], user) taskSQL, taskQueryParam = hasProcessedTaskSQL(templateTypeArr[i], user) - resultArr = append(resultArr, strconv.Itoa(queryCount(requestSQL, requestQueryParam...)+queryCount(taskSQL, taskQueryParam...))) + resultArr = append(resultArr, strconv.Itoa(dao.QueryCount(requestSQL, requestQueryParam...)+dao.QueryCount(taskSQL, taskQueryParam...))) } return } @@ -188,7 +193,7 @@ func GetSubmitCount(user string) (resultArr []string) { var sql string for i := 0; i < len(templateTypeArr); i++ { sql, queryParam = submitSQL(0, templateTypeArr[i], user) - resultArr = append(resultArr, strconv.Itoa(queryCount(sql, queryParam...))) + resultArr = append(resultArr, strconv.Itoa(dao.QueryCount(sql, queryParam...))) } return } @@ -215,7 +220,7 @@ func GetDraftCount(user string) (resultArr []string) { var sql string for i := 0; i < len(templateTypeArr); i++ { sql, queryParam = draftSQL(templateTypeArr[i], user) - resultArr = append(resultArr, strconv.Itoa(queryCount(sql, queryParam...))) + resultArr = append(resultArr, strconv.Itoa(dao.QueryCount(sql, queryParam...))) } return } @@ -232,7 +237,7 @@ func GetCollectCount(user string) (resultArr []string) { var sql string for i := 0; i < len(templateTypeArr); i++ { sql, queryParam = collectSQL(templateTypeArr[i], user) - resultArr = append(resultArr, strconv.Itoa(queryCount(sql, queryParam...))) + resultArr = append(resultArr, strconv.Itoa(dao.QueryCount(sql, queryParam...))) } return } @@ -255,7 +260,7 @@ func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, } else if param.Action == 2 { templateType = 0 } - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") switch param.Tab { case "pending": var roleFilterList []string @@ -300,7 +305,7 @@ func HistoryList(param *models.RequestHistoryParam, userRoles []string, userToke where := transHistoryConditionToSQL(param) // 查看本组数据 if param.Permission == "group" { - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") sql = "select id from request where `role` in (" + userRolesFilterSql + ")" queryParam = append(queryParam, userRolesFilterParam...) } @@ -525,7 +530,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m var operatorObjTypeMap = make(map[string]string) // 排序处理 if req.Param.Sorting != nil { - hashMap, _ := getJsonToXormMap(models.PlatformDataObj{}) + hashMap, _ := dao.GetJsonToXormMap(models.PlatformDataObj{}) if len(hashMap) > 0 { if req.Param.Sorting.Asc { newSQL += fmt.Sprintf(" ORDER BY %s ASC ", hashMap[req.Param.Sorting.Field]) @@ -538,12 +543,12 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m if page { pageInfo.StartIndex = req.Param.StartIndex pageInfo.PageSize = req.Param.PageSize - pageInfo.TotalRows = queryCount(newSQL, req.QueryParam...) + pageInfo.TotalRows = dao.QueryCount(newSQL, req.QueryParam...) pageSQL := newSQL + " limit ?,? " req.QueryParam = append(req.QueryParam, req.Param.StartIndex, req.Param.PageSize) - err = x.SQL(pageSQL, req.QueryParam...).Find(&rowsData) + err = dao.X.SQL(pageSQL, req.QueryParam...).Find(&rowsData) } else { - err = x.SQL(newSQL, req.QueryParam...).Find(&rowsData) + err = dao.X.SQL(newSQL, req.QueryParam...).Find(&rowsData) } if len(rowsData) > 0 { // 操作对象类型,新增模板是录入.历史模板操作对象类型为空,需要全量处理下 @@ -551,7 +556,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m // 查询当前用户所有收藏模板记录 collectMap, _ := QueryAllTemplateCollect(req.User) templateMap, _ := getAllRequestTemplate() - var actions []*execAction + var actions []*dao.ExecAction for _, platformDataObj := range rowsData { // 获取 使用编排 if len(templateMap) > 0 && templateMap[platformDataObj.TemplateId] != nil { @@ -578,7 +583,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m newStatus = "Termination" } if newStatus != "" && newStatus != platformDataObj.Status { - actions = append(actions, &execAction{Sql: "update request set status=?,updated_time=? where id=?", + actions = append(actions, &dao.ExecAction{Sql: "update request set status=?,updated_time=? where id=?", Param: []interface{}{newStatus, time.Now().Format(models.DateTimeFormat), platformDataObj.Id}}) platformDataObj.Status = newStatus } @@ -597,7 +602,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m for _, entity := range result.Data { if entity.Id == cacheObj.RootEntityId { platformDataObj.OperatorObj = entity.DisplayName - actions = append(actions, &execAction{Sql: "update request set operator_obj=? where id=?", Param: []interface{}{platformDataObj.OperatorObj, platformDataObj.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "update request set operator_obj=? where id=?", Param: []interface{}{platformDataObj.OperatorObj, platformDataObj.Id}}) } } } @@ -607,7 +612,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m calcRequestStayTime(platformDataObj) } if len(actions) > 0 { - updateRequestErr := transaction(actions) + updateRequestErr := dao.Transaction(actions) if updateRequestErr != nil { log.Logger.Error("Try to update request status fail", log.Error(updateRequestErr)) } @@ -623,22 +628,22 @@ func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, } else { permission = "USE" } - filterSql, _, queryParam := transFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTable{}, PrimaryKey: "id"}) - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") + filterSql, _, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTable{}, PrimaryKey: "id"}) + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") baseSql := fmt.Sprintf("select id,name,form,request_template,proc_instance_id,proc_instance_key,reporter,handler,report_time,emergency,status,expire_time,expect_time,confirm_time,created_by,created_time,updated_by,updated_time,rollback_desc from request where del_flag=0 and (created_by=? or request_template in (select id from request_template where id in (select request_template from request_template_role where role_type=? and `role` in ("+userRolesFilterSql+")))) %s ", filterSql) queryParam = append(append([]interface{}{operator, permission}, userRolesFilterParam...), queryParam...) if param.Paging { pageInfo.StartIndex = param.Pageable.StartIndex pageInfo.PageSize = param.Pageable.PageSize - pageInfo.TotalRows = queryCount(baseSql, queryParam...) - pageSql, pageParam := transPageInfoToSQL(*param.Pageable) + pageInfo.TotalRows = dao.QueryCount(baseSql, queryParam...) + pageSql, pageParam := dao.TransPageInfoToSQL(*param.Pageable) baseSql += pageSql queryParam = append(queryParam, pageParam...) } - err = x.SQL(baseSql, queryParam...).Find(&rowData) + err = dao.X.SQL(baseSql, queryParam...).Find(&rowData) if len(rowData) > 0 { var requestTemplateTable []*models.RequestTemplateTable - x.SQL("select id,name,status,version from request_template").Find(&requestTemplateTable) + dao.X.SQL("select id,name,status,version from request_template").Find(&requestTemplateTable) rtMap := make(map[string]string) for _, v := range requestTemplateTable { if v.Status != "confirm" { @@ -648,7 +653,7 @@ func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, } } rtRoleMap := getRequestTemplateMGMTRole() - var actions []*execAction + var actions []*dao.ExecAction for _, v := range rowData { v.RequestTemplateName = rtMap[v.RequestTemplate] if tmpRoles, b := rtRoleMap[v.RequestTemplate]; b { @@ -662,7 +667,7 @@ func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, newStatus = "Termination" } if newStatus != "" && newStatus != v.Status { - actions = append(actions, &execAction{Sql: "update request set status=? where id=?", Param: []interface{}{newStatus, v.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "update request set status=? where id=?", Param: []interface{}{newStatus, v.Id}}) v.Status = newStatus } } @@ -671,7 +676,7 @@ func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, } } if len(actions) > 0 { - updateStatusErr := transaction(actions) + updateStatusErr := dao.Transaction(actions) if updateStatusErr != nil { log.Logger.Error("Try to update request status fail", log.Error(updateStatusErr)) } @@ -683,7 +688,7 @@ func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, func getRequestTemplateMGMTRole() (result map[string][]string) { result = make(map[string][]string) var requestTemplateRole []*models.RequestTemplateRoleTable - x.SQL("select * from request_template_role where role_type='MGMT' order by request_template").Find(&requestTemplateRole) + dao.X.SQL("select * from request_template_role where role_type='MGMT' order by request_template").Find(&requestTemplateRole) if len(requestTemplateRole) == 0 { return result } @@ -889,14 +894,14 @@ func RevokeRequest(requestId, user string) (err error) { err = fmt.Errorf("request not yours") return } - _, err = x.Exec("update request set status ='Draft',revoke_flag=1,updated_time=? where id=?", nowTime, request.Id) + _, err = dao.X.Exec("update request set status ='Draft',revoke_flag=1,updated_time=? where id=?", nowTime, request.Id) return } func GetRequestWithRoot(requestId string) (result models.RequestTable, err error) { result = models.RequestTable{} var requestTable []*models.RequestTable - err = x.SQL("select id,name,form,request_template,proc_instance_id,proc_instance_key,reporter,report_time,emergency,status,cache,expire_time,expect_time,confirm_time,handler from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select id,name,form,request_template,proc_instance_id,proc_instance_key,reporter,report_time,emergency,status,cache,expire_time,expect_time,confirm_time,handler from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -921,7 +926,7 @@ func GetRequestWithRoot(requestId string) (result models.RequestTable, err error func GetRequest(requestId string) (result models.RequestTable, err error) { result = models.RequestTable{} var requestTable []*models.RequestTable - err = x.SQL("select id,name,form,request_template,proc_instance_id,proc_instance_key,reporter,report_time,emergency,status from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select id,name,form,request_template,proc_instance_id,proc_instance_key,reporter,report_time,emergency,status from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -938,7 +943,7 @@ func CreateRequest(param *models.RequestTable, operatorRoles []string, userToken if err != nil { return err } - var actions []*execAction + var actions []*dao.ExecAction err = SyncProcDefId(requestTemplateObj.Id, requestTemplateObj.ProcDefId, requestTemplateObj.ProcDefName, "", userToken) if err != nil { return fmt.Errorf("Try to sync proDefId fail,%s ", err.Error()) @@ -946,28 +951,28 @@ func CreateRequest(param *models.RequestTable, operatorRoles []string, userToken nowTime := time.Now().Format(models.DateTimeFormat) formGuid := guid.CreateGuid() param.Id = newRequestId() - formInsertAction := execAction{Sql: "insert into form(id,name,description,form_template,created_time,created_by,updated_time,updated_by) value (?,?,?,?,?,?,?,?)"} + formInsertAction := dao.ExecAction{Sql: "insert into form(id,name,description,form_template,created_time,created_by,updated_time,updated_by) value (?,?,?,?,?,?,?,?)"} formInsertAction.Param = []interface{}{formGuid, param.Name + models.SysTableIdConnector + "form", "", requestTemplateObj.FormTemplate, nowTime, param.CreatedBy, nowTime, param.CreatedBy} actions = append(actions, &formInsertAction) - requestInsertAction := execAction{Sql: "insert into request(id,name,form,request_template,reporter,emergency,report_role,status,expire_time," + + requestInsertAction := dao.ExecAction{Sql: "insert into request(id,name,form,request_template,reporter,emergency,report_role,status,expire_time," + "expect_time,handler,created_by,created_time,updated_by,updated_time,type,role) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} requestInsertAction.Param = []interface{}{param.Id, param.Name, formGuid, param.RequestTemplate, param.CreatedBy, param.Emergency, strings.Join(operatorRoles, ","), "Draft", "", param.ExpectTime, requestTemplateObj.Handler, param.CreatedBy, nowTime, param.CreatedBy, nowTime, param.Type, param.Role} actions = append(actions, &requestInsertAction) - return transactionWithoutForeignCheck(actions) + return dao.TransactionWithoutForeignCheck(actions) } func UpdateRequest(param *models.RequestTable) error { nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("update request set name=?,expect_time=?,emergency=?,handler=?,updated_by=?,updated_time=? where id=?", param.Name, param.ExpectTime, param.Emergency, param.Handler, param.UpdatedBy, nowTime, param.Id) + _, err := dao.X.Exec("update request set name=?,expect_time=?,emergency=?,handler=?,updated_by=?,updated_time=? where id=?", param.Name, param.ExpectTime, param.Emergency, param.Handler, param.UpdatedBy, nowTime, param.Id) return err } func DeleteRequest(requestId, operator string) error { nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("update request set del_flag=1,updated_by=?,updated_time=? where id=?", operator, nowTime, requestId) + _, err := dao.X.Exec("update request set del_flag=1,updated_by=?,updated_time=? where id=?", operator, nowTime, requestId) return err } @@ -977,7 +982,7 @@ func SaveRequestCacheNew(requestId, operator, userToken string, param *models.Re return err } var formItemNameQuery []*models.FormItemTemplateTable - err = x.SQL("select item_group,group_concat(name,',') as name from form_item_template where in_display_name='yes' and form_template in (select form_template from request_template where id in (select request_template from request where id=?)) group by item_group", requestId).Find(&formItemNameQuery) + err = dao.X.SQL("select item_group,group_concat(name,',') as name from form_item_template where in_display_name='yes' and form_template in (select form_template from request_template where id in (select request_template from request where id=?)) group by item_group", requestId).Find(&formItemNameQuery) itemGroupNameMap := make(map[string][]string) for _, v := range formItemNameQuery { itemGroupNameMap[v.ItemGroup] = strings.Split(v.Name, ",") @@ -1000,8 +1005,8 @@ func SaveRequestCacheNew(requestId, operator, userToken string, param *models.Re } nowTime := time.Now().Format(models.DateTimeFormat) actions := UpdateRequestFormItem(requestId, param) - actions = append(actions, &execAction{Sql: "update request set cache=?,updated_by=?,updated_time=?,operator_obj=? where id=?", Param: []interface{}{string(paramBytes), operator, nowTime, param.EntityName, requestId}}) - return transaction(actions) + actions = append(actions, &dao.ExecAction{Sql: "update request set cache=?,updated_by=?,updated_time=?,operator_obj=? where id=?", Param: []interface{}{string(paramBytes), operator, nowTime, param.EntityName, requestId}}) + return dao.Transaction(actions) } func SaveRequestCacheV2(requestId, operator, userToken string, param *models.RequestProDataV2Dto) error { @@ -1010,7 +1015,7 @@ func SaveRequestCacheV2(requestId, operator, userToken string, param *models.Req return err } var formItemNameQuery []*models.FormItemTemplateTable - err = x.SQL("select item_group,group_concat(name,',') as name from form_item_template where in_display_name='yes' and form_template in (select form_template from request_template where id in (select request_template from request where id=?)) group by item_group", requestId).Find(&formItemNameQuery) + err = dao.X.SQL("select item_group,group_concat(name,',') as name from form_item_template where in_display_name='yes' and form_template in (select form_template from request_template where id in (select request_template from request where id=?)) group by item_group", requestId).Find(&formItemNameQuery) itemGroupNameMap := make(map[string][]string) for _, v := range formItemNameQuery { itemGroupNameMap[v.ItemGroup] = strings.Split(v.Name, ",") @@ -1037,15 +1042,15 @@ func SaveRequestCacheV2(requestId, operator, userToken string, param *models.Req } nowTime := time.Now().Format(models.DateTimeFormat) actions := UpdateRequestFormItem(requestId, newParam) - actions = append(actions, &execAction{Sql: "update request set cache=?,updated_by=?,updated_time=?,name=?,description=?,expect_time=?,operator_obj=?" + + actions = append(actions, &dao.ExecAction{Sql: "update request set cache=?,updated_by=?,updated_time=?,name=?,description=?,expect_time=?,operator_obj=?" + " where id=?", Param: []interface{}{string(paramBytes), operator, nowTime, param.Name, param.Description, param.ExpectTime, param.EntityName, requestId}}) - return transaction(actions) + return dao.Transaction(actions) } func SaveRequestBindCache(requestId, operator string, param *models.RequestCacheData) error { cacheBytes, _ := json.Marshal(param) nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("update request set bind_cache=?,updated_by=?,updated_time=? where id=?", string(cacheBytes), operator, nowTime, requestId) + _, err := dao.X.Exec("update request set bind_cache=?,updated_by=?,updated_time=? where id=?", string(cacheBytes), operator, nowTime, requestId) return err } @@ -1066,10 +1071,10 @@ func concatItemDisplayName(rowData map[string]interface{}, nameList []string) st return strings.Join(displayNameList, "__") } -func UpdateRequestFormItem(requestId string, param *models.RequestPreDataDto) []*execAction { - var actions []*execAction +func UpdateRequestFormItem(requestId string, param *models.RequestPreDataDto) []*dao.ExecAction { + var actions []*dao.ExecAction requestObj, _ := GetRequest(requestId) - actions = append(actions, &execAction{Sql: "delete from form_item where form in (select form from request where id=?)", Param: []interface{}{requestId}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item where form in (select form from request where id=?)", Param: []interface{}{requestId}}) for _, v := range param.Data { for _, valueObj := range v.Value { tmpGuidList := guid.CreateGuidList(len(v.Title)) @@ -1080,10 +1085,10 @@ func UpdateRequestFormItem(requestId string, param *models.RequestPreDataDto) [] for _, interfaceV := range tmpV.([]interface{}) { tmpStringV = append(tmpStringV, fmt.Sprintf("%s", interfaceV)) } - actions = append(actions, &execAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], requestObj.Form, title.Id, title.Name, strings.Join(tmpStringV, ","), title.ItemGroup, valueObj.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], requestObj.Form, title.Id, title.Name, strings.Join(tmpStringV, ","), title.ItemGroup, valueObj.Id}}) } } else { - actions = append(actions, &execAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], requestObj.Form, title.Id, title.Name, valueObj.EntityData[title.Name], title.ItemGroup, valueObj.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], requestObj.Form, title.Id, title.Name, valueObj.EntityData[title.Name], title.ItemGroup, valueObj.Id}}) } } } @@ -1094,7 +1099,7 @@ func UpdateRequestFormItem(requestId string, param *models.RequestPreDataDto) [] func GetRequestCache(requestId, cacheType string) (result interface{}, err error) { var requestTable []*models.RequestTable if cacheType == "data" { - err = x.SQL("select cache from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select cache from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -1109,7 +1114,7 @@ func GetRequestCache(requestId, cacheType string) (result interface{}, err error err = json.Unmarshal([]byte(requestTable[0].Cache), &dataCache) return dataCache, err } else { - err = x.SQL("select bind_cache from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select bind_cache from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -1128,7 +1133,7 @@ func GetRequestCache(requestId, cacheType string) (result interface{}, err error func getRequestTemplateByRequest(requestId string) (templateId string, err error) { var requestTable []*models.RequestTable - err = x.SQL("select request_template from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select request_template from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -1155,14 +1160,14 @@ func GetRequestRootForm(requestId string) (result models.RequestTemplateFormStru result.ProcDefId = requestTemplateObj.ProcDefId result.ProcDefKey = requestTemplateObj.ProcDefKey var items []*models.FormItemTemplateTable - x.SQL("select * from form_item_template where form_template=?", requestTemplateObj.FormTemplate).Find(&items) + dao.X.SQL("select * from form_item_template where form_template=?", requestTemplateObj.FormTemplate).Find(&items) result.FormItems = items return } func GetRequestPreData(requestId, entityDataId, userToken string) (result []*models.RequestPreDataTableObj, err error) { var requestTables []*models.RequestTable - err = x.SQL("select cache from request where id=?", requestId).Find(&requestTables) + err = dao.X.SQL("select cache from request where id=?", requestId).Find(&requestTables) if err != nil { return } @@ -1186,7 +1191,7 @@ func GetRequestPreData(requestId, entityDataId, userToken string) (result []*mod return result, tmpErr } var items []*models.FormItemTemplateTable - err = x.SQL("select * from form_item_template where form_template in (select form_template from request_template where id=?) order by item_group,sort", requestTemplateId).Find(&items) + err = dao.X.SQL("select * from form_item_template where form_template in (select form_template from request_template where id=?) order by item_group,sort", requestTemplateId).Find(&items) if err != nil { return } @@ -1360,7 +1365,7 @@ func sortRequestEntity(param []*models.RequestPreDataTableObj) models.RequestPre func StartRequest(requestId, operator, userToken string, cacheData models.RequestCacheData) (result models.StartInstanceResultData, err error) { var requestTemplateTable []*models.RequestTemplateTable - x.SQL("select * from request_template where id in (select request_template from request where id=?)", requestId).Find(&requestTemplateTable) + dao.X.SQL("select * from request_template where id in (select request_template from request where id=?)", requestId).Find(&requestTemplateTable) if len(requestTemplateTable) == 0 { return result, fmt.Errorf("Can not find requestTemplate with request:%s ", requestId) } @@ -1407,7 +1412,7 @@ func StartRequest(requestId, operator, userToken string, cacheData models.Reques result = respResult.Data nowTime := time.Now().Format(models.DateTimeFormat) expireTime := calcExpireTime(nowTime, requestTemplateTable[0].ExpireDay) - _, err = x.Exec("update request set handler=?,proc_instance_id=?,proc_instance_key=?,confirm_time=?,expire_time=?,status=?,bind_cache=?,updated_by=?,updated_time=? where id=?", operator, strconv.Itoa(result.Id), result.ProcInstKey, nowTime, expireTime, respResult.Data.Status, string(cacheBytes), operator, nowTime, requestId) + _, err = dao.X.Exec("update request set handler=?,proc_instance_id=?,proc_instance_key=?,confirm_time=?,expire_time=?,status=?,bind_cache=?,updated_by=?,updated_time=? where id=?", operator, strconv.Itoa(result.Id), result.ProcInstKey, nowTime, expireTime, respResult.Data.Status, string(cacheBytes), operator, nowTime, requestId) return } @@ -1422,7 +1427,7 @@ func UpdateRequestStatus(requestId, status, operator, userToken, description str } bindCacheBytes, _ := json.Marshal(bindData) bindCache := string(bindCacheBytes) - _, err = x.Exec("update request set status=?,reporter=?,report_time=?,bind_cache=?,updated_by=?,updated_time=?,rollback_desc=null,revoke_flag=0 where id=?", status, operator, nowTime, bindCache, operator, nowTime, requestId) + _, err = dao.X.Exec("update request set status=?,reporter=?,report_time=?,bind_cache=?,updated_by=?,updated_time=?,rollback_desc=null,revoke_flag=0 where id=?", status, operator, nowTime, bindCache, operator, nowTime, requestId) if err == nil { notifyRoleMail(requestId) } @@ -1432,16 +1437,16 @@ func UpdateRequestStatus(requestId, status, operator, userToken, description str err = exterror.New().UpdateRequestHandlerStatusError return err } - _, err = x.Exec("update request set status=?,rollback_desc=?,updated_by=?,handler=?,updated_time=?,confirm_time=? where id=?", status, description, operator, operator, nowTime, nowTime, requestId) + _, err = dao.X.Exec("update request set status=?,rollback_desc=?,updated_by=?,handler=?,updated_time=?,confirm_time=? where id=?", status, description, operator, operator, nowTime, nowTime, requestId) } else { - _, err = x.Exec("update request set status=?,updated_by=?,updated_time=? where id=?", status, operator, nowTime, requestId) + _, err = dao.X.Exec("update request set status=?,updated_by=?,updated_time=? where id=?", status, operator, nowTime, requestId) } return err } func fillBindingWithRequestData(requestId, userToken string, cacheData *models.RequestCacheData, existDepMap map[string][]string) { var items []*models.FormItemTemplateTable - x.SQL("select * from form_item_template where form_template in (select form_template from request_template where id in (select request_template from request where id=?)) order by entity,sort", requestId).Find(&items) + dao.X.SQL("select * from form_item_template where form_template in (select form_template from request_template where id in (select request_template from request where id=?)) order by entity,sort", requestId).Find(&items) itemMap := make(map[string][]string) for _, item := range items { if item.RefEntity == "" { @@ -1687,7 +1692,7 @@ func RequestTermination(requestId, operator, userToken string) error { return fmt.Errorf("Terminate instance fail,%s ", respResult.Message) } nowTime := time.Now().Format(models.DateTimeFormat) - _, err = x.Exec("update request set status='Termination',updated_by=?,updated_time=? where id=?", operator, nowTime, requestId) + _, err = dao.X.Exec("update request set status='Termination',updated_by=?,updated_time=? where id=?", operator, nowTime, requestId) return err } @@ -1717,7 +1722,7 @@ func GetCmdbReferenceData(attrId, userToken string, param models.QueryRequestPar func GetRequestPreBindData(requestId, userToken string) (result models.RequestCacheData, err error) { var requestTable []*models.RequestTable - err = x.SQL("select * from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select * from request where id=?", requestId).Find(&requestTable) if err != nil { return result, fmt.Errorf("Try to query request fail,%s ", err.Error()) } @@ -1773,7 +1778,7 @@ func GetRequestPreBindData(requestId, userToken string) (result models.RequestCa } } var entityNodeBind []*models.EntityNodeBindQueryObj - x.SQL("select distinct t1.node_def_id,t2.item_group from task_template t1 left join form_item_template t2 on t1.form_template=t2.form_template where t1.request_template=?", requestTable[0].RequestTemplate).Find(&entityNodeBind) + dao.X.SQL("select distinct t1.node_def_id,t2.item_group from task_template t1 left join form_item_template t2 on t1.form_template=t2.form_template where t1.request_template=?", requestTable[0].RequestTemplate).Find(&entityNodeBind) for _, v := range entityNodeBind { if _, b := entityBindMap[v.NodeDefId]; b { entityBindMap[v.NodeDefId] = append(entityBindMap[v.NodeDefId], v.ItemGroup) @@ -1825,7 +1830,7 @@ func buildEntityValueAttrData(titles []*models.FormItemTemplateTable, entityData } func RecordRequestTemplateLog(requestTemplateId, requestTemplateName, operator, operation, uri, content string) { - _, err := x.Exec("insert into operation_log(id,request_template,request_template_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", + _, err := dao.X.Exec("insert into operation_log(id,request_template,request_template_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", guid.CreateGuid(), requestTemplateId, requestTemplateName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) if err != nil { log.Logger.Error("Record request operation log fail", log.Error(err)) @@ -1833,7 +1838,7 @@ func RecordRequestTemplateLog(requestTemplateId, requestTemplateName, operator, } func RecordRequestLog(requestId, requestName, operator, operation, uri, content string) { - _, err := x.Exec("insert into operation_log(id,request,request_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", + _, err := dao.X.Exec("insert into operation_log(id,request,request_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", guid.CreateGuid(), requestId, requestName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) if err != nil { log.Logger.Error("Record request operation log fail", log.Error(err)) @@ -1841,7 +1846,7 @@ func RecordRequestLog(requestId, requestName, operator, operation, uri, content } func RecordTaskLog(taskId, taskName, operator, operation, uri, content string) { - _, err := x.Exec("insert into operation_log(id,task,task_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", + _, err := dao.X.Exec("insert into operation_log(id,task,task_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", guid.CreateGuid(), taskId, taskName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) if err != nil { log.Logger.Error("Record request operation log fail", log.Error(err)) @@ -1850,7 +1855,7 @@ func RecordTaskLog(taskId, taskName, operator, operation, uri, content string) { func GetRequestTaskList(requestId string) (result models.TaskQueryResult, err error) { var taskTable []*models.TaskTable - err = x.SQL("select id from task where request=? order by created_time desc", requestId).Find(&taskTable) + err = dao.X.SQL("select id from task where request=? order by created_time desc", requestId).Find(&taskTable) if err != nil { return } @@ -1860,7 +1865,7 @@ func GetRequestTaskList(requestId string) (result models.TaskQueryResult, err er } // get request var requests []*models.RequestTable - x.SQL("select * from request where id=?", requestId).Find(&requests) + dao.X.SQL("select * from request where id=?", requestId).Find(&requests) if len(requests) == 0 { return result, fmt.Errorf("Can not find request with id:%s ", requestId) } @@ -1870,7 +1875,7 @@ func GetRequestTaskList(requestId string) (result models.TaskQueryResult, err er return result, fmt.Errorf("Try to json unmarshal request cache fail,%s ", err.Error()) } var requestTemplateTable []*models.RequestTemplateTable - x.SQL("select * from request_template where id in (select request_template from request where id=?)", requestId).Find(&requestTemplateTable) + dao.X.SQL("select * from request_template where id in (select request_template from request where id=?)", requestId).Find(&requestTemplateTable) requestQuery := models.TaskQueryObj{RequestId: requestId, RequestName: requests[0].Name, Reporter: requests[0].Reporter, ReportTime: requests[0].ReportTime, Comment: requests[0].Result, Editable: false} requestQuery.FormData = requestCache.Data requestQuery.AttachFiles = GetRequestAttachFileList(requestId) @@ -1890,7 +1895,7 @@ func GetRequestTaskList(requestId string) (result models.TaskQueryResult, err er func GetRequestTaskListV2(requestId string) (taskQueryList []*models.TaskQueryObj, err error) { var taskTable []*models.TaskTable - err = x.SQL("select id from task where request=? order by created_time desc", requestId).Find(&taskTable) + err = dao.X.SQL("select id from task where request=? order by created_time desc", requestId).Find(&taskTable) if err != nil { return } @@ -1900,7 +1905,7 @@ func GetRequestTaskListV2(requestId string) (taskQueryList []*models.TaskQueryOb } // get request var requests []*models.RequestTable - x.SQL("select * from request where id=?", requestId).Find(&requests) + dao.X.SQL("select * from request where id=?", requestId).Find(&requests) if len(requests) == 0 { err = fmt.Errorf("Can not find request with id:%s ", requestId) return @@ -1959,8 +1964,8 @@ func GetRequestDetailV2(requestId, userToken string) (result models.RequestDetai // get request var requests []*models.RequestTable var taskQueryList []*models.TaskQueryObj - var actions []*execAction - x.SQL("select * from request where id=?", requestId).Find(&requests) + var actions []*dao.ExecAction + dao.X.SQL("select * from request where id=?", requestId).Find(&requests) if len(requests) == 0 { return result, fmt.Errorf("Can not find request with id:%s ", requestId) } @@ -1970,12 +1975,12 @@ func GetRequestDetailV2(requestId, userToken string) (result models.RequestDetai newStatus = "Termination" } if newStatus != "" && newStatus != requests[0].Status { - actions = append(actions, &execAction{Sql: "update request set status=?,updated_time=? where id=?", + actions = append(actions, &dao.ExecAction{Sql: "update request set status=?,updated_time=? where id=?", Param: []interface{}{newStatus, time.Now().Format(models.DateTimeFormat), requests[0].Id}}) requests[0].Status = newStatus } if len(actions) > 0 { - updateRequestErr := transaction(actions) + updateRequestErr := dao.Transaction(actions) if updateRequestErr != nil { log.Logger.Error("Try to update request status fail", log.Error(updateRequestErr)) } @@ -2298,7 +2303,7 @@ func notifyRoleMail(requestId string) error { } log.Logger.Info("Start notify request mail", log.String("requestId", requestId)) var roleTable []*models.RoleTable - err := x.SQL("select id,email from `role` where id in (select `role` from request_template_role where role_type='MGMT' and request_template in (select request_template from request where id=?))", requestId).Find(&roleTable) + err := dao.X.SQL("select id,email from `role` where id in (select `role` from request_template_role where role_type='MGMT' and request_template in (select request_template from request where id=?))", requestId).Find(&roleTable) if err != nil { return fmt.Errorf("Notify role mail query roles fail,%s ", err.Error()) } @@ -2311,7 +2316,7 @@ func notifyRoleMail(requestId string) error { return nil } var requestTable []*models.RequestTable - x.SQL("select t1.id,t1.name,t2.name as request_template,t1.reporter,t1.report_time,t1.emergency from request t1 left join request_template t2 on t1.request_template=t2.id where t1.id=?", requestId).Find(&requestTable) + dao.X.SQL("select t1.id,t1.name,t2.name as request_template,t1.reporter,t1.report_time,t1.emergency from request t1 left join request_template t2 on t1.request_template=t2.id where t1.id=?", requestId).Find(&requestTable) if len(requestTable) == 0 { return nil } @@ -2330,7 +2335,7 @@ func CopyRequest(requestId, createdBy string) (result models.RequestTable, err e parentRequest := &models.RequestTable{} var requestTable []*models.RequestTable var requestTemplate models.RequestTemplateTable - err = x.SQL("select * from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select * from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -2350,7 +2355,7 @@ func CopyRequest(requestId, createdBy string) (result models.RequestTable, err e parentRequest.ExpectTime = time.Now().Add(d).Format(models.DateTimeFormat) result = *parentRequest var formTable []*models.FormTable - err = x.SQL("select * from form where id=?", parentRequest.Form).Find(&formTable) + err = dao.X.SQL("select * from form where id=?", parentRequest.Form).Find(&formTable) if err != nil { return } @@ -2360,46 +2365,46 @@ func CopyRequest(requestId, createdBy string) (result models.RequestTable, err e } parentForm := formTable[0] var formItemTable []*models.FormItemTable - err = x.SQL("select * from form_item where form=?", parentRequest.Form).Find(&formItemTable) + err = dao.X.SQL("select * from form_item where form=?", parentRequest.Form).Find(&formItemTable) if err != nil { return } - var actions []*execAction + var actions []*dao.ExecAction nowTime := time.Now().Format(models.DateTimeFormat) formGuid := guid.CreateGuid() newRequestId := newRequestId() result.Id = newRequestId - formInsertAction := execAction{Sql: "insert into form(id,name,description,form_template,created_time,created_by,updated_time,updated_by) value (?,?,?,?,?,?,?,?)"} + formInsertAction := dao.ExecAction{Sql: "insert into form(id,name,description,form_template,created_time,created_by,updated_time,updated_by) value (?,?,?,?,?,?,?,?)"} formInsertAction.Param = []interface{}{formGuid, parentRequest.Name + models.SysTableIdConnector + "form", "", parentForm.FormTemplate, nowTime, createdBy, nowTime, createdBy} actions = append(actions, &formInsertAction) - requestInsertAction := execAction{Sql: "insert into request(id,name,form,request_template,reporter,emergency,report_role,status," + + requestInsertAction := dao.ExecAction{Sql: "insert into request(id,name,form,request_template,reporter,emergency,report_role,status," + "cache,expire_time,expect_time,handler,created_by,created_time,updated_by,updated_time,parent,type,role) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} requestInsertAction.Param = []interface{}{newRequestId, parentRequest.Name, formGuid, parentRequest.RequestTemplate, createdBy, parentRequest.Emergency, parentRequest.ReportRole, "Draft", parentRequest.Cache, "", parentRequest.ExpectTime, parentRequest.Handler, createdBy, nowTime, createdBy, nowTime, parentRequest.Id, parentRequest.Type, parentRequest.Role} actions = append(actions, &requestInsertAction) for _, formItemRow := range formItemTable { - actions = append(actions, &execAction{Sql: "INSERT INTO form_item (id,form,form_item_template,name,value,item_group,row_data_id) VALUES (?,?,?,?,?,?,?)", Param: []interface{}{ + actions = append(actions, &dao.ExecAction{Sql: "INSERT INTO form_item (id,form,form_item_template,name,value,item_group,row_data_id) VALUES (?,?,?,?,?,?,?)", Param: []interface{}{ guid.CreateGuid(), formGuid, formItemRow.FormItemTemplate, formItemRow.Name, formItemRow.Value, formItemRow.ItemGroup, formItemRow.RowDataId, }}) } // copy attach file var attachFileRows []*models.AttachFileTable - err = x.SQL("select * from attach_file where request=?", requestId).Find(&attachFileRows) + err = dao.X.SQL("select * from attach_file where request=?", requestId).Find(&attachFileRows) if err != nil { err = fmt.Errorf("query attach file table fail:%s ", err.Error()) return } for _, v := range attachFileRows { - actions = append(actions, &execAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,request,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{ + actions = append(actions, &dao.ExecAction{Sql: "insert into attach_file(id,name,s3_bucket_name,s3_key_name,request,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?)", Param: []interface{}{ guid.CreateGuid(), v.Name, v.S3BucketName, v.S3KeyName, newRequestId, createdBy, nowTime, createdBy, nowTime}}) } - err = transactionWithoutForeignCheck(actions) + err = dao.TransactionWithoutForeignCheck(actions) return } func GetRequestParent(requestId string) (parentRequestId string, err error) { var requestTable []*models.RequestTable - err = x.SQL("select `parent` from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select `parent` from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -2416,7 +2421,7 @@ func newRequestId() (requestId string) { requestId = fmt.Sprintf("%s", time.Now().Format("20060102")) requestIdLock.Lock() defer requestIdLock.Unlock() - result, err := x.QueryString(fmt.Sprintf("select count(1) as num from request where created_time>='%s 00:00:00'", dateString)) + result, err := dao.X.QueryString(fmt.Sprintf("select count(1) as num from request where created_time>='%s 00:00:00'", dateString)) if err != nil { log.Logger.Error("try to new request id fail with count table num", log.Error(err)) requestId = fmt.Sprintf("%s-%s", requestId, guid.CreateGuid()) @@ -2434,7 +2439,7 @@ func newRequestId() (requestId string) { func GetSimpleRequest(requestId string) (request models.RequestTable, err error) { var requestTable []*models.RequestTable - err = x.SQL("select * from request where id=?", requestId).Find(&requestTable) + err = dao.X.SQL("select * from request where id=?", requestId).Find(&requestTable) if err != nil { return } @@ -2447,11 +2452,11 @@ func GetSimpleRequest(requestId string) (request models.RequestTable, err error) // UpdateRequestHandler 请求/发布 认领&转给我逻辑 func UpdateRequestHandler(requestId, user string) (err error) { - var actions []*execAction + var actions []*dao.ExecAction nowTime := time.Now().Format(models.DateTimeFormat) - actions = append(actions, &execAction{Sql: "update request set handler= ?,updated_by= ?,updated_time= ? where id= ?", + actions = append(actions, &dao.ExecAction{Sql: "update request set handler= ?,updated_by= ?,updated_time= ? where id= ?", Param: []interface{}{user, user, nowTime, requestId}}) - err = transaction(actions) + err = dao.Transaction(actions) return } @@ -2571,7 +2576,7 @@ func transCollectConditionToSQL(param *models.QueryCollectTemplateParam) (where } if len(param.UseRole) > 0 { var templateIdList []string - x.SQL("select request_template from request_template_role where role_type='USE' and role in (" + getSQL(param.UseRole) + ")").Find(&templateIdList) + dao.X.SQL("select request_template from request_template_role where role_type='USE' and role in (" + getSQL(param.UseRole) + ")").Find(&templateIdList) if len(templateIdList) > 0 { where = where + " and id in (" + getSQL(templateIdList) + ")" } @@ -2595,7 +2600,7 @@ func getSQL(status []string) string { func getTaskApproveHandler(requestId string, result models.TaskTemplateDto) string { // 审批人以 任务表审批人为主,任务可以认领转给我会修改任务审批人 var taskList []*models.TaskTable - x.SQL("select name,handler,node_def_id,node_name from task where request = ?", requestId).Find(&taskList) + dao.X.SQL("select name,handler,node_def_id,node_name from task where request = ?", requestId).Find(&taskList) if len(taskList) > 0 { for _, task := range taskList { if task.NodeDefId == result.NodeDefId && task.Handler != "" { @@ -2859,7 +2864,7 @@ func getRequestForm(request *models.RequestTable, userToken string) (form models } var tmpTemplate []*models.RequestTemplateTmp var version string - err := x.SQL("select rt.name as template_name,rt.status,rtg.name as template_group_name,rt.version,rt.proc_def_id,rt.expire_day from request_template rt join "+ + err := dao.X.SQL("select rt.name as template_name,rt.status,rtg.name as template_group_name,rt.version,rt.proc_def_id,rt.expire_day from request_template rt join "+ "request_template_group rtg on rt.group = rtg.id where rt.id= ?", request.RequestTemplate).Find(&tmpTemplate) if err != nil { return @@ -2992,9 +2997,9 @@ func GetFilterItem(param models.FilterRequestParam) (data *models.FilterItem, er var handlerMap = make(map[string]bool) var sql = "select rt.id as template_id,rt.name as template_name,rt.version,rt.type as template_type,rt.operator_obj_type,rt.proc_def_name,r.created_by," + "r.handler from request r join request_template rt on r.request_template = rt.id where r.created_time > ?" - err = x.SQL(sql, param.StartTime).Find(&dataList) + err = dao.X.SQL(sql, param.StartTime).Find(&dataList) var handlerList []string - x.SQL("select handler from task_template").Find(&handlerList) + dao.X.SQL("select handler from task_template").Find(&handlerList) if err != nil { return } diff --git a/taskman-server/services/db/request_template.go b/taskman-server/service/request_template_service.go similarity index 74% rename from taskman-server/services/db/request_template.go rename to taskman-server/service/request_template_service.go index 2fb3695c..1cbfff53 100644 --- a/taskman-server/services/db/request_template.go +++ b/taskman-server/service/request_template_service.go @@ -1,4 +1,4 @@ -package db +package service import ( "encoding/json" @@ -6,6 +6,7 @@ import ( "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "io/ioutil" "net/http" @@ -15,21 +16,25 @@ import ( "time" ) +type RequestTemplateService struct { + requestTemplateDao dao.RequestTemplateDao +} + func QueryRequestTemplateGroup(param *models.QueryRequestParam, userRoles []string) (pageInfo models.PageInfo, rowData []*models.RequestTemplateGroupTable, err error) { rowData = []*models.RequestTemplateGroupTable{} - filterSql, queryColumn, queryParam := transFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateGroupTable{}, PrimaryKey: "id"}) - userRoleFilterSql, userRoleFilterParams := createListParams(userRoles, "") + filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateGroupTable{}, PrimaryKey: "id"}) + userRoleFilterSql, userRoleFilterParams := dao.CreateListParams(userRoles, "") baseSql := fmt.Sprintf("SELECT %s FROM request_template_group WHERE manage_role in ("+userRoleFilterSql+") and del_flag=0 %s ", queryColumn, filterSql) queryParam = append(userRoleFilterParams, queryParam...) if param.Paging { pageInfo.StartIndex = param.Pageable.StartIndex pageInfo.PageSize = param.Pageable.PageSize - pageInfo.TotalRows = queryCount(baseSql, queryParam...) - pageSql, pageParam := transPageInfoToSQL(*param.Pageable) + pageInfo.TotalRows = dao.QueryCount(baseSql, queryParam...) + pageSql, pageParam := dao.TransPageInfoToSQL(*param.Pageable) baseSql += pageSql queryParam = append(queryParam, pageParam...) } - err = x.SQL(baseSql, queryParam...).Find(&rowData) + err = dao.X.SQL(baseSql, queryParam...).Find(&rowData) if len(rowData) > 0 { roleMap, _ := getRoleMap() for _, row := range rowData { @@ -44,7 +49,7 @@ func QueryRequestTemplateGroup(param *models.QueryRequestParam, userRoles []stri func CreateRequestTemplateGroup(param *models.RequestTemplateGroupTable) error { param.Id = guid.CreateGuid() nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("insert into request_template_group(id,name,description,manage_role,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?)", + _, err := dao.X.Exec("insert into request_template_group(id,name,description,manage_role,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?)", param.Id, param.Name, param.Description, param.ManageRole, param.CreatedBy, nowTime, param.CreatedBy, nowTime) if err != nil { err = fmt.Errorf("Insert database error:%s ", err.Error()) @@ -54,7 +59,7 @@ func CreateRequestTemplateGroup(param *models.RequestTemplateGroupTable) error { func UpdateRequestTemplateGroup(param *models.RequestTemplateGroupTable) error { nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("update request_template_group set name=?,description =?,manage_role=?,updated_by=?,updated_time=? where id=?", + _, err := dao.X.Exec("update request_template_group set name=?,description =?,manage_role=?,updated_by=?,updated_time=? where id=?", param.Name, param.Description, param.ManageRole, param.UpdatedBy, nowTime, param.Id) if err != nil { err = fmt.Errorf("Update database error:%s ", err.Error()) @@ -63,7 +68,7 @@ func UpdateRequestTemplateGroup(param *models.RequestTemplateGroupTable) error { } func DeleteRequestTemplateGroup(id string) error { - _, err := x.Exec("update request_template_group set del_flag=1 where id=?", id) + _, err := dao.X.Exec("update request_template_group set del_flag=1 where id=?", id) if err != nil { err = fmt.Errorf("Delete database error:%s ", err.Error()) } @@ -71,10 +76,10 @@ func DeleteRequestTemplateGroup(id string) error { } func CheckRequestTemplateGroupRoles(id string, roles []string) error { - rolesFilterSql, rolesFilterParam := createListParams(roles, "") + rolesFilterSql, rolesFilterParam := dao.CreateListParams(roles, "") var requestTemplateGroupRows []*models.RequestTemplateGroupTable rolesFilterParam = append([]interface{}{id}, rolesFilterParam...) - err := x.SQL("select id from request_template_group where id=? and manage_role in ("+rolesFilterSql+")", rolesFilterParam...).Find(&requestTemplateGroupRows) + err := dao.X.SQL("select id from request_template_group where id=? and manage_role in ("+rolesFilterSql+")", rolesFilterParam...).Find(&requestTemplateGroupRows) if err != nil { return fmt.Errorf("Try to query database data fail,%s ", err.Error()) } @@ -325,7 +330,7 @@ func SyncCoreRole() { return } var roleTable, addRoleList, delRoleList []*models.RoleTable - err = x.SQL("select * from role").Find(&roleTable) + err = dao.X.SQL("select * from role").Find(&roleTable) if err != nil { log.Logger.Error("Try to sync core role fail", log.Error(err)) return @@ -354,21 +359,21 @@ func SyncCoreRole() { delRoleList = append(delRoleList, &models.RoleTable{Id: v.Id}) } } - var actions []*execAction + var actions []*dao.ExecAction for _, role := range addRoleList { - actions = append(actions, &execAction{Sql: "insert into `role`(id,display_name,core_id,email,updated_time) value (?,?,?,?,NOW())", Param: []interface{}{role.Id, role.DisplayName, role.CoreId, role.Email}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into `role`(id,display_name,core_id,email,updated_time) value (?,?,?,?,NOW())", Param: []interface{}{role.Id, role.DisplayName, role.CoreId, role.Email}}) } if len(delRoleList) > 0 { roleIdList := []string{} for _, role := range delRoleList { - actions = append(actions, &execAction{Sql: "delete from `role` where id=?", Param: []interface{}{role.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from `role` where id=?", Param: []interface{}{role.Id}}) roleIdList = append(roleIdList, role.Id) } - actions = append(actions, &execAction{Sql: "update form_template set `role`=NULL where `role` in ('" + strings.Join(roleIdList, "','") + "')"}) - actions = append(actions, &execAction{Sql: "update request_template_group set manage_role=NULL where manage_role in ('" + strings.Join(roleIdList, "','") + "')"}) + actions = append(actions, &dao.ExecAction{Sql: "update form_template set `role`=NULL where `role` in ('" + strings.Join(roleIdList, "','") + "')"}) + actions = append(actions, &dao.ExecAction{Sql: "update request_template_group set manage_role=NULL where manage_role in ('" + strings.Join(roleIdList, "','") + "')"}) } if len(actions) > 0 { - err = transactionWithoutForeignCheck(actions) + err = dao.TransactionWithoutForeignCheck(actions) if err != nil { log.Logger.Error("Sync core role fail", log.Error(err)) } @@ -378,10 +383,10 @@ func SyncCoreRole() { func GetRoleList(ids []string) (result []*models.RoleTable, err error) { result = []*models.RoleTable{} if len(ids) == 0 { - err = x.SQL("select * from role").Find(&result) + err = dao.X.SQL("select * from role").Find(&result) } else { - idFilterSql, idFilterParam := createListParams(ids, "") - err = x.SQL("select * from role where id in ("+idFilterSql+")", idFilterParam...).Find(&result) + idFilterSql, idFilterParam := dao.CreateListParams(ids, "") + err = dao.X.SQL("select * from role where id in ("+idFilterSql+")", idFilterParam...).Find(&result) } return } @@ -411,7 +416,7 @@ func QueryRequestTemplate(param *models.QueryRequestParam, userToken string, use } var tmpIds []string var tmpErr error - roleFilterSql, roleFilterParam := createListParams(inValueStringList, "") + roleFilterSql, roleFilterParam := dao.CreateListParams(inValueStringList, "") if v.Name == "mgmtRoles" { tmpIds, tmpErr = getRequestTemplateIdsBySql("select t1.id from request_template t1 left join request_template_role t2 on t1.id=t2.request_template where t2.role_type='MGMT' and t2.role in ("+roleFilterSql+")", roleFilterParam) } else { @@ -432,19 +437,19 @@ func QueryRequestTemplate(param *models.QueryRequestParam, userToken string, use param.Filters = newFilters } rowData := []*models.RequestTemplateTable{} - filterSql, queryColumn, queryParam := transFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateTable{}, PrimaryKey: "id", Prefix: "t1"}) - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") + filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateTable{}, PrimaryKey: "id", Prefix: "t1"}) + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") queryParam = append(userRolesFilterParam, queryParam...) baseSql := fmt.Sprintf("SELECT %s FROM (select * from request_template where del_flag=0 or (del_flag=2 and id not in (select record_id from request_template where del_flag=2 and record_id<>''))) t1 WHERE t1.id in (select request_template from request_template_role where role_type='MGMT' and `role` in ("+userRolesFilterSql+")) %s %s ", queryColumn, extFilterSql, filterSql) if param.Paging { pageInfo.StartIndex = param.Pageable.StartIndex pageInfo.PageSize = param.Pageable.PageSize - pageInfo.TotalRows = queryCount(baseSql, queryParam...) - pageSql, pageParam := transPageInfoToSQL(*param.Pageable) + pageInfo.TotalRows = dao.QueryCount(baseSql, queryParam...) + pageSql, pageParam := dao.TransPageInfoToSQL(*param.Pageable) baseSql += pageSql queryParam = append(queryParam, pageParam...) } - err = x.SQL(baseSql, queryParam...).Find(&rowData) + err = dao.X.SQL(baseSql, queryParam...).Find(&rowData) if len(rowData) == 0 || err != nil { return } @@ -460,7 +465,7 @@ func QueryRequestTemplate(param *models.QueryRequestParam, userToken string, use queryRoleSql += "select t1.id,CONCAT(t2.role,'::',t3.display_name) as 'role_obj' from request_template t1 left join request_template_role t2 on t1.id=t2.request_template left join role t3 on t2.role=t3.id where t1.id in ('" + strings.Join(rtIds, "','") + "') and t2.role_type='USE'" queryRoleSql += ") t4 group by t4.id" var requestTemplateRows []*models.RequestTemplateRoleTable - err = x.SQL(queryRoleSql).Find(&requestTemplateRows) + err = dao.X.SQL(queryRoleSql).Find(&requestTemplateRows) if err != nil { return } @@ -521,9 +526,9 @@ func getRequestTemplateModifyType(requestTemplate *models.RequestTemplateTable) func CheckRequestTemplateRoles(requestTemplateId string, userRoles []string) error { var requestTemplateRoleRows []*models.RequestTemplateRoleTable - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") userRolesFilterParam = append([]interface{}{requestTemplateId}, userRolesFilterParam...) - err := x.SQL("select request_template from request_template_role where request_template=? and role_type='MGMT' and `role` in ("+userRolesFilterSql+")", userRolesFilterParam...).Find(&requestTemplateRoleRows) + err := dao.X.SQL("select request_template from request_template_role where request_template=? and role_type='MGMT' and `role` in ("+userRolesFilterSql+")", userRolesFilterParam...).Find(&requestTemplateRoleRows) if err != nil { return fmt.Errorf("Try to query database data fail:%s ", err.Error()) } @@ -591,10 +596,10 @@ func checkProDefId(proDefId, proDefName, proDefKey, userToken string) (exist boo return } -func getUpdateNodeDefIdActions(requestTemplateId, userToken string) (actions []*execAction) { - actions = []*execAction{} +func getUpdateNodeDefIdActions(requestTemplateId, userToken string) (actions []*dao.ExecAction) { + actions = []*dao.ExecAction{} var taskTemplate []*models.TaskTemplateTable - x.SQL("select * from task_template where request_template=?", requestTemplateId).Find(&taskTemplate) + dao.X.SQL("select * from task_template where request_template=?", requestTemplateId).Find(&taskTemplate) if len(taskTemplate) == 0 { return actions } @@ -609,8 +614,8 @@ func getUpdateNodeDefIdActions(requestTemplateId, userToken string) (actions []* } if nowDefId, b := nodeMap[v.NodeId]; b { if v.NodeDefId != nowDefId { - actions = append(actions, &execAction{Sql: "update task_template set node_def_id=? where node_id=?", Param: []interface{}{nowDefId, v.NodeId}}) - actions = append(actions, &execAction{Sql: "update task set node_def_id=? where task_template=?", Param: []interface{}{nowDefId, v.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "update task_template set node_def_id=? where node_id=?", Param: []interface{}{nowDefId, v.NodeId}}) + actions = append(actions, &dao.ExecAction{Sql: "update task set node_def_id=? where task_template=?", Param: []interface{}{nowDefId, v.Id}}) } } } @@ -623,23 +628,23 @@ func SyncProcDefId(requestTemplateId, proDefId, proDefName, proDefKey, userToken if err != nil { return err } - var actions []*execAction + var actions []*dao.ExecAction if !proExistFlag { if proDefKey != "" { - actions = append(actions, &execAction{Sql: "update request_template set proc_def_id=? where id=?", Param: []interface{}{newProDefId, requestTemplateId}}) + actions = append(actions, &dao.ExecAction{Sql: "update request_template set proc_def_id=? where id=?", Param: []interface{}{newProDefId, requestTemplateId}}) } else { - actions = append(actions, &execAction{Sql: "update request_template set proc_def_id=? where proc_def_name=?", Param: []interface{}{newProDefId, proDefName}}) + actions = append(actions, &dao.ExecAction{Sql: "update request_template set proc_def_id=? where proc_def_name=?", Param: []interface{}{newProDefId, proDefName}}) } - err = transaction(actions) + err = dao.Transaction(actions) if err != nil { return fmt.Errorf("Update requestTemplate procDefId fail,%s ", err.Error()) } log.Logger.Info("Update requestTemplate proDefId done") - actions = []*execAction{} + actions = []*dao.ExecAction{} } tmpActions := getUpdateNodeDefIdActions(requestTemplateId, userToken) if len(tmpActions) > 0 { - err = transaction(tmpActions) + err = dao.Transaction(tmpActions) if err != nil { return fmt.Errorf("Update template node def id fail,%s ", err.Error()) } @@ -650,7 +655,7 @@ func SyncProcDefId(requestTemplateId, proDefId, proDefName, proDefKey, userToken func getRequestTemplateIdsBySql(sql string, param []interface{}) (ids []string, err error) { var requestTemplateTables []*models.RequestTemplateTable - err = x.SQL(sql, param...).Find(&requestTemplateTables) + err = dao.X.SQL(sql, param...).Find(&requestTemplateTables) ids = []string{} for _, v := range requestTemplateTables { ids = append(ids, v.Id) @@ -659,47 +664,47 @@ func getRequestTemplateIdsBySql(sql string, param []interface{}) (ids []string, } func CreateRequestTemplate(param *models.RequestTemplateUpdateParam) (result models.RequestTemplateQueryObj, err error) { - var actions []*execAction + var actions []*dao.ExecAction newGuid := guid.CreateGuid() result = models.RequestTemplateQueryObj{RequestTemplateTable: param.RequestTemplateTable, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} result.Id = newGuid nowTime := time.Now().Format(models.DateTimeFormat) - insertAction := execAction{Sql: "insert into request_template(id,`group`,name,description,tags,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,expire_day,handler,created_by,created_time,updated_by,updated_time,type,operator_obj_type,parent_id) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} + insertAction := dao.ExecAction{Sql: "insert into request_template(id,`group`,name,description,tags,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,expire_day,handler,created_by,created_time,updated_by,updated_time,type,operator_obj_type,parent_id) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} insertAction.Param = []interface{}{newGuid, param.Group, param.Name, param.Description, param.Tags, param.PackageName, param.EntityName, param.ProcDefKey, param.ProcDefId, param.ProcDefName, param.ExpireDay, param.Handler, param.CreatedBy, nowTime, param.CreatedBy, nowTime, param.Type, param.OperatorObjType, newGuid} actions = append(actions, &insertAction) for _, v := range param.MGMTRoles { result.MGMTRoles = append(result.MGMTRoles, &models.RoleTable{Id: v}) - actions = append(actions, &execAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{newGuid + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", newGuid, v, "MGMT"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{newGuid + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", newGuid, v, "MGMT"}}) } for _, v := range param.USERoles { result.USERoles = append(result.USERoles, &models.RoleTable{Id: v}) - actions = append(actions, &execAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{newGuid + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", newGuid, v, "USE"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{newGuid + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", newGuid, v, "USE"}}) } - err = transaction(actions) + err = dao.Transaction(actions) return } func UpdateRequestTemplate(param *models.RequestTemplateUpdateParam) (result models.RequestTemplateQueryObj, err error) { - var actions []*execAction + var actions []*dao.ExecAction nowTime := time.Now().Format(models.DateTimeFormat) result = models.RequestTemplateQueryObj{RequestTemplateTable: param.RequestTemplateTable, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} - updateAction := execAction{Sql: "update request_template set status='created',`group`=?,name=?,description=?,tags=?,package_name=?,entity_name=?,proc_def_key=?,proc_def_id=?,proc_def_name=?,expire_day=?,handler=?,updated_by=?,updated_time=?,type=? where id=?"} + updateAction := dao.ExecAction{Sql: "update request_template set status='created',`group`=?,name=?,description=?,tags=?,package_name=?,entity_name=?,proc_def_key=?,proc_def_id=?,proc_def_name=?,expire_day=?,handler=?,updated_by=?,updated_time=?,type=? where id=?"} updateAction.Param = []interface{}{param.Group, param.Name, param.Description, param.Tags, param.PackageName, param.EntityName, param.ProcDefKey, param.ProcDefId, param.ProcDefName, param.ExpireDay, param.Handler, param.UpdatedBy, nowTime, param.Type, param.Id} actions = append(actions, &updateAction) - actions = append(actions, &execAction{Sql: "delete from request_template_role where request_template=?", Param: []interface{}{param.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from request_template_role where request_template=?", Param: []interface{}{param.Id}}) for _, v := range param.MGMTRoles { result.MGMTRoles = append(result.MGMTRoles, &models.RoleTable{Id: v}) - actions = append(actions, &execAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", param.Id, v, "MGMT"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", param.Id, v, "MGMT"}}) } for _, v := range param.USERoles { result.USERoles = append(result.USERoles, &models.RoleTable{Id: v}) - actions = append(actions, &execAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", param.Id, v, "USE"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", param.Id, v, "USE"}}) } - err = transaction(actions) + err = dao.Transaction(actions) return } -func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*execAction, err error) { +func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*dao.ExecAction, err error) { rtObj, err := GetSimpleRequestTemplate(id) if err != nil { return actions, err @@ -708,36 +713,36 @@ func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*execAction return actions, fmt.Errorf("confirm status can not delete") } var taskTemplateTable []*models.TaskTemplateTable - x.SQL("select id,form_template from task_template where request_template=?", id).Find(&taskTemplateTable) + dao.X.SQL("select id,form_template from task_template where request_template=?", id).Find(&taskTemplateTable) formTemplateIds := []string{rtObj.FormTemplate} for _, v := range taskTemplateTable { formTemplateIds = append(formTemplateIds, v.FormTemplate) } - actions = []*execAction{} + actions = []*dao.ExecAction{} var requestTable []*models.RequestTable - x.SQL("select id,name from request where request_template=?", id).Find(&requestTable) + dao.X.SQL("select id,name from request where request_template=?", id).Find(&requestTable) if len(requestTable) > 0 { var formTable []*models.FormTable - x.SQL("select id from form where form_template in ('" + strings.Join(formTemplateIds, "','") + "')").Find(&formTable) + dao.X.SQL("select id from form where form_template in ('" + strings.Join(formTemplateIds, "','") + "')").Find(&formTable) formIds := []string{} for _, v := range formTable { formIds = append(formIds, v.Id) } //actions = append(actions, &execAction{Sql: "delete from operation_log where task in (select id from task where task_template in (select id from task_template where request_template=?))", Param: []interface{}{id}}) //actions = append(actions, &execAction{Sql: "delete from operation_log where request in (select id from request where request_template=?)", Param: []interface{}{id}}) - actions = append(actions, &execAction{Sql: "delete from task where task_template in (select id from task_template where request_template=?)", Param: []interface{}{id}}) - actions = append(actions, &execAction{Sql: "delete from request where request_template=?", Param: []interface{}{id}}) - actions = append(actions, &execAction{Sql: "delete from form_item where form in ('" + strings.Join(formIds, "','") + "')", Param: []interface{}{}}) - actions = append(actions, &execAction{Sql: "delete from form where form_template in ('" + strings.Join(formTemplateIds, "','") + "')", Param: []interface{}{}}) - } - actions = append(actions, &execAction{Sql: "delete from task_template_role where task_template in (select id from task_template where request_template=?)", Param: []interface{}{id}}) - actions = append(actions, &execAction{Sql: "delete from task_template where request_template=?", Param: []interface{}{id}}) - actions = append(actions, &execAction{Sql: "delete from request_template_role where request_template=?", Param: []interface{}{id}}) - actions = append(actions, &execAction{Sql: "delete from request_template where id=?", Param: []interface{}{id}}) - actions = append(actions, &execAction{Sql: "delete from form_item_template where form_template in ('" + strings.Join(formTemplateIds, "','") + "')", Param: []interface{}{}}) - actions = append(actions, &execAction{Sql: "delete from form_template where id in ('" + strings.Join(formTemplateIds, "','") + "')", Param: []interface{}{}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from task where task_template in (select id from task_template where request_template=?)", Param: []interface{}{id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from request where request_template=?", Param: []interface{}{id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item where form in ('" + strings.Join(formIds, "','") + "')", Param: []interface{}{}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form where form_template in ('" + strings.Join(formTemplateIds, "','") + "')", Param: []interface{}{}}) + } + actions = append(actions, &dao.ExecAction{Sql: "delete from task_template_role where task_template in (select id from task_template where request_template=?)", Param: []interface{}{id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from task_template where request_template=?", Param: []interface{}{id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from request_template_role where request_template=?", Param: []interface{}{id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from request_template where id=?", Param: []interface{}{id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item_template where form_template in ('" + strings.Join(formTemplateIds, "','") + "')", Param: []interface{}{}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_template where id in ('" + strings.Join(formTemplateIds, "','") + "')", Param: []interface{}{}}) if !getActionFlag { - err = transaction(actions) + err = dao.Transaction(actions) } return actions, err } @@ -789,7 +794,7 @@ func ListRequestTemplateEntityAttrs(id, userToken string) (result []*models.Proc func GetRequestTemplateEntityAttrs(id string) (result []*models.ProcEntityAttributeObj, err error) { result = []*models.ProcEntityAttributeObj{} var requestTemplateTable []*models.RequestTemplateTable - err = x.SQL("select entity_attrs from request_template where id=?", id).Find(&requestTemplateTable) + err = dao.X.SQL("select entity_attrs from request_template where id=?", id).Find(&requestTemplateTable) if err != nil { return } @@ -810,13 +815,13 @@ func GetRequestTemplateEntityAttrs(id string) (result []*models.ProcEntityAttrib func UpdateRequestTemplateEntityAttrs(id string, attrs []*models.ProcEntityAttributeObj, operator string) error { b, _ := json.Marshal(attrs) nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("update request_template set entity_attrs=?,updated_time=?,updated_by=? where id=?", string(b), nowTime, operator, id) + _, err := dao.X.Exec("update request_template set entity_attrs=?,updated_time=?,updated_by=? where id=?", string(b), nowTime, operator, id) return err } func GetSimpleRequestTemplate(id string) (result models.RequestTemplateTable, err error) { var requestTemplateTable []*models.RequestTemplateTable - err = x.SQL("select * from request_template where id=?", id).Find(&requestTemplateTable) + err = dao.X.SQL("select * from request_template where id=?", id).Find(&requestTemplateTable) if err != nil { err = fmt.Errorf("Try to query database fail,%s ", err.Error()) return @@ -832,7 +837,7 @@ func GetSimpleRequestTemplate(id string) (result models.RequestTemplateTable, er func GetRequestTemplateManageRole(id string) (role string) { var roleList []string - err := x.SQL("select role from request_template_role where request_template=? and role_type='MGMT'", id).Find(&roleList) + err := dao.X.SQL("select role from request_template_role where request_template=? and role_type='MGMT'", id).Find(&roleList) if err != nil { err = fmt.Errorf("Try to query database fail,%s ", err.Error()) return @@ -844,7 +849,7 @@ func GetRequestTemplateManageRole(id string) (role string) { } func getRequestTemplateRole(templateId string) (requestTemplateRoleList []*models.RequestTemplateRoleTable, err error) { - err = x.SQL("select * from request_template_role where request_template=?", templateId).Find(&requestTemplateRoleList) + err = dao.X.SQL("select * from request_template_role where request_template=?", templateId).Find(&requestTemplateRoleList) if err != nil { err = fmt.Errorf("Try to query database fail,%s ", err.Error()) return @@ -855,7 +860,7 @@ func getRequestTemplateRole(templateId string) (requestTemplateRoleList []*model func getAllRequestTemplate() (templateMap map[string]*models.RequestTemplateTable, err error) { templateMap = make(map[string]*models.RequestTemplateTable) var requestTemplateTable []*models.RequestTemplateTable - err = x.SQL("select * from request_template").Find(&requestTemplateTable) + err = dao.X.SQL("select * from request_template").Find(&requestTemplateTable) if err != nil { err = fmt.Errorf("Try to query database fail,%s ", err.Error()) return @@ -871,7 +876,7 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { if err != nil { return err } - existQuery, tmpErr := x.QueryString("select id,name,version from request_template where del_flag!=1 and record_id=?", requestTemplateObj.Id) + existQuery, tmpErr := dao.X.QueryString("select id,name,version from request_template where del_flag!=1 and record_id=?", requestTemplateObj.Id) if tmpErr != nil { return fmt.Errorf("Query database fail,%s ", tmpErr.Error()) } @@ -882,9 +887,9 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { version := buildVersionNum(requestTemplateObj.Version) newRequestTemplateId := guid.CreateGuid() newRequestFormTemplateId := guid.CreateGuid() - var actions []*execAction + var actions []*dao.ExecAction if requestTemplateObj.ParentId == "" { - actions = append(actions, &execAction{Sql: fmt.Sprintf("insert into request_template(id,`group`,name,description,form_template,"+ + actions = append(actions, &dao.ExecAction{Sql: fmt.Sprintf("insert into request_template(id,`group`,name,description,form_template,"+ "tags,status,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,created_by,created_time,updated_by,updated_time,"+ "entity_attrs,record_id,`version`,confirm_time,expire_day,handler,type,operator_obj_type) select '%s' as id,`group`,name,description,'%s' as form_template,"+ "tags,'created' as status,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,'%s' as created_by,'%s' as created_time,"+ @@ -892,7 +897,7 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { "type,operator_obj_type from request_template where id='%s'", newRequestTemplateId, newRequestFormTemplateId, operator, nowTime, operator, nowTime, requestTemplateObj.Id, version, requestTemplateObj.Id)}) } else { - actions = append(actions, &execAction{Sql: fmt.Sprintf("insert into request_template(id,`group`,name,description,form_template,"+ + actions = append(actions, &dao.ExecAction{Sql: fmt.Sprintf("insert into request_template(id,`group`,name,description,form_template,"+ "tags,status,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,created_by,created_time,updated_by,updated_time,"+ "entity_attrs,record_id,`version`,confirm_time,expire_day,handler,type,operator_obj_type,parent_id) select '%s' as id,`group`,name,"+ "description,'%s' as form_template,tags,'created' as status,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,"+ @@ -906,17 +911,17 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { } actions = append(actions, newRequestFormActions...) var requestTemplateRoles []*models.RequestTemplateRoleTable - x.SQL("select * from request_template_role where request_template=?", requestTemplateObj.Id).Find(&requestTemplateRoles) + dao.X.SQL("select * from request_template_role where request_template=?", requestTemplateObj.Id).Find(&requestTemplateRoles) for _, v := range requestTemplateRoles { tmpId := newRequestTemplateId + models.SysTableIdConnector + v.Role + models.SysTableIdConnector + v.RoleType - actions = append(actions, &execAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{tmpId, newRequestTemplateId, v.Role, v.RoleType}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{tmpId, newRequestTemplateId, v.Role, v.RoleType}}) } var taskTemplates []*models.TaskTemplateTable - x.SQL("select id,form_template from task_template where request_template=?", requestTemplateObj.Id).Find(&taskTemplates) + dao.X.SQL("select id,form_template from task_template where request_template=?", requestTemplateObj.Id).Find(&taskTemplates) newTaskGuids := guid.CreateGuidList(len(taskTemplates)) newTaskFormGuids := guid.CreateGuidList(len(taskTemplates)) for i, task := range taskTemplates { - actions = append(actions, &execAction{Sql: fmt.Sprintf("insert into task_template(id,name,description,form_template,request_template,node_id,node_def_id,node_name,expire_day,handler,created_by,created_time,updated_by,updated_time) select '%s' as id,name,description,'%s' as form_template,'%s' as request_template,node_id,node_def_id,node_name,expire_day,handler,created_by,created_time,updated_by,updated_time from task_template where id='%s'", newTaskGuids[i], newTaskFormGuids[i], newRequestTemplateId, task.Id)}) + actions = append(actions, &dao.ExecAction{Sql: fmt.Sprintf("insert into task_template(id,name,description,form_template,request_template,node_id,node_def_id,node_name,expire_day,handler,created_by,created_time,updated_by,updated_time) select '%s' as id,name,description,'%s' as form_template,'%s' as request_template,node_id,node_def_id,node_name,expire_day,handler,created_by,created_time,updated_by,updated_time from task_template where id='%s'", newTaskGuids[i], newTaskFormGuids[i], newRequestTemplateId, task.Id)}) tmpTaskFormActions, tmpErr := getFormCopyActions(task.FormTemplate, newTaskFormGuids[i]) if tmpErr != nil { err = fmt.Errorf("Try to copy task form fail,%s ", tmpErr.Error()) @@ -933,7 +938,7 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { if err != nil { return err } - return transactionWithoutForeignCheck(actions) + return dao.TransactionWithoutForeignCheck(actions) } func ConfirmRequestTemplate(requestTemplateId string) error { @@ -961,41 +966,41 @@ func ConfirmRequestTemplate(requestTemplateId string) error { if version == "" { version = "v1" } - var actions []*execAction - actions = append(actions, &execAction{Sql: "update request_template set status='confirm',`version`=?,confirm_time=?,del_flag=2,parent_id=? where id=?", Param: []interface{}{version, nowTime, parentId, requestTemplateObj.Id}}) - return transaction(actions) + var actions []*dao.ExecAction + actions = append(actions, &dao.ExecAction{Sql: "update request_template set status='confirm',`version`=?,confirm_time=?,del_flag=2,parent_id=? where id=?", Param: []interface{}{version, nowTime, parentId, requestTemplateObj.Id}}) + return dao.Transaction(actions) } -func getFormCopyActions(oldFormTemplateId, newFormTemplateId string) (actions []*execAction, err error) { +func getFormCopyActions(oldFormTemplateId, newFormTemplateId string) (actions []*dao.ExecAction, err error) { var itemRows []*models.FormItemTemplateTable - err = x.SQL("select id from form_item_template where form_template=?", oldFormTemplateId).Find(&itemRows) + err = dao.X.SQL("select id from form_item_template where form_template=?", oldFormTemplateId).Find(&itemRows) if err != nil { return } - actions = append(actions, &execAction{Sql: fmt.Sprintf("insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) select '%s' as id,name,description,created_by,created_time,updated_by,updated_time from form_template where id='%s'", newFormTemplateId, oldFormTemplateId)}) + actions = append(actions, &dao.ExecAction{Sql: fmt.Sprintf("insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) select '%s' as id,name,description,created_by,created_time,updated_by,updated_time from form_template where id='%s'", newFormTemplateId, oldFormTemplateId)}) newGuidList := guid.CreateGuidList(len(itemRows)) for i, item := range itemRows { - actions = append(actions, &execAction{Sql: fmt.Sprintf("insert into form_item_template(id,form_template,name,description,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,item_group,item_group_name,in_display_name,is_ref_inside,multiple,default_clear) select '%s' as id,'%s' as form_template,name,description,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,item_group,item_group_name,in_display_name,is_ref_inside,multiple,default_clear from form_item_template where id='%s'", newGuidList[i], newFormTemplateId, item.Id)}) + actions = append(actions, &dao.ExecAction{Sql: fmt.Sprintf("insert into form_item_template(id,form_template,name,description,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,item_group,item_group_name,in_display_name,is_ref_inside,multiple,default_clear) select '%s' as id,'%s' as form_template,name,description,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,item_group,item_group_name,in_display_name,is_ref_inside,multiple,default_clear from form_item_template where id='%s'", newGuidList[i], newFormTemplateId, item.Id)}) } return } -func getTaskTemplateRoleActions(oldTaskTemplateId, newTaskTemplateId string) (actions []*execAction, err error) { +func getTaskTemplateRoleActions(oldTaskTemplateId, newTaskTemplateId string) (actions []*dao.ExecAction, err error) { var taskTemplateRoles []*models.TaskTemplateRoleTable - err = x.SQL("select * from task_template_role where task_template=?", oldTaskTemplateId).Find(&taskTemplateRoles) + err = dao.X.SQL("select * from task_template_role where task_template=?", oldTaskTemplateId).Find(&taskTemplateRoles) if err != nil { return } for _, v := range taskTemplateRoles { tmpId := newTaskTemplateId + models.SysTableIdConnector + v.Role + models.SysTableIdConnector + v.RoleType - actions = append(actions, &execAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{tmpId, newTaskTemplateId, v.Role, v.RoleType}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{tmpId, newTaskTemplateId, v.Role, v.RoleType}}) } return } func validateConfirm(requestTemplateId string) error { var taskTemplateTable []*models.TaskTemplateTable - x.SQL("select id from task_template where request_template=? and form_template IS NOT NULL", requestTemplateId).Find(&taskTemplateTable) + dao.X.SQL("select id from task_template where request_template=? and form_template IS NOT NULL", requestTemplateId).Find(&taskTemplateTable) if len(requestTemplateId) == 0 { return fmt.Errorf("Please config task template ") } @@ -1004,7 +1009,7 @@ func validateConfirm(requestTemplateId string) error { func SetRequestTemplateToCreated(id, operator string) { nowTime := time.Now().Format(models.DateTimeFormat) - _, err := x.Exec("update request_template set status='created',updated_by=?,updated_time=? where id=?", operator, nowTime, id) + _, err := dao.X.Exec("update request_template set status='created',updated_by=?,updated_time=? where id=?", operator, nowTime, id) if err != nil { log.Logger.Error("Update request template to created status fail", log.Error(err), log.String("operator", operator), log.String("requestTemplateId", id)) } @@ -1013,9 +1018,9 @@ func SetRequestTemplateToCreated(id, operator string) { func GetRequestTemplateByUser(userRoles []string) (result []*models.UserRequestTemplateQueryObj, err error) { result = []*models.UserRequestTemplateQueryObj{} var requestTemplateTable, tmpTemplateTable []*models.RequestTemplateTable - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") queryParam := append(userRolesFilterParam, userRolesFilterParam...) - err = x.SQL("select * from request_template where (del_flag=2 and id in (select request_template from request_template_role where role_type='USE' and `role` in ("+userRolesFilterSql+"))) or (del_flag=0 and id in (select request_template from request_template_role where role_type='MGMT' and `role` in ("+userRolesFilterSql+"))) order by `group`,tags,status,id", queryParam...).Find(&requestTemplateTable) + err = dao.X.SQL("select * from request_template where (del_flag=2 and id in (select request_template from request_template_role where role_type='USE' and `role` in ("+userRolesFilterSql+"))) or (del_flag=0 and id in (select request_template from request_template_role where role_type='MGMT' and `role` in ("+userRolesFilterSql+"))) order by `group`,tags,status,id", queryParam...).Find(&requestTemplateTable) if err != nil { return } @@ -1076,7 +1081,7 @@ func GetRequestTemplateByUser(userRoles []string) (result []*models.UserRequestT } requestTemplateTable = tmpTemplateTable var groupTable []*models.RequestTemplateGroupTable - x.SQL("select id,name,description from request_template_group").Find(&groupTable) + dao.X.SQL("select id,name,description from request_template_group").Find(&groupTable) groupMap := make(map[string]*models.RequestTemplateGroupTable) for _, v := range groupTable { groupMap[v.Id] = v @@ -1114,12 +1119,12 @@ func GetRequestTemplateByUserV2(user, userToken string, userRoles []string) (res var userRoleMap = convertArray2Map(userRoles) result = []*models.UserRequestTemplateQueryObjNew{} useGroupMap, _ := getAllRequestTemplateGroup() - userRolesFilterSql, userRolesFilterParam := createListParams(userRoles, "") - err = x.SQL("select * from request_template ").Find(&allTemplateTable) + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") + err = dao.X.SQL("select * from request_template ").Find(&allTemplateTable) if err != nil { return } - err = x.SQL("select * from request_template where del_flag=2 and id in (select request_template from request_template_role where role_type='USE' and `role` in ("+userRolesFilterSql+")) order by `group`,tags,status,id", userRolesFilterParam...).Find(&requestTemplateTable) + err = dao.X.SQL("select * from request_template where del_flag=2 and id in (select request_template from request_template_role where role_type='USE' and `role` in ("+userRolesFilterSql+")) order by `group`,tags,status,id", userRolesFilterParam...).Find(&requestTemplateTable) if err != nil { return } @@ -1127,7 +1132,7 @@ func GetRequestTemplateByUserV2(user, userToken string, userRoles []string) (res return } requestTemplateLatestMap = getLatestVersionTemplate(requestTemplateTable, allTemplateTable) - err = x.SQL("select * from request_template_role where role_type='MGMT'").Find(&requestTemplateRoleTable) + err = dao.X.SQL("select * from request_template_role where role_type='MGMT'").Find(&requestTemplateRoleTable) if err != nil { return } @@ -1202,7 +1207,7 @@ func GetRequestTemplateByUserV2(user, userToken string, userRoles []string) (res for _, template := range requestTemplateTable { collectFlag = 0 var tempRoleArr, roleArr []string - err = x.SQL("SELECT role FROM request_template_role WHERE request_template = ? AND role_type = 'USE' ", template.Id).Find(&tempRoleArr) + err = dao.X.SQL("SELECT role FROM request_template_role WHERE request_template = ? AND role_type = 'USE' ", template.Id).Find(&tempRoleArr) if err != nil { continue } @@ -1358,7 +1363,7 @@ func groupRequestTemplateByTags(templates []*models.RequestTemplateTable) []*mod func getRequestTemplateRoles(requestTemplateId, roleType string) []string { result := []string{} var rtRoles []*models.RequestTemplateRoleTable - x.SQL("select `role` from request_template_role where request_template=? and role_type=?", requestTemplateId, roleType).Find(&rtRoles) + dao.X.SQL("select `role` from request_template_role where request_template=? and role_type=?", requestTemplateId, roleType).Find(&rtRoles) for _, v := range rtRoles { result = append(result, v.Role) } @@ -1368,7 +1373,7 @@ func getRequestTemplateRoles(requestTemplateId, roleType string) []string { func getMGmtRequestTemplateRoles() map[string]string { var roleMap = make(map[string]string, 0) var rtRoles []*models.RequestTemplateRoleTable - x.SQL("select * from request_template_role where role_type='MGMT'").Find(&rtRoles) + dao.X.SQL("select * from request_template_role where role_type='MGMT'").Find(&rtRoles) for _, v := range rtRoles { roleMap[v.RequestTemplate] = v.Role } @@ -1378,8 +1383,8 @@ func getMGmtRequestTemplateRoles() map[string]string { func QueryUserByRoles(roles []string, userToken string) (result []string, err error) { result = []string{} var roleTable []*models.RoleTable - rolesFilterSql, rolesFilterParam := createListParams(roles, "") - err = x.SQL("select * from `role` where id in ("+rolesFilterSql+")", rolesFilterParam...).Find(&roleTable) + rolesFilterSql, rolesFilterParam := dao.CreateListParams(roles, "") + err = dao.X.SQL("select * from `role` where id in ("+rolesFilterSql+")", rolesFilterParam...).Find(&roleTable) if err != nil || len(roleTable) == 0 { return } @@ -1436,7 +1441,7 @@ func queryCoreUser(roleId, userToken string) (result []string, err error) { func GetRequestTemplateTags(group string) (result []string, err error) { result = []string{} var requestTemplates []*models.RequestTemplateTable - err = x.SQL("select distinct tags from request_template where `group`=?", group).Find(&requestTemplates) + err = dao.X.SQL("select distinct tags from request_template where `group`=?", group).Find(&requestTemplates) for _, v := range requestTemplates { if v.Tags == "" { continue @@ -1453,7 +1458,7 @@ func RequestTemplateExport(requestTemplateId string) (result models.RequestTempl result.TaskTemplateRole = []*models.TaskTemplateRoleTable{} result.FormTemplate = []*models.FormTemplateTable{} result.FormItemTemplate = []*models.FormItemTemplateTable{} - err = x.SQL("select * from request_template where id=?", requestTemplateId).Find(&requestTemplateTable) + err = dao.X.SQL("select * from request_template where id=?", requestTemplateId).Find(&requestTemplateTable) if err != nil { return } @@ -1462,13 +1467,13 @@ func RequestTemplateExport(requestTemplateId string) (result models.RequestTempl return } result.RequestTemplate = *requestTemplateTable[0] - x.SQL("select * from request_template_role where request_template=?", requestTemplateId).Find(&result.RequestTemplateRole) - x.SQL("select * from task_template where request_template=?", requestTemplateId).Find(&result.TaskTemplate) - x.SQL("select * from task_template_role where task_template in (select id from task_template where request_template=?)", requestTemplateId).Find(&result.TaskTemplateRole) - x.SQL("select * from form_template where id in (select form_template from request_template where id=? union select form_template from task_template where request_template=?)", requestTemplateId, requestTemplateId).Find(&result.FormTemplate) - x.SQL("select * from form_item_template where form_template in (select id from form_template where id in (select form_template from request_template where id=? union select form_template from task_template where request_template=?))", requestTemplateId, requestTemplateId).Find(&result.FormItemTemplate) + dao.X.SQL("select * from request_template_role where request_template=?", requestTemplateId).Find(&result.RequestTemplateRole) + dao.X.SQL("select * from task_template where request_template=?", requestTemplateId).Find(&result.TaskTemplate) + dao.X.SQL("select * from task_template_role where task_template in (select id from task_template where request_template=?)", requestTemplateId).Find(&result.TaskTemplateRole) + dao.X.SQL("select * from form_template where id in (select form_template from request_template where id=? union select form_template from task_template where request_template=?)", requestTemplateId, requestTemplateId).Find(&result.FormTemplate) + dao.X.SQL("select * from form_item_template where form_template in (select id from form_template where id in (select form_template from request_template where id=? union select form_template from task_template where request_template=?))", requestTemplateId, requestTemplateId).Find(&result.FormItemTemplate) var requestTemplateGroupTable []*models.RequestTemplateGroupTable - x.SQL("select * from request_template_group where id=?", result.RequestTemplate.Group).Find(&requestTemplateGroupTable) + dao.X.SQL("select * from request_template_group where id=?", result.RequestTemplate.Group).Find(&requestTemplateGroupTable) if len(requestTemplateGroupTable) > 0 { result.RequestTemplateGroup = *requestTemplateGroupTable[0] } @@ -1476,7 +1481,7 @@ func RequestTemplateExport(requestTemplateId string) (result models.RequestTempl } func RequestTemplateImport(input models.RequestTemplateExport, userToken, confirmToken, operator string) (templateName, backToken string, err error) { - var actions []*execAction + var actions []*dao.ExecAction var inputVersion = getTemplateVersion(&input.RequestTemplate) var templateList []*models.RequestTemplateTable // 记录重复并且是草稿态的Id @@ -1574,35 +1579,35 @@ func RequestTemplateImport(input models.RequestTemplateExport, userToken, confir } nowTime := time.Now().Format(models.DateTimeFormat) for _, v := range input.FormTemplate { - actions = append(actions, &execAction{Sql: "insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?)", Param: []interface{}{v.Id, v.Name, v.Description, operator, nowTime, operator, nowTime}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?)", Param: []interface{}{v.Id, v.Name, v.Description, operator, nowTime, operator, nowTime}}) } for _, v := range input.FormItemTemplate { - tmpAction := execAction{Sql: "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} + tmpAction := dao.ExecAction{Sql: "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} tmpAction.Param = []interface{}{v.Id, v.FormTemplate, v.Name, v.Description, v.ItemGroup, v.ItemGroupName, v.DefaultValue, v.Sort, v.PackageName, v.Entity, v.AttrDefId, v.AttrDefName, v.AttrDefDataType, v.ElementType, v.Title, v.Width, v.RefPackageName, v.RefEntity, v.DataOptions, v.Required, v.Regular, v.IsEdit, v.IsView, v.IsOutput, v.InDisplayName, v.IsRefInside, v.Multiple, v.DefaultClear} actions = append(actions, &tmpAction) } var roleTable []*models.RoleTable - x.SQL("select id from `role`").Find(&roleTable) + dao.X.SQL("select id from `role`").Find(&roleTable) roleMap := make(map[string]int) for _, v := range roleTable { roleMap[v.Id] = 1 } var requestTemplateGroupTable []*models.RequestTemplateGroupTable - x.SQL("select id from request_template_group where id=?", input.RequestTemplate.Group).Find(&requestTemplateGroupTable) + dao.X.SQL("select id from request_template_group where id=?", input.RequestTemplate.Group).Find(&requestTemplateGroupTable) if len(requestTemplateGroupTable) == 0 { if _, b := roleMap[input.RequestTemplateGroup.ManageRole]; !b { input.RequestTemplateGroup.ManageRole = models.AdminRole } - actions = append(actions, &execAction{Sql: "insert into request_template_group(id,name,description,manage_role,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?)", Param: []interface{}{input.RequestTemplateGroup.Id, input.RequestTemplateGroup.Name, input.RequestTemplateGroup.Description, input.RequestTemplateGroup.ManageRole, operator, nowTime, operator, nowTime}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_group(id,name,description,manage_role,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?)", Param: []interface{}{input.RequestTemplateGroup.Id, input.RequestTemplateGroup.Name, input.RequestTemplateGroup.Description, input.RequestTemplateGroup.ManageRole, operator, nowTime, operator, nowTime}}) } input.RequestTemplate.Status = "created" input.RequestTemplate.ConfirmTime = "" - rtAction := execAction{Sql: "insert into request_template(id,`group`,name,description,form_template,tags,record_id,`version`,confirm_time,status,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,expire_day,created_by,created_time,updated_by,updated_time,entity_attrs,handler,type,operator_obj_type) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} + rtAction := dao.ExecAction{Sql: "insert into request_template(id,`group`,name,description,form_template,tags,record_id,`version`,confirm_time,status,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,expire_day,created_by,created_time,updated_by,updated_time,entity_attrs,handler,type,operator_obj_type) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} rtAction.Param = []interface{}{input.RequestTemplate.Id, input.RequestTemplate.Group, input.RequestTemplate.Name, input.RequestTemplate.Description, input.RequestTemplate.FormTemplate, input.RequestTemplate.Tags, input.RequestTemplate.RecordId, input.RequestTemplate.Version, input.RequestTemplate.ConfirmTime, input.RequestTemplate.Status, input.RequestTemplate.PackageName, input.RequestTemplate.EntityName, input.RequestTemplate.ProcDefKey, input.RequestTemplate.ProcDefId, input.RequestTemplate.ProcDefName, input.RequestTemplate.ExpireDay, operator, nowTime, operator, nowTime, input.RequestTemplate.EntityAttrs, input.RequestTemplate.Handler, input.RequestTemplate.Type, input.RequestTemplate.OperatorObjType} actions = append(actions, &rtAction) for _, v := range input.TaskTemplate { - tmpAction := execAction{Sql: "insert into task_template(id,name,description,form_template,request_template,node_id,node_def_id,node_name,expire_day,handler,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} + tmpAction := dao.ExecAction{Sql: "insert into task_template(id,name,description,form_template,request_template,node_id,node_def_id,node_name,expire_day,handler,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} tmpAction.Param = []interface{}{v.Id, v.Name, v.Description, v.FormTemplate, v.RequestTemplate, v.NodeId, v.NodeDefId, v.NodeName, v.ExpireDay, v.Handler, operator, nowTime, operator, nowTime} actions = append(actions, &tmpAction) } @@ -1610,18 +1615,18 @@ func RequestTemplateImport(input models.RequestTemplateExport, userToken, confir for _, v := range input.RequestTemplateRole { if _, b := roleMap[v.Role]; b { rtRoleFetch = true - actions = append(actions, &execAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{v.Id, v.RequestTemplate, v.Role, v.RoleType}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{v.Id, v.RequestTemplate, v.Role, v.RoleType}}) } } if !rtRoleFetch { - actions = append(actions, &execAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{guid.CreateGuid() + models.SysTableIdConnector + models.AdminRole + models.SysTableIdConnector + "MGMT", input.RequestTemplate.Id, models.AdminRole, "MGMT"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{guid.CreateGuid() + models.SysTableIdConnector + models.AdminRole + models.SysTableIdConnector + "MGMT", input.RequestTemplate.Id, models.AdminRole, "MGMT"}}) } for _, v := range input.TaskTemplateRole { if _, b := roleMap[v.Role]; b { - actions = append(actions, &execAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{v.Id, v.TaskTemplate, v.Role, v.RoleType}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{v.Id, v.TaskTemplate, v.Role, v.RoleType}}) } } - err = transaction(actions) + err = dao.Transaction(actions) return } @@ -1682,12 +1687,12 @@ func getTemplateVersion(template *models.RequestTemplateTable) int { } func getTemplateListByName(templateName string) (requestTemplateTable []*models.RequestTemplateTable, err error) { - err = x.SQL("select id,name,version,status from request_template where name=?", templateName).Find(&requestTemplateTable) + err = dao.X.SQL("select id,name,version,status from request_template where name=?", templateName).Find(&requestTemplateTable) return } func DisableRequestTemplate(requestTemplateId, operator string) (err error) { - queryRows, queryErr := x.QueryString("select status from request_template where id=?", requestTemplateId) + queryRows, queryErr := dao.X.QueryString("select status from request_template where id=?", requestTemplateId) if queryErr != nil { err = queryErr return @@ -1700,12 +1705,12 @@ func DisableRequestTemplate(requestTemplateId, operator string) (err error) { err = fmt.Errorf("only confirm status template can disable") return } - _, err = x.Exec("update request_template set status='disable' where id=?", requestTemplateId) + _, err = dao.X.Exec("update request_template set status='disable' where id=?", requestTemplateId) return } func EnableRequestTemplate(requestTemplateId, operator string) (err error) { - queryRows, queryErr := x.QueryString("select status from request_template where id=?", requestTemplateId) + queryRows, queryErr := dao.X.QueryString("select status from request_template where id=?", requestTemplateId) if queryErr != nil { err = queryErr return @@ -1718,14 +1723,14 @@ func EnableRequestTemplate(requestTemplateId, operator string) (err error) { err = fmt.Errorf("only disable status template can enable") return } - _, err = x.Exec("update request_template set status='confirm' where id=?", requestTemplateId) + _, err = dao.X.Exec("update request_template set status='confirm' where id=?", requestTemplateId) return } func getAllRequestTemplateGroup() (groupMap map[string]*models.RequestTemplateGroupTable, err error) { groupMap = make(map[string]*models.RequestTemplateGroupTable) var allGroupTable []*models.RequestTemplateGroupTable - err = x.SQL("select id,name,description,manage_role,created_time,updated_time from request_template_group").Find(&allGroupTable) + err = dao.X.SQL("select id,name,description,manage_role,created_time,updated_time from request_template_group").Find(&allGroupTable) if err != nil { return } @@ -1736,7 +1741,7 @@ func getAllRequestTemplateGroup() (groupMap map[string]*models.RequestTemplateGr } func UpdateRequestTemplateParentId(requestTemplate models.RequestTemplateTable) (parentId string) { - var actions []*execAction + var actions []*dao.ExecAction var templateIds []string // 老模板有多个版本,需要更新所有版本,并找到 recordId为空的记录 requestTemplateMap, _ := getAllRequestTemplate() @@ -1756,11 +1761,11 @@ func UpdateRequestTemplateParentId(requestTemplate models.RequestTemplateTable) } if len(templateIds) > 0 && parentId != "" { for _, templateId := range templateIds { - actions = append(actions, &execAction{Sql: "update request_template set parent_id=? where id=?", Param: []interface{}{parentId, templateId}}) + actions = append(actions, &dao.ExecAction{Sql: "update request_template set parent_id=? where id=?", Param: []interface{}{parentId, templateId}}) } } if len(actions) > 0 { - updateErr := transaction(actions) + updateErr := dao.Transaction(actions) if updateErr != nil { log.Logger.Error("Try to update request_template parent_id fail", log.Error(updateErr)) } @@ -1769,10 +1774,10 @@ func UpdateRequestTemplateParentId(requestTemplate models.RequestTemplateTable) } func UpdateRequestTemplateParentIdById(templateId, parentId string) (err error) { - var actions []*execAction - actions = append(actions, &execAction{Sql: "update request_template set parent_id=? where id=?", Param: []interface{}{parentId, templateId}}) + var actions []*dao.ExecAction + actions = append(actions, &dao.ExecAction{Sql: "update request_template set parent_id=? where id=?", Param: []interface{}{parentId, templateId}}) if len(actions) > 0 { - err = transaction(actions) + err = dao.Transaction(actions) if err != nil { log.Logger.Error("Try to update request_template parent_id fail", log.Error(err)) } diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go new file mode 100644 index 00000000..f436cf6f --- /dev/null +++ b/taskman-server/service/service.go @@ -0,0 +1,60 @@ +package service + +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + "xorm.io/xorm" +) + +var ( + // db操作 + db *xorm.Engine + // 文件上传 service + attachFileService AttachFileService + // 模板收藏 service + collectTemplateService CollectTemplateService + // 表单模板 service + formTemplateService FormTemplateService + // CMDB service + refSelectService RefSelectService + // 请求 service + requestService RequestService + // 请求模板 service + requestTemplateService RequestTemplateService + // 任务 service + taskService TaskService +) + +func New() (err error) { + var engine *xorm.Engine + // 初始化Db + engine, err = dao.InitDatabase() + if err != nil { + return + } + // 初始化Dao + requestDao := dao.RequestDao{DB: engine} + attachFileDao := dao.AttachFileDao{DB: engine} + // 初始化Service + requestService = RequestService{requestDao: requestDao} + attachFileService = AttachFileService{attachFileDao: attachFileDao} + db = engine + return +} + +// GetRequestService 获取请求service +func GetRequestService() RequestService { + return requestService +} + +// transaction 事务处理 +func transaction(f func(session *xorm.Session) error) (err error) { + session := db.NewSession() + defer session.Close() + session.Begin() + err = f(session) + if err != nil { + session.Rollback() + } + session.Commit() + return +} diff --git a/taskman-server/services/db/task.go b/taskman-server/service/task_service.go similarity index 77% rename from taskman-server/services/db/task.go rename to taskman-server/service/task_service.go index a490d4d0..37ae7614 100644 --- a/taskman-server/services/db/task.go +++ b/taskman-server/service/task_service.go @@ -1,4 +1,4 @@ -package db +package service import ( "bytes" @@ -8,6 +8,7 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "io/ioutil" "net/http" @@ -16,10 +17,14 @@ import ( "time" ) +type TaskService struct { + taskDao dao.TaskDao +} + func GetTaskFormStruct(procInstId, nodeDefId string) (result models.TaskMetaResult, err error) { result = models.TaskMetaResult{Status: "OK", Message: "Success"} var items []*models.FormItemTemplateTable - err = x.SQL("select * from form_item_template where form_template in (select form_template from task_template where node_def_id=? and request_template in (select request_template from request where proc_instance_id=?))", nodeDefId, procInstId).Find(&items) + err = dao.X.SQL("select * from form_item_template where form_template in (select form_template from task_template where node_def_id=? and request_template in (select request_template from request where proc_instance_id=?))", nodeDefId, procInstId).Find(&items) if err != nil { return } @@ -42,11 +47,11 @@ func PluginTaskCreate(input *models.PluginTaskCreateRequestObj, callRequestId, d log.Logger.Debug("task create", log.JsonObj("input", input)) result = &models.PluginTaskCreateOutputObj{CallbackParameter: input.CallbackParameter, ErrorCode: "0", ErrorMessage: "", Comment: ""} var requestTable []*models.RequestTable - err = x.SQL("select id,form,request_template,emergency,type from request where proc_instance_id=?", input.ProcInstId).Find(&requestTable) + err = dao.X.SQL("select id,form,request_template,emergency,type from request where proc_instance_id=?", input.ProcInstId).Find(&requestTable) if err != nil { return result, taskId, fmt.Errorf("Try to check proc_instance_id:%s is in request fail,%s ", input.ProcInstId, err.Error()) } - var actions []*execAction + var actions []*dao.ExecAction nowTime := time.Now().Format(models.DateTimeFormat) newTaskFormObj := models.FormTable{Id: guid.CreateGuid(), Name: "form_" + input.TaskName} input.RoleName = remakeTaskReportRole(input.RoleName) @@ -68,10 +73,10 @@ func PluginTaskCreate(input *models.PluginTaskCreateRequestObj, callRequestId, d if dueMin > 0 { customExpireTime = time.Now().Add(time.Duration(dueMin) * time.Minute).Format(models.DateTimeFormat) } - taskInsertAction := execAction{Sql: "insert into task(id,name,description,status,proc_def_id,proc_def_key,node_def_id,node_name,callback_url,callback_parameter,reporter,report_role,report_time,expire_time,emergency,callback_request_id,next_option,handler,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} + taskInsertAction := dao.ExecAction{Sql: "insert into task(id,name,description,status,proc_def_id,proc_def_key,node_def_id,node_name,callback_url,callback_parameter,reporter,report_role,report_time,expire_time,emergency,callback_request_id,next_option,handler,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} taskInsertAction.Param = []interface{}{newTaskObj.Id, newTaskObj.Name, newTaskObj.Description, newTaskObj.Status, newTaskObj.ProcDefId, newTaskObj.ProcDefKey, newTaskObj.NodeDefId, newTaskObj.NodeName, newTaskObj.CallbackUrl, newTaskObj.CallbackParameter, newTaskObj.Reporter, newTaskObj.ReportRole, nowTime, customExpireTime, newTaskObj.Emergency, callRequestId, newTaskObj.NextOption, newTaskObj.Handler, "system", nowTime, "system", nowTime} actions = append(actions, &taskInsertAction) - err = transaction(actions) + err = dao.Transaction(actions) return } itemTemplateMap := getFormItemTemplateMap(taskFormInput.FormMetaId) @@ -83,7 +88,7 @@ func PluginTaskCreate(input *models.PluginTaskCreateRequestObj, callRequestId, d newTaskObj.Emergency = requestTable[0].Emergency newTaskObj.TemplateType = requestTable[0].Type var taskTemplateTable []*models.TaskTemplateTable - x.SQL("select * from task_template where request_template=? and node_def_id=?", requestTable[0].RequestTemplate, taskFormInput.TaskNodeDefId).Find(&taskTemplateTable) + dao.X.SQL("select * from task_template where request_template=? and node_def_id=?", requestTable[0].RequestTemplate, taskFormInput.TaskNodeDefId).Find(&taskTemplateTable) if len(taskTemplateTable) > 0 { newTaskObj.TaskTemplate = taskTemplateTable[0].Id newTaskObj.NodeName = taskTemplateTable[0].NodeName @@ -101,7 +106,7 @@ func PluginTaskCreate(input *models.PluginTaskCreateRequestObj, callRequestId, d } } log.Logger.Debug("debug1", log.JsonObj("newTaskFormObj", newTaskFormObj)) - taskInsertAction := execAction{Sql: "insert into task(id,name,description,form,status,request,task_template,proc_def_id,proc_def_key,node_def_id," + + taskInsertAction := dao.ExecAction{Sql: "insert into task(id,name,description,form,status,request,task_template,proc_def_id,proc_def_key,node_def_id," + "node_name,callback_url,callback_parameter,reporter,report_role,report_time,emergency,cache,callback_request_id,next_option,expire_time," + "handler,created_by,created_time,updated_by,updated_time,template_type) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} taskInsertAction.Param = []interface{}{newTaskObj.Id, newTaskObj.Name, newTaskObj.Description, newTaskObj.Form, newTaskObj.Status, @@ -110,12 +115,12 @@ func PluginTaskCreate(input *models.PluginTaskCreateRequestObj, callRequestId, d input.TaskFormInput, callRequestId, newTaskObj.NextOption, newTaskObj.ExpireTime, newTaskObj.Handler, "system", nowTime, "system", nowTime, newTaskObj.TemplateType} actions = append(actions, &taskInsertAction) - actions = append(actions, &execAction{Sql: "insert into form(id,name,form_template) value (?,?,?)", Param: []interface{}{newTaskFormObj.Id, newTaskFormObj.Name, newTaskFormObj.FormTemplate}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form(id,name,form_template) value (?,?,?)", Param: []interface{}{newTaskFormObj.Id, newTaskFormObj.Name, newTaskFormObj.FormTemplate}}) for _, formDataEntity := range taskFormInput.FormDataEntities { tmpGuidList := guid.CreateGuidList(len(formDataEntity.FormItemValues)) for i, formDataItem := range formDataEntity.FormItemValues { tmpItemGroup := itemTemplateMap[formDataItem.FormItemMetaId].ItemGroup - actions = append(actions, &execAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], newTaskFormObj.Id, formDataItem.FormItemMetaId, formDataItem.AttrName, formDataItem.AttrValue, tmpItemGroup, formDataItem.Oid}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], newTaskFormObj.Id, formDataItem.FormItemMetaId, formDataItem.AttrName, formDataItem.AttrValue, tmpItemGroup, formDataItem.Oid}}) } } customItems, tmpErr := getLastCustomFormItem(newTaskObj.Request, newTaskFormObj.FormTemplate, newTaskFormObj.Id) @@ -126,10 +131,10 @@ func PluginTaskCreate(input *models.PluginTaskCreateRequestObj, callRequestId, d if len(customItems) > 0 { tmpGuidList := guid.CreateGuidList(len(customItems)) for i, customItem := range customItems { - actions = append(actions, &execAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], customItem.Form, customItem.FormItemTemplate, customItem.Name, customItem.Value, customItem.ItemGroup, customItem.RowDataId}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{tmpGuidList[i], customItem.Form, customItem.FormItemTemplate, customItem.Name, customItem.Value, customItem.ItemGroup, customItem.RowDataId}}) } } - err = transactionWithoutForeignCheck(actions) + err = dao.TransactionWithoutForeignCheck(actions) return } @@ -139,7 +144,7 @@ func getLastCustomFormItem(requestId, taskFormTemplateId, newTaskFormId string) return } var formItemTemplates []*models.FormItemTemplateTable - err = x.SQL("select * from form_item_template where entity='' and form_template=?", taskFormTemplateId).Find(&formItemTemplates) + err = dao.X.SQL("select * from form_item_template where entity='' and form_template=?", taskFormTemplateId).Find(&formItemTemplates) if len(formItemTemplates) == 0 || err != nil { return } @@ -150,7 +155,7 @@ func getLastCustomFormItem(requestId, taskFormTemplateId, newTaskFormId string) filterList = append(filterList, fmt.Sprintf("(item_group='%s' and name='%s')", v.ItemGroup, v.Name)) } var formItems []*models.FormItemTable - err = x.SQL("select * from form_item where ("+strings.Join(filterList, " or ")+") and form in (select form from request where id=? union select form from task where request=?) order by item_group,name,id desc", requestId, requestId).Find(&formItems) + err = dao.X.SQL("select * from form_item where ("+strings.Join(filterList, " or ")+") and form in (select form from request where id=? union select form from task where request=?) order by item_group,name,id desc", requestId, requestId).Find(&formItems) //if len(formItems) == 0 { // for _, v := range formItemTemplates { // tmpKey := fmt.Sprintf("%s_%s", v.ItemGroup, v.Name) @@ -173,7 +178,7 @@ func getLastCustomFormItem(requestId, taskFormTemplateId, newTaskFormId string) func getFormItemTemplateMap(formTemplateId string) map[string]*models.FormItemTemplateTable { resultMap := make(map[string]*models.FormItemTemplateTable) var itemTemplateTable []*models.FormItemTemplateTable - x.SQL("select * from form_item_template where form_template=?", formTemplateId).Find(&itemTemplateTable) + dao.X.SQL("select * from form_item_template where form_template=?", formTemplateId).Find(&itemTemplateTable) for _, v := range itemTemplateTable { resultMap[v.Id] = v } @@ -203,17 +208,17 @@ func ListTask(param *models.QueryRequestParam, userRoles []string, operator stri } roleFilterSql = strings.Join(roleFilterList, " or ") } - filterSql, _, queryParam := transFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.TaskTable{}, PrimaryKey: "id", Prefix: "t1"}) + filterSql, _, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.TaskTable{}, PrimaryKey: "id", Prefix: "t1"}) baseSql := fmt.Sprintf("select t1.id,t1.name,t1.description,t1.form,t1.status,t1.`version`,t1.request,t1.task_template,t1.node_name,t1.reporter,t1.report_role,t1.report_time,t1.emergency,t1.handler,t1.created_by,t1.created_time,t1.updated_by,t1.updated_time,t1.expire_time from (select * from task where task_template in (select task_template from task_template_role where role_type='USE' and `role` in ('"+strings.Join(userRoles, "','")+"')) union select * from task where task_template is null and (%s)) t1 where t1.del_flag=0 %s ", roleFilterSql, filterSql) if param.Paging { pageInfo.StartIndex = param.Pageable.StartIndex pageInfo.PageSize = param.Pageable.PageSize - pageInfo.TotalRows = queryCount(baseSql, queryParam...) - pageSql, pageParam := transPageInfoToSQL(*param.Pageable) + pageInfo.TotalRows = dao.QueryCount(baseSql, queryParam...) + pageSql, pageParam := dao.TransPageInfoToSQL(*param.Pageable) baseSql += pageSql queryParam = append(queryParam, pageParam...) } - err = x.SQL(baseSql, queryParam...).Find(&rowData) + err = dao.X.SQL(baseSql, queryParam...).Find(&rowData) if err != nil { return models.PageInfo{}, nil, err } @@ -233,7 +238,7 @@ func ListTask(param *models.QueryRequestParam, userRoles []string, operator stri } } var requestTables []*models.RequestTable - x.SQL("select t1.id,t1.name,t1.reporter,t1.report_time,t2.name as request_template from request t1 left join request_template t2 on t1.request_template=t2.id where t1.id in ('" + strings.Join(requestIdList, "','") + "')").Find(&requestTables) + dao.X.SQL("select t1.id,t1.name,t1.reporter,t1.report_time,t2.name as request_template from request t1 left join request_template t2 on t1.request_template=t2.id where t1.id in ('" + strings.Join(requestIdList, "','") + "')").Find(&requestTables) requestMap := make(map[string]*models.RequestTable) for _, v := range requestTables { requestMap[v.Id] = v @@ -259,7 +264,7 @@ func ListTask(param *models.QueryRequestParam, userRoles []string, operator stri func getTaskTemplateRoles() map[string][]string { result := make(map[string][]string) var taskRoles []*models.TaskTemplateRoleTable - x.SQL("select * from task_template_role where role_type='USE' order by task_template").Find(&taskRoles) + dao.X.SQL("select * from task_template_role where role_type='USE' order by task_template").Find(&taskRoles) if len(taskRoles) == 0 { return result } @@ -297,7 +302,7 @@ func GetTask(taskId string) (result models.TaskQueryResult, err error) { } // get request var requests []*models.RequestTable - x.SQL("select * from request where id=?", taskObj.Request).Find(&requests) + dao.X.SQL("select * from request where id=?", taskObj.Request).Find(&requests) if len(requests) == 0 { return result, fmt.Errorf("Can not find request with id:%s ", taskObj.Request) } @@ -318,7 +323,7 @@ func GetTask(taskId string) (result models.TaskQueryResult, err error) { return result, fmt.Errorf("Try to json unmarshal request cache fail,%s ", err.Error()) } var requestTemplateTable []*models.RequestTemplateTable - x.SQL("select * from request_template where id in (select request_template from request where id=?)", taskObj.Request).Find(&requestTemplateTable) + dao.X.SQL("select * from request_template where id in (select request_template from request where id=?)", taskObj.Request).Find(&requestTemplateTable) requestQuery := models.TaskQueryObj{RequestId: taskObj.Request, RequestName: requests[0].Name, Reporter: requests[0].Reporter, ReportTime: requests[0].ReportTime, Comment: requests[0].Result, Editable: false} requestQuery.AttachFiles = GetRequestAttachFileList(taskObj.Request) requestQuery.ExpireTime = requests[0].ExpireTime @@ -335,13 +340,13 @@ func GetTask(taskId string) (result models.TaskQueryResult, err error) { } // get task list var taskHandlerRows []*models.TaskHandlerQueryData - x.SQL("select t1.id,t2.handler,t4.display_name from task t1 left join task_template t2 on t1.task_template=t2.id left join task_template_role t3 on t1.task_template=t3.task_template left join `role` t4 on t3.`role`=t4.id where t1.request=?", taskObj.Request).Find(&taskHandlerRows) + dao.X.SQL("select t1.id,t2.handler,t4.display_name from task t1 left join task_template t2 on t1.task_template=t2.id left join task_template_role t3 on t1.task_template=t3.task_template left join `role` t4 on t3.`role`=t4.id where t1.request=?", taskObj.Request).Find(&taskHandlerRows) taskHandlerMap := make(map[string]*models.TaskHandlerQueryData) for _, row := range taskHandlerRows { taskHandlerMap[row.Id] = row } var taskList []*models.TaskTable - x.SQL("select * from task where request=? and report_time<='"+taskObj.ReportTime+"' order by created_time", taskObj.Request).Find(&taskList) + dao.X.SQL("select * from task where request=? and report_time<='"+taskObj.ReportTime+"' order by created_time", taskObj.Request).Find(&taskList) for _, v := range taskList { tmpTaskForm, tmpErr := queryTaskForm(v) if tmpErr != nil { @@ -386,7 +391,7 @@ func GetTaskV2(taskId string) (taskQueryList []*models.TaskQueryObj, err error) } // get request var requests []*models.RequestTable - x.SQL("select * from request where id=?", taskObj.Request).Find(&requests) + dao.X.SQL("select * from request where id=?", taskObj.Request).Find(&requests) if len(requests) == 0 { err = fmt.Errorf("Can not find request with id:%s ", taskObj.Request) return @@ -411,7 +416,7 @@ func GetTaskV2(taskId string) (taskQueryList []*models.TaskQueryObj, err error) return } var requestTemplateTable []*models.RequestTemplateTable - x.SQL("select * from request_template where id in (select request_template from request where id=?)", taskObj.Request).Find(&requestTemplateTable) + dao.X.SQL("select * from request_template where id in (select request_template from request where id=?)", taskObj.Request).Find(&requestTemplateTable) requestQuery := models.TaskQueryObj{RequestId: taskObj.Request, RequestName: requests[0].Name, Reporter: requests[0].Reporter, ReportTime: requests[0].ReportTime, Comment: requests[0].Result, Editable: false, RollbackDesc: requests[0].RollbackDesc} requestQuery.AttachFiles = GetRequestAttachFileList(taskObj.Request) requestQuery.ExpireTime = requests[0].ExpireTime @@ -428,13 +433,13 @@ func GetTaskV2(taskId string) (taskQueryList []*models.TaskQueryObj, err error) taskQueryList = append(taskQueryList, []*models.TaskQueryObj{&requestQuery, getPendingRequestData(requests[0])}...) // get task list var taskHandlerRows []*models.TaskHandlerQueryData - x.SQL("select t1.id,t2.handler,t4.display_name from task t1 left join task_template t2 on t1.task_template=t2.id left join task_template_role t3 on t1.task_template=t3.task_template left join `role` t4 on t3.`role`=t4.id where t1.request=?", taskObj.Request).Find(&taskHandlerRows) + dao.X.SQL("select t1.id,t2.handler,t4.display_name from task t1 left join task_template t2 on t1.task_template=t2.id left join task_template_role t3 on t1.task_template=t3.task_template left join `role` t4 on t3.`role`=t4.id where t1.request=?", taskObj.Request).Find(&taskHandlerRows) taskHandlerMap := make(map[string]*models.TaskHandlerQueryData) for _, row := range taskHandlerRows { taskHandlerMap[row.Id] = row } var taskList []*models.TaskTable - x.SQL("select * from task where request=? and report_time<='"+taskObj.ReportTime+"' order by created_time", taskObj.Request).Find(&taskList) + dao.X.SQL("select * from task where request=? and report_time<='"+taskObj.ReportTime+"' order by created_time", taskObj.Request).Find(&taskList) for _, v := range taskList { tmpTaskForm, tmpErr := queryTaskForm(v) if tmpErr != nil { @@ -475,7 +480,7 @@ func queryTaskForm(taskObj *models.TaskTable) (taskForm models.TaskQueryObj, err return } var itemTemplates []*models.FormItemTemplateTable - err = x.SQL("select * from form_item_template where form_template in (select form_template from task_template where id=?) order by item_group,sort", taskObj.TaskTemplate).Find(&itemTemplates) + err = dao.X.SQL("select * from form_item_template where form_template in (select form_template from task_template where id=?) order by item_group,sort", taskObj.TaskTemplate).Find(&itemTemplates) if err != nil { return } @@ -485,7 +490,7 @@ func queryTaskForm(taskObj *models.TaskTable) (taskForm models.TaskQueryObj, err formResult := getItemTemplateTitle(itemTemplates) taskForm.FormData = formResult var items []*models.FormItemTable - x.SQL("select * from form_item where form=? order by item_group,row_data_id", taskObj.Form).Find(&items) + dao.X.SQL("select * from form_item where form=? order by item_group,row_data_id", taskObj.Form).Find(&items) if len(items) == 0 { return } @@ -543,7 +548,7 @@ func queryTaskForm(taskObj *models.TaskTable) (taskForm models.TaskQueryObj, err func getRequestTimeStep(requestTemplateId string) (result []*models.TaskQueryTimeStep, err error) { var requestTemplateTable []*models.RequestTemplateTable - err = x.SQL("select id,name from request_template where id=?", requestTemplateId).Find(&requestTemplateTable) + err = dao.X.SQL("select id,name from request_template where id=?", requestTemplateId).Find(&requestTemplateTable) if err != nil { return } @@ -552,7 +557,7 @@ func getRequestTimeStep(requestTemplateId string) (result []*models.TaskQueryTim } result = append(result, &models.TaskQueryTimeStep{RequestTemplateId: requestTemplateTable[0].Id, Name: "Start", Active: false}) var taskTemplateTable []*models.TaskTemplateTable - x.SQL("select id,name from task_template where request_template=?", requestTemplateId).Find(&taskTemplateTable) + dao.X.SQL("select id,name from task_template where request_template=?", requestTemplateId).Find(&taskTemplateTable) for _, v := range taskTemplateTable { result = append(result, &models.TaskQueryTimeStep{RequestTemplateId: requestTemplateId, TaskTemplateId: v.Id, Name: v.Name, Active: false}) } @@ -561,7 +566,7 @@ func getRequestTimeStep(requestTemplateId string) (result []*models.TaskQueryTim func getSimpleTask(taskId string) (result models.TaskTable, err error) { var taskTable []*models.TaskTable - err = x.SQL("select * from task where id=?", taskId).Find(&taskTable) + err = dao.X.SQL("select * from task where id=?", taskId).Find(&taskTable) if err != nil { return } @@ -575,7 +580,7 @@ func getSimpleTask(taskId string) (result models.TaskTable, err error) { func getTaskMapByRequestId(requestId string) (taskMap map[string]*models.TaskTable, err error) { taskMap = make(map[string]*models.TaskTable) var taskTable []*models.TaskTable - err = x.SQL("select * from task where request = ?", requestId).Find(&taskTable) + err = dao.X.SQL("select * from task where request = ?", requestId).Find(&taskTable) if err != nil { return } @@ -626,11 +631,11 @@ func ApproveTask(taskId, operator, userToken string, param models.TaskApprovePar nowTime := time.Now().Format(models.DateTimeFormat) if respResult.Status != "OK" { if strings.Contains(respResult.Message, "None process instance found") { - x.Exec("update task set status='done',updated_by=?,updated_time=? where id=?", operator, nowTime, taskId) + dao.X.Exec("update task set status='done',updated_by=?,updated_time=? where id=?", operator, nowTime, taskId) } return fmt.Errorf("Callback fail,%s ", respResult.Message) } - _, err = x.Exec("update task set callback_data=?,result=?,chose_option=?,status=?,updated_by=?,updated_time=? where id=?", string(requestBytes), param.Comment, param.ChoseOption, "done", operator, nowTime, taskId) + _, err = dao.X.Exec("update task set callback_data=?,result=?,chose_option=?,status=?,updated_by=?,updated_time=? where id=?", string(requestBytes), param.Comment, param.ChoseOption, "done", operator, nowTime, taskId) if err != nil { return fmt.Errorf("Callback succeed,but update database task row fail,%s ", err.Error()) } @@ -656,7 +661,7 @@ func getApproveCallbackParam(taskId string) (result models.PluginTaskCreateResp, return result, callbackUrl, fmt.Errorf("Try to json unmarshal cache data fail:%s ", err.Error()) } var items []*models.TaskFormItemQueryObj - err = x.SQL("select t1.*,t2.attr_def_data_type,t2.element_type from form_item t1 left join form_item_template t2 on t1.form_item_template=t2.id where form=?", taskObj.Form).Find(&items) + err = dao.X.SQL("select t1.*,t2.attr_def_data_type,t2.element_type from form_item t1 left join form_item_template t2 on t1.form_item_template=t2.id where form=?", taskObj.Form).Find(&items) if err != nil { return result, callbackUrl, fmt.Errorf("Try to query form item fail:%s ", err.Error()) } @@ -677,20 +682,20 @@ func getApproveCallbackParam(taskId string) (result models.PluginTaskCreateResp, } func SaveTaskForm(taskId, operator string, param models.TaskApproveParam) error { - var actions []*execAction + var actions []*dao.ExecAction taskObj, err := getSimpleTask(taskId) if err != nil { return err } var existFormItemTable []*models.FormItemTable - x.SQL("select * from form_item where form in (select form from task where id=?)", taskId).Find(&existFormItemTable) + dao.X.SQL("select * from form_item where form in (select form from task where id=?)", taskId).Find(&existFormItemTable) existFormItemMap := make(map[string]int) inputItemMap := make(map[string]int) for _, v := range existFormItemTable { existFormItemMap[fmt.Sprintf("%s^%s^%s", v.ItemGroup, v.Name, v.RowDataId)] = 1 } nowTime := time.Now().Format(models.DateTimeFormat) - actions = append(actions, &execAction{Sql: "update task set `result`=?,chose_option=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{param.Comment, param.ChoseOption, operator, nowTime, taskId}}) + actions = append(actions, &dao.ExecAction{Sql: "update task set `result`=?,chose_option=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{param.Comment, param.ChoseOption, operator, nowTime, taskId}}) if taskObj.Request != "" { for _, tableForm := range param.FormData { tmpColumnMap := make(map[string]string) @@ -715,15 +720,15 @@ func SaveTaskForm(taskId, operator string, param models.TaskApproveParam) error tmpV = append(tmpV, fmt.Sprintf("%s", interfaceV)) } if _, bbb := existFormItemMap[tmpExistKey]; !bbb { - actions = append(actions, &execAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{guid.CreateGuid(), taskObj.Form, titleId, k, strings.Join(tmpV, ","), tableForm.ItemGroup, valueObj.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{guid.CreateGuid(), taskObj.Form, titleId, k, strings.Join(tmpV, ","), tableForm.ItemGroup, valueObj.Id}}) } else { - actions = append(actions, &execAction{Sql: "update form_item set value=? where form=? and row_data_id=? and name=?", Param: []interface{}{strings.Join(tmpV, ","), taskObj.Form, valueObj.Id, k}}) + actions = append(actions, &dao.ExecAction{Sql: "update form_item set value=? where form=? and row_data_id=? and name=?", Param: []interface{}{strings.Join(tmpV, ","), taskObj.Form, valueObj.Id, k}}) } } else { if _, bbb := existFormItemMap[tmpExistKey]; !bbb { - actions = append(actions, &execAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{guid.CreateGuid(), taskObj.Form, titleId, k, v, tableForm.ItemGroup, valueObj.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into form_item(id,form,form_item_template,name,value,item_group,row_data_id) value (?,?,?,?,?,?,?)", Param: []interface{}{guid.CreateGuid(), taskObj.Form, titleId, k, v, tableForm.ItemGroup, valueObj.Id}}) } else { - actions = append(actions, &execAction{Sql: "update form_item set value=? where form=? and row_data_id=? and name=?", Param: []interface{}{v, taskObj.Form, valueObj.Id, k}}) + actions = append(actions, &dao.ExecAction{Sql: "update form_item set value=? where form=? and row_data_id=? and name=?", Param: []interface{}{v, taskObj.Form, valueObj.Id, k}}) } } } @@ -732,11 +737,11 @@ func SaveTaskForm(taskId, operator string, param models.TaskApproveParam) error } for _, row := range existFormItemTable { if _, ok := inputItemMap[fmt.Sprintf("%s^%s^%s", row.ItemGroup, row.Name, row.RowDataId)]; !ok { - actions = append(actions, &execAction{Sql: "delete from form_item where id=?", Param: []interface{}{row.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item where id=?", Param: []interface{}{row.Id}}) } } } - return transaction(actions) + return dao.Transaction(actions) } func ChangeTaskStatus(taskId, operator, operation, lastedUpdateTime string) (taskObj models.TaskTable, err error) { @@ -751,28 +756,28 @@ func ChangeTaskStatus(taskId, operator, operation, lastedUpdateTime string) (tas if taskObj.Status == "done" { return taskObj, fmt.Errorf("Task aleary done with %s %s ", taskObj.UpdatedBy, taskObj.UpdatedTime) } - var actions []*execAction + var actions []*dao.ExecAction nowTime := time.Now().Format(models.DateTimeFormat) if operation == "mark" { - actions = append(actions, &execAction{Sql: "update task set status=?,handler=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"marked", operator, operator, nowTime, taskId}}) + actions = append(actions, &dao.ExecAction{Sql: "update task set status=?,handler=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"marked", operator, operator, nowTime, taskId}}) } else if operation == "start" { if operator != taskObj.Handler { return taskObj, fmt.Errorf("Task handler is %s ", taskObj.Handler) } - actions = append(actions, &execAction{Sql: "update task set status=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"doing", operator, nowTime, taskId}}) + actions = append(actions, &dao.ExecAction{Sql: "update task set status=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"doing", operator, nowTime, taskId}}) } else if operation == "quit" { if operator != taskObj.Handler { return taskObj, fmt.Errorf("Task handler is %s ", taskObj.Handler) } - actions = append(actions, &execAction{Sql: "update task set status=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"marked", operator, nowTime, taskId}}) + actions = append(actions, &dao.ExecAction{Sql: "update task set status=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"marked", operator, nowTime, taskId}}) } else if operation == "give" { // 转给我 if taskObj.Status == "done" { return taskObj, fmt.Errorf("Task status:%s is not marked ", taskObj.Status) } - actions = append(actions, &execAction{Sql: "update task set status=?,handler=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"marked", operator, operator, nowTime, taskId}}) + actions = append(actions, &dao.ExecAction{Sql: "update task set status=?,handler=?,updated_by=?,updated_time=? where id=?", Param: []interface{}{"marked", operator, operator, nowTime, taskId}}) } - err = transaction(actions) + err = dao.Transaction(actions) if err != nil { return taskObj, err } @@ -812,7 +817,7 @@ func NotifyTaskMail(taskId string) error { taskObj, _ := getSimpleTask(taskId) log.Logger.Info("Start notify task mail", log.String("taskId", taskId)) var roleTable []*models.RoleTable - x.SQL("select id,email from `role` where id in (select `role` from task_template_role where role_type='USE' and task_template in (select task_template from task where id=?))", taskId).Find(&roleTable) + dao.X.SQL("select id,email from `role` where id in (select `role` from task_template_role where role_type='USE' and task_template in (select task_template from task where id=?))", taskId).Find(&roleTable) reportRoleString := taskObj.ReportRole reportRoleString = strings.ReplaceAll(reportRoleString, "[", "") reportRoleString = strings.ReplaceAll(reportRoleString, "]", "") @@ -830,7 +835,7 @@ func NotifyTaskMail(taskId string) error { return fmt.Errorf("handle role email is empty ") } var taskTable []*models.TaskTable - x.SQL("select t1.id,t1.name,t1.description,t2.name as request,t1.node_name,t1.emergency,t1.reporter,t1.created_time from task t1 left join request t2 on t1.request=t2.id where t1.id=?", taskId).Find(&taskTable) + dao.X.SQL("select t1.id,t1.name,t1.description,t2.name as request,t1.node_name,t1.emergency,t1.reporter,t1.created_time from task t1 left join request t2 on t1.request=t2.id where t1.id=?", taskId).Find(&taskTable) if len(taskTable) == 0 { return fmt.Errorf("can not find task with id:%s ", taskId) } @@ -846,7 +851,7 @@ func NotifyTaskMail(taskId string) error { func GetSimpleTask(taskId string) (task models.TaskTable, err error) { var taskTable []*models.TaskTable - err = x.SQL("select * from task where id=?", taskId).Find(&taskTable) + err = dao.X.SQL("select * from task where id=?", taskId).Find(&taskTable) if err != nil { return } diff --git a/taskman-server/services/db/task_template.go b/taskman-server/service/task_template_service.go similarity index 66% rename from taskman-server/services/db/task_template.go rename to taskman-server/service/task_template_service.go index 5dd25f59..293d2928 100644 --- a/taskman-server/services/db/task_template.go +++ b/taskman-server/service/task_template_service.go @@ -1,13 +1,18 @@ -package db +package service import ( "fmt" "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "time" ) +type TaskTemplateService struct { + taskTemplateDao dao.TaskTemplateRoleDao +} + func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models.TaskTemplateDto, err error) { result = models.TaskTemplateDto{} taskTemplate, getTaskErr := getSimpleTaskTemplate("", requestTemplateId, proNodeId, nodeId) @@ -26,7 +31,7 @@ func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models result.USERoles = []string{} result.RequestTemplateId = requestTemplateId var formTemplateTable []*models.FormTemplateTable - err = x.SQL("select * from form_template where id=?", taskTemplate.FormTemplate).Find(&formTemplateTable) + err = dao.X.SQL("select * from form_template where id=?", taskTemplate.FormTemplate).Find(&formTemplateTable) if err != nil { err = fmt.Errorf("Try to query form template table fail,%s ", err.Error()) return @@ -40,11 +45,11 @@ func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models result.UpdatedTime = formTemplateTable[0].UpdatedTime result.UpdatedBy = formTemplateTable[0].UpdatedBy var formItemTemplate []*models.FormItemTemplateTable - x.SQL("select * from form_item_template where form_template=?", taskTemplate.FormTemplate).Find(&formItemTemplate) + dao.X.SQL("select * from form_item_template where form_template=?", taskTemplate.FormTemplate).Find(&formItemTemplate) result.Items = formItemTemplate roleMap, _ := getRoleMap() var taskRoleTable []*models.TaskTemplateRoleTable - x.SQL("select `role`,role_type from task_template_role where task_template=?", taskTemplate.Id).Find(&taskRoleTable) + dao.X.SQL("select `role`,role_type from task_template_role where task_template=?", taskTemplate.Id).Find(&taskRoleTable) for _, role := range taskRoleTable { if role.RoleType == "MGMT" { result.MGMTRoleObjs = append(result.MGMTRoleObjs, roleMap[role.Role]) @@ -66,14 +71,14 @@ func CreateTaskTemplate(param models.TaskTemplateDto, requestTemplateId string) formCreateParam := models.FormTemplateDto{Name: param.Name, Description: param.Description, UpdatedBy: param.UpdatedBy, Items: param.Items, NowTime: nowTime} actions, formId := getFormTemplateCreateActions(formCreateParam) taskTemplateId := guid.CreateGuid() - actions = append(actions, &execAction{Sql: "insert into task_template(id,name,description,form_template,request_template,node_id,node_def_id,node_name,expire_day,handler) value (?,?,?,?,?,?,?,?,?,?)", Param: []interface{}{taskTemplateId, param.Name, param.Description, formId, requestTemplateId, param.NodeId, param.NodeDefId, param.NodeDefName, param.ExpireDay, param.Handler}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into task_template(id,name,description,form_template,request_template,node_id,node_def_id,node_name,expire_day,handler) value (?,?,?,?,?,?,?,?,?,?)", Param: []interface{}{taskTemplateId, param.Name, param.Description, formId, requestTemplateId, param.NodeId, param.NodeDefId, param.NodeDefName, param.ExpireDay, param.Handler}}) for _, v := range param.MGMTRoles { - actions = append(actions, &execAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{taskTemplateId + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", taskTemplateId, v, "MGMT"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{taskTemplateId + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", taskTemplateId, v, "MGMT"}}) } for _, v := range param.USERoles { - actions = append(actions, &execAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{taskTemplateId + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", taskTemplateId, v, "USE"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{taskTemplateId + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", taskTemplateId, v, "USE"}}) } - return transactionWithoutForeignCheck(actions) + return dao.TransactionWithoutForeignCheck(actions) } func UpdateTaskTemplate(param models.TaskTemplateDto) error { @@ -87,15 +92,15 @@ func UpdateTaskTemplate(param models.TaskTemplateDto) error { if getActionErr != nil { return getActionErr } - actions = append(actions, &execAction{Sql: "delete from task_template_role where task_template=?", Param: []interface{}{param.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from task_template_role where task_template=?", Param: []interface{}{param.Id}}) for _, v := range param.MGMTRoles { - actions = append(actions, &execAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", param.Id, v, "MGMT"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", param.Id, v, "MGMT"}}) } for _, v := range param.USERoles { - actions = append(actions, &execAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", param.Id, v, "USE"}}) + actions = append(actions, &dao.ExecAction{Sql: "insert into task_template_role(id,task_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{param.Id + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", param.Id, v, "USE"}}) } - actions = append(actions, &execAction{Sql: "update task_template set name=?,description=?,expire_day=?,handler=? where id=?", Param: []interface{}{param.Name, param.Description, param.ExpireDay, param.Handler, param.Id}}) - return transaction(actions) + actions = append(actions, &dao.ExecAction{Sql: "update task_template set name=?,description=?,expire_day=?,handler=? where id=?", Param: []interface{}{param.Name, param.Description, param.ExpireDay, param.Handler, param.Id}}) + return dao.Transaction(actions) } func getSimpleTaskTemplate(id, requestTemplate, proNodeId, nodeId string) (result models.TaskTemplateTable, err error) { @@ -118,7 +123,7 @@ func getSimpleTaskTemplate(id, requestTemplate, proNodeId, nodeId string) (resul baseSql += " and node_id=?" params = append(params, nodeId) } - err = x.SQL(baseSql, params...).Find(&taskTemplateTable) + err = dao.X.SQL(baseSql, params...).Find(&taskTemplateTable) if err != nil { err = fmt.Errorf("Try to query database fail,%s ", err.Error()) return @@ -135,7 +140,7 @@ func getSimpleTaskTemplate(id, requestTemplate, proNodeId, nodeId string) (resul func getRoleMap() (result map[string]*models.RoleTable, err error) { result = make(map[string]*models.RoleTable) var roleTable []*models.RoleTable - err = x.SQL("select id,display_name from `role`").Find(&roleTable) + err = dao.X.SQL("select id,display_name from `role`").Find(&roleTable) if err != nil { return } @@ -148,7 +153,7 @@ func getRoleMap() (result map[string]*models.RoleTable, err error) { func getTaskTemplateHandler(requestTemplate string) (taskTemplateMap map[string]*models.TaskTemplateVo, err error) { taskTemplateMap = make(map[string]*models.TaskTemplateVo) var taskTemplateList []*models.TaskTemplateVo - err = x.SQL("select t.id,t.handler,tr.role from task_template t join task_template_role tr on "+ + err = dao.X.SQL("select t.id,t.handler,tr.role from task_template t join task_template_role tr on "+ "t.id=tr.task_template where t.request_template = ?", requestTemplate).Find(&taskTemplateList) if len(taskTemplateList) > 0 { for _, taskTemplate := range taskTemplateList { @@ -162,7 +167,7 @@ func GetTaskTemplateMapByRequestTemplate(requestTemplate string) (taskTemplateMa taskTemplateMap = make(map[string]int) var rowsData []*models.TaskTemplateTable sql := "select * from task_template where request_template = ?" - err = x.SQL(sql, requestTemplate).Find(&rowsData) + err = dao.X.SQL(sql, requestTemplate).Find(&rowsData) if len(rowsData) > 0 { for _, row := range rowsData { taskTemplateMap[row.Name] = row.ExpireDay diff --git a/taskman-server/services/db/validate.go b/taskman-server/service/validate.go similarity index 92% rename from taskman-server/services/db/validate.go rename to taskman-server/service/validate.go index e22bc46e..9a2fa216 100644 --- a/taskman-server/services/db/validate.go +++ b/taskman-server/service/validate.go @@ -1,8 +1,9 @@ -package db +package service import ( "fmt" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "regexp" "strings" @@ -75,7 +76,7 @@ func validateFormDataRegular(input *models.RequestPreDataTableObj, userToken str func getFormItemTemplateNameMap(idList []string) map[string]*models.FormItemTemplateTable { resultMap := make(map[string]*models.FormItemTemplateTable) var itemTemplateTable []*models.FormItemTemplateTable - x.SQL("select * from form_item_template where id in ('" + strings.Join(idList, "','") + "')").Find(&itemTemplateTable) + dao.X.SQL("select * from form_item_template where id in ('" + strings.Join(idList, "','") + "')").Find(&itemTemplateTable) for _, v := range itemTemplateTable { resultMap[v.Name] = v } From 4c608cef7e8c59bf7b08668b291b40eb1aeca5b2 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Tue, 6 Feb 2024 18:09:09 +0800 Subject: [PATCH 002/618] =?UTF-8?q?=E8=AF=B7=E6=B1=82=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 2 + taskman-server/api/v1/form/form_template.go | 23 ++- .../api/v1/request/request_template.go | 97 ++++++++-- taskman-server/common/network/network.go | 47 +++++ taskman-server/dao/request_template_dao.go | 20 +- taskman-server/models/approve.go | 47 +++++ taskman-server/models/const.go | 11 ++ taskman-server/models/form_template.go | 17 ++ taskman-server/models/process_defintions.go | 99 ++++++++++ taskman-server/models/request_template.go | 82 +++++--- taskman-server/models/response.go | 26 +++ taskman-server/models/user_role.go | 17 ++ taskman-server/remote/proc_def_remote.go | 76 ++++++++ taskman-server/remote/user_role_remote.go | 71 +++++++ .../service/request_template_service.go | 183 ++++++++++++++++++ taskman-server/service/service.go | 7 + 16 files changed, 778 insertions(+), 47 deletions(-) create mode 100644 taskman-server/common/network/network.go create mode 100644 taskman-server/models/approve.go create mode 100644 taskman-server/models/process_defintions.go create mode 100644 taskman-server/models/user_role.go create mode 100644 taskman-server/remote/proc_def_remote.go create mode 100644 taskman-server/remote/user_role_remote.go diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 5f31394f..387e4dd1 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -43,6 +43,8 @@ func init() { &handlerFuncObj{Url: "/request-template", Method: "POST", HandlerFunc: request.CreateRequestTemplate}, &handlerFuncObj{Url: "/request-template", Method: "PUT", HandlerFunc: request.UpdateRequestTemplate}, &handlerFuncObj{Url: "/request-template", Method: "DELETE", HandlerFunc: request.DeleteRequestTemplate}, + &handlerFuncObj{Url: "/request-template/handler/update", Method: "POST", HandlerFunc: request.UpdateRequestTemplateHandler}, + &handlerFuncObj{Url: "/request-template/status/update", Method: "POST", HandlerFunc: request.UpdateRequestTemplateStatus}, &handlerFuncObj{Url: "/request-template/:id/attrs/update", Method: "PUT", HandlerFunc: request.UpdateRequestTemplateEntityAttrs}, &handlerFuncObj{Url: "/request-template/:id/attrs/get", Method: "GET", HandlerFunc: request.GetRequestTemplateEntityAttrs}, &handlerFuncObj{Url: "/request-template/:id/attrs/list", Method: "GET", HandlerFunc: request.ListRequestTemplateEntityAttrs}, diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index 37df3106..ce6e0701 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -1,12 +1,17 @@ package form import ( + "fmt" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" ) +var ( + requestTemplateService = service.GetRequestTemplateService() +) + func GetRequestFormTemplate(c *gin.Context) { id := c.Param("id") if id == "" { @@ -49,8 +54,24 @@ func UpdateRequestFormTemplate(c *gin.Context) { } func ConfirmRequestFormTemplate(c *gin.Context) { + var requestTemplate *models.RequestTemplateTable + var err error id := c.Param("id") - err := service.ConfirmRequestTemplate(id) + requestTemplate, err = requestTemplateService.GetRequestTemplate(id) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + if requestTemplate == nil { + middleware.ReturnError(c, fmt.Errorf("param id is vailid")) + return + } + // 只要待确认状态下才能去发布 + if requestTemplate.Status != string(models.RequestTemplateStatusPending) { + middleware.ReturnError(c, fmt.Errorf("illegal operation")) + return + } + err = service.ConfirmRequestTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/api/v1/request/request_template.go b/taskman-server/api/v1/request/request_template.go index 30e9357d..0b5bb343 100644 --- a/taskman-server/api/v1/request/request_template.go +++ b/taskman-server/api/v1/request/request_template.go @@ -3,17 +3,23 @@ package request import ( "encoding/json" "fmt" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "io/ioutil" "net/http" "strings" "time" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" ) +var ( + requestTemplateService = service.GetRequestTemplateService() +) + func QueryRequestTemplateGroup(c *gin.Context) { var param models.QueryRequestParam if err := c.ShouldBindJSON(¶m); err != nil { @@ -85,26 +91,11 @@ func DeleteRequestTemplateGroup(c *gin.Context) { } func GetCoreProcessList(c *gin.Context) { - result, err := service.GetCoreProcessListNew(c.GetHeader("Authorization")) - //procList, err := service.GetCoreProcessListAll(c.GetHeader("Authorization"), "MGMT", models.ProcessFetchTabs) + result, err := requestTemplateService.GetCoreProcessListNew(c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return } - //result := []*models.ProcDefObj{} - //for _, v := range procList { - // tmpData := models.ProcDefObj{ProcDefId: v.ProcDefId, ProcDefKey: v.ProcDefKey, ProcDefName: v.ProcDefName, Status: v.Status, CreatedTime: v.CreatedTime, RootEntity: models.ProcEntity{}} - // tmpEntity := v.RootEntity - // if filterIndex := strings.Index(tmpEntity, "{"); filterIndex > 0 { - // tmpEntity = tmpEntity[:filterIndex] - // } - // if strings.Contains(tmpEntity, ":") { - // tmpEntitySplit := strings.Split(tmpEntity, ":") - // tmpData.RootEntity.PackageName = tmpEntitySplit[0] - // tmpData.RootEntity.Name = tmpEntitySplit[1] - // } - // result = append(result, &tmpData) - //} middleware.ReturnData(c, result) } @@ -155,7 +146,7 @@ func QueryRequestTemplate(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := service.QueryRequestTemplate(¶m, c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) + pageInfo, rowData, err := requestTemplateService.QueryRequestTemplate(¶m, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -183,6 +174,76 @@ func CreateRequestTemplate(c *gin.Context) { middleware.ReturnData(c, result) } +// UpdateRequestTemplateHandler 请求模板处理:转给我 +func UpdateRequestTemplateHandler(c *gin.Context) { + var param models.RequestTemplateHandlerDto + var requestTemplate *models.RequestTemplateTable + var err error + if err = c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + if param.RequestTemplateId == "" { + middleware.ReturnParamEmptyError(c, "requestTemplateId") + return + } + requestTemplate, err = requestTemplateService.GetRequestTemplate(param.RequestTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + if requestTemplate == nil { + middleware.ReturnError(c, fmt.Errorf("requestTemplateId not exist")) + return + } + // 处理时间校验 + if common.GetLowVersionUnixMillis(requestTemplate.UpdatedTime) != param.LatestUpdateTime { + err = exterror.New().DealWithAtTheSameTimeError + middleware.ReturnError(c, err) + return + } + if requestTemplate.Status == string(models.RequestTemplateStatusConfirm) { + middleware.ReturnError(c, fmt.Errorf("request template has deployed")) + return + } + err = requestTemplateService.UpdateRequestTemplateHandler(requestTemplate.Id, middleware.GetRequestUser(c)) + if err != nil { + middleware.ReturnError(c, err) + return + } + middleware.ReturnSuccess(c) +} + +// UpdateRequestTemplateStatus 更新请求模板状态 +func UpdateRequestTemplateStatus(c *gin.Context) { + var param models.RequestTemplateStatusUpdateParam + var requestTemplate *models.RequestTemplateTable + var err error + if err = c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + requestTemplate, err = requestTemplateService.GetRequestTemplate(param.RequestTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + if requestTemplate == nil { + middleware.ReturnError(c, fmt.Errorf("requestTemplateId not exist")) + return + } + if requestTemplate.Status != param.Status { + middleware.ReturnParamValidateError(c, fmt.Errorf("param status invalid")) + return + } + err = requestTemplateService.UpdateRequestTemplateStatus(param.RequestTemplateId, middleware.GetRequestUser(c), param.TargetStatus, param.Reason) + if err != nil { + middleware.ReturnError(c, err) + return + } + middleware.ReturnSuccess(c) +} + func UpdateRequestTemplate(c *gin.Context) { var param models.RequestTemplateUpdateParam if err := c.ShouldBindJSON(¶m); err != nil { diff --git a/taskman-server/common/network/network.go b/taskman-server/common/network/network.go new file mode 100644 index 00000000..40f76e7c --- /dev/null +++ b/taskman-server/common/network/network.go @@ -0,0 +1,47 @@ +package network + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strings" +) + +// HttpGet Get请求 +func HttpGet(url, userToken, language string) (byteArr []byte, err error) { + req, newReqErr := http.NewRequest(http.MethodGet, url, strings.NewReader("")) + if newReqErr != nil { + err = fmt.Errorf("Try to new http request fail,%s ", newReqErr.Error()) + return + } + req.Header.Set("Authorization", userToken) + req.Header.Set("Accept-Language", language) + resp, respErr := http.DefaultClient.Do(req) + if respErr != nil { + err = fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) + return + } + byteArr, _ = io.ReadAll(resp.Body) + defer resp.Body.Close() + return +} + +// HttpPost Post请求 +func HttpPost(url, userToken, language string, postBytes []byte) (byteArr []byte, err error) { + req, reqErr := http.NewRequest(http.MethodPost, url, bytes.NewReader(postBytes)) + if reqErr != nil { + err = fmt.Errorf("new http reqeust fail,%s ", reqErr.Error()) + return + } + req.Header.Set("Authorization", userToken) + req.Header.Set("Accept-Language", language) + resp, respErr := http.DefaultClient.Do(req) + if respErr != nil { + err = fmt.Errorf("do http reqeust fail,%s ", reqErr.Error()) + return + } + byteArr, _ = io.ReadAll(resp.Body) + defer resp.Body.Close() + return +} diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index f09d2ec8..be720b35 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -1,7 +1,25 @@ package dao -import "xorm.io/xorm" +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "xorm.io/xorm" +) type RequestTemplateDao struct { DB *xorm.Engine } + +func (d RequestTemplateDao) Update(requestTemplate models.RequestTemplateTable) (err error) { + _, err = d.DB.ID(requestTemplate.Id).Update(&requestTemplate) + return +} + +func (d RequestTemplateDao) UpdateByTransaction(session *xorm.Session, requestTemplate models.RequestTemplateTable) (err error) { + _, err = session.ID(requestTemplate.Id).Update(&requestTemplate) + return +} + +func (d RequestTemplateDao) Get(requestTemplateId string) (requestTemplate *models.RequestTemplateTable, err error) { + _, err = d.DB.ID(requestTemplateId).Get(requestTemplate) + return +} diff --git a/taskman-server/models/approve.go b/taskman-server/models/approve.go new file mode 100644 index 00000000..2ea0005b --- /dev/null +++ b/taskman-server/models/approve.go @@ -0,0 +1,47 @@ +package models + +// RequestApproveTable 请求审批表 +type RequestApproveTable struct { + Id string `json:"id" xorm:"id"` + Request string `json:"request" xorm:"request"` // 请求ID + Name string `json:"name" xorm:"name"` // 审批名称 + ExpireDay string `json:"expireDay" xorm:"expire_day"` // 审批时效 + Type string `json:"type" xorm:"type"` // 审批类型:审批类型: administrator 管理员,pass 自动通过,custom 自定义 + Sort int `json:"sort" xorm:"sort"` // 执行顺序 + FormTemplate string `json:"formTemplate" xorm:"form_template"` // 表单ID + Method string `json:"method" xorm:"method"` // 分配类型:单人:single, 协同: anyone 并行:all + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` +} + +func (RequestApproveTable) TableName() string { + return "request_approve" +} + +// RequestApproveRoleTable 请求审批角色表 +type RequestApproveRoleTable struct { + Id string `json:"id" xorm:"id"` + RequestApprove string `json:"requestApprove" xorm:"request_approve"` // 请求审批ID + Role string `json:"role" xorm:"role"` // 角色 + handler string `json:"handler" xorm:"handler"` // 处理人 + CreatedTime string `json:"createdTime" xorm:"created_time"` +} + +func (RequestApproveRoleTable) TableName() string { + return "request_approve_role" +} + +// TaskApproveRoleTable 任务审批表 +type TaskApproveRoleTable struct { + Id string `json:"id" xorm:"id"` + Task string `json:"task" xorm:"task"` // 任务审批ID + Role string `json:"role" xorm:"role"` // 角色 + handler string `json:"handler" xorm:"handler"` // 处理人 + CreatedTime string `json:"createdTime" xorm:"created_time"` +} + +func (TaskApproveRoleTable) TableName() string { + return "task_approve_role" +} diff --git a/taskman-server/models/const.go b/taskman-server/models/const.go index f4e8cefc..b1115c14 100644 --- a/taskman-server/models/const.go +++ b/taskman-server/models/const.go @@ -32,3 +32,14 @@ const ( ReleaseType TemplateType = "release" // 发布 OtherType TemplateType = "other" // 其他 ) + +// RequestTemplateStatus 请求模板状态 +type RequestTemplateStatus string + +const ( + RequestTemplateStatusCreated RequestTemplateStatus = "created" // 创建 + RequestTemplateStatusDisabled RequestTemplateStatus = "disabled" // 禁用 + RequestTemplateStatusPending RequestTemplateStatus = "pending" // 待发布 + RequestTemplateStatusConfirm RequestTemplateStatus = "confirm" // 已发布 + +) diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index 98dbcf78..371da9da 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -11,6 +11,10 @@ type FormTemplateTable struct { DelFlag int `json:"delFlag" xorm:"del_flag"` } +func (FormTemplateTable) TableName() string { + return "form_template" +} + type FormTable struct { Id string `json:"id" xorm:"id"` Name string `json:"name" xorm:"name"` @@ -23,11 +27,16 @@ type FormTable struct { DelFlag int `json:"delFlag" xorm:"del_flag"` } +func (FormTable) TableName() string { + return "form" +} + type FormItemTemplateTable struct { Id string `json:"id" xorm:"id"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` ItemGroup string `json:"itemGroup" xorm:"item_group"` + ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义,request 请求信息 ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` FormTemplate string `json:"formTemplate" xorm:"form_template"` DefaultValue string `json:"defaultValue" xorm:"default_value"` @@ -55,6 +64,10 @@ type FormItemTemplateTable struct { SelectList []*EntityDataObj `json:"selectList" xorm:"-"` } +func (FormItemTemplateTable) TableName() string { + return "form_item_template" +} + type FormItemTable struct { Id string `json:"id" xorm:"id"` Form string `json:"form" xorm:"form"` @@ -65,6 +78,10 @@ type FormItemTable struct { RowDataId string `json:"rowDataId" xorm:"row_data_id"` } +func (FormItemTable) TableName() string { + return "form_item" +} + type FormTemplateDto struct { Id string `json:"id"` Name string `json:"name"` diff --git a/taskman-server/models/process_defintions.go b/taskman-server/models/process_defintions.go new file mode 100644 index 00000000..c3f2799b --- /dev/null +++ b/taskman-server/models/process_defintions.go @@ -0,0 +1,99 @@ +package models + +import ( + "time" +) + +type ProcDefQueryDto struct { + ManageRole string `json:"manageRole"` //管理角色 + ProcDefList []*ProcDefDto `json:"dataList"` // 编排列表 +} + +type QueryProcessDefinitionParam struct { + ProcDefId string `json:"procDefId"` // 编排Id + ProcDefName string `json:"procDefName"` // 编排名称 + Plugins []string `json:"plugins"` // 授权插件 + UpdatedTimeStart string `json:"updatedTimeStart"` // 更新时间开始 + UpdatedTimeEnd string `json:"updatedTimeEnd"` // 更新时间结束 + Status string `json:"status"` // disabled 禁用 draft草稿 deployed 发布状态 + CreatedBy string `json:"createdBy"` // 创建人 + UpdatedBy string `json:"updatedBy"` // 更新人 + Scene string `json:"scene"` // 使用场景 + UserRoles []string // 用户角色 +} + +type ProcDefDto struct { + Id string `json:"id"` // 唯一标识 + Key string `json:"key"` // 编排key + Name string `json:"name"` // 编排名称 + Version string `json:"version"` // 版本 + RootEntity string `json:"rootEntity"` // 根节点 + Status string `json:"status"` // 状态 + Tags string `json:"tags"` // 标签 + AuthPlugins []string `json:"authPlugins"` // 授权插件 + Scene string `json:"scene"` // 使用场景 + ConflictCheck bool `json:"conflictCheck"` // 冲突检测 + CreatedBy string `json:"createdBy"` // 创建人 + CreatedTime string `json:"createdTime"` // 创建时间 + UpdatedBy string `json:"updatedBy"` // 更新人 + UpdatedTime string `json:"updatedTime"` // 更新时间 + EnableCreated bool `json:"enableCreated"` // 能否创建新版本 + EnableModifyName bool `json:"enableModifyName"` // 能否修改名称 + UseRoles []string `json:"userRoles"` // 使用角色 +} + +type EntityProDefDto struct { + Id string `json:"id"` // 唯一标识 + PackageName string `json:"packageName"` // 包名称 + Name string `json:"name"` // 名称 + DisplayName string `json:"displayName"` // 显示名称 + Description string `json:"description"` // 描述 +} + +type DataModel struct { + PluginPackageDataModel + Entities []*DataModelEntity `json:"entities"` +} + +type DataModelEntity struct { + Id string `json:"id"` // 唯一标识 + DataModelId string `json:"dataModelId"` // 所属数据模型 + DataModelVersion int `json:"dataModelVersion"` // 版本 + PackageName string `json:"packageName"` // 包名 + Name string `json:"name"` // 模型名 + DisplayName string `json:"displayName"` // 显示名 + Description string `json:"description"` // 描述 +} + +type PluginPackageDataModel struct { + Id string `json:"id"` // 唯一标识 + Version int `json:"version"` // 版本 + PackageName string `json:"packageName"` // 包名 + IsDynamic bool `json:"dynamic"` // 是否动态 + UpdatePath string `json:"updatePath"` // 请求路径 + UpdateMethod string `json:"updateMethod"` // 请求方法 + UpdateSource string `json:"updateSource"` // 来源 + UpdatedTime time.Time `json:"updatedTime"` // 更新时间 + UpdateTime int64 `json:"updateTime"` // 旧更新时间,毫秒时间戳 +} + +func ConvertModelsList2Map(nodesList []*DataModel) map[string]ProcEntity { + var entityMap = make(map[string]ProcEntity) + if len(nodesList) > 0 { + for _, model := range nodesList { + for _, entity := range model.Entities { + if entity.PackageName != "" && entity.Name != "" { + entityMap[entity.PackageName+":"+entity.Name] = ProcEntity{ + Id: entity.DataModelId, + PackageName: entity.PackageName, + Name: entity.Name, + Description: entity.Description, + DisplayName: entity.DisplayName, + Attributes: nil, + } + } + } + } + } + return entityMap +} diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index 2223bd9d..9aa10bd6 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -1,32 +1,43 @@ package models type RequestTemplateTable struct { - Id string `json:"id" xorm:"id"` - Group string `json:"group" xorm:"group"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` - FormTemplate string `json:"formTemplate" xorm:"form_template"` - Tags string `json:"tags" xorm:"tags"` - Status string `json:"status" xorm:"status"` - RecordId string `json:"recordId" xorm:"record_id"` - Version string `json:"version" xorm:"version"` - ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` - PackageName string `json:"packageName" xorm:"package_name"` - EntityName string `json:"entityName" xorm:"entity_name"` - ProcDefKey string `json:"procDefKey" xorm:"proc_def_key"` - ProcDefId string `json:"procDefId" xorm:"proc_def_id"` - ProcDefName string `json:"procDefName" xorm:"proc_def_name"` - CreatedBy string `json:"createdBy" xorm:"created_by"` - CreatedTime string `json:"createdTime" xorm:"created_time"` - UpdatedBy string `json:"updatedBy" xorm:"updated_by"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - EntityAttrs string `json:"entityAttrs" xorm:"entity_attrs"` - ExpireDay int `json:"expireDay" xorm:"expire_day"` - Handler string `json:"handler" xorm:"handler"` - DelFlag int `json:"delFlag" xorm:"del_flag"` - Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 - OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 - ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID + Id string `json:"id" xorm:"id"` + Group string `json:"group" xorm:"group"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + FormTemplate string `json:"formTemplate" xorm:"form_template"` + Tags string `json:"tags" xorm:"tags"` + Status string `json:"status" xorm:"status"` + RecordId string `json:"recordId" xorm:"record_id"` + Version string `json:"version" xorm:"version"` + ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` + PackageName string `json:"packageName" xorm:"package_name"` + EntityName string `json:"entityName" xorm:"entity_name"` + ProcDefKey string `json:"procDefKey" xorm:"proc_def_key"` + ProcDefId string `json:"procDefId" xorm:"proc_def_id"` + ProcDefName string `json:"procDefName" xorm:"proc_def_name"` + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + EntityAttrs string `json:"entityAttrs" xorm:"entity_attrs"` + ExpireDay int `json:"expireDay" xorm:"expire_day"` + Handler string `json:"handler" xorm:"handler"` + DelFlag int `json:"delFlag" xorm:"del_flag"` + Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 + OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 + ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID + ApproveBy string `json:"approveBy" xorm:"approve_by"` // 模板发布审批人 + PendingSwitch bool `json:"pendingSwitch" xorm:"pending_switch"` // 是否加入确认定版流程 + PendingRole string `json:"pendingRole" xorm:"pending_role"` // 定版角色 + PendingHandler string `json:"pendingHandler" xorm:"pending_handler"` // 定版处理人 + ConfirmSwitch bool `json:"confirmSwitch" xorm:"confirm_switch"` // 是否加入确认流程 + ConfirmExpireDay int `json:"confirmExpireDay" xorm:"confirm_expire_day"` // 是否加入确认流程 + RollbackDesc string `json:"rollbackDesc" xorm:"rollback_desc"` // 退回理由 +} + +func (RequestTemplateTable) TableName() string { + return "request_template" } type RequestTemplateGroupTable struct { @@ -42,6 +53,10 @@ type RequestTemplateGroupTable struct { DelFlag int `json:"delFlag" xorm:"del_flag"` } +func (RequestTemplateGroupTable) TableName() string { + return "request_template_group" +} + type RoleTable struct { Id string `json:"id" xorm:"id"` DisplayName string `json:"displayName" xorm:"display_name"` @@ -57,6 +72,11 @@ type RequestTemplateRoleTable struct { RoleType string `json:"roleType" xorm:"role_type"` } +type RequestTemplateHandlerDto struct { + RequestTemplateId string `json:"request_template_id"` //模板id + LatestUpdateTime string `json:"latestUpdateTime"` //最后更新时间 +} + type CoreProcessQueryResponse struct { Status string `json:"status"` Message string `json:"message"` @@ -95,7 +115,15 @@ type RequestTemplateQueryObj struct { MGMTRoles []*RoleTable `json:"mgmtRoles"` USERoles []*RoleTable `json:"useRoles"` OperateOptions []string `json:"operateOptions"` - ModifyType bool `json:"modifyType"` // 是否能够修改模板类型 + ModifyType bool `json:"modifyType"` // 是否能够修改模板类型 + Administrator string `json:"administrator"` // 角色管理员 +} + +type RequestTemplateStatusUpdateParam struct { + RequestTemplateId string `json:"requestTemplateId"` // 请求模板ID + Status string `json:"status"` // 当前状态 + TargetStatus string `json:"targetStatus"` // 目标状态 + Reason string `json:"reason"` // 原因 } type RequestTemplateUpdateParam struct { diff --git a/taskman-server/models/response.go b/taskman-server/models/response.go index 462ca8bb..18501042 100644 --- a/taskman-server/models/response.go +++ b/taskman-server/models/response.go @@ -39,3 +39,29 @@ type SysLogTable struct { DataKeyName string `json:"dataKeyName" xorm:"data_key_name"` Response string `json:"response" xorm:"response"` } + +type HttpResponseMeta struct { + Code int `json:"-"` + Status string `json:"status"` + Message string `json:"message"` +} + +type QueryRolesResponse struct { + HttpResponseMeta + Data []*SimpleLocalRoleDto `json:"data"` +} + +type QueryUserResponse struct { + HttpResponseMeta + Data []*UserDto `json:"data"` +} + +type QueryProcessDefinitionResponse struct { + HttpResponseMeta + Data []*ProcDefQueryDto `json:"data"` +} + +type QueryAllModelsResponse struct { + HttpResponseMeta + Data []*DataModel `json:"data"` +} diff --git a/taskman-server/models/user_role.go b/taskman-server/models/user_role.go new file mode 100644 index 00000000..4e7c41f8 --- /dev/null +++ b/taskman-server/models/user_role.go @@ -0,0 +1,17 @@ +package models + +type SimpleLocalRoleDto struct { + ID string `json:"id"` + Name string `json:"name"` + DisplayName string `json:"displayName"` + Email string `json:"email"` + Status string `json:"status"` // Deleted, NotDeleted + Administrator string `json:"administrator"` // 角色管理员 +} + +type UserDto struct { + ID string `json:"id"` + UserName string `json:"username"` + Password string `json:"password"` + AuthType string `json:"authType"` // LOCAL,UM +} diff --git a/taskman-server/remote/proc_def_remote.go b/taskman-server/remote/proc_def_remote.go new file mode 100644 index 00000000..06c4c60d --- /dev/null +++ b/taskman-server/remote/proc_def_remote.go @@ -0,0 +1,76 @@ +package remote + +import ( + "encoding/json" + "fmt" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/network" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" +) + +const ( + // pathQueryProcessDefinitions 查询编排 + pathQueryProcessDefinitions = "/platform/v1/process/definitions/list" + // pathQueryModel 查询model + pathQueryModel = "/platform/v1/models" +) + +// QueryProcessDefinitionList 查询编排列表 +func QueryProcessDefinitionList(userToken, language string, param models.QueryProcessDefinitionParam) (processList []*models.ProcDefDto, err error) { + var response models.QueryProcessDefinitionResponse + var procDefMap = make(map[string]*models.ProcDefDto) + processList = make([]*models.ProcDefDto, 0) + postBytes, _ := json.Marshal(param) + byteArr, err := network.HttpPost(models.Config.Wecube.BaseUrl+pathQueryProcessDefinitions, userToken, language, postBytes) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + return + } + if len(response.Data) > 0 { + for _, queryDto := range response.Data { + if len(queryDto.ProcDefList) > 0 { + for _, dto := range queryDto.ProcDefList { + procDefMap[dto.Id] = dto + } + } + } + } + if len(procDefMap) > 0 { + if err != nil { + return + } + for _, dto := range procDefMap { + processList = append(processList, dto) + } + } + return +} + +// QueryAllModels 查询所有模型 +func QueryAllModels(userToken, language string) (nodesList []*models.DataModel, err error) { + var response models.QueryAllModelsResponse + nodesList = make([]*models.DataModel, 0) + byteArr, err := network.HttpGet(models.Config.Wecube.BaseUrl+pathQueryModel, userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + if len(response.Data) > 0 { + nodesList = response.Data + } + return +} diff --git a/taskman-server/remote/user_role_remote.go b/taskman-server/remote/user_role_remote.go new file mode 100644 index 00000000..6bfde0ab --- /dev/null +++ b/taskman-server/remote/user_role_remote.go @@ -0,0 +1,71 @@ +package remote + +import ( + "encoding/json" + "fmt" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/network" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" +) + +const ( + // pathRetrieveAllRoles 查询所有角色 + pathRetrieveAllRoles = "/platform/v1/roles/retrieve?all=%s" + // pathRetrieveAllUser 查询所有用户 + pathRetrieveAllUser = "/platform/v1/users/retrieve" +) + +// QueryAllRoles 查询所有角色 +func QueryAllRoles(requiredAll, userToken, language string) (roleMap map[string]*models.SimpleLocalRoleDto, err error) { + var response models.QueryRolesResponse + var userMap map[string]*models.UserDto + roleMap = make(map[string]*models.SimpleLocalRoleDto) + byteArr, err := network.HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathRetrieveAllRoles, requiredAll), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + if len(response.Data) > 0 { + userMap, err = QueryAllUser(userToken, language) + if err != nil { + return + } + for _, data := range response.Data { + if len(userMap) > 0 && userMap[data.Administrator] != nil { + data.Administrator = userMap[data.Administrator].UserName + } + roleMap[data.Name] = data + } + } + return +} + +// QueryAllUser 查询所有用户 +func QueryAllUser(userToken, language string) (userMap map[string]*models.UserDto, err error) { + var response models.QueryUserResponse + userMap = make(map[string]*models.UserDto) + byteArr, err := network.HttpGet(models.Config.Wecube.BaseUrl+pathRetrieveAllUser, userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + if len(response.Data) > 0 { + for _, data := range response.Data { + userMap[data.ID] = data + } + } + return +} diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 1cbfff53..52211884 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -8,6 +8,7 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/remote" "io/ioutil" "net/http" "sort" @@ -20,6 +21,188 @@ type RequestTemplateService struct { requestTemplateDao dao.RequestTemplateDao } +func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestParam, userToken, language string, userRoles []string) (pageInfo models.PageInfo, result []*models.RequestTemplateQueryObj, err error) { + var roleMap = make(map[string]*models.SimpleLocalRoleDto) + extFilterSql := "" + result = []*models.RequestTemplateQueryObj{} + isQueryMessage := false + if len(param.Filters) > 0 { + var newFilters []*models.QueryRequestFilterObj + for _, v := range param.Filters { + if v.Name == "id" { + isQueryMessage = true + } + if v.Name == "mgmtRoles" || v.Name == "useRoles" { + inValueList := v.Value.([]interface{}) + var inValueStringList []string + for _, inValueInterfaceObj := range inValueList { + if inValueInterfaceObj == nil { + inValueStringList = append(inValueStringList, "") + } else { + inValueStringList = append(inValueStringList, inValueInterfaceObj.(string)) + } + } + if len(inValueStringList) == 0 { + continue + } + var tmpIds []string + var tmpErr error + roleFilterSql, roleFilterParam := dao.CreateListParams(inValueStringList, "") + if v.Name == "mgmtRoles" { + tmpIds, tmpErr = getRequestTemplateIdsBySql("select t1.id from request_template t1 left join request_template_role t2 on t1.id=t2.request_template where t2.role_type='MGMT' and t2.role in ("+roleFilterSql+")", roleFilterParam) + } else { + tmpIds, tmpErr = getRequestTemplateIdsBySql("select t1.id from request_template t1 left join request_template_role t2 on t1.id=t2.request_template where t2.role_type='USE' and t2.role in ("+roleFilterSql+")", roleFilterParam) + } + if tmpErr != nil { + err = fmt.Errorf("Try to query filter role id fail,%s ", tmpErr.Error()) + break + } + extFilterSql += " and id in ('" + strings.Join(tmpIds, "','") + "') " + } else { + newFilters = append(newFilters, v) + } + } + if err != nil { + return models.PageInfo{}, nil, err + } + param.Filters = newFilters + } + var rowData []*models.RequestTemplateTable + filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateTable{}, PrimaryKey: "id", Prefix: "t1"}) + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") + queryParam = append(userRolesFilterParam, queryParam...) + baseSql := fmt.Sprintf("SELECT %s FROM (select * from request_template where del_flag=0 or (del_flag=2 and id not in (select record_id from request_template where del_flag=2 and record_id<>''))) t1 WHERE t1.id in (select request_template from request_template_role where role_type='MGMT' and `role` in ("+userRolesFilterSql+")) %s %s ", queryColumn, extFilterSql, filterSql) + if param.Paging { + pageInfo.StartIndex = param.Pageable.StartIndex + pageInfo.PageSize = param.Pageable.PageSize + pageInfo.TotalRows = dao.QueryCount(baseSql, queryParam...) + pageSql, pageParam := dao.TransPageInfoToSQL(*param.Pageable) + baseSql += pageSql + queryParam = append(queryParam, pageParam...) + } + err = dao.X.SQL(baseSql, queryParam...).Find(&rowData) + if len(rowData) == 0 || err != nil { + return + } + var rtIds []string + for _, row := range rowData { + rtIds = append(rtIds, row.Id) + } + queryRoleSql := "select t4.id,GROUP_CONCAT(t4.role_obj) as 'role','mgmt' as 'role_type' from (" + queryRoleSql += "select t1.id,CONCAT(t2.role,'::',t3.display_name) as 'role_obj' from request_template t1 left join request_template_role t2 on t1.id=t2.request_template left join role t3 on t2.role=t3.id where t1.id in ('" + strings.Join(rtIds, "','") + "') and t2.role_type='MGMT'" + queryRoleSql += ") t4 group by t4.id" + queryRoleSql += " UNION " + queryRoleSql += "select t4.id,GROUP_CONCAT(t4.role_obj) as 'role','use' as 'role_type' from (" + queryRoleSql += "select t1.id,CONCAT(t2.role,'::',t3.display_name) as 'role_obj' from request_template t1 left join request_template_role t2 on t1.id=t2.request_template left join role t3 on t2.role=t3.id where t1.id in ('" + strings.Join(rtIds, "','") + "') and t2.role_type='USE'" + queryRoleSql += ") t4 group by t4.id" + var requestTemplateRows []*models.RequestTemplateRoleTable + err = dao.X.SQL(queryRoleSql).Find(&requestTemplateRows) + if err != nil { + return + } + var mgmtRoleMap = make(map[string][]*models.RoleTable) + var useRoleMap = make(map[string][]*models.RoleTable) + for _, v := range requestTemplateRows { + var tmpRoles []*models.RoleTable + for _, vv := range strings.Split(v.Role, ",") { + tmpSplit := strings.Split(vv, "::") + tmpRoles = append(tmpRoles, &models.RoleTable{Id: tmpSplit[0], DisplayName: tmpSplit[1]}) + } + if v.RoleType == "mgmt" { + mgmtRoleMap[v.Id] = tmpRoles + } else { + useRoleMap[v.Id] = tmpRoles + } + } + if isQueryMessage { + for _, v := range rowData { + tmpErr := SyncProcDefId(v.Id, v.ProcDefId, v.ProcDefName, v.ProcDefKey, userToken) + if tmpErr != nil { + err = fmt.Errorf("Try to sync proDefId fail,%s ", tmpErr.Error()) + break + } + } + if err != nil { + return + } + } + roleMap, err = remote.QueryAllRoles("Y", userToken, language) + if err != nil { + return + } + for _, v := range rowData { + tmpObj := models.RequestTemplateQueryObj{RequestTemplateTable: *v, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} + if _, b := mgmtRoleMap[v.Id]; b { + tmpObj.MGMTRoles = mgmtRoleMap[v.Id] + } + if _, b := useRoleMap[v.Id]; b { + tmpObj.USERoles = useRoleMap[v.Id] + } + if v.Status == "confirm" { + tmpObj.OperateOptions = []string{"query", "fork", "export", "disable"} + } else if v.Status == "created" { + tmpObj.OperateOptions = []string{"edit", "delete"} + } else if v.Status == "disable" { + tmpObj.OperateOptions = []string{"query", "enable"} + } + tmpObj.ModifyType = getRequestTemplateModifyType(v) + // 模板管理角色收敛,只能唯一,读取角色管理员 + if len(tmpObj.MGMTRoles) > 0 && roleMap[tmpObj.MGMTRoles[0].Id] != nil { + tmpObj.Administrator = roleMap[tmpObj.MGMTRoles[0].Id].Administrator + } + result = append(result, &tmpObj) + } + return +} + +func (s RequestTemplateService) UpdateRequestTemplateHandler(requestTemplateId, handler string) (err error) { + return s.requestTemplateDao.Update(models.RequestTemplateTable{Id: requestTemplateId, Handler: handler, UpdatedBy: handler, + UpdatedTime: time.Now().Format(models.DateTimeFormat)}) +} + +func (s RequestTemplateService) UpdateRequestTemplateStatus(requestTemplateId, user, status, reason string) (err error) { + requestTemplate := models.RequestTemplateTable{Id: requestTemplateId, Status: status, UpdatedBy: user, + UpdatedTime: time.Now().Format(models.DateTimeFormat)} + // 状态更新到草稿,需要退回 + if status == string(models.Draft) { + requestTemplate.RollbackDesc = reason + } + return s.requestTemplateDao.Update(requestTemplate) +} + +func (s RequestTemplateService) GetRequestTemplate(requestTemplateId string) (requestTemplate *models.RequestTemplateTable, err error) { + return s.requestTemplateDao.Get(requestTemplateId) +} + +func (s RequestTemplateService) GetCoreProcessListNew(userToken, language string) (processList []*models.ProcDefObj, err error) { + var procDefDtoList []*models.ProcDefDto + var nodesList []*models.DataModel + var entityMap = make(map[string]models.ProcEntity) + processList = make([]*models.ProcDefObj, 0) + procDefDtoList, err = remote.QueryProcessDefinitionList(userToken, language, models.QueryProcessDefinitionParam{Plugins: []string{"taskman"}, Status: "deployed"}) + if err != nil { + return + } + nodesList, err = remote.QueryAllModels(userToken, language) + if err != nil { + return + } + entityMap = models.ConvertModelsList2Map(nodesList) + if len(procDefDtoList) > 0 { + for _, dto := range procDefDtoList { + processList = append(processList, &models.ProcDefObj{ + ProcDefId: dto.Id, + ProcDefKey: dto.Key, + ProcDefName: dto.Name, + Status: dto.Status, + RootEntity: entityMap[dto.RootEntity], + CreatedTime: dto.CreatedTime, + }) + } + } + return +} + func QueryRequestTemplateGroup(param *models.QueryRequestParam, userRoles []string) (pageInfo models.PageInfo, rowData []*models.RequestTemplateGroupTable, err error) { rowData = []*models.RequestTemplateGroupTable{} filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateGroupTable{}, PrimaryKey: "id"}) diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index f436cf6f..a3de7ee1 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -34,9 +34,11 @@ func New() (err error) { // 初始化Dao requestDao := dao.RequestDao{DB: engine} attachFileDao := dao.AttachFileDao{DB: engine} + requestTemplateDao := dao.RequestTemplateDao{DB: engine} // 初始化Service requestService = RequestService{requestDao: requestDao} attachFileService = AttachFileService{attachFileDao: attachFileDao} + requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao} db = engine return } @@ -46,6 +48,11 @@ func GetRequestService() RequestService { return requestService } +// GetRequestTemplateService 获取请求模板 service +func GetRequestTemplateService() RequestTemplateService { + return requestTemplateService +} + // transaction 事务处理 func transaction(f func(session *xorm.Session) error) (err error) { session := db.NewSession() From 044eb3ea9570c11a712d2ffc3d3f7a01daa094ef Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 7 Feb 2024 01:45:00 +0800 Subject: [PATCH 003/618] =?UTF-8?q?model=E6=95=B0=E6=8D=AE=E6=8B=86?= =?UTF-8?q?=E5=88=86.=E9=A1=B9=E7=9B=AE=E7=BB=93=E6=9E=84=E6=8B=86?= =?UTF-8?q?=E5=88=86=E6=94=B9=E6=88=90mvc=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/form/form_template.go | 3 +- taskman-server/api/v1/request/request.go | 14 +- .../api/v1/request/request_template.go | 23 +- taskman-server/api/v1/task/task.go | 8 +- taskman-server/api/v1/task/task_template.go | 6 +- taskman-server/api/v2/request/request.go | 9 +- taskman-server/dao/db.go | 2 +- taskman-server/dao/operation_log_dao.go | 9 +- taskman-server/dao/request_template_dao.go | 13 +- .../dao/request_template_role_dao.go | 18 +- ...late_role.go => task_template_role_dao.go} | 4 +- taskman-server/models/approve.go | 26 -- taskman-server/models/attach_file.go | 15 + taskman-server/models/collect.go | 11 - taskman-server/models/collect_template.go | 14 + taskman-server/models/const.go | 7 + taskman-server/models/data_model.go | 95 ++++++ taskman-server/models/form.go | 17 + taskman-server/models/form_item.go | 15 + taskman-server/models/form_item_template.go | 38 +++ taskman-server/models/form_template.go | 67 ---- taskman-server/models/operation_log.go | 38 +++ taskman-server/models/param.go | 10 + taskman-server/models/process_defintions.go | 248 ++++++++++++-- taskman-server/models/request.go | 241 ++++---------- taskman-server/models/request_approve_role.go | 14 + taskman-server/models/request_template.go | 303 ++++-------------- .../models/request_template_group.go | 40 +++ .../models/request_template_role.go | 21 ++ taskman-server/models/response.go | 35 ++ taskman-server/models/role.go | 13 + taskman-server/models/task.go | 9 - taskman-server/models/task_approve_role.go | 14 + taskman-server/models/workflow.go | 83 ----- .../proc_def_rpc.go} | 2 +- .../user_role_rpc.go} | 2 +- .../service/operation_log_service.go | 37 +++ taskman-server/service/ref_select_service.go | 6 +- taskman-server/service/request_service.go | 28 +- .../service/request_template_service.go | 273 ++++------------ taskman-server/service/service.go | 12 +- 41 files changed, 921 insertions(+), 922 deletions(-) rename taskman-server/dao/{task_template_role.go => task_template_role_dao.go} (71%) create mode 100644 taskman-server/models/attach_file.go delete mode 100644 taskman-server/models/collect.go create mode 100644 taskman-server/models/data_model.go create mode 100644 taskman-server/models/form.go create mode 100644 taskman-server/models/form_item.go create mode 100644 taskman-server/models/form_item_template.go create mode 100644 taskman-server/models/operation_log.go create mode 100644 taskman-server/models/request_approve_role.go create mode 100644 taskman-server/models/request_template_group.go create mode 100644 taskman-server/models/request_template_role.go create mode 100644 taskman-server/models/role.go create mode 100644 taskman-server/models/task_approve_role.go delete mode 100644 taskman-server/models/workflow.go rename taskman-server/{remote/proc_def_remote.go => rpc/proc_def_rpc.go} (99%) rename taskman-server/{remote/user_role_remote.go => rpc/user_role_rpc.go} (99%) create mode 100644 taskman-server/service/operation_log_service.go diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index ce6e0701..2d6d333d 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -10,6 +10,7 @@ import ( var ( requestTemplateService = service.GetRequestTemplateService() + operationLogService = service.GetOperationLogService() ) func GetRequestFormTemplate(c *gin.Context) { @@ -76,7 +77,7 @@ func ConfirmRequestFormTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "confirmRequestTemplate", c.Request.RequestURI, "") + operationLogService.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "confirmRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } diff --git a/taskman-server/api/v1/request/request.go b/taskman-server/api/v1/request/request.go index 1d44696b..a354d928 100644 --- a/taskman-server/api/v1/request/request.go +++ b/taskman-server/api/v1/request/request.go @@ -205,7 +205,7 @@ func CreateRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } @@ -226,7 +226,7 @@ func UpdateRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestLog(param.Id, param.Name, param.UpdatedBy, "updateRequest", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestLog(param.Id, param.Name, param.UpdatedBy, "updateRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } @@ -237,7 +237,7 @@ func DeleteRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "deleteRequest", c.Request.RequestURI, "") + operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "deleteRequest", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } @@ -294,7 +294,7 @@ func StartRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, instanceId) } @@ -315,7 +315,7 @@ func UpdateRequestStatus(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "setRequestStatus", c.Request.RequestURI, status) + operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "setRequestStatus", c.Request.RequestURI, status) middleware.ReturnSuccess(c) } @@ -464,7 +464,7 @@ func CopyRequest(c *gin.Context) { if err != nil { middleware.ReturnServerHandleError(c, err) } else { - service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "copyRequest", c.Request.RequestURI, "") + operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "copyRequest", c.Request.RequestURI, "") middleware.ReturnData(c, result) } } @@ -530,7 +530,7 @@ func GetProcessDefinitions(c *gin.Context) { middleware.ReturnData(c, rowData) } -// GetWorkFlowNodes 获取工作流执行节点 +// GetExecutionNodes 获取工作流执行节点 func GetExecutionNodes(c *gin.Context) { procInstanceId := c.Param("procInstanceId") nodeInstanceId := c.Param("nodeInstanceId") diff --git a/taskman-server/api/v1/request/request_template.go b/taskman-server/api/v1/request/request_template.go index 0b5bb343..f7cc0d9f 100644 --- a/taskman-server/api/v1/request/request_template.go +++ b/taskman-server/api/v1/request/request_template.go @@ -18,6 +18,7 @@ import ( var ( requestTemplateService = service.GetRequestTemplateService() + operationLogService = service.GetOperationLogService() ) func QueryRequestTemplateGroup(c *gin.Context) { @@ -165,12 +166,12 @@ func CreateRequestTemplate(c *gin.Context) { return } param.CreatedBy = middleware.GetRequestUser(c) - result, err := service.CreateRequestTemplate(¶m) + result, err := requestTemplateService.CreateRequestTemplate(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "createRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "createRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, result) } @@ -206,6 +207,10 @@ func UpdateRequestTemplateHandler(c *gin.Context) { middleware.ReturnError(c, fmt.Errorf("request template has deployed")) return } + if err := requestTemplateService.CheckRequestTemplateRoles(param.RequestTemplateId, middleware.GetRequestRoles(c)); err != nil { + middleware.ReturnDataPermissionError(c, err) + return + } err = requestTemplateService.UpdateRequestTemplateHandler(requestTemplate.Id, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnError(c, err) @@ -258,7 +263,7 @@ func UpdateRequestTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - if err := service.CheckRequestTemplateRoles(param.Id, middleware.GetRequestRoles(c)); err != nil { + if err := requestTemplateService.CheckRequestTemplateRoles(param.Id, middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionError(c, err) return } @@ -268,7 +273,7 @@ func UpdateRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "updateRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "updateRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, result) } @@ -294,7 +299,7 @@ func DeleteRequestTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - if err := service.CheckRequestTemplateRoles(id, middleware.GetRequestRoles(c)); err != nil { + if err := requestTemplateService.CheckRequestTemplateRoles(id, middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionError(c, err) return } @@ -347,7 +352,7 @@ func UpdateRequestTemplateEntityAttrs(c *gin.Context) { return } service.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) - service.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateRequestTemplateAttr", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateRequestTemplateAttr", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnSuccess(c) } @@ -367,7 +372,7 @@ func ForkConfirmRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "forkRequestTemplate", c.Request.RequestURI, "") + operationLogService.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "forkRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } @@ -449,7 +454,7 @@ func DisableRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "disableRequestTemplate", c.Request.RequestURI, "") + operationLogService.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "disableRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } @@ -460,6 +465,6 @@ func EnableRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "enableRequestTemplate", c.Request.RequestURI, "") + operationLogService.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "enableRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } diff --git a/taskman-server/api/v1/task/task.go b/taskman-server/api/v1/task/task.go index 0c6fe2f1..c2426be0 100644 --- a/taskman-server/api/v1/task/task.go +++ b/taskman-server/api/v1/task/task.go @@ -119,7 +119,7 @@ func SaveTaskForm(c *gin.Context) { if err != nil { middleware.ReturnServerHandleError(c, err) } else { - service.RecordTaskLog(taskId, task.Name, operator, "saveTask", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordTaskLog(taskId, task.Name, operator, "saveTask", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnSuccess(c) } } @@ -190,7 +190,7 @@ func ApproveTask(c *gin.Context) { if err != nil { middleware.ReturnServerHandleError(c, err) } else { - service.RecordTaskLog(taskId, taskTable.Name, operator, "approveTask", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordTaskLog(taskId, taskTable.Name, operator, "approveTask", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnSuccess(c) } } @@ -208,7 +208,7 @@ func ChangeTaskStatus(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "changeTaskStatus", c.Request.RequestURI, operation) + operationLogService.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "changeTaskStatus", c.Request.RequestURI, operation) middleware.ReturnData(c, taskObj) } @@ -238,7 +238,7 @@ func UploadTaskAttachFile(c *gin.Context) { if err != nil { middleware.ReturnServerHandleError(c, err) } else { - service.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "uploadTaskFile", c.Request.RequestURI, file.Filename) + operationLogService.RecordTaskLog(taskId, "", middleware.GetRequestUser(c), "uploadTaskFile", c.Request.RequestURI, file.Filename) middleware.ReturnData(c, service.GetTaskAttachFileList(taskId)) } } diff --git a/taskman-server/api/v1/task/task_template.go b/taskman-server/api/v1/task/task_template.go index 8ec72d2b..35d77701 100644 --- a/taskman-server/api/v1/task/task_template.go +++ b/taskman-server/api/v1/task/task_template.go @@ -8,6 +8,10 @@ import ( "github.com/gin-gonic/gin" ) +var ( + operationLogService = service.GetOperationLogService() +) + func GetTaskTemplate(c *gin.Context) { requestTemplateId := c.Param("requestTemplateId") proNodeId := c.Param("proNodeId") @@ -43,7 +47,7 @@ func UpdateTaskTemplate(c *gin.Context) { return } service.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) - service.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateTaskTemplate", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateTaskTemplate", c.Request.RequestURI, c.GetString("requestBody")) result, _ := service.GetTaskTemplate(id, param.NodeDefId, "") middleware.ReturnData(c, result) } diff --git a/taskman-server/api/v2/request/request.go b/taskman-server/api/v2/request/request.go index 7361145e..778a98a7 100644 --- a/taskman-server/api/v2/request/request.go +++ b/taskman-server/api/v2/request/request.go @@ -9,6 +9,11 @@ import ( "time" ) +var ( + requestTemplateService = service.GetRequestTemplateService() + operationLogService = service.GetOperationLogService() +) + // GetRequestDetail 新版请求详情 func GetRequestDetail(c *gin.Context) { requestId := c.Param("requestId") @@ -58,7 +63,7 @@ func CreateRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } @@ -143,6 +148,6 @@ func StartRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - service.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) + operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, instanceId) } diff --git a/taskman-server/dao/db.go b/taskman-server/dao/db.go index d78489d6..e7a60ee6 100644 --- a/taskman-server/dao/db.go +++ b/taskman-server/dao/db.go @@ -163,7 +163,7 @@ func TransFiltersToSQL(queryParam *models.QueryRequestParam, transParam *models. param = append(param, fmt.Sprintf("%%%s%%", filter.Value)) } else if filter.Operator == "in" { inValueList := filter.Value.([]interface{}) - inValueStringList := []string{} + var inValueStringList []string for _, inValueInterfaceObj := range inValueList { if inValueInterfaceObj == nil { inValueStringList = append(inValueStringList, "") diff --git a/taskman-server/dao/operation_log_dao.go b/taskman-server/dao/operation_log_dao.go index fb4a80d2..7d6b194e 100644 --- a/taskman-server/dao/operation_log_dao.go +++ b/taskman-server/dao/operation_log_dao.go @@ -1,7 +1,14 @@ package dao -import "xorm.io/xorm" +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "xorm.io/xorm" +) type OperationLogDao struct { DB *xorm.Engine } + +func (d OperationLogDao) AddOperationLog(record *models.OperationLogTable) (affected int64, err error) { + return d.DB.Insert(record) +} diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index be720b35..b625f81f 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -9,13 +9,16 @@ type RequestTemplateDao struct { DB *xorm.Engine } -func (d RequestTemplateDao) Update(requestTemplate models.RequestTemplateTable) (err error) { - _, err = d.DB.ID(requestTemplate.Id).Update(&requestTemplate) - return +func (d RequestTemplateDao) Add(session *xorm.Session, requestTemplate *models.RequestTemplateTable) (affected int64, err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + return session.Insert(requestTemplate) } -func (d RequestTemplateDao) UpdateByTransaction(session *xorm.Session, requestTemplate models.RequestTemplateTable) (err error) { - _, err = session.ID(requestTemplate.Id).Update(&requestTemplate) +func (d RequestTemplateDao) Update(requestTemplate models.RequestTemplateTable) (err error) { + _, err = d.DB.ID(requestTemplate.Id).Update(&requestTemplate) return } diff --git a/taskman-server/dao/request_template_role_dao.go b/taskman-server/dao/request_template_role_dao.go index f671e873..0e54d2c3 100644 --- a/taskman-server/dao/request_template_role_dao.go +++ b/taskman-server/dao/request_template_role_dao.go @@ -1,7 +1,23 @@ package dao -import "xorm.io/xorm" +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "xorm.io/xorm" +) type RequestTemplateRoleDao struct { DB *xorm.Engine } + +func (d RequestTemplateRoleDao) CheckRequestTemplateRoles(requestTemplateId string, userRoles []string) (bool, error) { + return d.DB.Table(models.RequestTemplateRoleTable{}.TableName()).Where("request_template=?", requestTemplateId).And("role_type", + "MGMT").In("role", userRoles).Exist() +} + +func (d RequestTemplateRoleDao) Add(session *xorm.Session, requestTemplateRole *models.RequestTemplateRoleTable) (affected int64, err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + return session.Insert(requestTemplateRole) +} diff --git a/taskman-server/dao/task_template_role.go b/taskman-server/dao/task_template_role_dao.go similarity index 71% rename from taskman-server/dao/task_template_role.go rename to taskman-server/dao/task_template_role_dao.go index 1ba0dec4..fc9a4ff7 100644 --- a/taskman-server/dao/task_template_role.go +++ b/taskman-server/dao/task_template_role_dao.go @@ -1,6 +1,8 @@ package dao -import "xorm.io/xorm" +import ( + "xorm.io/xorm" +) type TaskTemplateRoleDao struct { DB *xorm.Engine diff --git a/taskman-server/models/approve.go b/taskman-server/models/approve.go index 2ea0005b..44c9be1e 100644 --- a/taskman-server/models/approve.go +++ b/taskman-server/models/approve.go @@ -19,29 +19,3 @@ type RequestApproveTable struct { func (RequestApproveTable) TableName() string { return "request_approve" } - -// RequestApproveRoleTable 请求审批角色表 -type RequestApproveRoleTable struct { - Id string `json:"id" xorm:"id"` - RequestApprove string `json:"requestApprove" xorm:"request_approve"` // 请求审批ID - Role string `json:"role" xorm:"role"` // 角色 - handler string `json:"handler" xorm:"handler"` // 处理人 - CreatedTime string `json:"createdTime" xorm:"created_time"` -} - -func (RequestApproveRoleTable) TableName() string { - return "request_approve_role" -} - -// TaskApproveRoleTable 任务审批表 -type TaskApproveRoleTable struct { - Id string `json:"id" xorm:"id"` - Task string `json:"task" xorm:"task"` // 任务审批ID - Role string `json:"role" xorm:"role"` // 角色 - handler string `json:"handler" xorm:"handler"` // 处理人 - CreatedTime string `json:"createdTime" xorm:"created_time"` -} - -func (TaskApproveRoleTable) TableName() string { - return "task_approve_role" -} diff --git a/taskman-server/models/attach_file.go b/taskman-server/models/attach_file.go new file mode 100644 index 00000000..1bf2b7de --- /dev/null +++ b/taskman-server/models/attach_file.go @@ -0,0 +1,15 @@ +package models + +type AttachFileTable struct { + Id string `json:"id" xorm:"id"` + Name string `json:"name" xorm:"name"` + S3BucketName string `json:"s3BucketName" xorm:"s3_bucket_name"` + S3KeyName string `json:"s3KeyName" xorm:"s3_key_name"` + DelFlag int `json:"delFlag" xorm:"del_flag"` + Request string `json:"request" xorm:"request"` + Task string `json:"task" xorm:"task"` +} + +func (AttachFileTable) TableName() string { + return "attach_file" +} diff --git a/taskman-server/models/collect.go b/taskman-server/models/collect.go deleted file mode 100644 index 26b8afde..00000000 --- a/taskman-server/models/collect.go +++ /dev/null @@ -1,11 +0,0 @@ -package models - -type CollectFilterItem struct { - TemplateGroupList []*KeyValuePair `json:"templateList"` // 模板组列表 - OperatorObjTypeList []string `json:"operatorObjTypeList"` // 操作对象类型列表 - ProcDefNameList []string `json:"procDefNameList"` // 使用编排 - OwnerList []string `json:"ownerList"` // 属主 - TagList []string `json:"tagList"` // 标签 - ManageRoleList []string `json:"manageRoleList"` // 属主角色 - UseRoleList []string `json:"useRoleList"` // 使用角色 -} diff --git a/taskman-server/models/collect_template.go b/taskman-server/models/collect_template.go index e221a853..080105cb 100644 --- a/taskman-server/models/collect_template.go +++ b/taskman-server/models/collect_template.go @@ -9,3 +9,17 @@ type CollectTemplateTable struct { Type int `json:"type" xorm:"type"` // 类型:0表示请求 1发布 CreatedTime string `json:"createdTime" xorm:"created_time"` } + +func (CollectTemplateTable) TableName() string { + return "collect_template" +} + +type CollectFilterItem struct { + TemplateGroupList []*KeyValuePair `json:"templateList"` // 模板组列表 + OperatorObjTypeList []string `json:"operatorObjTypeList"` // 操作对象类型列表 + ProcDefNameList []string `json:"procDefNameList"` // 使用编排 + OwnerList []string `json:"ownerList"` // 属主 + TagList []string `json:"tagList"` // 标签 + ManageRoleList []string `json:"manageRoleList"` // 属主角色 + UseRoleList []string `json:"useRoleList"` // 使用角色 +} diff --git a/taskman-server/models/const.go b/taskman-server/models/const.go index b1115c14..0532b6c6 100644 --- a/taskman-server/models/const.go +++ b/taskman-server/models/const.go @@ -41,5 +41,12 @@ const ( RequestTemplateStatusDisabled RequestTemplateStatus = "disabled" // 禁用 RequestTemplateStatusPending RequestTemplateStatus = "pending" // 待发布 RequestTemplateStatusConfirm RequestTemplateStatus = "confirm" // 已发布 +) + +// RolePermission 角色权限 +type RolePermission string +const ( + RolePermissionUse RolePermission = "USE" + RolePermissionMGMT RolePermission = "MGMT" ) diff --git a/taskman-server/models/data_model.go b/taskman-server/models/data_model.go new file mode 100644 index 00000000..0a62f350 --- /dev/null +++ b/taskman-server/models/data_model.go @@ -0,0 +1,95 @@ +package models + +import "time" + +type DataModel struct { + PluginPackageDataModel + Entities []*DataModelEntity `json:"entities"` +} + +type DataModelEntity struct { + Id string `json:"id"` // 唯一标识 + DataModelId string `json:"dataModelId"` // 所属数据模型 + DataModelVersion int `json:"dataModelVersion"` // 版本 + PackageName string `json:"packageName"` // 包名 + Name string `json:"name"` // 模型名 + DisplayName string `json:"displayName"` // 显示名 + Description string `json:"description"` // 描述 +} + +type EntityQueryResult struct { + Status string `json:"status"` + Message string `json:"message"` + Data []*EntityDataObj `json:"data"` +} + +type EntityDataObj struct { + Id string `json:"guid"` + DisplayName string `json:"key_name"` + IsNew bool `json:"isNew"` + PackageName string `json:"package_name"` + Entity string `json:"entity"` +} + +type EntityTreeResult struct { + Status string `json:"status"` + Message string `json:"message"` + Data EntityTreeData `json:"data"` +} + +type EntityTreeData struct { + EntityTreeNodes []*EntityTreeObj `json:"entityTreeNodes"` + ProcessSessionId string `json:"processSessionId"` +} + +type EntityTreeObj struct { + PackageName string `json:"packageName"` + EntityName string `json:"entityName"` + DataId string `json:"dataId"` + DisplayName string `json:"displayName"` + FullDataId interface{} `json:"fullDataId"` + Id string `json:"id"` + EntityData map[string]interface{} `json:"entityData"` + PreviousIds []string `json:"previousIds"` + SucceedingIds []string `json:"succeedingIds"` + EntityDataOp string `json:"entityDataOp"` +} + +type PluginPackageDataModel struct { + Id string `json:"id"` // 唯一标识 + Version int `json:"version"` // 版本 + PackageName string `json:"packageName"` // 包名 + IsDynamic bool `json:"dynamic"` // 是否动态 + UpdatePath string `json:"updatePath"` // 请求路径 + UpdateMethod string `json:"updateMethod"` // 请求方法 + UpdateSource string `json:"updateSource"` // 来源 + UpdatedTime time.Time `json:"updatedTime"` // 更新时间 + UpdateTime int64 `json:"updateTime"` // 旧更新时间,毫秒时间戳 +} + +type ProcEntityAttributeObj struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + DataType string `json:"dataType"` + Mandatory bool `json:"mandatory"` + RefPackageName string `json:"refPackageName"` + RefEntityName string `json:"refEntityName"` + RefAttrName string `json:"refAttrName"` + ReferenceId string `json:"referenceId"` + Active bool `json:"active"` + EntityId string `json:"entityId"` + EntityName string `json:"entityName"` + EntityDisplayName string `json:"entityDisplayName"` + EntityPackage string `json:"entityPackage"` + Multiple string `json:"multiple"` +} + +type ProcEntity struct { + Id string `json:"id"` + PackageName string `json:"packageName"` + Name string `json:"name"` + Description string `json:"description"` + DisplayName string `json:"displayName"` + Attributes []*ProcEntityAttributeObj `json:"attributes"` +} diff --git a/taskman-server/models/form.go b/taskman-server/models/form.go new file mode 100644 index 00000000..b9b35e8f --- /dev/null +++ b/taskman-server/models/form.go @@ -0,0 +1,17 @@ +package models + +type FormTable struct { + Id string `json:"id" xorm:"id"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + FormTemplate string `json:"formTemplate" xorm:"form_template"` + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + DelFlag int `json:"delFlag" xorm:"del_flag"` +} + +func (FormTable) TableName() string { + return "form" +} diff --git a/taskman-server/models/form_item.go b/taskman-server/models/form_item.go new file mode 100644 index 00000000..b881d7ba --- /dev/null +++ b/taskman-server/models/form_item.go @@ -0,0 +1,15 @@ +package models + +type FormItemTable struct { + Id string `json:"id" xorm:"id"` + Form string `json:"form" xorm:"form"` + FormItemTemplate string `json:"formItemTemplate" xorm:"form_item_template"` + Name string `json:"name" xorm:"name"` + Value string `json:"value" xorm:"value"` + ItemGroup string `json:"itemGroup" xorm:"item_group"` + RowDataId string `json:"rowDataId" xorm:"row_data_id"` +} + +func (FormItemTable) TableName() string { + return "form_item" +} diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go new file mode 100644 index 00000000..b5cc0705 --- /dev/null +++ b/taskman-server/models/form_item_template.go @@ -0,0 +1,38 @@ +package models + +type FormItemTemplateTable struct { + Id string `json:"id" xorm:"id"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + ItemGroup string `json:"itemGroup" xorm:"item_group"` + ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义,request 请求信息 + ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` + FormTemplate string `json:"formTemplate" xorm:"form_template"` + DefaultValue string `json:"defaultValue" xorm:"default_value"` + Sort int `json:"sort" xorm:"sort"` + PackageName string `json:"packageName" xorm:"package_name"` + Entity string `json:"entity" xorm:"entity"` + AttrDefId string `json:"attrDefId" xorm:"attr_def_id"` + AttrDefName string `json:"attrDefName" xorm:"attr_def_name"` + AttrDefDataType string `json:"attrDefDataType" xorm:"attr_def_data_type"` + ElementType string `json:"elementType" xorm:"element_type"` + Title string `json:"title" xorm:"title"` + Width int `json:"width" xorm:"width"` + RefPackageName string `json:"refPackageName" xorm:"ref_package_name"` + RefEntity string `json:"refEntity" xorm:"ref_entity"` + DataOptions string `json:"dataOptions" xorm:"data_options"` + Required string `json:"required" xorm:"required"` + Regular string `json:"regular" xorm:"regular"` + IsEdit string `json:"isEdit" xorm:"is_edit"` + IsView string `json:"isView" xorm:"is_view"` + IsOutput string `json:"isOutput" xorm:"is_output"` + InDisplayName string `json:"inDisplayName" xorm:"in_display_name"` + IsRefInside string `json:"isRefInside" xorm:"is_ref_inside"` + Multiple string `json:"multiple" xorm:"multiple"` + DefaultClear string `json:"defaultClear" xorm:"default_clear"` + SelectList []*EntityDataObj `json:"selectList" xorm:"-"` +} + +func (FormItemTemplateTable) TableName() string { + return "form_item_template" +} diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index 371da9da..deb9fc52 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -15,73 +15,6 @@ func (FormTemplateTable) TableName() string { return "form_template" } -type FormTable struct { - Id string `json:"id" xorm:"id"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` - FormTemplate string `json:"formTemplate" xorm:"form_template"` - CreatedBy string `json:"createdBy" xorm:"created_by"` - CreatedTime string `json:"createdTime" xorm:"created_time"` - UpdatedBy string `json:"updatedBy" xorm:"updated_by"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - DelFlag int `json:"delFlag" xorm:"del_flag"` -} - -func (FormTable) TableName() string { - return "form" -} - -type FormItemTemplateTable struct { - Id string `json:"id" xorm:"id"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` - ItemGroup string `json:"itemGroup" xorm:"item_group"` - ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义,request 请求信息 - ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` - FormTemplate string `json:"formTemplate" xorm:"form_template"` - DefaultValue string `json:"defaultValue" xorm:"default_value"` - Sort int `json:"sort" xorm:"sort"` - PackageName string `json:"packageName" xorm:"package_name"` - Entity string `json:"entity" xorm:"entity"` - AttrDefId string `json:"attrDefId" xorm:"attr_def_id"` - AttrDefName string `json:"attrDefName" xorm:"attr_def_name"` - AttrDefDataType string `json:"attrDefDataType" xorm:"attr_def_data_type"` - ElementType string `json:"elementType" xorm:"element_type"` - Title string `json:"title" xorm:"title"` - Width int `json:"width" xorm:"width"` - RefPackageName string `json:"refPackageName" xorm:"ref_package_name"` - RefEntity string `json:"refEntity" xorm:"ref_entity"` - DataOptions string `json:"dataOptions" xorm:"data_options"` - Required string `json:"required" xorm:"required"` - Regular string `json:"regular" xorm:"regular"` - IsEdit string `json:"isEdit" xorm:"is_edit"` - IsView string `json:"isView" xorm:"is_view"` - IsOutput string `json:"isOutput" xorm:"is_output"` - InDisplayName string `json:"inDisplayName" xorm:"in_display_name"` - IsRefInside string `json:"isRefInside" xorm:"is_ref_inside"` - Multiple string `json:"multiple" xorm:"multiple"` - DefaultClear string `json:"defaultClear" xorm:"default_clear"` - SelectList []*EntityDataObj `json:"selectList" xorm:"-"` -} - -func (FormItemTemplateTable) TableName() string { - return "form_item_template" -} - -type FormItemTable struct { - Id string `json:"id" xorm:"id"` - Form string `json:"form" xorm:"form"` - FormItemTemplate string `json:"formItemTemplate" xorm:"form_item_template"` - Name string `json:"name" xorm:"name"` - Value string `json:"value" xorm:"value"` - ItemGroup string `json:"itemGroup" xorm:"item_group"` - RowDataId string `json:"rowDataId" xorm:"row_data_id"` -} - -func (FormItemTable) TableName() string { - return "form_item" -} - type FormTemplateDto struct { Id string `json:"id"` Name string `json:"name"` diff --git a/taskman-server/models/operation_log.go b/taskman-server/models/operation_log.go new file mode 100644 index 00000000..f09afb2c --- /dev/null +++ b/taskman-server/models/operation_log.go @@ -0,0 +1,38 @@ +package models + +import ( + "github.com/WeBankPartners/go-common-lib/guid" + "time" +) + +type OperationLogTable struct { + Id string `json:"id" xorm:"id"` + Request string `json:"request" xorm:"request"` + RequestName string `json:"requestName" xorm:"request_name"` + RequestTemplate string `json:"requestTemplate" xorm:"request_template"` + RequestTemplateName string `json:"requestTemplateName" xorm:"request_template_name"` + Task string `json:"task" xorm:"task"` + TaskName string `json:"taskName" xorm:"task_name"` + Operation string `json:"operation" xorm:"operation"` + Operator string `json:"operator" xorm:"operator"` + Content string `json:"content" xorm:"content"` + Uri string `json:"uri" xorm:"uri"` + OpTime string `json:"opTime" xorm:"op_time"` +} + +func (OperationLogTable) TableName() string { + return "operation_log" +} + +func CreateRecordRequestTemplateLog(requestTemplateId, requestTemplateName, operator, operation, uri, content string) *OperationLogTable { + return &OperationLogTable{ + Id: guid.CreateGuid(), + RequestTemplate: requestTemplateId, + RequestTemplateName: requestTemplateName, + Operation: operation, + Operator: operator, + Content: content, + Uri: uri, + OpTime: time.Now().Format(DateTimeFormat), + } +} diff --git a/taskman-server/models/param.go b/taskman-server/models/param.go index 88b4abb2..990ddb6f 100644 --- a/taskman-server/models/param.go +++ b/taskman-server/models/param.go @@ -117,3 +117,13 @@ type PlatDataParam struct { User string UserToken string } + +type RequestQueryParam struct { + TemplateId string `json:"templateId"` // 模板id + RequestId string `json:"requestId"` // 请求id +} + +type TerminateInstanceParam struct { + ProcInstId string `json:"procInstId"` + ProcInstKey string `json:"procInstKey"` +} diff --git a/taskman-server/models/process_defintions.go b/taskman-server/models/process_defintions.go index c3f2799b..7cd9a818 100644 --- a/taskman-server/models/process_defintions.go +++ b/taskman-server/models/process_defintions.go @@ -1,9 +1,5 @@ package models -import ( - "time" -) - type ProcDefQueryDto struct { ManageRole string `json:"manageRole"` //管理角色 ProcDefList []*ProcDefDto `json:"dataList"` // 编排列表 @@ -50,31 +46,233 @@ type EntityProDefDto struct { Description string `json:"description"` // 描述 } -type DataModel struct { - PluginPackageDataModel - Entities []*DataModelEntity `json:"entities"` +type ProcDefObj struct { + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + ProcDefName string `json:"procDefName"` + Status string `json:"status"` + RootEntity ProcEntity `json:"rootEntity"` + CreatedTime string `json:"createdTime"` +} + +type ProcAllDefObj struct { + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + ProcDefName string `json:"procDefName"` + Status string `json:"status"` + RootEntity string `json:"rootEntity"` + CreatedTime string `json:"createdTime"` +} + +type ProcAllQueryResponse struct { + Status string `json:"status"` + Message string `json:"message"` + Data []*ProcAllDefObj `json:"data"` +} + +type ProcNodeObj struct { + NodeId string `json:"nodeId"` + NodeName string `json:"nodeName"` + NodeType string `json:"nodeType"` + NodeDefId string `json:"nodeDefId"` + TaskCategory string `json:"taskCategory"` + RoutineExp string `json:"routineExp"` + ServiceId string `json:"serviceId"` + ServiceName string `json:"serviceName"` + OrderedNo string `json:"orderedNo"` + OrderedNum int `json:"-"` + DynamicBind string `json:"dynamicbind"` + BoundEntities []*ProcEntity `json:"boundEntities"` +} + +type CodeProcessQueryObj struct { + ExcludeMode string `json:"excludeMode"` + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + ProcDefName string `json:"procDefName"` + ProcDefVersion string `json:"procDefVersion"` + RootEntity string `json:"rootEntity"` + Status string `json:"status"` + CreatedTime string `json:"createdTime"` + CreatedUnixTime int64 `json:"-"` + Tags string `json:"tags"` +} + +type WorkflowRsp struct { + Status string `json:"status"` + Message string `json:"message"` + Data Workflow `json:"data"` +} + +type Workflow struct { + Status string `json:"status"` + DefinitionsInfo *DefinitionsInfo `json:"define_data"` + InstancesInfo *InstancesInfo `json:"instance_data"` +} + +type DefinitionsInfo struct { + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + ProcDefName string `json:"procDefName"` + ProcDefVersion string `json:"procDefVersion"` + Status string `json:"status"` + ProcDefData string `json:"procDefData"` + CreatedTime string `json:"createdTime"` + ExcludeMode string `json:"excludeMode"` + Tags string `json:"tags"` + PermissionToRole string `json:"permissionToRole"` + FlowNodes []*WorkflowNode `json:"flowNodes"` +} + +type InstancesInfo struct { + Id int `json:"id"` + ProcInstKey string `json:"procInstKey"` + ProcInstName string `json:"procInstName"` + CreatedTime string `json:"createdTime"` + Operator string `json:"operator"` + Status string `json:"status"` + ProcDefId string `json:"procDefId"` + EntityTypeId string `json:"entityTypeId"` + EntityDataId string `json:"entityDataId"` + TaskNodes []*WorkflowNode `json:"taskNodeInstances"` +} + +// WorkflowNode 任务编排节点 +type WorkflowNode struct { + Id int `json:"id"` + ProInstId int `json:"proInstId"` + ProInstKey string `json:"proInstKey"` + NodeId string `json:"nodeId"` + NodeName string `json:"nodeName"` + NodeType string `json:"nodeType"` + NodeDefId string `json:"nodeDefId"` + Status string `json:"status"` + OrderedNo string `json:"orderedNo"` + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + RoutineExpression string `json:"routineExpression"` + TaskCategory string `json:"taskCategory"` + ServiceId string `json:"serviceId"` + DynamicBind string `json:"dynamicBind"` + Description string `json:"description"` + PreviousNodeIds []string `json:"previousNodeIds"` + SucceedingNodeIds []string `json:"succeedingNodeIds"` +} + +type FlowNodes struct { + NodeID string `json:"nodeId"` + NodeName string `json:"nodeName"` + NodeType string `json:"nodeType"` + NodeDefID string `json:"nodeDefId"` + Status string `json:"status"` + OrderedNo string `json:"orderedNo"` + ProcDefID string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + RoutineExpression string `json:"routineExpression"` + TaskCategory interface{} `json:"taskCategory"` + ServiceID string `json:"serviceId"` + DynamicBind string `json:"dynamicBind"` + Description string `json:"description"` + PreviousNodeIds []string `json:"previousNodeIds"` + SucceedingNodeIds []string `json:"succeedingNodeIds"` +} +type DefinitionsData struct { + ProcDefID string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + ProcDefName string `json:"procDefName"` + ProcDefVersion string `json:"procDefVersion"` + Status string `json:"status"` + ProcDefData interface{} `json:"procDefData"` + RootEntity string `json:"rootEntity"` + CreatedTime interface{} `json:"createdTime"` + ExcludeMode string `json:"excludeMode"` + Tags interface{} `json:"tags"` + PermissionToRole interface{} `json:"permissionToRole"` + FlowNodes []FlowNodes `json:"flowNodes"` +} +type TaskNodeInstances struct { + NodeID string `json:"nodeId"` + NodeName string `json:"nodeName"` + NodeType string `json:"nodeType"` + NodeDefID string `json:"nodeDefId"` + Status string `json:"status"` + OrderedNo interface{} `json:"orderedNo"` + ProcDefID string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + RoutineExpression interface{} `json:"routineExpression"` + TaskCategory interface{} `json:"taskCategory"` + ServiceID interface{} `json:"serviceId"` + DynamicBind interface{} `json:"dynamicBind"` + Description interface{} `json:"description"` + PreviousNodeIds []interface{} `json:"previousNodeIds"` + SucceedingNodeIds []string `json:"succeedingNodeIds"` + ProcInstID int `json:"procInstId"` + ProcInstKey string `json:"procInstKey"` + ID int `json:"id"` +} +type ProcessInstance struct { + ID int `json:"id"` + ProcInstKey string `json:"procInstKey"` + ProcInstName string `json:"procInstName"` + CreatedTime string `json:"createdTime"` + Operator string `json:"operator"` + Status string `json:"status"` + ProcDefID string `json:"procDefId"` + EntityTypeID string `json:"entityTypeId"` + EntityDataID string `json:"entityDataId"` + TaskNodeInstances []TaskNodeInstances `json:"taskNodeInstances"` +} + +type EntityNodeBindQueryObj struct { + NodeDefId string `xorm:"node_def_id"` + ItemGroup string `xorm:"item_group"` +} + +type InstanceStatusQuery struct { + Status string `json:"status"` + Message string `json:"message"` + Data InstanceStatusQueryObj `json:"data"` +} + +type InstanceStatusQueryObj struct { + Id int `json:"id"` + ProcDefId string `json:"procDefId"` + ProcInstKey string `json:"procInstKey"` + ProcInstName string `json:"procInstName"` + Status string `json:"status"` + TaskNodeInstances []*InstanceStatusQueryNode `json:"taskNodeInstances"` +} + +type InstanceStatusQueryNode struct { + Id int `json:"id"` + NodeId string `json:"nodeId"` + NodeDefId string `json:"nodeDefId"` + NodeName string `json:"nodeName"` + NodeType string `json:"nodeType"` + Status string `json:"status"` + OrderedNo string `json:"orderedNo"` +} + +type StartInstanceResultData struct { + Id int `json:"id"` + ProcInstKey string `json:"procInstKey"` + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + Status string `json:"status"` +} + +type ProcNodeObjList []*ProcNodeObj + +func (s ProcNodeObjList) Len() int { + return len(s) } -type DataModelEntity struct { - Id string `json:"id"` // 唯一标识 - DataModelId string `json:"dataModelId"` // 所属数据模型 - DataModelVersion int `json:"dataModelVersion"` // 版本 - PackageName string `json:"packageName"` // 包名 - Name string `json:"name"` // 模型名 - DisplayName string `json:"displayName"` // 显示名 - Description string `json:"description"` // 描述 +func (s ProcNodeObjList) Swap(i, j int) { + s[i], s[j] = s[j], s[i] } -type PluginPackageDataModel struct { - Id string `json:"id"` // 唯一标识 - Version int `json:"version"` // 版本 - PackageName string `json:"packageName"` // 包名 - IsDynamic bool `json:"dynamic"` // 是否动态 - UpdatePath string `json:"updatePath"` // 请求路径 - UpdateMethod string `json:"updateMethod"` // 请求方法 - UpdateSource string `json:"updateSource"` // 来源 - UpdatedTime time.Time `json:"updatedTime"` // 更新时间 - UpdateTime int64 `json:"updateTime"` // 旧更新时间,毫秒时间戳 +func (s ProcNodeObjList) Less(i, j int) bool { + return s[i].OrderedNum < s[j].OrderedNum } func ConvertModelsList2Map(nodesList []*DataModel) map[string]ProcEntity { diff --git a/taskman-server/models/request.go b/taskman-server/models/request.go index 1268c6c2..8b606ebf 100644 --- a/taskman-server/models/request.go +++ b/taskman-server/models/request.go @@ -2,6 +2,49 @@ package models import "strings" +type RequestTable struct { + Id string `json:"id" xorm:"id"` + Name string `json:"name" xorm:"name"` + Form string `json:"form" xorm:"form"` + RequestTemplate string `json:"requestTemplate" xorm:"request_template"` + RequestTemplateName string `json:"requestTemplateName" xorm:"-"` + ProcInstanceId string `json:"procInstanceId" xorm:"proc_instance_id"` + ProcInstanceKey string `json:"procInstanceKey" xorm:"proc_instance_key"` + Reporter string `json:"reporter" xorm:"reporter"` + Handler string `json:"handler" xorm:"handler"` + ReportTime string `json:"reportTime" xorm:"report_time"` + Emergency int `json:"emergency" xorm:"emergency"` + ReportRole string `json:"reportRole" xorm:"report_role"` + Status string `json:"status" xorm:"status"` + Cache string `json:"cache" xorm:"cache"` + BindCache string `json:"bindCache" xorm:"bind_cache"` + Result string `json:"result" xorm:"result"` + ExpireTime string `json:"expireTime" xorm:"expire_time"` + ExpectTime string `json:"expectTime" xorm:"expect_time"` + ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + DelFlag int `json:"delFlag" xorm:"del_flag"` + HandleRoles []string `json:"handleRoles" xorm:"-"` + AttachFiles []*AttachFileTable `json:"attachFiles" xorm:"-"` + Parent string `json:"parent" xorm:"parent"` + CompletedTime string `json:"completedTime" xorm:"-"` + RollbackDesc string `json:"rollbackDesc" xorm:"rollback_desc"` + Type int `json:"type" xorm:"type"` + OperatorObj string `json:"operatorObj" xorm:"operator_obj"` + Description string `json:"description" xorm:"description"` // 请求描述 + Role string `json:"role" xorm:"role"` // 创建请求的role + RevokeFlag int `json:"revokeFlag" xorm:"revoke_flag"` // 撤回标志 0表示没被撤回,1表示撤回 + ExpireDay int `json:"expireDay" xorm:"-"` // 模板过期时间 + TemplateVersion string `json:"templateVersion" xorm:"-"` // 模板版本 +} + +func (RequestTable) TableName() string { + return "request" +} + // PlatformData 工作台数据 type PlatformData struct { Pending string `json:"pending"` // 待处理, eg:7;2 使用;分割开 7表示发布个数,2表示请求个数 @@ -58,11 +101,6 @@ type PlatformDataObj struct { TaskStayTimeTotal int `json:"taskStayTimeTotal" xorm:"-"` // 任务停留时长总数 } -type RequestQueryParam struct { - TemplateId string `json:"templateId"` // 模板id - RequestId string `json:"requestId"` // 请求id -} - type RequestProgressObj struct { NodeId string `json:"nodeId" xorm:"node_id"` NodeDefId string `json:"nodeDefId" xorm:"node_def_id"` @@ -72,108 +110,6 @@ type RequestProgressObj struct { OrderedNo string `json:"orderNo" xorm:"-"` // 排序字段 } -// CollectDataObj 收藏数据项 -type CollectDataObj struct { - ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID - Id string `json:"id" xorm:"id"` // 模版ID - Name string `json:"name" xorm:"name"` // 模版名称 - Version string `json:"version" xorm:"version"` // 模版名称 - Status int `json:"status" xorm:"status"` // 模版状态: 1可使用 2已禁用 3权限被移除 - TemplateGroupId string `json:"templateGourpId" xorm:"template_group_id"` // 模版组ID - TemplateGroup string `json:"templateGroup" xorm:"template_group"` // 模版组 - TemplateGroupRole string `json:"templateGroupRole" xorm:"template_group_role"` // 模版组角色 - OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 - ProcDefName string `json:"procDefName" xorm:"proc_def_name"` // 使用编排 - ManageRole string `json:"manageRole" xorm:"manage_role"` // 属主角色 - Owner string `json:"owner" xorm:"owner"` // 属主 - UseRole string `json:"useRole" xorm:"use_role"` // 使用角色 - Tags string `json:"tags" xorm:"tags"` // 标签 - WorkNode []string `json:"workNode" xorm:"work_node"` // 人工任务 - CreatedTime string `json:"createdTime" xorm:"created_time"` // 创建时间 - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` // 更新时间 -} - -type EntityQueryResult struct { - Status string `json:"status"` - Message string `json:"message"` - Data []*EntityDataObj `json:"data"` -} - -type EntityDataObj struct { - Id string `json:"guid"` - DisplayName string `json:"key_name"` - IsNew bool `json:"isNew"` - PackageName string `json:"package_name"` - Entity string `json:"entity"` -} - -type EntityTreeResult struct { - Status string `json:"status"` - Message string `json:"message"` - Data EntityTreeData `json:"data"` -} - -type EntityTreeData struct { - EntityTreeNodes []*EntityTreeObj `json:"entityTreeNodes"` - ProcessSessionId string `json:"processSessionId"` -} - -type EntityTreeObj struct { - PackageName string `json:"packageName"` - EntityName string `json:"entityName"` - DataId string `json:"dataId"` - DisplayName string `json:"displayName"` - FullDataId interface{} `json:"fullDataId"` - Id string `json:"id"` - EntityData map[string]interface{} `json:"entityData"` - PreviousIds []string `json:"previousIds"` - SucceedingIds []string `json:"succeedingIds"` - EntityDataOp string `json:"entityDataOp"` -} - -type RequestTable struct { - Id string `json:"id" xorm:"id"` - Name string `json:"name" xorm:"name"` - Form string `json:"form" xorm:"form"` - RequestTemplate string `json:"requestTemplate" xorm:"request_template"` - RequestTemplateName string `json:"requestTemplateName" xorm:"-"` - ProcInstanceId string `json:"procInstanceId" xorm:"proc_instance_id"` - ProcInstanceKey string `json:"procInstanceKey" xorm:"proc_instance_key"` - Reporter string `json:"reporter" xorm:"reporter"` - Handler string `json:"handler" xorm:"handler"` - ReportTime string `json:"reportTime" xorm:"report_time"` - Emergency int `json:"emergency" xorm:"emergency"` - ReportRole string `json:"reportRole" xorm:"report_role"` - Status string `json:"status" xorm:"status"` - Cache string `json:"cache" xorm:"cache"` - BindCache string `json:"bindCache" xorm:"bind_cache"` - Result string `json:"result" xorm:"result"` - ExpireTime string `json:"expireTime" xorm:"expire_time"` - ExpectTime string `json:"expectTime" xorm:"expect_time"` - ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` - CreatedBy string `json:"createdBy" xorm:"created_by"` - CreatedTime string `json:"createdTime" xorm:"created_time"` - UpdatedBy string `json:"updatedBy" xorm:"updated_by"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - DelFlag int `json:"delFlag" xorm:"del_flag"` - HandleRoles []string `json:"handleRoles" xorm:"-"` - AttachFiles []*AttachFileTable `json:"attachFiles" xorm:"-"` - Parent string `json:"parent" xorm:"parent"` - CompletedTime string `json:"completedTime" xorm:"-"` - RollbackDesc string `json:"rollbackDesc" xorm:"rollback_desc"` - Type int `json:"type" xorm:"type"` - OperatorObj string `json:"operatorObj" xorm:"operator_obj"` - Description string `json:"description" xorm:"description"` // 请求描述 - Role string `json:"role" xorm:"role"` // 创建请求的role - RevokeFlag int `json:"revokeFlag" xorm:"revoke_flag"` // 撤回标志 0表示没被撤回,1表示撤回 - ExpireDay int `json:"expireDay" xorm:"-"` // 模板过期时间 - TemplateVersion string `json:"templateVersion" xorm:"-"` // 模板版本 -} - -func (RequestTable) TableName() string { - return "request" -} - type ExpireObj struct { Percent float64 `json:"percent"` ReportTime string `json:"reportTime"` @@ -184,16 +120,6 @@ type ExpireObj struct { UseDay float64 `json:"useDay"` } -type AttachFileTable struct { - Id string `json:"id" xorm:"id"` - Name string `json:"name" xorm:"name"` - S3BucketName string `json:"s3BucketName" xorm:"s3_bucket_name"` - S3KeyName string `json:"s3KeyName" xorm:"s3_key_name"` - DelFlag int `json:"delFlag" xorm:"del_flag"` - Request string `json:"request" xorm:"request"` - Task string `json:"task" xorm:"task"` -} - type RequestCacheData struct { ProcDefId string `json:"procDefId"` ProcDefKey string `json:"procDefKey"` @@ -232,6 +158,22 @@ type RequestCacheEntityAttrValue struct { DataValue interface{} `json:"dataValue"` } +type RequestProcessData struct { + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + RootEntityOid string `json:"rootEntityOid"` + Entities []*RequestCacheEntityValue `json:"entities"` + Bindings []*RequestProcessTaskNodeBindObj `json:"bindings"` +} + +type RequestProcessTaskNodeBindObj struct { + NodeId string `json:"nodeId"` + NodeDefId string `json:"nodeDefId"` + Oid string `json:"oid"` + EntityDataId string `json:"entityDataId"` + BindFlag string `json:"bindFlag"` +} + type RequestPreDataTableObj struct { PackageName string `json:"packageName"` Entity string `json:"entity"` @@ -243,20 +185,6 @@ type RequestPreDataTableObj struct { Value []*EntityTreeObj `json:"value"` } -type StartInstanceResult struct { - Status string `json:"status"` - Message string `json:"message"` - Data StartInstanceResultData `json:"data"` -} - -type StartInstanceResultData struct { - Id int `json:"id"` - ProcInstKey string `json:"procInstKey"` - ProcDefId string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - Status string `json:"status"` -} - type RequestPreDataSort []*RequestPreDataTableObj func (s RequestPreDataSort) Len() int { @@ -289,57 +217,6 @@ type RequestProDataV2Dto struct { Data []*RequestPreDataTableObj `json:"data"` } -type TerminateInstanceParam struct { - ProcInstId string `json:"procInstId"` - ProcInstKey string `json:"procInstKey"` -} - -type EntityNodeBindQueryObj struct { - NodeDefId string `xorm:"node_def_id"` - ItemGroup string `xorm:"item_group"` -} - -type InstanceStatusQuery struct { - Status string `json:"status"` - Message string `json:"message"` - Data InstanceStatusQueryObj `json:"data"` -} - -type InstanceStatusQueryObj struct { - Id int `json:"id"` - ProcDefId string `json:"procDefId"` - ProcInstKey string `json:"procInstKey"` - ProcInstName string `json:"procInstName"` - Status string `json:"status"` - TaskNodeInstances []*InstanceStatusQueryNode `json:"taskNodeInstances"` -} - -type InstanceStatusQueryNode struct { - Id int `json:"id"` - NodeId string `json:"nodeId"` - NodeDefId string `json:"nodeDefId"` - NodeName string `json:"nodeName"` - NodeType string `json:"nodeType"` - Status string `json:"status"` - OrderedNo string `json:"orderedNo"` -} - -type RequestProcessData struct { - ProcDefId string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - RootEntityOid string `json:"rootEntityOid"` - Entities []*RequestCacheEntityValue `json:"entities"` - Bindings []*RequestProcessTaskNodeBindObj `json:"bindings"` -} - -type RequestProcessTaskNodeBindObj struct { - NodeId string `json:"nodeId"` - NodeDefId string `json:"nodeDefId"` - Oid string `json:"oid"` - EntityDataId string `json:"entityDataId"` - BindFlag string `json:"bindFlag"` -} - type WorkflowEntityQuery struct { Status string `json:"status"` Message string `json:"message"` diff --git a/taskman-server/models/request_approve_role.go b/taskman-server/models/request_approve_role.go new file mode 100644 index 00000000..3c4d55bd --- /dev/null +++ b/taskman-server/models/request_approve_role.go @@ -0,0 +1,14 @@ +package models + +// RequestApproveRoleTable 请求审批角色表 +type RequestApproveRoleTable struct { + Id string `json:"id" xorm:"id"` + RequestApprove string `json:"requestApprove" xorm:"request_approve"` // 请求审批ID + Role string `json:"role" xorm:"role"` // 角色 + handler string `json:"handler" xorm:"handler"` // 处理人 + CreatedTime string `json:"createdTime" xorm:"created_time"` +} + +func (RequestApproveRoleTable) TableName() string { + return "request_approve_role" +} diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index 9aa10bd6..bb75ff3c 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -1,5 +1,9 @@ package models +import ( + "time" +) + type RequestTemplateTable struct { Id string `json:"id" xorm:"id"` Group string `json:"group" xorm:"group"` @@ -40,36 +44,25 @@ func (RequestTemplateTable) TableName() string { return "request_template" } -type RequestTemplateGroupTable struct { - Id string `json:"id" xorm:"id"` - Name string `json:"name" xorm:"name" binding:"required"` - Description string `json:"description" xorm:"description"` - ManageRole string `json:"manageRole" xorm:"manage_role" binding:"required"` - ManageRoleObj RoleTable `json:"manageRoleObj" xorm:"-"` - CreatedBy string `json:"createdBy" xorm:"created_by"` - CreatedTime string `json:"createdTime" xorm:"created_time"` - UpdatedBy string `json:"updatedBy" xorm:"updated_by"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - DelFlag int `json:"delFlag" xorm:"del_flag"` -} - -func (RequestTemplateGroupTable) TableName() string { - return "request_template_group" -} - -type RoleTable struct { - Id string `json:"id" xorm:"id"` - DisplayName string `json:"displayName" xorm:"display_name"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - CoreId string `json:"coreId" xorm:"core_id"` - Email string `json:"email"` -} - -type RequestTemplateRoleTable struct { - Id string `json:"id" xorm:"id"` - RequestTemplate string `json:"requestTemplate" xorm:"request_template"` - Role string `json:"role" xorm:"role"` - RoleType string `json:"roleType" xorm:"role_type"` +// CollectDataObj 收藏数据项 +type CollectDataObj struct { + ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID + Id string `json:"id" xorm:"id"` // 模版ID + Name string `json:"name" xorm:"name"` // 模版名称 + Version string `json:"version" xorm:"version"` // 模版名称 + Status int `json:"status" xorm:"status"` // 模版状态: 1可使用 2已禁用 3权限被移除 + TemplateGroupId string `json:"templateGourpId" xorm:"template_group_id"` // 模版组ID + TemplateGroup string `json:"templateGroup" xorm:"template_group"` // 模版组 + TemplateGroupRole string `json:"templateGroupRole" xorm:"template_group_role"` // 模版组角色 + OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 + ProcDefName string `json:"procDefName" xorm:"proc_def_name"` // 使用编排 + ManageRole string `json:"manageRole" xorm:"manage_role"` // 属主角色 + Owner string `json:"owner" xorm:"owner"` // 属主 + UseRole string `json:"useRole" xorm:"use_role"` // 使用角色 + Tags string `json:"tags" xorm:"tags"` // 标签 + WorkNode []string `json:"workNode" xorm:"work_node"` // 人工任务 + CreatedTime string `json:"createdTime" xorm:"created_time"` // 创建时间 + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` // 更新时间 } type RequestTemplateHandlerDto struct { @@ -77,39 +70,6 @@ type RequestTemplateHandlerDto struct { LatestUpdateTime string `json:"latestUpdateTime"` //最后更新时间 } -type CoreProcessQueryResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data []*CodeProcessQueryObj `json:"data"` -} - -type CodeProcessQueryObj struct { - ExcludeMode string `json:"excludeMode"` - ProcDefId string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - ProcDefName string `json:"procDefName"` - ProcDefVersion string `json:"procDefVersion"` - RootEntity string `json:"rootEntity"` - Status string `json:"status"` - CreatedTime string `json:"createdTime"` - CreatedUnixTime int64 `json:"-"` - Tags string `json:"tags"` -} -type RequestTemplateTableObj struct { - Id string `json:"id" xorm:"id"` - Name string `json:"name" xorm:"name"` - Version string `json:"version" xorm:"version"` - Tags string `json:"tags" xorm:"tags"` - Status string `json:"status" xorm:"status"` - UpdatedBy string `json:"updatedBy" xorm:"updated_by"` - Handler string `json:"handler" xorm:"handler"` - Role string `json:"role" xorm:"role"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - CollectFlag int `json:"collectFlag" xorm:"collect_flag"` // 是否收藏 1表示已收藏 - Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 - OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 -} - type RequestTemplateQueryObj struct { RequestTemplateTable MGMTRoles []*RoleTable `json:"mgmtRoles"` @@ -132,84 +92,6 @@ type RequestTemplateUpdateParam struct { USERoles []string `json:"useRoles"` } -type ProcEntityAttributeObj struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - DataType string `json:"dataType"` - Mandatory bool `json:"mandatory"` - RefPackageName string `json:"refPackageName"` - RefEntityName string `json:"refEntityName"` - RefAttrName string `json:"refAttrName"` - ReferenceId string `json:"referenceId"` - Active bool `json:"active"` - EntityId string `json:"entityId"` - EntityName string `json:"entityName"` - EntityDisplayName string `json:"entityDisplayName"` - EntityPackage string `json:"entityPackage"` - Multiple string `json:"multiple"` -} - -type ProcEntity struct { - Id string `json:"id"` - PackageName string `json:"packageName"` - Name string `json:"name"` - Description string `json:"description"` - DisplayName string `json:"displayName"` - Attributes []*ProcEntityAttributeObj `json:"attributes"` -} - -type ProcDefObj struct { - ProcDefId string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - ProcDefName string `json:"procDefName"` - Status string `json:"status"` - RootEntity ProcEntity `json:"rootEntity"` - CreatedTime string `json:"createdTime"` -} - -type ProcQueryResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data []*ProcDefObj `json:"data"` -} - -type ProcAllDefObj struct { - ProcDefId string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - ProcDefName string `json:"procDefName"` - Status string `json:"status"` - RootEntity string `json:"rootEntity"` - CreatedTime string `json:"createdTime"` -} - -type ProcAllQueryResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data []*ProcAllDefObj `json:"data"` -} - -type ProcNodeObj struct { - NodeId string `json:"nodeId"` - NodeName string `json:"nodeName"` - NodeType string `json:"nodeType"` - NodeDefId string `json:"nodeDefId"` - TaskCategory string `json:"taskCategory"` - RoutineExp string `json:"routineExp"` - ServiceId string `json:"serviceId"` - ServiceName string `json:"serviceName"` - OrderedNo string `json:"orderedNo"` - OrderedNum int `json:"-"` - DynamicBind string `json:"dynamicbind"` - BoundEntities []*ProcEntity `json:"boundEntities"` -} - -type ProcNodeQueryResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data []*ProcNodeObj `json:"data"` -} - type UserRequestTemplateQueryObj struct { GroupId string `json:"groupId"` GroupName string `json:"groupName"` @@ -218,12 +100,19 @@ type UserRequestTemplateQueryObj struct { Tags []*UserRequestTemplateTagObj `json:"tags"` } -type TemplateGroupObj struct { - GroupId string `json:"groupId"` - GroupName string `json:"groupName"` - CreatedTime string `json:"createdTime"` - UpdatedTime string `json:"updatedTime"` - Templates []*RequestTemplateTableObj `json:"templates"` +type RequestTemplateTableObj struct { + Id string `json:"id" xorm:"id"` + Name string `json:"name" xorm:"name"` + Version string `json:"version" xorm:"version"` + Tags string `json:"tags" xorm:"tags"` + Status string `json:"status" xorm:"status"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + Handler string `json:"handler" xorm:"handler"` + Role string `json:"role" xorm:"role"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + CollectFlag int `json:"collectFlag" xorm:"collect_flag"` // 是否收藏 1表示已收藏 + Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 + OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 } type UserRequestTemplateQueryObjNew struct { @@ -256,20 +145,6 @@ type TaskTemplateFormStruct struct { FormItems []*FormItemTemplateTable `json:"formItems"` } -type ProcNodeObjList []*ProcNodeObj - -func (s ProcNodeObjList) Len() int { - return len(s) -} - -func (s ProcNodeObjList) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s ProcNodeObjList) Less(i, j int) bool { - return s[i].OrderedNum < s[j].OrderedNum -} - type RequestTemplateExport struct { RequestTemplate RequestTemplateTable `json:"requestTemplate"` FormTemplate []*FormTemplateTable `json:"formTemplate"` @@ -280,67 +155,6 @@ type RequestTemplateExport struct { RequestTemplateGroup RequestTemplateGroupTable `json:"requestTemplateGroup"` } -type WorkflowRsp struct { - Status string `json:"status"` - Message string `json:"message"` - Data Workflow `json:"data"` -} - -type Workflow struct { - Status string `json:"status"` - DefinitionsInfo *DefinitionsInfo `json:"define_data"` - InstancesInfo *InstancesInfo `json:"instance_data"` -} - -type DefinitionsInfo struct { - ProcDefId string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - ProcDefName string `json:"procDefName"` - ProcDefVersion string `json:"procDefVersion"` - Status string `json:"status"` - ProcDefData string `json:"procDefData"` - CreatedTime string `json:"createdTime"` - ExcludeMode string `json:"excludeMode"` - Tags string `json:"tags"` - PermissionToRole string `json:"permissionToRole"` - FlowNodes []*WorkflowNode `json:"flowNodes"` -} - -type InstancesInfo struct { - Id int `json:"id"` - ProcInstKey string `json:"procInstKey"` - ProcInstName string `json:"procInstName"` - CreatedTime string `json:"createdTime"` - Operator string `json:"operator"` - Status string `json:"status"` - ProcDefId string `json:"procDefId"` - EntityTypeId string `json:"entityTypeId"` - EntityDataId string `json:"entityDataId"` - TaskNodes []*WorkflowNode `json:"taskNodeInstances"` -} - -// WorkflowNode 任务编排节点 -type WorkflowNode struct { - Id int `json:"id"` - ProInstId int `json:"proInstId"` - ProInstKey string `json:"proInstKey"` - NodeId string `json:"nodeId"` - NodeName string `json:"nodeName"` - NodeType string `json:"nodeType"` - NodeDefId string `json:"nodeDefId"` - Status string `json:"status"` - OrderedNo string `json:"orderedNo"` - ProcDefId string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - RoutineExpression string `json:"routineExpression"` - TaskCategory string `json:"taskCategory"` - ServiceId string `json:"serviceId"` - DynamicBind string `json:"dynamicBind"` - Description string `json:"description"` - PreviousNodeIds []string `json:"previousNodeIds"` - SucceedingNodeIds []string `json:"succeedingNodeIds"` -} - type RequestTemplateTmp struct { ProcDefId string `json:"procDefId" xorm:"proc_def_id` TemplateName string `json:"templateName" xorm:"template_name` @@ -355,20 +169,6 @@ type ImportData struct { TemplateName string `json:"templateName"` } -type TemplateGroupSort []*TemplateGroupObj - -func (s TemplateGroupSort) Len() int { - return len(s) -} - -func (s TemplateGroupSort) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s TemplateGroupSort) Less(i, j int) bool { - return s[i].UpdatedTime > s[j].UpdatedTime -} - type RequestTemplateSort []*RequestTemplateTableObj func (s RequestTemplateSort) Len() int { @@ -382,3 +182,34 @@ func (s RequestTemplateSort) Swap(i, j int) { func (s RequestTemplateSort) Less(i, j int) bool { return s[i].UpdatedTime > s[j].UpdatedTime } + +func ConvertRequestTemplateUpdateParam2RequestTemplate(param *RequestTemplateUpdateParam) *RequestTemplateTable { + nowTime := time.Now().Format(DateTimeFormat) + return &RequestTemplateTable{ + Id: param.Id, + Group: param.Group, + Name: param.Name, + Description: param.Description, + Tags: param.Tags, + PackageName: param.PackageName, + EntityName: param.EntityName, + ProcDefKey: param.ProcDefKey, + ProcDefId: param.ProcDefId, + ProcDefName: param.ProcDefName, + CreatedBy: param.CreatedBy, + CreatedTime: nowTime, + UpdatedBy: param.CreatedBy, + UpdatedTime: nowTime, + ExpireDay: param.ExpireDay, + Handler: param.Handler, + Type: param.Type, + OperatorObjType: param.OperatorObjType, + ParentId: param.Id, + ApproveBy: param.ApproveBy, + PendingSwitch: param.PendingSwitch, + PendingRole: param.PendingRole, + PendingHandler: param.PendingHandler, + ConfirmSwitch: param.ConfirmSwitch, + ConfirmExpireDay: param.ConfirmExpireDay, + } +} diff --git a/taskman-server/models/request_template_group.go b/taskman-server/models/request_template_group.go new file mode 100644 index 00000000..f4ca01ad --- /dev/null +++ b/taskman-server/models/request_template_group.go @@ -0,0 +1,40 @@ +package models + +type RequestTemplateGroupTable struct { + Id string `json:"id" xorm:"id"` + Name string `json:"name" xorm:"name" binding:"required"` + Description string `json:"description" xorm:"description"` + ManageRole string `json:"manageRole" xorm:"manage_role" binding:"required"` + ManageRoleObj RoleTable `json:"manageRoleObj" xorm:"-"` + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + DelFlag int `json:"delFlag" xorm:"del_flag"` +} + +func (RequestTemplateGroupTable) TableName() string { + return "request_template_group" +} + +type TemplateGroupObj struct { + GroupId string `json:"groupId"` + GroupName string `json:"groupName"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` + Templates []*RequestTemplateTableObj `json:"templates"` +} + +type TemplateGroupSort []*TemplateGroupObj + +func (s TemplateGroupSort) Len() int { + return len(s) +} + +func (s TemplateGroupSort) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +func (s TemplateGroupSort) Less(i, j int) bool { + return s[i].UpdatedTime > s[j].UpdatedTime +} diff --git a/taskman-server/models/request_template_role.go b/taskman-server/models/request_template_role.go new file mode 100644 index 00000000..a632ee4c --- /dev/null +++ b/taskman-server/models/request_template_role.go @@ -0,0 +1,21 @@ +package models + +type RequestTemplateRoleTable struct { + Id string `json:"id" xorm:"id"` + RequestTemplate string `json:"requestTemplate" xorm:"request_template"` + Role string `json:"role" xorm:"role"` + RoleType string `json:"roleType" xorm:"role_type"` +} + +func (RequestTemplateRoleTable) TableName() string { + return "request_template_role" +} + +func CreateRequestTemplateRoleTable(requestTemplateId, role string, permission RolePermission) *RequestTemplateRoleTable { + return &RequestTemplateRoleTable{ + Id: requestTemplateId + SysTableIdConnector + role + SysTableIdConnector + string(permission), + RequestTemplate: requestTemplateId, + Role: role, + RoleType: string(permission), + } +} diff --git a/taskman-server/models/response.go b/taskman-server/models/response.go index 18501042..bf37923d 100644 --- a/taskman-server/models/response.go +++ b/taskman-server/models/response.go @@ -65,3 +65,38 @@ type QueryAllModelsResponse struct { HttpResponseMeta Data []*DataModel `json:"data"` } + +type ProcNodeQueryResponse struct { + HttpResponseMeta + Data []*ProcNodeObj `json:"data"` +} + +type CoreProcessQueryResponse struct { + HttpResponseMeta + Data []*CodeProcessQueryObj `json:"data"` +} + +type ProcessDefinitionsResponse struct { + HttpResponseMeta + Data *DefinitionsData `json:"data"` +} + +type ProcessInstanceResponse struct { + HttpResponseMeta + Data *ProcessInstance `json:"data"` +} + +type ExecutionResponse struct { + HttpResponseMeta + Data interface{} `json:"data"` +} + +type ProcQueryResponse struct { + HttpResponseMeta + Data []*ProcDefObj `json:"data"` +} + +type StartInstanceResponse struct { + HttpResponseMeta + Data StartInstanceResultData `json:"data"` +} diff --git a/taskman-server/models/role.go b/taskman-server/models/role.go new file mode 100644 index 00000000..965d5c64 --- /dev/null +++ b/taskman-server/models/role.go @@ -0,0 +1,13 @@ +package models + +type RoleTable struct { + Id string `json:"id" xorm:"id"` + DisplayName string `json:"displayName" xorm:"display_name"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + CoreId string `json:"coreId" xorm:"core_id"` + Email string `json:"email"` +} + +func (RoleTable) TableName() string { + return "role" +} diff --git a/taskman-server/models/task.go b/taskman-server/models/task.go index c656d3e0..b811466d 100644 --- a/taskman-server/models/task.go +++ b/taskman-server/models/task.go @@ -214,15 +214,6 @@ type TaskApproveParam struct { ChoseOption string `json:"choseOption"` } -type OperationLogTable struct { - Id string `json:"id" xorm:"id"` - Request string `json:"request" xorm:"request"` - Task string `json:"task" xorm:"task"` - Operation string `json:"operation" xorm:"operation"` - Operator string `json:"operator" xorm:"operator"` - OpTime string `json:"opTime" xorm:"op_time"` -} - type TaskHandlerQueryData struct { Id string `xorm:"id"` Handler string `xorm:"handler"` diff --git a/taskman-server/models/task_approve_role.go b/taskman-server/models/task_approve_role.go new file mode 100644 index 00000000..ce51b98a --- /dev/null +++ b/taskman-server/models/task_approve_role.go @@ -0,0 +1,14 @@ +package models + +// TaskApproveRoleTable 任务审批表 +type TaskApproveRoleTable struct { + Id string `json:"id" xorm:"id"` + Task string `json:"task" xorm:"task"` // 任务审批ID + Role string `json:"role" xorm:"role"` // 角色 + handler string `json:"handler" xorm:"handler"` // 处理人 + CreatedTime string `json:"createdTime" xorm:"created_time"` +} + +func (TaskApproveRoleTable) TableName() string { + return "task_approve_role" +} diff --git a/taskman-server/models/workflow.go b/taskman-server/models/workflow.go deleted file mode 100644 index b8671f2b..00000000 --- a/taskman-server/models/workflow.go +++ /dev/null @@ -1,83 +0,0 @@ -package models - -type ProcessDefinitionsResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data *DefinitionsData `json:"data"` -} -type FlowNodes struct { - NodeID string `json:"nodeId"` - NodeName string `json:"nodeName"` - NodeType string `json:"nodeType"` - NodeDefID string `json:"nodeDefId"` - Status string `json:"status"` - OrderedNo string `json:"orderedNo"` - ProcDefID string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - RoutineExpression string `json:"routineExpression"` - TaskCategory interface{} `json:"taskCategory"` - ServiceID string `json:"serviceId"` - DynamicBind string `json:"dynamicBind"` - Description string `json:"description"` - PreviousNodeIds []string `json:"previousNodeIds"` - SucceedingNodeIds []string `json:"succeedingNodeIds"` -} -type DefinitionsData struct { - ProcDefID string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - ProcDefName string `json:"procDefName"` - ProcDefVersion string `json:"procDefVersion"` - Status string `json:"status"` - ProcDefData interface{} `json:"procDefData"` - RootEntity string `json:"rootEntity"` - CreatedTime interface{} `json:"createdTime"` - ExcludeMode string `json:"excludeMode"` - Tags interface{} `json:"tags"` - PermissionToRole interface{} `json:"permissionToRole"` - FlowNodes []FlowNodes `json:"flowNodes"` -} - -type ProcessInstanceResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data *ProcessInstance `json:"data"` -} - -type TaskNodeInstances struct { - NodeID string `json:"nodeId"` - NodeName string `json:"nodeName"` - NodeType string `json:"nodeType"` - NodeDefID string `json:"nodeDefId"` - Status string `json:"status"` - OrderedNo interface{} `json:"orderedNo"` - ProcDefID string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - RoutineExpression interface{} `json:"routineExpression"` - TaskCategory interface{} `json:"taskCategory"` - ServiceID interface{} `json:"serviceId"` - DynamicBind interface{} `json:"dynamicBind"` - Description interface{} `json:"description"` - PreviousNodeIds []interface{} `json:"previousNodeIds"` - SucceedingNodeIds []string `json:"succeedingNodeIds"` - ProcInstID int `json:"procInstId"` - ProcInstKey string `json:"procInstKey"` - ID int `json:"id"` -} -type ProcessInstance struct { - ID int `json:"id"` - ProcInstKey string `json:"procInstKey"` - ProcInstName string `json:"procInstName"` - CreatedTime string `json:"createdTime"` - Operator string `json:"operator"` - Status string `json:"status"` - ProcDefID string `json:"procDefId"` - EntityTypeID string `json:"entityTypeId"` - EntityDataID string `json:"entityDataId"` - TaskNodeInstances []TaskNodeInstances `json:"taskNodeInstances"` -} - -type ExecutionResponse struct { - Status string `json:"status"` - Message string `json:"message"` - Data interface{} `json:"data"` -} diff --git a/taskman-server/remote/proc_def_remote.go b/taskman-server/rpc/proc_def_rpc.go similarity index 99% rename from taskman-server/remote/proc_def_remote.go rename to taskman-server/rpc/proc_def_rpc.go index 06c4c60d..8ab6458d 100644 --- a/taskman-server/remote/proc_def_remote.go +++ b/taskman-server/rpc/proc_def_rpc.go @@ -1,4 +1,4 @@ -package remote +package rpc import ( "encoding/json" diff --git a/taskman-server/remote/user_role_remote.go b/taskman-server/rpc/user_role_rpc.go similarity index 99% rename from taskman-server/remote/user_role_remote.go rename to taskman-server/rpc/user_role_rpc.go index 6bfde0ab..3b53e173 100644 --- a/taskman-server/remote/user_role_remote.go +++ b/taskman-server/rpc/user_role_rpc.go @@ -1,4 +1,4 @@ -package remote +package rpc import ( "encoding/json" diff --git a/taskman-server/service/operation_log_service.go b/taskman-server/service/operation_log_service.go new file mode 100644 index 00000000..ee4546a8 --- /dev/null +++ b/taskman-server/service/operation_log_service.go @@ -0,0 +1,37 @@ +package service + +import ( + "github.com/WeBankPartners/go-common-lib/guid" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "time" +) + +type OperationLogService struct { + operationLogDao dao.OperationLogDao +} + +func (s OperationLogService) RecordRequestTemplateLog(requestTemplateId, requestTemplateName, operator, operation, uri, content string) { + _, err := dao.X.Exec("insert into operation_log(id,request_template,request_template_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", + guid.CreateGuid(), requestTemplateId, requestTemplateName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) + if err != nil { + log.Logger.Error("Record request operation log fail", log.Error(err)) + } +} + +func (s OperationLogService) RecordRequestLog(requestId, requestName, operator, operation, uri, content string) { + _, err := dao.X.Exec("insert into operation_log(id,request,request_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", + guid.CreateGuid(), requestId, requestName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) + if err != nil { + log.Logger.Error("Record request operation log fail", log.Error(err)) + } +} + +func (s OperationLogService) RecordTaskLog(taskId, taskName, operator, operation, uri, content string) { + _, err := dao.X.Exec("insert into operation_log(id,task,task_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", + guid.CreateGuid(), taskId, taskName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) + if err != nil { + log.Logger.Error("Record request operation log fail", log.Error(err)) + } +} diff --git a/taskman-server/service/ref_select_service.go b/taskman-server/service/ref_select_service.go index d9b25830..f680848d 100644 --- a/taskman-server/service/ref_select_service.go +++ b/taskman-server/service/ref_select_service.go @@ -17,7 +17,7 @@ type RefSelectService struct { func GetCMDBRefSelectResult(input *models.RefSelectParam) (result []*models.EntityDataObj, err error) { result = []*models.EntityDataObj{} - // if param map data have no new data -> get remote data + same entity new data + // if param map data have no new data -> get rpc data + same entity new data refFlag, options, tmpErr := checkIfNeedAnalyze(input) log.Logger.Info("isContainNewMap", log.String("isContainNewMap", fmt.Sprintf("%d", refFlag))) if refFlag == -1 { @@ -35,7 +35,7 @@ func GetCMDBRefSelectResult(input *models.RefSelectParam) (result []*models.Enti if getFilterErr != nil { return result, getFilterErr } - // if filter empty -> get remote data + same entity new data + // if filter empty -> get rpc data + same entity new data if filterString == "" { result, err = getRefDataWithoutFilter(input) return @@ -620,7 +620,7 @@ func getRemoteEntityOptions(url, userToken string, inputMap map[string]string) ( reqParam = url[strings.Index(url, "=")+1:] url = url[:strings.Index(url, "?")] } - log.Logger.Info("curl remote entity options", log.String("url", url), log.String("method", method), log.String("param", reqParam)) + log.Logger.Info("curl rpc entity options", log.String("url", url), log.String("method", method), log.String("param", reqParam)) req, reqErr := http.NewRequest(method, url, strings.NewReader(reqParam)) if reqErr != nil { err = fmt.Errorf("Try to new request fail,%s ", reqErr.Error()) diff --git a/taskman-server/service/request_service.go b/taskman-server/service/request_service.go index 6df6366d..93a83f49 100644 --- a/taskman-server/service/request_service.go +++ b/taskman-server/service/request_service.go @@ -1397,7 +1397,7 @@ func StartRequest(requestId, operator, userToken string, cacheData models.Reques err = fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) return } - var respResult models.StartInstanceResult + var respResult models.StartInstanceResponse b, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() err = json.Unmarshal(b, &respResult) @@ -1681,7 +1681,7 @@ func RequestTermination(requestId, operator, userToken string) error { if respErr != nil { return fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) } - var respResult models.StartInstanceResult + var respResult models.StartInstanceResponse b, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() err = json.Unmarshal(b, &respResult) @@ -1829,30 +1829,6 @@ func buildEntityValueAttrData(titles []*models.FormItemTemplateTable, entityData return } -func RecordRequestTemplateLog(requestTemplateId, requestTemplateName, operator, operation, uri, content string) { - _, err := dao.X.Exec("insert into operation_log(id,request_template,request_template_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", - guid.CreateGuid(), requestTemplateId, requestTemplateName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) - if err != nil { - log.Logger.Error("Record request operation log fail", log.Error(err)) - } -} - -func RecordRequestLog(requestId, requestName, operator, operation, uri, content string) { - _, err := dao.X.Exec("insert into operation_log(id,request,request_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", - guid.CreateGuid(), requestId, requestName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) - if err != nil { - log.Logger.Error("Record request operation log fail", log.Error(err)) - } -} - -func RecordTaskLog(taskId, taskName, operator, operation, uri, content string) { - _, err := dao.X.Exec("insert into operation_log(id,task,task_name,operation,uri,content,operator,op_time) values (?,?,?,?,?,?,?,?)", - guid.CreateGuid(), taskId, taskName, operation, uri, content, operator, time.Now().Format(models.DateTimeFormat)) - if err != nil { - log.Logger.Error("Record request operation log fail", log.Error(err)) - } -} - func GetRequestTaskList(requestId string) (result models.TaskQueryResult, err error) { var taskTable []*models.TaskTable err = dao.X.SQL("select id from task where request=? order by created_time desc", requestId).Find(&taskTable) diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 52211884..a98a76d4 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -3,22 +3,26 @@ package service import ( "encoding/json" "fmt" - "github.com/WeBankPartners/go-common-lib/guid" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/remote" "io/ioutil" "net/http" "sort" "strconv" "strings" "time" + "xorm.io/xorm" + + "github.com/WeBankPartners/go-common-lib/guid" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/rpc" ) type RequestTemplateService struct { - requestTemplateDao dao.RequestTemplateDao + requestTemplateDao dao.RequestTemplateDao + requestTemplateRoleDao dao.RequestTemplateRoleDao + operationLogDao dao.OperationLogDao } func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestParam, userToken, language string, userRoles []string) (pageInfo models.PageInfo, result []*models.RequestTemplateQueryObj, err error) { @@ -126,7 +130,7 @@ func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestP return } } - roleMap, err = remote.QueryAllRoles("Y", userToken, language) + roleMap, err = rpc.QueryAllRoles("Y", userToken, language) if err != nil { return } @@ -179,11 +183,11 @@ func (s RequestTemplateService) GetCoreProcessListNew(userToken, language string var nodesList []*models.DataModel var entityMap = make(map[string]models.ProcEntity) processList = make([]*models.ProcDefObj, 0) - procDefDtoList, err = remote.QueryProcessDefinitionList(userToken, language, models.QueryProcessDefinitionParam{Plugins: []string{"taskman"}, Status: "deployed"}) + procDefDtoList, err = rpc.QueryProcessDefinitionList(userToken, language, models.QueryProcessDefinitionParam{Plugins: []string{"taskman"}, Status: "deployed"}) if err != nil { return } - nodesList, err = remote.QueryAllModels(userToken, language) + nodesList, err = rpc.QueryAllModels(userToken, language) if err != nil { return } @@ -203,6 +207,47 @@ func (s RequestTemplateService) GetCoreProcessListNew(userToken, language string return } +func (s RequestTemplateService) CheckRequestTemplateRoles(requestTemplateId string, userRoles []string) error { + has, err := s.requestTemplateRoleDao.CheckRequestTemplateRoles(requestTemplateId, userRoles) + if err != nil { + return err + } + if !has { + return fmt.Errorf(models.RowDataPermissionErr) + } + return nil +} + +func (s RequestTemplateService) CreateRequestTemplate(param *models.RequestTemplateUpdateParam) (result models.RequestTemplateQueryObj, err error) { + newGuid := guid.CreateGuid() + param.Id = newGuid + result = models.RequestTemplateQueryObj{RequestTemplateTable: param.RequestTemplateTable, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} + result.Id = newGuid + err = transaction(func(session *xorm.Session) error { + var err error + _, err = s.requestTemplateDao.Add(session, models.ConvertRequestTemplateUpdateParam2RequestTemplate(param)) + if err != nil { + return err + } + for _, role := range param.MGMTRoles { + result.MGMTRoles = append(result.MGMTRoles, &models.RoleTable{Id: role}) + _, err = s.requestTemplateRoleDao.Add(session, models.CreateRequestTemplateRoleTable(newGuid, role, models.RolePermissionMGMT)) + if err != nil { + return err + } + } + for _, role := range param.USERoles { + result.USERoles = append(result.USERoles, &models.RoleTable{Id: role}) + _, err = s.requestTemplateRoleDao.Add(session, models.CreateRequestTemplateRoleTable(newGuid, role, models.RolePermissionUse)) + if err != nil { + return err + } + } + return nil + }) + return +} + func QueryRequestTemplateGroup(param *models.QueryRequestParam, userRoles []string) (pageInfo models.PageInfo, rowData []*models.RequestTemplateGroupTable, err error) { rowData = []*models.RequestTemplateGroupTable{} filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateGroupTable{}, PrimaryKey: "id"}) @@ -398,54 +443,6 @@ func GetProcessNodesByProc(requestTemplateObj models.RequestTemplateTable, userT return } -func GetCoreProcessList(userToken string) (processList []*models.CodeProcessQueryObj, err error) { - req, reqErr := http.NewRequest(http.MethodGet, models.Config.Wecube.BaseUrl+"/platform/v1/process/definitions?includeDraft=0&permission=USE&tags="+models.ProcessFetchTabs, nil) - if reqErr != nil { - err = fmt.Errorf("Try to new http request to core fail,%s ", reqErr.Error()) - return - } - req.Header.Set("Authorization", userToken) - http.DefaultClient.CloseIdleConnections() - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - err = fmt.Errorf("Try to do request to core fail,%s ", respErr.Error()) - return - } - var respObj models.CoreProcessQueryResponse - respBytes, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(respBytes, &respObj) - log.Logger.Debug("Get core process list", log.String("body", string(respBytes))) - if err != nil { - err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) - return - } - if len(respObj.Data) == 0 { - processList = []*models.CodeProcessQueryObj{} - return - } - procMap := make(map[string]*models.CodeProcessQueryObj) - for _, v := range respObj.Data { - tmpT, tmpErr := time.Parse(models.DateTimeFormat, v.CreatedTime) - if tmpErr == nil { - v.CreatedUnixTime = tmpT.Unix() - } - if oldProc, b := procMap[v.ProcDefKey]; b { - if oldProc.CreatedUnixTime < v.CreatedUnixTime { - procMap[v.ProcDefKey] = v - } - } else { - procMap[v.ProcDefKey] = v - } - } - for _, v := range respObj.Data { - if procMap[v.ProcDefKey].ProcDefId == v.ProcDefId { - processList = append(processList, v) - } - } - return -} - func getRoleMail(roleList []*models.RoleTable) (mailList []string) { if models.CoreToken.BaseUrl == "" || len(roleList) == 0 { return @@ -574,131 +571,6 @@ func GetRoleList(ids []string) (result []*models.RoleTable, err error) { return } -func QueryRequestTemplate(param *models.QueryRequestParam, userToken string, userRoles []string) (pageInfo models.PageInfo, result []*models.RequestTemplateQueryObj, err error) { - extFilterSql := "" - result = []*models.RequestTemplateQueryObj{} - isQueryMessage := false - if len(param.Filters) > 0 { - newFilters := []*models.QueryRequestFilterObj{} - for _, v := range param.Filters { - if v.Name == "id" { - isQueryMessage = true - } - if v.Name == "mgmtRoles" || v.Name == "useRoles" { - inValueList := v.Value.([]interface{}) - inValueStringList := []string{} - for _, inValueInterfaceObj := range inValueList { - if inValueInterfaceObj == nil { - inValueStringList = append(inValueStringList, "") - } else { - inValueStringList = append(inValueStringList, inValueInterfaceObj.(string)) - } - } - if len(inValueStringList) == 0 { - continue - } - var tmpIds []string - var tmpErr error - roleFilterSql, roleFilterParam := dao.CreateListParams(inValueStringList, "") - if v.Name == "mgmtRoles" { - tmpIds, tmpErr = getRequestTemplateIdsBySql("select t1.id from request_template t1 left join request_template_role t2 on t1.id=t2.request_template where t2.role_type='MGMT' and t2.role in ("+roleFilterSql+")", roleFilterParam) - } else { - tmpIds, tmpErr = getRequestTemplateIdsBySql("select t1.id from request_template t1 left join request_template_role t2 on t1.id=t2.request_template where t2.role_type='USE' and t2.role in ("+roleFilterSql+")", roleFilterParam) - } - if tmpErr != nil { - err = fmt.Errorf("Try to query filter role id fail,%s ", tmpErr.Error()) - break - } - extFilterSql += " and id in ('" + strings.Join(tmpIds, "','") + "') " - } else { - newFilters = append(newFilters, v) - } - } - if err != nil { - return models.PageInfo{}, nil, err - } - param.Filters = newFilters - } - rowData := []*models.RequestTemplateTable{} - filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateTable{}, PrimaryKey: "id", Prefix: "t1"}) - userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") - queryParam = append(userRolesFilterParam, queryParam...) - baseSql := fmt.Sprintf("SELECT %s FROM (select * from request_template where del_flag=0 or (del_flag=2 and id not in (select record_id from request_template where del_flag=2 and record_id<>''))) t1 WHERE t1.id in (select request_template from request_template_role where role_type='MGMT' and `role` in ("+userRolesFilterSql+")) %s %s ", queryColumn, extFilterSql, filterSql) - if param.Paging { - pageInfo.StartIndex = param.Pageable.StartIndex - pageInfo.PageSize = param.Pageable.PageSize - pageInfo.TotalRows = dao.QueryCount(baseSql, queryParam...) - pageSql, pageParam := dao.TransPageInfoToSQL(*param.Pageable) - baseSql += pageSql - queryParam = append(queryParam, pageParam...) - } - err = dao.X.SQL(baseSql, queryParam...).Find(&rowData) - if len(rowData) == 0 || err != nil { - return - } - var rtIds []string - for _, row := range rowData { - rtIds = append(rtIds, row.Id) - } - queryRoleSql := "select t4.id,GROUP_CONCAT(t4.role_obj) as 'role','mgmt' as 'role_type' from (" - queryRoleSql += "select t1.id,CONCAT(t2.role,'::',t3.display_name) as 'role_obj' from request_template t1 left join request_template_role t2 on t1.id=t2.request_template left join role t3 on t2.role=t3.id where t1.id in ('" + strings.Join(rtIds, "','") + "') and t2.role_type='MGMT'" - queryRoleSql += ") t4 group by t4.id" - queryRoleSql += " UNION " - queryRoleSql += "select t4.id,GROUP_CONCAT(t4.role_obj) as 'role','use' as 'role_type' from (" - queryRoleSql += "select t1.id,CONCAT(t2.role,'::',t3.display_name) as 'role_obj' from request_template t1 left join request_template_role t2 on t1.id=t2.request_template left join role t3 on t2.role=t3.id where t1.id in ('" + strings.Join(rtIds, "','") + "') and t2.role_type='USE'" - queryRoleSql += ") t4 group by t4.id" - var requestTemplateRows []*models.RequestTemplateRoleTable - err = dao.X.SQL(queryRoleSql).Find(&requestTemplateRows) - if err != nil { - return - } - var mgmtRoleMap = make(map[string][]*models.RoleTable) - var useRoleMap = make(map[string][]*models.RoleTable) - for _, v := range requestTemplateRows { - tmpRoles := []*models.RoleTable{} - for _, vv := range strings.Split(v.Role, ",") { - tmpSplit := strings.Split(vv, "::") - tmpRoles = append(tmpRoles, &models.RoleTable{Id: tmpSplit[0], DisplayName: tmpSplit[1]}) - } - if v.RoleType == "mgmt" { - mgmtRoleMap[v.Id] = tmpRoles - } else { - useRoleMap[v.Id] = tmpRoles - } - } - if isQueryMessage { - for _, v := range rowData { - tmpErr := SyncProcDefId(v.Id, v.ProcDefId, v.ProcDefName, v.ProcDefKey, userToken) - if tmpErr != nil { - err = fmt.Errorf("Try to sync proDefId fail,%s ", tmpErr.Error()) - break - } - } - if err != nil { - return - } - } - for _, v := range rowData { - tmpObj := models.RequestTemplateQueryObj{RequestTemplateTable: *v, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} - if _, b := mgmtRoleMap[v.Id]; b { - tmpObj.MGMTRoles = mgmtRoleMap[v.Id] - } - if _, b := useRoleMap[v.Id]; b { - tmpObj.USERoles = useRoleMap[v.Id] - } - if v.Status == "confirm" { - tmpObj.OperateOptions = []string{"query", "fork", "export", "disable"} - } else if v.Status == "created" { - tmpObj.OperateOptions = []string{"edit", "delete"} - } else if v.Status == "disable" { - tmpObj.OperateOptions = []string{"query", "enable"} - } - tmpObj.ModifyType = getRequestTemplateModifyType(v) - result = append(result, &tmpObj) - } - return -} - // getRequestTemplateModifyType 模板版本 > v1表示 模板有多个版本,不允许多个版本都去修改模板类型,要求保持一致 func getRequestTemplateModifyType(requestTemplate *models.RequestTemplateTable) bool { if strings.Compare(requestTemplate.Version, "v1") > 0 { @@ -707,20 +579,6 @@ func getRequestTemplateModifyType(requestTemplate *models.RequestTemplateTable) return true } -func CheckRequestTemplateRoles(requestTemplateId string, userRoles []string) error { - var requestTemplateRoleRows []*models.RequestTemplateRoleTable - userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") - userRolesFilterParam = append([]interface{}{requestTemplateId}, userRolesFilterParam...) - err := dao.X.SQL("select request_template from request_template_role where request_template=? and role_type='MGMT' and `role` in ("+userRolesFilterSql+")", userRolesFilterParam...).Find(&requestTemplateRoleRows) - if err != nil { - return fmt.Errorf("Try to query database data fail:%s ", err.Error()) - } - if len(requestTemplateRoleRows) == 0 { - return fmt.Errorf(models.RowDataPermissionErr) - } - return nil -} - func checkProDefId(proDefId, proDefName, proDefKey, userToken string) (exist bool, newProDefId string, err error) { exist = false var processList []*models.ProcDefObj @@ -846,27 +704,6 @@ func getRequestTemplateIdsBySql(sql string, param []interface{}) (ids []string, return } -func CreateRequestTemplate(param *models.RequestTemplateUpdateParam) (result models.RequestTemplateQueryObj, err error) { - var actions []*dao.ExecAction - newGuid := guid.CreateGuid() - result = models.RequestTemplateQueryObj{RequestTemplateTable: param.RequestTemplateTable, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} - result.Id = newGuid - nowTime := time.Now().Format(models.DateTimeFormat) - insertAction := dao.ExecAction{Sql: "insert into request_template(id,`group`,name,description,tags,package_name,entity_name,proc_def_key,proc_def_id,proc_def_name,expire_day,handler,created_by,created_time,updated_by,updated_time,type,operator_obj_type,parent_id) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} - insertAction.Param = []interface{}{newGuid, param.Group, param.Name, param.Description, param.Tags, param.PackageName, param.EntityName, param.ProcDefKey, param.ProcDefId, param.ProcDefName, param.ExpireDay, param.Handler, param.CreatedBy, nowTime, param.CreatedBy, nowTime, param.Type, param.OperatorObjType, newGuid} - actions = append(actions, &insertAction) - for _, v := range param.MGMTRoles { - result.MGMTRoles = append(result.MGMTRoles, &models.RoleTable{Id: v}) - actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{newGuid + models.SysTableIdConnector + v + models.SysTableIdConnector + "MGMT", newGuid, v, "MGMT"}}) - } - for _, v := range param.USERoles { - result.USERoles = append(result.USERoles, &models.RoleTable{Id: v}) - actions = append(actions, &dao.ExecAction{Sql: "insert into request_template_role(id,request_template,`role`,role_type) value (?,?,?,?)", Param: []interface{}{newGuid + models.SysTableIdConnector + v + models.SysTableIdConnector + "USE", newGuid, v, "USE"}}) - } - err = dao.Transaction(actions) - return -} - func UpdateRequestTemplate(param *models.RequestTemplateUpdateParam) (result models.RequestTemplateQueryObj, err error) { var actions []*dao.ExecAction nowTime := time.Now().Format(models.DateTimeFormat) diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index a3de7ee1..ab13c146 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -22,6 +22,8 @@ var ( requestTemplateService RequestTemplateService // 任务 service taskService TaskService + // 记录 service + operationLogService OperationLogService ) func New() (err error) { @@ -35,10 +37,13 @@ func New() (err error) { requestDao := dao.RequestDao{DB: engine} attachFileDao := dao.AttachFileDao{DB: engine} requestTemplateDao := dao.RequestTemplateDao{DB: engine} + requestTemplateRoleDao := dao.RequestTemplateRoleDao{DB: engine} + operationLogDao := dao.OperationLogDao{DB: engine} // 初始化Service requestService = RequestService{requestDao: requestDao} attachFileService = AttachFileService{attachFileDao: attachFileDao} - requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao} + requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao, requestTemplateRoleDao: requestTemplateRoleDao, operationLogDao: operationLogDao} + operationLogService = OperationLogService{operationLogDao: operationLogDao} db = engine return } @@ -53,6 +58,11 @@ func GetRequestTemplateService() RequestTemplateService { return requestTemplateService } +// GetOperationLogService 获取记录日志 service +func GetOperationLogService() OperationLogService { + return operationLogService +} + // transaction 事务处理 func transaction(f func(session *xorm.Session) error) (err error) { session := db.NewSession() From 0b6120b45ce143dec0ef39825aab31ca6c9e88f7 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 7 Feb 2024 11:11:36 +0800 Subject: [PATCH 004/618] =?UTF-8?q?http=E8=B0=83=E7=94=A8=E4=BD=8E?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E5=85=BC=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/{common/network => rpc}/network.go | 8 ++++---- taskman-server/rpc/proc_def_rpc.go | 5 ++--- taskman-server/rpc/user_role_rpc.go | 5 ++--- 3 files changed, 8 insertions(+), 10 deletions(-) rename taskman-server/{common/network => rpc}/network.go (91%) diff --git a/taskman-server/common/network/network.go b/taskman-server/rpc/network.go similarity index 91% rename from taskman-server/common/network/network.go rename to taskman-server/rpc/network.go index 40f76e7c..38eb68a1 100644 --- a/taskman-server/common/network/network.go +++ b/taskman-server/rpc/network.go @@ -1,9 +1,9 @@ -package network +package rpc import ( "bytes" "fmt" - "io" + "io/ioutil" "net/http" "strings" ) @@ -22,7 +22,7 @@ func HttpGet(url, userToken, language string) (byteArr []byte, err error) { err = fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) return } - byteArr, _ = io.ReadAll(resp.Body) + byteArr, _ = ioutil.ReadAll(resp.Body) defer resp.Body.Close() return } @@ -41,7 +41,7 @@ func HttpPost(url, userToken, language string, postBytes []byte) (byteArr []byte err = fmt.Errorf("do http reqeust fail,%s ", reqErr.Error()) return } - byteArr, _ = io.ReadAll(resp.Body) + byteArr, _ = ioutil.ReadAll(resp.Body) defer resp.Body.Close() return } diff --git a/taskman-server/rpc/proc_def_rpc.go b/taskman-server/rpc/proc_def_rpc.go index 8ab6458d..950ae9ba 100644 --- a/taskman-server/rpc/proc_def_rpc.go +++ b/taskman-server/rpc/proc_def_rpc.go @@ -3,7 +3,6 @@ package rpc import ( "encoding/json" "fmt" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/network" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" ) @@ -20,7 +19,7 @@ func QueryProcessDefinitionList(userToken, language string, param models.QueryPr var procDefMap = make(map[string]*models.ProcDefDto) processList = make([]*models.ProcDefDto, 0) postBytes, _ := json.Marshal(param) - byteArr, err := network.HttpPost(models.Config.Wecube.BaseUrl+pathQueryProcessDefinitions, userToken, language, postBytes) + byteArr, err := HttpPost(models.Config.Wecube.BaseUrl+pathQueryProcessDefinitions, userToken, language, postBytes) if err != nil { return } @@ -57,7 +56,7 @@ func QueryProcessDefinitionList(userToken, language string, param models.QueryPr func QueryAllModels(userToken, language string) (nodesList []*models.DataModel, err error) { var response models.QueryAllModelsResponse nodesList = make([]*models.DataModel, 0) - byteArr, err := network.HttpGet(models.Config.Wecube.BaseUrl+pathQueryModel, userToken, language) + byteArr, err := HttpGet(models.Config.Wecube.BaseUrl+pathQueryModel, userToken, language) if err != nil { return } diff --git a/taskman-server/rpc/user_role_rpc.go b/taskman-server/rpc/user_role_rpc.go index 3b53e173..728f977a 100644 --- a/taskman-server/rpc/user_role_rpc.go +++ b/taskman-server/rpc/user_role_rpc.go @@ -3,7 +3,6 @@ package rpc import ( "encoding/json" "fmt" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/network" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" ) @@ -19,7 +18,7 @@ func QueryAllRoles(requiredAll, userToken, language string) (roleMap map[string] var response models.QueryRolesResponse var userMap map[string]*models.UserDto roleMap = make(map[string]*models.SimpleLocalRoleDto) - byteArr, err := network.HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathRetrieveAllRoles, requiredAll), userToken, language) + byteArr, err := HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathRetrieveAllRoles, requiredAll), userToken, language) if err != nil { return } @@ -50,7 +49,7 @@ func QueryAllRoles(requiredAll, userToken, language string) (roleMap map[string] func QueryAllUser(userToken, language string) (userMap map[string]*models.UserDto, err error) { var response models.QueryUserResponse userMap = make(map[string]*models.UserDto) - byteArr, err := network.HttpGet(models.Config.Wecube.BaseUrl+pathRetrieveAllUser, userToken, language) + byteArr, err := HttpGet(models.Config.Wecube.BaseUrl+pathRetrieveAllUser, userToken, language) if err != nil { return } From 20e8bd50e420eb1679466dff625692122f8f883c Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 7 Feb 2024 11:45:24 +0800 Subject: [PATCH 005/618] =?UTF-8?q?http=E5=88=87=E6=8D=A2=E8=B0=83?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/rpc/proc_def_rpc.go | 7 +++++-- taskman-server/service/request_template_service.go | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/taskman-server/rpc/proc_def_rpc.go b/taskman-server/rpc/proc_def_rpc.go index 950ae9ba..6cfbc876 100644 --- a/taskman-server/rpc/proc_def_rpc.go +++ b/taskman-server/rpc/proc_def_rpc.go @@ -11,6 +11,9 @@ const ( pathQueryProcessDefinitions = "/platform/v1/process/definitions/list" // pathQueryModel 查询model pathQueryModel = "/platform/v1/models" + + // @todo 后面调整回来 models.Config.Wecube.BaseUrl + BaseUrl = "http://106.52.160.142:18080" ) // QueryProcessDefinitionList 查询编排列表 @@ -19,7 +22,7 @@ func QueryProcessDefinitionList(userToken, language string, param models.QueryPr var procDefMap = make(map[string]*models.ProcDefDto) processList = make([]*models.ProcDefDto, 0) postBytes, _ := json.Marshal(param) - byteArr, err := HttpPost(models.Config.Wecube.BaseUrl+pathQueryProcessDefinitions, userToken, language, postBytes) + byteArr, err := HttpPost(BaseUrl+pathQueryProcessDefinitions, userToken, language, postBytes) if err != nil { return } @@ -56,7 +59,7 @@ func QueryProcessDefinitionList(userToken, language string, param models.QueryPr func QueryAllModels(userToken, language string) (nodesList []*models.DataModel, err error) { var response models.QueryAllModelsResponse nodesList = make([]*models.DataModel, 0) - byteArr, err := HttpGet(models.Config.Wecube.BaseUrl+pathQueryModel, userToken, language) + byteArr, err := HttpGet(BaseUrl+pathQueryModel, userToken, language) if err != nil { return } diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index a98a76d4..668e0724 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -549,7 +549,7 @@ func SyncCoreRole() { actions = append(actions, &dao.ExecAction{Sql: "delete from `role` where id=?", Param: []interface{}{role.Id}}) roleIdList = append(roleIdList, role.Id) } - actions = append(actions, &dao.ExecAction{Sql: "update form_template set `role`=NULL where `role` in ('" + strings.Join(roleIdList, "','") + "')"}) + //actions = append(actions, &dao.ExecAction{Sql: "update form_template set `role`=NULL where `role` in ('" + strings.Join(roleIdList, "','") + "')"}) actions = append(actions, &dao.ExecAction{Sql: "update request_template_group set manage_role=NULL where manage_role in ('" + strings.Join(roleIdList, "','") + "')"}) } if len(actions) > 0 { From b2321d23abe3a52572341a14d5ea3fb48dd89cc3 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 7 Feb 2024 14:53:31 +0800 Subject: [PATCH 006/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=94=B9=E9=80=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/dao/request_template_dao.go | 3 ++- taskman-server/models/request_template.go | 18 +++++++++++++----- .../service/request_template_service.go | 10 +++++----- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index b625f81f..0b4ede24 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -9,12 +9,13 @@ type RequestTemplateDao struct { DB *xorm.Engine } +// Add 添加模板,由于直接调用对象插入,formTemplate为""又是外键所以插入报错,所以采用SQL插入 func (d RequestTemplateDao) Add(session *xorm.Session, requestTemplate *models.RequestTemplateTable) (affected int64, err error) { if session == nil { session = d.DB.NewSession() defer session.Close() } - return session.Insert(requestTemplate) + return session.InsertOne(requestTemplate) } func (d RequestTemplateDao) Update(requestTemplate models.RequestTemplateTable) (err error) { diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index bb75ff3c..6ca4ac83 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -5,11 +5,12 @@ import ( ) type RequestTemplateTable struct { - Id string `json:"id" xorm:"id"` - Group string `json:"group" xorm:"group"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` - FormTemplate string `json:"formTemplate" xorm:"form_template"` + Id string `json:"id" xorm:"id"` + Group string `json:"group" xorm:"group"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + FormTemplate *string `json:"formTemplate" xorm:"form_template"` // 此处定义成指针类型原因: request_template表插入数据, + // form_template字段为""也会被插入,又是外键就会报错 Tags string `json:"tags" xorm:"tags"` Status string `json:"status" xorm:"status"` RecordId string `json:"recordId" xorm:"record_id"` @@ -44,6 +45,13 @@ func (RequestTemplateTable) TableName() string { return "request_template" } +func (r RequestTemplateTable) GetFormTemplate() string { + return *r.FormTemplate +} +func (r RequestTemplateTable) SetFormTemplate(formTemplate string) { + *r.FormTemplate = formTemplate +} + // CollectDataObj 收藏数据项 type CollectDataObj struct { ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 668e0724..941162d8 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -734,7 +734,7 @@ func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*dao.ExecAc } var taskTemplateTable []*models.TaskTemplateTable dao.X.SQL("select id,form_template from task_template where request_template=?", id).Find(&taskTemplateTable) - formTemplateIds := []string{rtObj.FormTemplate} + formTemplateIds := []string{rtObj.GetFormTemplate()} for _, v := range taskTemplateTable { formTemplateIds = append(formTemplateIds, v.FormTemplate) } @@ -925,7 +925,7 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { "'' as confirm_time,expire_day,handler,type,operator_obj_type,'%s' as parent_id from request_template where id='%s'", newRequestTemplateId, newRequestFormTemplateId, operator, nowTime, operator, nowTime, requestTemplateObj.Id, version, requestTemplateObj.Id, requestTemplateObj.ParentId)}) } - newRequestFormActions, tmpErr := getFormCopyActions(requestTemplateObj.FormTemplate, newRequestFormTemplateId) + newRequestFormActions, tmpErr := getFormCopyActions(requestTemplateObj.GetFormTemplate(), newRequestFormTemplateId) if tmpErr != nil { return fmt.Errorf("Try to copy request form fail,%s ", tmpErr.Error()) } @@ -967,7 +967,7 @@ func ConfirmRequestTemplate(requestTemplateId string) error { if err != nil { return err } - if requestTemplateObj.FormTemplate == "" { + if requestTemplateObj.GetFormTemplate() == "" { return fmt.Errorf("Please config request template form ") } if requestTemplateObj.Status == "confirm" { @@ -1664,8 +1664,8 @@ func createNewImportTemplate(input models.RequestTemplateExport, recordId string historyFormTemplateId := formTemplate.Id formTemplate.Id = guid.CreateGuid() // 修改模板里面的 formTemplateId - if input.RequestTemplate.FormTemplate == historyFormTemplateId { - input.RequestTemplate.FormTemplate = formTemplate.Id + if input.RequestTemplate.GetFormTemplate() == historyFormTemplateId { + input.RequestTemplate.SetFormTemplate(formTemplate.Id) } for _, formItemTemplate := range input.FormItemTemplate { formItemTemplate.Id = guid.CreateGuid() From 787d8d0f58e3ff97d3c5cd5ae9742036c108955d Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 7 Feb 2024 15:26:37 +0800 Subject: [PATCH 007/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/form/form_template.go | 9 +---- taskman-server/api/v1/request/request.go | 12 +++--- .../api/v1/request/request_template.go | 37 ++++++++----------- .../dao/request_template_role_dao.go | 2 +- 4 files changed, 25 insertions(+), 35 deletions(-) diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index 2d6d333d..d06a45dc 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -8,11 +8,6 @@ import ( "github.com/gin-gonic/gin" ) -var ( - requestTemplateService = service.GetRequestTemplateService() - operationLogService = service.GetOperationLogService() -) - func GetRequestFormTemplate(c *gin.Context) { id := c.Param("id") if id == "" { @@ -58,7 +53,7 @@ func ConfirmRequestFormTemplate(c *gin.Context) { var requestTemplate *models.RequestTemplateTable var err error id := c.Param("id") - requestTemplate, err = requestTemplateService.GetRequestTemplate(id) + requestTemplate, err = service.GetRequestTemplateService().GetRequestTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -77,7 +72,7 @@ func ConfirmRequestFormTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "confirmRequestTemplate", c.Request.RequestURI, "") + service.GetOperationLogService().RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "confirmRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } diff --git a/taskman-server/api/v1/request/request.go b/taskman-server/api/v1/request/request.go index a354d928..b393f08d 100644 --- a/taskman-server/api/v1/request/request.go +++ b/taskman-server/api/v1/request/request.go @@ -205,7 +205,7 @@ func CreateRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.GetOperationLogService().RecordRequestLog(param.Id, param.Name, param.CreatedBy, "createRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } @@ -226,7 +226,7 @@ func UpdateRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestLog(param.Id, param.Name, param.UpdatedBy, "updateRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.GetOperationLogService().RecordRequestLog(param.Id, param.Name, param.UpdatedBy, "updateRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, param) } @@ -237,7 +237,7 @@ func DeleteRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "deleteRequest", c.Request.RequestURI, "") + service.GetOperationLogService().RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "deleteRequest", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } @@ -294,7 +294,7 @@ func StartRequest(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) + service.GetOperationLogService().RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "startRequest", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, instanceId) } @@ -315,7 +315,7 @@ func UpdateRequestStatus(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "setRequestStatus", c.Request.RequestURI, status) + service.GetOperationLogService().RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "setRequestStatus", c.Request.RequestURI, status) middleware.ReturnSuccess(c) } @@ -464,7 +464,7 @@ func CopyRequest(c *gin.Context) { if err != nil { middleware.ReturnServerHandleError(c, err) } else { - operationLogService.RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "copyRequest", c.Request.RequestURI, "") + service.GetOperationLogService().RecordRequestLog(requestId, "", middleware.GetRequestUser(c), "copyRequest", c.Request.RequestURI, "") middleware.ReturnData(c, result) } } diff --git a/taskman-server/api/v1/request/request_template.go b/taskman-server/api/v1/request/request_template.go index f7cc0d9f..cffa2873 100644 --- a/taskman-server/api/v1/request/request_template.go +++ b/taskman-server/api/v1/request/request_template.go @@ -16,11 +16,6 @@ import ( "github.com/gin-gonic/gin" ) -var ( - requestTemplateService = service.GetRequestTemplateService() - operationLogService = service.GetOperationLogService() -) - func QueryRequestTemplateGroup(c *gin.Context) { var param models.QueryRequestParam if err := c.ShouldBindJSON(¶m); err != nil { @@ -92,7 +87,7 @@ func DeleteRequestTemplateGroup(c *gin.Context) { } func GetCoreProcessList(c *gin.Context) { - result, err := requestTemplateService.GetCoreProcessListNew(c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + result, err := service.GetRequestTemplateService().GetCoreProcessListNew(c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -147,7 +142,7 @@ func QueryRequestTemplate(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := requestTemplateService.QueryRequestTemplate(¶m, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestRoles(c)) + pageInfo, rowData, err := service.GetRequestTemplateService().QueryRequestTemplate(¶m, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -166,12 +161,12 @@ func CreateRequestTemplate(c *gin.Context) { return } param.CreatedBy = middleware.GetRequestUser(c) - result, err := requestTemplateService.CreateRequestTemplate(¶m) + result, err := service.GetRequestTemplateService().CreateRequestTemplate(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "createRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) + service.GetOperationLogService().RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "createRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, result) } @@ -188,7 +183,7 @@ func UpdateRequestTemplateHandler(c *gin.Context) { middleware.ReturnParamEmptyError(c, "requestTemplateId") return } - requestTemplate, err = requestTemplateService.GetRequestTemplate(param.RequestTemplateId) + requestTemplate, err = service.GetRequestTemplateService().GetRequestTemplate(param.RequestTemplateId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -207,11 +202,11 @@ func UpdateRequestTemplateHandler(c *gin.Context) { middleware.ReturnError(c, fmt.Errorf("request template has deployed")) return } - if err := requestTemplateService.CheckRequestTemplateRoles(param.RequestTemplateId, middleware.GetRequestRoles(c)); err != nil { + if err := service.GetRequestTemplateService().CheckRequestTemplateRoles(param.RequestTemplateId, middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionError(c, err) return } - err = requestTemplateService.UpdateRequestTemplateHandler(requestTemplate.Id, middleware.GetRequestUser(c)) + err = service.GetRequestTemplateService().UpdateRequestTemplateHandler(requestTemplate.Id, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnError(c, err) return @@ -228,7 +223,7 @@ func UpdateRequestTemplateStatus(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - requestTemplate, err = requestTemplateService.GetRequestTemplate(param.RequestTemplateId) + requestTemplate, err = service.GetRequestTemplateService().GetRequestTemplate(param.RequestTemplateId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -241,7 +236,7 @@ func UpdateRequestTemplateStatus(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("param status invalid")) return } - err = requestTemplateService.UpdateRequestTemplateStatus(param.RequestTemplateId, middleware.GetRequestUser(c), param.TargetStatus, param.Reason) + err = service.GetRequestTemplateService().UpdateRequestTemplateStatus(param.RequestTemplateId, middleware.GetRequestUser(c), param.TargetStatus, param.Reason) if err != nil { middleware.ReturnError(c, err) return @@ -263,7 +258,7 @@ func UpdateRequestTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - if err := requestTemplateService.CheckRequestTemplateRoles(param.Id, middleware.GetRequestRoles(c)); err != nil { + if err := service.GetRequestTemplateService().CheckRequestTemplateRoles(param.Id, middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionError(c, err) return } @@ -273,7 +268,7 @@ func UpdateRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "updateRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) + service.GetOperationLogService().RecordRequestTemplateLog(result.Id, result.Name, param.CreatedBy, "updateRequestTemplate", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnData(c, result) } @@ -299,7 +294,7 @@ func DeleteRequestTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - if err := requestTemplateService.CheckRequestTemplateRoles(id, middleware.GetRequestRoles(c)); err != nil { + if err := service.GetRequestTemplateService().CheckRequestTemplateRoles(id, middleware.GetRequestRoles(c)); err != nil { middleware.ReturnDataPermissionError(c, err) return } @@ -352,7 +347,7 @@ func UpdateRequestTemplateEntityAttrs(c *gin.Context) { return } service.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) - operationLogService.RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateRequestTemplateAttr", c.Request.RequestURI, c.GetString("requestBody")) + service.GetOperationLogService().RecordRequestTemplateLog(id, "", middleware.GetRequestUser(c), "updateRequestTemplateAttr", c.Request.RequestURI, c.GetString("requestBody")) middleware.ReturnSuccess(c) } @@ -372,7 +367,7 @@ func ForkConfirmRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "forkRequestTemplate", c.Request.RequestURI, "") + service.GetOperationLogService().RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "forkRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } @@ -454,7 +449,7 @@ func DisableRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "disableRequestTemplate", c.Request.RequestURI, "") + service.GetOperationLogService().RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "disableRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } @@ -465,6 +460,6 @@ func EnableRequestTemplate(c *gin.Context) { middleware.ReturnServerHandleError(c, err) return } - operationLogService.RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "enableRequestTemplate", c.Request.RequestURI, "") + service.GetOperationLogService().RecordRequestTemplateLog(requestTemplateId, "", middleware.GetRequestUser(c), "enableRequestTemplate", c.Request.RequestURI, "") middleware.ReturnSuccess(c) } diff --git a/taskman-server/dao/request_template_role_dao.go b/taskman-server/dao/request_template_role_dao.go index 0e54d2c3..d2e9947f 100644 --- a/taskman-server/dao/request_template_role_dao.go +++ b/taskman-server/dao/request_template_role_dao.go @@ -10,7 +10,7 @@ type RequestTemplateRoleDao struct { } func (d RequestTemplateRoleDao) CheckRequestTemplateRoles(requestTemplateId string, userRoles []string) (bool, error) { - return d.DB.Table(models.RequestTemplateRoleTable{}.TableName()).Where("request_template=?", requestTemplateId).And("role_type", + return d.DB.Table(models.RequestTemplateRoleTable{}.TableName()).Where("request_template=?", requestTemplateId).And("role_type=?", "MGMT").In("role", userRoles).Exist() } From 9428cc12bc96e00e8a049ad672fa51de4f9f033d Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Thu, 8 Feb 2024 18:17:29 +0800 Subject: [PATCH 008/618] =?UTF-8?q?=E8=B0=83=E7=94=A8=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E7=BC=96=E6=8E=92=E6=8E=A5=E5=8F=A3=E3=80=81=E8=A7=92=E8=89=B2?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E6=95=B4=E7=90=86=E5=BD=92=E7=B1=BB,?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 4 +- taskman-server/api/v1/collect/collect.go | 6 +- taskman-server/api/v1/request/request.go | 43 +- .../api/v1/request/request_template.go | 24 +- taskman-server/api/v1/task/task.go | 2 +- taskman-server/api/v2/request/request.go | 8 +- .../api/v2/request/request_template.go | 2 +- taskman-server/dao/request_template_dao.go | 2 +- taskman-server/models/const.go | 39 +- taskman-server/models/param.go | 8 + taskman-server/models/process_defintions.go | 183 +++++--- taskman-server/models/request.go | 29 -- taskman-server/models/response.go | 24 +- taskman-server/rpc/network.go | 1 + taskman-server/rpc/proc_def_rpc.go | 212 ++++++++- taskman-server/rpc/user_role_rpc.go | 21 + .../service/collect_template_service.go | 6 +- taskman-server/service/cron.go | 2 +- .../service/form_template_service.go | 2 +- taskman-server/service/proc_def_service.go | 175 +++++++ taskman-server/service/ref_select_service.go | 2 +- taskman-server/service/request_service.go | 434 ++++++------------ .../service/request_template_service.go | 323 +++---------- taskman-server/service/service.go | 8 + taskman-server/service/task_service.go | 23 +- 25 files changed, 845 insertions(+), 738 deletions(-) create mode 100644 taskman-server/service/proc_def_service.go diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 387e4dd1..630eb4bc 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -98,7 +98,7 @@ func init() { &handlerFuncObj{Url: "/request/progress", Method: "POST", HandlerFunc: request.GetRequestProgress}, &handlerFuncObj{Url: "/request/process/definitions/:templateId", Method: "GET", HandlerFunc: request.GetProcessDefinitions}, &handlerFuncObj{Url: "/request/process/instances/:instanceId", Method: "GET", HandlerFunc: request.GetProcessInstance}, - &handlerFuncObj{Url: "/request/workflow/task_node/:procInstanceId/:nodeInstanceId", Method: "POST", HandlerFunc: request.GetExecutionNodes}, + &handlerFuncObj{Url: "/request/workflow/task_node/:procInstanceId/:nodeInstanceId", Method: "POST", HandlerFunc: request.GetProcDefTaskNodeContext}, &handlerFuncObj{Url: "/request/history/list", Method: "POST", HandlerFunc: request.HistoryList}, &handlerFuncObj{Url: "/request/export", Method: "POST", HandlerFunc: request.Export}, // For core 1:get task form template 2:create task @@ -173,7 +173,7 @@ func InitHttpServer() { } // entity query - r.POST(urlPrefix+"/entities/request/query", request.QueryWorkflowEntity) + r.POST(urlPrefix+"/entities/request/query", request.QueryProcDefEntity) r.Run(":" + models.Config.HttpServer.Port) } diff --git a/taskman-server/api/v1/collect/collect.go b/taskman-server/api/v1/collect/collect.go index b6ed5483..834c8aba 100644 --- a/taskman-server/api/v1/collect/collect.go +++ b/taskman-server/api/v1/collect/collect.go @@ -22,7 +22,7 @@ func AddTemplateCollect(c *gin.Context) { return } var parentId string - requestTemplate, err := service.GetSimpleRequestTemplate(param.TemplateId) + requestTemplate, err := service.GetRequestTemplateService().GetSimpleRequestTemplate(param.TemplateId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -86,7 +86,7 @@ func QueryTemplateCollect(c *gin.Context) { if param.PageSize == 0 { param.PageSize = 10 } - pageInfo, rowData, err := service.QueryTemplateCollect(¶m, middleware.GetRequestUser(c), c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) + pageInfo, rowData, err := service.QueryTemplateCollect(¶m, middleware.GetRequestUser(c), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -112,7 +112,7 @@ func FilterItem(c *gin.Context) { // getRequestTemplateParentId 根据模板id查找 最开始版本模板id func getRequestTemplateParentId(templateId string) (string, error) { // 根据 templateId 查找parent_id,模板会变更产生多个版本,只需要关联最开始版本 - requestTemplate, err := service.GetSimpleRequestTemplate(templateId) + requestTemplate, err := service.GetRequestTemplateService().GetSimpleRequestTemplate(templateId) if err != nil { return "", err } diff --git a/taskman-server/api/v1/request/request.go b/taskman-server/api/v1/request/request.go index b393f08d..34a48d55 100644 --- a/taskman-server/api/v1/request/request.go +++ b/taskman-server/api/v1/request/request.go @@ -17,7 +17,7 @@ func GetEntityData(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("Param requestId can not empty ")) return } - result, err := service.GetEntityData(id, c.GetHeader("Authorization")) + result, err := service.GetEntityData(id, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -32,7 +32,7 @@ func ProcessDataPreview(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("Param requestTemplateId or entityDataId can not empty ")) return } - result, err := service.ProcessDataPreview(requestTemplateId, entityDataId, c.GetHeader("Authorization")) + result, err := service.ProcessDataPreview(requestTemplateId, entityDataId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -43,7 +43,7 @@ func ProcessDataPreview(c *gin.Context) { func GetRequestPreviewData(c *gin.Context) { requestId := c.Query("requestId") entityDataId := c.Query("rootEntityId") - result, err := service.GetRequestPreData(requestId, entityDataId, c.GetHeader("Authorization")) + result, err := service.GetRequestPreData(requestId, entityDataId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -92,7 +92,7 @@ func DataList(c *gin.Context) { if param.PageSize == 0 { param.PageSize = 10 } - pageInfo, rowData, err := service.DataList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c)) + pageInfo, rowData, err := service.DataList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -121,7 +121,7 @@ func HistoryList(c *gin.Context) { if param.PageSize == 0 { param.PageSize = 10 } - pageInfo, rowData, err := service.HistoryList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c)) + pageInfo, rowData, err := service.HistoryList(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), middleware.GetRequestUser(c), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -151,7 +151,7 @@ func ListRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := service.ListRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), permission, middleware.GetRequestUser(c)) + pageInfo, rowData, err := service.ListRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), permission, middleware.GetRequestUser(c), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -200,7 +200,7 @@ func CreateRequest(c *gin.Context) { return } param.CreatedBy = middleware.GetRequestUser(c) - err := service.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization")) + err := service.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -289,7 +289,7 @@ func StartRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - instanceId, err := service.StartRequest(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization"), param) + instanceId, err := service.StartRequest(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), param) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -310,7 +310,7 @@ func UpdateRequestStatus(c *gin.Context) { if bindErr := c.ShouldBindJSON(¶m); bindErr == nil { description = param.Description } - err := service.UpdateRequestStatus(requestId, status, middleware.GetRequestUser(c), c.GetHeader("Authorization"), description) + err := service.UpdateRequestStatus(requestId, status, middleware.GetRequestUser(c), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), description) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -321,7 +321,7 @@ func UpdateRequestStatus(c *gin.Context) { func TerminateRequest(c *gin.Context) { requestId := c.Param("requestId") - err := service.RequestTermination(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization")) + err := service.RequestTermination(requestId, middleware.GetRequestUser(c), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) } else { @@ -451,9 +451,12 @@ func RemoveAttachFile(c *gin.Context) { } } -func QueryWorkflowEntity(c *gin.Context) { - result := models.WorkflowEntityQuery{Status: "OK", Message: "Success", Data: []*models.WorkflowEntityDataObj{}} - result.Data = append(result.Data, &models.WorkflowEntityDataObj{Id: "taskman_request_id", DisplayName: "request"}) +func QueryProcDefEntity(c *gin.Context) { + result := models.ProcDefRootEntityResponse{ + HttpResponseMeta: models.HttpResponseMeta{Status: "OK", Message: "Success"}, + Data: []*models.ProcDefEntityDataObj{}, + } + result.Data = append(result.Data, &models.ProcDefEntityDataObj{Id: "taskman_request_id", DisplayName: "request"}) c.JSON(http.StatusOK, result) } @@ -488,7 +491,7 @@ func GetRequestProgress(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - rowsData, err = service.GetRequestProgress(param.RequestId, c.GetHeader("Authorization")) + rowsData, err = service.GetRequestProgress(param.RequestId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -505,7 +508,7 @@ func GetProcessInstance(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - rowData, err = service.GetProcessInstance(instanceId, c.GetHeader("Authorization")) + rowData, err = service.GetProcDefService().GetProcessDefineInstance(instanceId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -513,7 +516,7 @@ func GetProcessInstance(c *gin.Context) { middleware.ReturnData(c, rowData) } -// ProcessDefinitions 流程定义 +// GetProcessDefinitions 流程定义 func GetProcessDefinitions(c *gin.Context) { var rowData *models.DefinitionsData var err error @@ -522,7 +525,7 @@ func GetProcessDefinitions(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - rowData, err = service.GetProcessDefinitions(templateId, c.GetHeader("Authorization")) + rowData, err = service.GetProcessDefinitions(templateId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -530,11 +533,11 @@ func GetProcessDefinitions(c *gin.Context) { middleware.ReturnData(c, rowData) } -// GetExecutionNodes 获取工作流执行节点 -func GetExecutionNodes(c *gin.Context) { +// GetProcDefTaskNodeContext 获取工作流执行节点 +func GetProcDefTaskNodeContext(c *gin.Context) { procInstanceId := c.Param("procInstanceId") nodeInstanceId := c.Param("nodeInstanceId") - rowData, err := service.GetExecutionNodes(c.GetHeader("Authorization"), procInstanceId, nodeInstanceId) + rowData, err := service.GetProcDefService().GetProcDefTaskNodeContext(procInstanceId, nodeInstanceId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/api/v1/request/request_template.go b/taskman-server/api/v1/request/request_template.go index cffa2873..ba917ad5 100644 --- a/taskman-server/api/v1/request/request_template.go +++ b/taskman-server/api/v1/request/request_template.go @@ -87,7 +87,8 @@ func DeleteRequestTemplateGroup(c *gin.Context) { } func GetCoreProcessList(c *gin.Context) { - result, err := service.GetRequestTemplateService().GetCoreProcessListNew(c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + mangeRole := c.Query("role") + result, err := service.GetProcDefService().GetCoreProcessListNew(c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), mangeRole) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -96,18 +97,20 @@ func GetCoreProcessList(c *gin.Context) { } func GetCoreProcNodes(c *gin.Context) { + var nodeList []*models.ProcNodeObj + var err error requestTemplateId := c.Param("id") getType := c.Param("type") - result, err := service.GetProcessNodesByProc(models.RequestTemplateTable{Id: requestTemplateId}, c.GetHeader("Authorization"), getType) + nodeList, err = service.GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: requestTemplateId}, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), getType) if err != nil { middleware.ReturnServerHandleError(c, err) return } - middleware.ReturnData(c, result) + middleware.ReturnData(c, nodeList) } func GetRoleList(c *gin.Context) { - service.SyncCoreRole() + service.SyncCoreRole(c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) result, err := service.GetRoleList([]string{}) if err != nil { middleware.ReturnServerHandleError(c, err) @@ -118,7 +121,7 @@ func GetRoleList(c *gin.Context) { func GetUserByRoles(c *gin.Context) { roleString := c.Query("roles") - result, err := service.QueryUserByRoles(strings.Split(roleString, ","), c.GetHeader("Authorization")) + result, err := service.QueryUserByRoles(strings.Split(roleString, ","), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -127,7 +130,7 @@ func GetUserByRoles(c *gin.Context) { } func GetUserRoles(c *gin.Context) { - service.SyncCoreRole() + service.SyncCoreRole(c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) result, err := service.GetRoleList(middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) @@ -142,7 +145,8 @@ func QueryRequestTemplate(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - pageInfo, rowData, err := service.GetRequestTemplateService().QueryRequestTemplate(¶m, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestRoles(c)) + pageInfo, rowData, err := service.GetRequestTemplateService().QueryRequestTemplate(¶m, models.CommonParam{Token: c.GetHeader("Authorization"), + Language: c.GetHeader(middleware.AcceptLanguageHeader), Roles: middleware.GetRequestRoles(c)}) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -308,7 +312,7 @@ func DeleteRequestTemplate(c *gin.Context) { func ListRequestTemplateEntityAttrs(c *gin.Context) { id := c.Param("id") - result, err := service.ListRequestTemplateEntityAttrs(id, c.GetHeader("Authorization")) + result, err := service.ListRequestTemplateEntityAttrs(id, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -420,7 +424,7 @@ func ImportRequestTemplate(c *gin.Context) { c.JSON(http.StatusInternalServerError, models.ResponseErrorJson{StatusCode: "PARAM_HANDLE_ERROR", StatusMessage: "Json unmarshal fail error:" + err.Error(), Data: nil}) return } - templateName, backToken, importErr := service.RequestTemplateImport(paramObj, c.GetHeader("Authorization"), "", middleware.GetRequestUser(c)) + templateName, backToken, importErr := service.RequestTemplateImport(paramObj, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), "", middleware.GetRequestUser(c)) if importErr != nil { middleware.ReturnServerHandleError(c, importErr) return @@ -434,7 +438,7 @@ func ImportRequestTemplate(c *gin.Context) { func ConfirmImportRequestTemplate(c *gin.Context) { confirmToken := c.Param("confirmToken") - _, _, err := service.RequestTemplateImport(models.RequestTemplateExport{}, c.GetHeader("Authorization"), confirmToken, middleware.GetRequestUser(c)) + _, _, err := service.RequestTemplateImport(models.RequestTemplateExport{}, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), confirmToken, middleware.GetRequestUser(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/api/v1/task/task.go b/taskman-server/api/v1/task/task.go index c2426be0..ec51aeed 100644 --- a/taskman-server/api/v1/task/task.go +++ b/taskman-server/api/v1/task/task.go @@ -49,7 +49,7 @@ func CreateTask(c *gin.Context) { output.ErrorMessage = tmpErr.Error() err = tmpErr } else { - notifyErr := service.NotifyTaskMail(taskId) + notifyErr := service.NotifyTaskMail(taskId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if notifyErr != nil { log.Logger.Error("Notify task mail fail", log.Error(notifyErr)) } diff --git a/taskman-server/api/v2/request/request.go b/taskman-server/api/v2/request/request.go index 778a98a7..b5ce61a0 100644 --- a/taskman-server/api/v2/request/request.go +++ b/taskman-server/api/v2/request/request.go @@ -17,7 +17,7 @@ var ( // GetRequestDetail 新版请求详情 func GetRequestDetail(c *gin.Context) { requestId := c.Param("requestId") - result, err := service.GetRequestDetailV2(requestId, c.GetHeader("Authorization")) + result, err := service.GetRequestDetailV2(requestId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -39,7 +39,7 @@ func CreateRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("Param role can not empty ")) return } - template, err := service.GetSimpleRequestTemplate(param.RequestTemplate) + template, err := service.GetRequestTemplateService().GetSimpleRequestTemplate(param.RequestTemplate) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -58,7 +58,7 @@ func CreateRequest(c *gin.Context) { } else { param.TemplateVersion = template.Version } - err = service.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization")) + err = service.CreateRequest(¶m, middleware.GetRequestRoles(c), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -143,7 +143,7 @@ func StartRequest(c *gin.Context) { middleware.ReturnParamValidateError(c, fmt.Errorf("request handler not permission!")) return } - instanceId, err := service.StartRequest(requestId, operator, c.GetHeader("Authorization"), param) + instanceId, err := service.StartRequest(requestId, operator, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), param) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/api/v2/request/request_template.go b/taskman-server/api/v2/request/request_template.go index 52ffb8b6..23d7f3a9 100644 --- a/taskman-server/api/v2/request/request_template.go +++ b/taskman-server/api/v2/request/request_template.go @@ -8,7 +8,7 @@ import ( // GetRequestTemplateByUser 选择模板 func GetRequestTemplateByUser(c *gin.Context) { - result, err := service.GetRequestTemplateByUserV2(middleware.GetRequestUser(c), c.GetHeader("Authorization"), middleware.GetRequestRoles(c)) + result, err := service.GetRequestTemplateService().GetRequestTemplateByUserV2(middleware.GetRequestUser(c), c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), middleware.GetRequestRoles(c)) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index 0b4ede24..3f8c23ad 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -9,7 +9,7 @@ type RequestTemplateDao struct { DB *xorm.Engine } -// Add 添加模板,由于直接调用对象插入,formTemplate为""又是外键所以插入报错,所以采用SQL插入 +// Add 添加模板 func (d RequestTemplateDao) Add(session *xorm.Session, requestTemplate *models.RequestTemplateTable) (affected int64, err error) { if session == nil { session = d.DB.NewSession() diff --git a/taskman-server/models/const.go b/taskman-server/models/const.go index 0532b6c6..48fedacc 100644 --- a/taskman-server/models/const.go +++ b/taskman-server/models/const.go @@ -10,20 +10,22 @@ const ( DefaultHttpErrorCode = "ERROR" ) -// Status 定义请求状态 -type Status string +// RequestStatus 定义请求状态 +type RequestStatus string const ( - Draft Status = "Draft" // 草稿 - Pending Status = "Pending" // 等待定版 - InProgress Status = "InProgress" // 执行中 - InProgressFaulted Status = "InProgress(Faulted)" // 节点报错 - Termination Status = "Termination" // 手动终止 - Completed Status = "Completed" // 成功 - InProgressTimeOuted Status = "InProgress(Timeouted)" // 节点超时 - Faulted Status = "Faulted" // 自动退出 + RequestStatusDraft RequestStatus = "Draft" // 草稿 + RequestStatusPending RequestStatus = "Pending" // 等待定版 + RequestStatusInProgress RequestStatus = "InProgress" // 执行中 + RequestStatusInProgressFaulted RequestStatus = "InProgress(Faulted)" // 节点报错 + RequestStatusTermination RequestStatus = "Termination" // 手动终止 + RequestStatusCompleted RequestStatus = "Completed" // 成功 + RequestStatusInProgressTimeOuted RequestStatus = "InProgress(Timeouted)" // 节点超时 + RequestStatusFaulted RequestStatus = "Faulted" // 自动退出 ) +const ProcDefStatusTimeout = "Timeouted" //编排状态超时 + // TemplateType 模板类型 type TemplateType string @@ -50,3 +52,20 @@ const ( RolePermissionUse RolePermission = "USE" RolePermissionMGMT RolePermission = "MGMT" ) + +// ProcDefNodeType 编排节点类型 +type ProcDefNodeType string + +const ( + ProcDefNodeTypeStart ProcDefNodeType = "start" //开始 + ProcDefNodeTypeEnd ProcDefNodeType = "end" //结束 + ProcDefNodeTypeAbnormal ProcDefNodeType = "abnormal" //异常 + ProcDefNodeTypeDecision ProcDefNodeType = "decision" //判断 + ProcDefNodeTypeFork ProcDefNodeType = "fork" //分流 + ProcDefNodeTypeMerge ProcDefNodeType = "merge" //汇聚 + ProcDefNodeTypeHuman ProcDefNodeType = "human" //人工节点 + ProcDefNodeTypeAutomatic ProcDefNodeType = "automatic" //自动节点 + ProcDefNodeTypeData ProcDefNodeType = "data" //数据节点 + ProcDefNodeTypeDate ProcDefNodeType = "date" //时间节点 + ProcDefNodeTypeTimeInterval ProcDefNodeType = "timeInterval" //时间间隔 +) diff --git a/taskman-server/models/param.go b/taskman-server/models/param.go index 990ddb6f..a8ed1e98 100644 --- a/taskman-server/models/param.go +++ b/taskman-server/models/param.go @@ -127,3 +127,11 @@ type TerminateInstanceParam struct { ProcInstId string `json:"procInstId"` ProcInstKey string `json:"procInstKey"` } + +// CommonParam 通用参数 +type CommonParam struct { + User string // 登录用户 + Roles []string // 用户角色 + Token string // 鉴权token + Language string // 环境语言 +} diff --git a/taskman-server/models/process_defintions.go b/taskman-server/models/process_defintions.go index 7cd9a818..5dfa12e7 100644 --- a/taskman-server/models/process_defintions.go +++ b/taskman-server/models/process_defintions.go @@ -1,5 +1,27 @@ package models +import ( + "strings" + "time" +) + +type ProcDef struct { + Id string `json:"id"` // 唯一标识 + Key string `json:"key"` // 编排key + Name string `json:"name"` // 编排名称 + Version string `json:"version"` // 版本 + RootEntity string `json:"rootEntity"` // 根节点 + Status string `json:"status"` // 状态 + Tags string `json:"tags"` // 标签 + ForPlugin string `json:"forPlugin"` // 授权插件 + Scene string `json:"scene"` // 使用场景 + ConflictCheck bool `json:"conflictCheck"` // 冲突检测 + CreatedBy string `json:"createdBy"` // 创建人 + CreatedTime time.Time `json:"createdTime"` // 创建时间 + UpdatedBy string `json:"updatedBy"` // 更新人 + UpdatedTime time.Time `json:"updatedTime"` // 更新时间 +} + type ProcDefQueryDto struct { ManageRole string `json:"manageRole"` //管理角色 ProcDefList []*ProcDefDto `json:"dataList"` // 编排列表 @@ -160,67 +182,90 @@ type WorkflowNode struct { } type FlowNodes struct { - NodeID string `json:"nodeId"` - NodeName string `json:"nodeName"` - NodeType string `json:"nodeType"` - NodeDefID string `json:"nodeDefId"` - Status string `json:"status"` - OrderedNo string `json:"orderedNo"` - ProcDefID string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - RoutineExpression string `json:"routineExpression"` - TaskCategory interface{} `json:"taskCategory"` - ServiceID string `json:"serviceId"` - DynamicBind string `json:"dynamicBind"` - Description string `json:"description"` - PreviousNodeIds []string `json:"previousNodeIds"` - SucceedingNodeIds []string `json:"succeedingNodeIds"` + NodeID string `json:"nodeId"` + NodeName string `json:"nodeName"` + NodeType string `json:"nodeType"` + NodeDefID string `json:"nodeDefId"` + Status string `json:"status"` + OrderedNo string `json:"orderedNo"` + ProcDefID string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + RoutineExpression string `json:"routineExpression"` + ServiceId string `json:"serviceId"` + DynamicBind string `json:"dynamicBind"` + Description string `json:"description"` + PreviousNodeIds []string `json:"previousNodeIds"` + SucceedingNodeIds []string `json:"succeedingNodeIds"` +} + +type ProcDefNode struct { + Id string `json:"id"` // 唯一标识 + NodeId string `json:"nodeId"` // 前端nodeID + ProcDefId string `json:"procDefId"` // 编排id + Name string `json:"name"` // 节点名称 + Description string `json:"description"` // 节点描述 + Status string `json:"status"` // 状态 + NodeType string `json:"nodeType"` // 节点类型 + ServiceName string `json:"serviceName"` // 插件服务名 + DynamicBind bool `json:"dynamicBind"` // 是否动态绑定 + BindNodeId string `json:"bindNodeId" ` // 动态绑定节点 + RiskCheck bool `json:"riskCheck"` // 是否高危检测 + RoutineExpression string `json:"routineExpression"` // 定位规则 + ContextParamNodes string `json:"contextParamNodes"` // 上下文参数节点 + Timeout int `json:"timeout"` // 超时时间分钟 + TimeConfig string `json:"timeConfig"` // 节点配置 + OrderedNo int `json:"orderedNo"` // 节点顺序 + UiStyle string `json:"uiStyle"` // 前端样式 + CreatedBy string `json:"createdBy"` // 创建人 + CreatedTime time.Time `json:"createdTime"` // 创建时间 + UpdatedBy string `json:"updatedBy"` // 更新人 + UpdatedTime time.Time `json:"updatedTime"` // 更新时间 } + type DefinitionsData struct { - ProcDefID string `json:"procDefId"` - ProcDefKey string `json:"procDefKey"` - ProcDefName string `json:"procDefName"` - ProcDefVersion string `json:"procDefVersion"` - Status string `json:"status"` - ProcDefData interface{} `json:"procDefData"` - RootEntity string `json:"rootEntity"` - CreatedTime interface{} `json:"createdTime"` - ExcludeMode string `json:"excludeMode"` - Tags interface{} `json:"tags"` - PermissionToRole interface{} `json:"permissionToRole"` - FlowNodes []FlowNodes `json:"flowNodes"` + ProcDefId string `json:"procDefId"` + ProcDefKey string `json:"procDefKey"` + ProcDefName string `json:"procDefName"` + ProcDefVersion string `json:"procDefVersion"` + Status string `json:"status"` + ProcDefData string `json:"procDefData"` + RootEntity string `json:"rootEntity"` + CreatedTime string `json:"createdTime"` + ExcludeMode string `json:"excludeMode"` + Tags string `json:"tags"` + FlowNodes []*FlowNodes `json:"flowNodes"` } type TaskNodeInstances struct { - NodeID string `json:"nodeId"` + NodeId string `json:"nodeId"` NodeName string `json:"nodeName"` NodeType string `json:"nodeType"` - NodeDefID string `json:"nodeDefId"` + NodeDefId string `json:"nodeDefId"` Status string `json:"status"` - OrderedNo interface{} `json:"orderedNo"` - ProcDefID string `json:"procDefId"` + OrderedNo string `json:"orderedNo"` + ProcDefId string `json:"procDefId"` ProcDefKey string `json:"procDefKey"` RoutineExpression interface{} `json:"routineExpression"` TaskCategory interface{} `json:"taskCategory"` - ServiceID interface{} `json:"serviceId"` + ServiceId string `json:"serviceId"` DynamicBind interface{} `json:"dynamicBind"` - Description interface{} `json:"description"` + Description string `json:"description"` PreviousNodeIds []interface{} `json:"previousNodeIds"` SucceedingNodeIds []string `json:"succeedingNodeIds"` - ProcInstID int `json:"procInstId"` + ProcInstId int `json:"procInstId"` ProcInstKey string `json:"procInstKey"` - ID int `json:"id"` } + type ProcessInstance struct { - ID int `json:"id"` - ProcInstKey string `json:"procInstKey"` - ProcInstName string `json:"procInstName"` - CreatedTime string `json:"createdTime"` - Operator string `json:"operator"` - Status string `json:"status"` - ProcDefID string `json:"procDefId"` - EntityTypeID string `json:"entityTypeId"` - EntityDataID string `json:"entityDataId"` - TaskNodeInstances []TaskNodeInstances `json:"taskNodeInstances"` + ID int `json:"id"` + ProcInstKey string `json:"procInstKey"` + ProcInstName string `json:"procInstName"` + CreatedTime string `json:"createdTime"` + Operator string `json:"operator"` + Status string `json:"status"` + ProcDefID string `json:"procDefId"` + EntityTypeID string `json:"entityTypeId"` + EntityDataID string `json:"entityDataId"` + TaskNodeInstances []*TaskNodeInstances `json:"taskNodeInstances"` } type EntityNodeBindQueryObj struct { @@ -228,31 +273,6 @@ type EntityNodeBindQueryObj struct { ItemGroup string `xorm:"item_group"` } -type InstanceStatusQuery struct { - Status string `json:"status"` - Message string `json:"message"` - Data InstanceStatusQueryObj `json:"data"` -} - -type InstanceStatusQueryObj struct { - Id int `json:"id"` - ProcDefId string `json:"procDefId"` - ProcInstKey string `json:"procInstKey"` - ProcInstName string `json:"procInstName"` - Status string `json:"status"` - TaskNodeInstances []*InstanceStatusQueryNode `json:"taskNodeInstances"` -} - -type InstanceStatusQueryNode struct { - Id int `json:"id"` - NodeId string `json:"nodeId"` - NodeDefId string `json:"nodeDefId"` - NodeName string `json:"nodeName"` - NodeType string `json:"nodeType"` - Status string `json:"status"` - OrderedNo string `json:"orderedNo"` -} - type StartInstanceResultData struct { Id int `json:"id"` ProcInstKey string `json:"procInstKey"` @@ -261,6 +281,11 @@ type StartInstanceResultData struct { Status string `json:"status"` } +type ProcDefEntityDataObj struct { + Id string `json:"id"` + DisplayName string `json:"displayName"` +} + type ProcNodeObjList []*ProcNodeObj func (s ProcNodeObjList) Len() int { @@ -275,6 +300,24 @@ func (s ProcNodeObjList) Less(i, j int) bool { return s[i].OrderedNum < s[j].OrderedNum } +type QueryNodeSort []*TaskNodeInstances + +func (q QueryNodeSort) Len() int { + return len(q) +} + +func (q QueryNodeSort) Less(i, j int) bool { + t := strings.Compare(q[i].OrderedNo, q[j].OrderedNo) + if t < 0 { + return true + } + return false +} + +func (q QueryNodeSort) Swap(i, j int) { + q[i], q[j] = q[j], q[i] +} + func ConvertModelsList2Map(nodesList []*DataModel) map[string]ProcEntity { var entityMap = make(map[string]ProcEntity) if len(nodesList) > 0 { diff --git a/taskman-server/models/request.go b/taskman-server/models/request.go index 8b606ebf..5e55ccda 100644 --- a/taskman-server/models/request.go +++ b/taskman-server/models/request.go @@ -217,17 +217,6 @@ type RequestProDataV2Dto struct { Data []*RequestPreDataTableObj `json:"data"` } -type WorkflowEntityQuery struct { - Status string `json:"status"` - Message string `json:"message"` - Data []*WorkflowEntityDataObj `json:"data"` -} - -type WorkflowEntityDataObj struct { - Id string `json:"id"` - DisplayName string `json:"displayName"` -} - type RequestForm struct { Id string `json:"id"` Name string `json:"name"` @@ -304,24 +293,6 @@ type UpdateRequestStatusParam struct { Description string `json:"description"` } -type QueryNodeSort []*InstanceStatusQueryNode - -func (q QueryNodeSort) Len() int { - return len(q) -} - -func (q QueryNodeSort) Less(i, j int) bool { - t := strings.Compare(q[i].OrderedNo, q[j].OrderedNo) - if t < 0 { - return true - } - return false -} - -func (q QueryNodeSort) Swap(i, j int) { - q[i], q[j] = q[j], q[i] -} - type RequestProgressObjSort []*RequestProgressObj func (q RequestProgressObjSort) Len() int { diff --git a/taskman-server/models/response.go b/taskman-server/models/response.go index bf37923d..a76e1ba5 100644 --- a/taskman-server/models/response.go +++ b/taskman-server/models/response.go @@ -61,6 +61,11 @@ type QueryProcessDefinitionResponse struct { Data []*ProcDefQueryDto `json:"data"` } +type QueryProcessAllDefinitionResponse struct { + HttpResponseMeta + Data []*ProcDef `json:"data"` +} + type QueryAllModelsResponse struct { HttpResponseMeta Data []*DataModel `json:"data"` @@ -71,6 +76,11 @@ type ProcNodeQueryResponse struct { Data []*ProcNodeObj `json:"data"` } +type ProcDefTaskNodesResponse struct { + HttpResponseMeta + Data []*ProcDefNode `json:"data"` +} + type CoreProcessQueryResponse struct { HttpResponseMeta Data []*CodeProcessQueryObj `json:"data"` @@ -86,7 +96,7 @@ type ProcessInstanceResponse struct { Data *ProcessInstance `json:"data"` } -type ExecutionResponse struct { +type ProcDefTaskNodeContextResponse struct { HttpResponseMeta Data interface{} `json:"data"` } @@ -98,5 +108,15 @@ type ProcQueryResponse struct { type StartInstanceResponse struct { HttpResponseMeta - Data StartInstanceResultData `json:"data"` + Data *StartInstanceResultData `json:"data"` +} + +type ProcDefRootEntityResponse struct { + HttpResponseMeta + Data []*ProcDefEntityDataObj `json:"data"` +} + +type EntityTreeResponse struct { + HttpResponseMeta + Data *EntityTreeData `json:"data"` } diff --git a/taskman-server/rpc/network.go b/taskman-server/rpc/network.go index 38eb68a1..45181841 100644 --- a/taskman-server/rpc/network.go +++ b/taskman-server/rpc/network.go @@ -36,6 +36,7 @@ func HttpPost(url, userToken, language string, postBytes []byte) (byteArr []byte } req.Header.Set("Authorization", userToken) req.Header.Set("Accept-Language", language) + req.Header.Set("Content-Type", "application/json") resp, respErr := http.DefaultClient.Do(req) if respErr != nil { err = fmt.Errorf("do http reqeust fail,%s ", reqErr.Error()) diff --git a/taskman-server/rpc/proc_def_rpc.go b/taskman-server/rpc/proc_def_rpc.go index 6cfbc876..9f18f208 100644 --- a/taskman-server/rpc/proc_def_rpc.go +++ b/taskman-server/rpc/proc_def_rpc.go @@ -3,12 +3,33 @@ package rpc import ( "encoding/json" "fmt" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" ) const ( // pathQueryProcessDefinitions 查询编排 pathQueryProcessDefinitions = "/platform/v1/process/definitions/list" + // pathAllQueryProcessDefinitions 查询插件所有编排 + pathAllQueryProcessDefinitions = "/platform/v1/process/definitions/%s/list" + // pathGetProcessDefinitions 查询编排详情 + pathGetProcessDefinitions = "/platform/v1/process/definitions/%s/outline" + // pathQueryProcessDefinitionsTaskNodes 查询编排节点 + pathQueryProcessDefinitionsTaskNodes = "/public/platform/v1/process/definitions/%s/tasknodes" + // pathQueryProcessDefinitionsInstance 编排实例 + pathQueryProcessDefinitionsInstance = "/platform/v1/process/instances/%s" + // pathQueryProcessDefinitionsEntityData 查询编排实例entityData + pathQueryProcessDefinitionsEntityData = "/platform/v1/process/instances/%s" + // pathQueryPreviewProcessDefinitionsEntity 编排设计entityData预览 + pathQueryPreviewProcessDefinitionsEntity = "/public/process/definitions/%s/preview/entities/%s" + // pathTerminationsProcessDefinitionsInstance 终止编排实例运行 + pathTerminationsProcessDefinitionsInstance = "/platform/v1/public/process/instances/%s/terminations" + // pathStartProcDefInstance 启动编排实例 + pathStartProcDefInstance = "/platform/v1/public/process/instances" + // pathQueryProcessDefinitionsInstanceTaskNodeContext 查询编排执行节点context + pathQueryProcessDefinitionsInstanceTaskNodeContext = "/platform/v1/process/instances/%s/tasknodes/%s/context" + // pathQueryModel 查询model pathQueryModel = "/platform/v1/models" @@ -16,8 +37,8 @@ const ( BaseUrl = "http://106.52.160.142:18080" ) -// QueryProcessDefinitionList 查询编排列表 -func QueryProcessDefinitionList(userToken, language string, param models.QueryProcessDefinitionParam) (processList []*models.ProcDefDto, err error) { +// QueryProcessDefinitionList 查询当前角色编排列表,并且根据属主角色进行过滤 +func QueryProcessDefinitionList(userToken, language, manageRole string, param models.QueryProcessDefinitionParam) (processList []*models.ProcDefDto, err error) { var response models.QueryProcessDefinitionResponse var procDefMap = make(map[string]*models.ProcDefDto) processList = make([]*models.ProcDefDto, 0) @@ -37,6 +58,9 @@ func QueryProcessDefinitionList(userToken, language string, param models.QueryPr } if len(response.Data) > 0 { for _, queryDto := range response.Data { + if manageRole != "" && manageRole != queryDto.ManageRole { + continue + } if len(queryDto.ProcDefList) > 0 { for _, dto := range queryDto.ProcDefList { procDefMap[dto.Id] = dto @@ -55,6 +79,52 @@ func QueryProcessDefinitionList(userToken, language string, param models.QueryPr return } +// GetProcessDefineTaskNodes 获取编排节点 +func GetProcessDefineTaskNodes(procDefId, userToken, language string) (list []*models.ProcDefNode, err error) { + var response models.ProcDefTaskNodesResponse + list = make([]*models.ProcDefNode, 0) + byteArr, err := HttpGet(fmt.Sprintf(BaseUrl+pathQueryProcessDefinitionsTaskNodes, procDefId), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + return + } + if len(response.Data) > 0 { + list = response.Data + } + return +} + +// QueryAllProcessDefinitionList 查询所有编排列表 +func QueryAllProcessDefinitionList(userToken, language string) (processList []*models.ProcDef, err error) { + var response models.QueryProcessAllDefinitionResponse + processList = make([]*models.ProcDef, 0) + byteArr, err := HttpGet(fmt.Sprintf(BaseUrl+pathAllQueryProcessDefinitions, "taskman"), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + return + } + if len(response.Data) > 0 { + processList = response.Data + } + return +} + // QueryAllModels 查询所有模型 func QueryAllModels(userToken, language string) (nodesList []*models.DataModel, err error) { var response models.QueryAllModelsResponse @@ -76,3 +146,141 @@ func QueryAllModels(userToken, language string) (nodesList []*models.DataModel, } return } + +// GetProcessInstance 查询编排实例 +func GetProcessInstance(userToken, language, instanceId string) (processInstance *models.ProcessInstance, err error) { + var response models.ProcessInstanceResponse + byteArr, err := HttpGet(fmt.Sprintf(BaseUrl+pathQueryProcessDefinitionsInstance, instanceId), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + processInstance = response.Data + return +} + +// GetProcessDefine 查询编排详情 +func GetProcessDefine(procDefId, userToken, language string) (result *models.DefinitionsData, err error) { + var response models.ProcessDefinitionsResponse + byteArr, err := HttpGet(fmt.Sprintf(BaseUrl+pathGetProcessDefinitions, procDefId), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + result = response.Data + return +} + +// GetProcDefRootEntities 查询编排实例RootEntity +func GetProcDefRootEntities(procDefId, userToken, language string) (list []*models.ProcDefEntityDataObj, err error) { + var response models.ProcDefRootEntityResponse + byteArr, err := HttpGet(fmt.Sprintf(BaseUrl+pathQueryProcessDefinitionsEntityData, procDefId), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + list = response.Data + return +} + +// GetProcDefDataPreview 查询编排设计 RootEntity +func GetProcDefDataPreview(procDefId, entityDataId, userToken, language string) (result *models.EntityTreeData, err error) { + var response models.EntityTreeResponse + byteArr, err := HttpGet(fmt.Sprintf(BaseUrl+pathQueryPreviewProcessDefinitionsEntity, procDefId, entityDataId), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + result = response.Data + return +} + +// GetProcDefTaskNodeContext 查询编排节点context +func GetProcDefTaskNodeContext(procInstanceId, taskNodeId, userToken, language string) (data interface{}, err error) { + var byteArr []byte + var response models.ProcDefTaskNodeContextResponse + byteArr, err = HttpGet(fmt.Sprintf(BaseUrl+pathQueryProcessDefinitionsInstanceTaskNodeContext, procInstanceId, taskNodeId), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + data = response.Data + return +} + +// TerminationsProcDefInstance 终止编排实例运行 +func TerminationsProcDefInstance(param models.TerminateInstanceParam, userToken, language string) (err error) { + var byteArr []byte + var response models.StartInstanceResponse + postBytes, _ := json.Marshal(param) + byteArr, err = HttpPost(fmt.Sprintf(BaseUrl+pathTerminationsProcessDefinitionsInstance, param.ProcInstId), userToken, language, postBytes) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + return +} + +// StartProcDefInstances 启动编排实例 +func StartProcDefInstances(param models.RequestProcessData, userToken, language string) (result *models.StartInstanceResultData, err error) { + var byteArr []byte + var response models.StartInstanceResponse + postBytes, _ := json.Marshal(param) + log.Logger.Info("Start request", log.String("param", string(postBytes))) + byteArr, err = HttpPost(BaseUrl+pathStartProcDefInstance, userToken, language, postBytes) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + result = response.Data + return +} diff --git a/taskman-server/rpc/user_role_rpc.go b/taskman-server/rpc/user_role_rpc.go index 728f977a..86074f22 100644 --- a/taskman-server/rpc/user_role_rpc.go +++ b/taskman-server/rpc/user_role_rpc.go @@ -11,6 +11,8 @@ const ( pathRetrieveAllRoles = "/platform/v1/roles/retrieve?all=%s" // pathRetrieveAllUser 查询所有用户 pathRetrieveAllUser = "/platform/v1/users/retrieve" + // pathRetrieveRoleUsers 查询角色用户列表 + pathRetrieveRoleUsers = "/platform/v1/roles/%s/users" ) // QueryAllRoles 查询所有角色 @@ -68,3 +70,22 @@ func QueryAllUser(userToken, language string) (userMap map[string]*models.UserDt } return } + +// QueryRolesUsers 查询角色用户列表 +func QueryRolesUsers(roleId, userToken, language string) (list []*models.UserDto, err error) { + var response models.QueryUserResponse + byteArr, err := HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathRetrieveRoleUsers, roleId), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + list = response.Data + return +} diff --git a/taskman-server/service/collect_template_service.go b/taskman-server/service/collect_template_service.go index 6f1de10f..f1fb8bfa 100644 --- a/taskman-server/service/collect_template_service.go +++ b/taskman-server/service/collect_template_service.go @@ -34,7 +34,7 @@ func DeleteTemplateCollect(templateId, user string) error { } // QueryTemplateCollect 查询模板收藏 -func QueryTemplateCollect(param *models.QueryCollectTemplateParam, user, userToken string, userRoles []string) (pageInfo models.PageInfo, rowData []*models.CollectDataObj, err error) { +func QueryTemplateCollect(param *models.QueryCollectTemplateParam, user, userToken, language string, userRoles []string) (pageInfo models.PageInfo, rowData []*models.CollectDataObj, err error) { var result models.ProcNodeObjList var collectTemplateList []*models.CollectTemplateTable var disableTemplateVersionMap = getAllDisableTemplateVersionMap() @@ -90,7 +90,7 @@ func QueryTemplateCollect(param *models.QueryCollectTemplateParam, user, userTok if len(rowData) > 0 { for _, collectObj := range rowData { templateUserRoleMap = make(map[string]bool, 0) - template, err := GetSimpleRequestTemplate(collectObj.Id) + template, err := GetRequestTemplateService().GetSimpleRequestTemplate(collectObj.Id) if err != nil { continue } @@ -121,7 +121,7 @@ func QueryTemplateCollect(param *models.QueryCollectTemplateParam, user, userTok // 模板使用权限变更,导致收藏模板时候角色,没权限新建请求 collectObj.Status = 3 } - result, err = GetProcessNodesByProc(models.RequestTemplateTable{Id: collectObj.Id}, userToken, "template") + result, err = GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: collectObj.Id}, userToken, language, "template") if err != nil { continue } diff --git a/taskman-server/service/cron.go b/taskman-server/service/cron.go index 5be01652..886409ea 100644 --- a/taskman-server/service/cron.go +++ b/taskman-server/service/cron.go @@ -38,7 +38,7 @@ func notifyAction() { tmpExpireObj := models.ExpireObj{ReportTime: v.CreatedTime, ExpireTime: v.ExpireTime, NowTime: time.Now().Format(models.DateTimeFormat)} calcExpireObj(&tmpExpireObj) if tmpExpireObj.Percent > 75 { - tmpErr := NotifyTaskMail(v.Id) + tmpErr := NotifyTaskMail(v.Id, models.CoreToken.GetCoreToken(), "") if tmpErr != nil { log.Logger.Error("notify task mail fail", log.String("taskId", v.Id), log.Error(tmpErr)) } else { diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index 8f667f33..b3b5c489 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -16,7 +16,7 @@ type FormTemplateService struct { func GetRequestFormTemplate(id string) (result models.FormTemplateDto, err error) { result = models.FormTemplateDto{Items: []*models.FormItemTemplateTable{}} - requestTemplate, getErr := GetSimpleRequestTemplate(id) + requestTemplate, getErr := GetRequestTemplateService().GetSimpleRequestTemplate(id) if getErr != nil { err = getErr return diff --git a/taskman-server/service/proc_def_service.go b/taskman-server/service/proc_def_service.go new file mode 100644 index 00000000..9f2e58bc --- /dev/null +++ b/taskman-server/service/proc_def_service.go @@ -0,0 +1,175 @@ +package service + +import ( + "fmt" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/rpc" + "sort" + "strconv" +) + +// 编排任务节点 +var taskNodeTypeMap = map[string]bool{ + string(models.ProcDefNodeTypeHuman): true, + string(models.ProcDefNodeTypeAutomatic): true, + string(models.ProcDefNodeTypeData): true, +} + +type ProcDefService struct { +} + +// GetCoreProcessListNew 获取用户角色下的编排列表 +func (s ProcDefService) GetCoreProcessListNew(userToken, language, manageRole string) (processList []*models.ProcDefObj, err error) { + var procDefDtoList []*models.ProcDefDto + var nodesList []*models.DataModel + var entityMap = make(map[string]models.ProcEntity) + processList = make([]*models.ProcDefObj, 0) + procDefDtoList, err = rpc.QueryProcessDefinitionList(userToken, language, manageRole, models.QueryProcessDefinitionParam{Plugins: []string{"taskman"}, Status: "deployed"}) + if err != nil { + return + } + nodesList, err = rpc.QueryAllModels(userToken, language) + if err != nil { + return + } + entityMap = models.ConvertModelsList2Map(nodesList) + if len(procDefDtoList) > 0 { + for _, dto := range procDefDtoList { + processList = append(processList, &models.ProcDefObj{ + ProcDefId: dto.Id, + ProcDefKey: dto.Key, + ProcDefName: dto.Name, + Status: dto.Status, + RootEntity: entityMap[dto.RootEntity], + CreatedTime: dto.CreatedTime, + }) + } + } + return +} + +// GetCoreProcessListAll 查询当前插件的所有编排 +func (s ProcDefService) GetCoreProcessListAll(userToken, language string) (processList []*models.ProcDefObj, err error) { + var procDefList []*models.ProcDef + var nodesList []*models.DataModel + var entityMap = make(map[string]models.ProcEntity) + processList = make([]*models.ProcDefObj, 0) + procDefList, err = rpc.QueryAllProcessDefinitionList(userToken, language) + if err != nil { + return + } + nodesList, err = rpc.QueryAllModels(userToken, language) + if err != nil { + return + } + entityMap = models.ConvertModelsList2Map(nodesList) + if len(procDefList) > 0 { + for _, model := range procDefList { + processList = append(processList, &models.ProcDefObj{ + ProcDefId: model.Id, + ProcDefKey: model.Key, + ProcDefName: model.Name, + Status: model.Status, + RootEntity: entityMap[model.RootEntity], + CreatedTime: model.CreatedTime.Format(models.DateTimeFormat), + }) + } + } + return +} + +// GetProcessDefine 获取编排定义 +func (s ProcDefService) GetProcessDefine(procDefId, userToken, language string) (result *models.DefinitionsData, err error) { + result, err = rpc.GetProcessDefine(procDefId, userToken, language) + if err != nil { + return + } + return +} + +// GetProcessDefineTaskNodes 获取编排节点 +func (s ProcDefService) GetProcessDefineTaskNodes(requestTemplate models.RequestTemplateTable, userToken, language, filterType string) (nodeList []*models.ProcNodeObj, err error) { + var dynamicBind = "n" + var allTaskNodeList []*models.ProcDefNode + nodeList = make([]*models.ProcNodeObj, 0) + if requestTemplate.ProcDefId == "" { + requestTemplate, err = GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplate.Id) + if err != nil { + return + } + } + if requestTemplate.ProcDefId == "" { + err = fmt.Errorf("Request template proDefId illegal ") + return + } + allTaskNodeList, err = rpc.GetProcessDefineTaskNodes(requestTemplate.ProcDefId, userToken, language) + if err != nil { + return + } + if len(allTaskNodeList) > 0 { + for _, node := range allTaskNodeList { + if _, ok := taskNodeTypeMap[node.NodeType]; !ok { + continue + } + if filterType == "template" { + // 模板只展示人工节点 + if node.NodeType != string(models.ProcDefNodeTypeHuman) { + continue + } + } else if filterType == "bind" { + if node.DynamicBind { + continue + } + } + if node.DynamicBind { + dynamicBind = "y" + } + nodeList = append(nodeList, &models.ProcNodeObj{ + NodeId: node.NodeId, + NodeName: node.Name, + NodeType: node.NodeType, + NodeDefId: node.ProcDefId, + TaskCategory: node.NodeType, + RoutineExp: node.RoutineExpression, + ServiceId: node.ServiceName, + ServiceName: node.ServiceName, + OrderedNo: strconv.Itoa(node.OrderedNo), + OrderedNum: node.OrderedNo, + DynamicBind: dynamicBind, + BoundEntities: nil, + }) + } + sort.Sort(models.ProcNodeObjList(nodeList)) + } + return +} + +// GetProcessDefineInstance 获取编排实例 +func (s ProcDefService) GetProcessDefineInstance(instanceId, userToken, language string) (processInstance *models.ProcessInstance, err error) { + return rpc.GetProcessInstance(userToken, language, instanceId) +} + +// GetProcDefRootEntities 获取编排RootEntity +func (s ProcDefService) GetProcDefRootEntities(procDefId, userToken, language string) (list []*models.ProcDefEntityDataObj, err error) { + return rpc.GetProcDefRootEntities(procDefId, userToken, language) +} + +// GetProcDefDataPreview 查询编排设计 RootEntity +func (s ProcDefService) GetProcDefDataPreview(procDefId, entityDataId, userToken, language string) (result *models.EntityTreeData, err error) { + return rpc.GetProcDefDataPreview(procDefId, entityDataId, userToken, language) +} + +// GetProcDefTaskNodeContext 查询编排设计 RootEntity +func (s ProcDefService) GetProcDefTaskNodeContext(procInstanceId, taskNodeId, userToken, language string) (data interface{}, err error) { + return rpc.GetProcDefTaskNodeContext(procInstanceId, taskNodeId, userToken, language) +} + +// TerminationsProcDefInstance 终止编排实例运行 +func (s ProcDefService) TerminationsProcDefInstance(param models.TerminateInstanceParam, userToken, language string) (err error) { + return rpc.TerminationsProcDefInstance(param, userToken, language) +} + +// StartProcDefInstances 启动编排实例 +func (s ProcDefService) StartProcDefInstances(param models.RequestProcessData, userToken, language string) (result *models.StartInstanceResultData, err error) { + return rpc.StartProcDefInstances(param, userToken, language) +} diff --git a/taskman-server/service/ref_select_service.go b/taskman-server/service/ref_select_service.go index f680848d..708b9c21 100644 --- a/taskman-server/service/ref_select_service.go +++ b/taskman-server/service/ref_select_service.go @@ -640,7 +640,7 @@ func getRemoteEntityOptions(url, userToken string, inputMap map[string]string) ( if resp.StatusCode != 200 { return result, fmt.Errorf("Do request fail,response statusCode:%d resp:%s ", resp.StatusCode, string(b)) } - var response models.WorkflowEntityQuery + var response models.ProcDefRootEntityResponse err = json.Unmarshal(b, &response) if err != nil { return result, fmt.Errorf("Json unmarshal response body fail,%s ", err.Error()) diff --git a/taskman-server/service/request_service.go b/taskman-server/service/request_service.go index 93a83f49..5d950a77 100644 --- a/taskman-server/service/request_service.go +++ b/taskman-server/service/request_service.go @@ -4,12 +4,6 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/WeBankPartners/go-common-lib/guid" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "github.com/tealeg/xlsx" "io/ioutil" "math" "net/http" @@ -18,6 +12,13 @@ import ( "strings" "sync" "time" + + "github.com/WeBankPartners/go-common-lib/guid" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "github.com/tealeg/xlsx" ) type RequestService struct { @@ -54,13 +55,13 @@ var ( templateTypeArr = []int{1, 0} // 模版类型: 1表示发布,0表示请求 ) -func GetEntityData(requestId, userToken string) (result models.EntityQueryResult, err error) { - var byteArr []byte +func GetEntityData(requestId, userToken, language string) (result models.EntityQueryResult, err error) { + var list []*models.ProcDefEntityDataObj requestTemplateId, tmpErr := getRequestTemplateByRequest(requestId) if tmpErr != nil { return result, tmpErr } - requestTemplateObj, getTemplateErr := GetSimpleRequestTemplate(requestTemplateId) + requestTemplateObj, getTemplateErr := GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplateId) if getTemplateErr != nil { err = getTemplateErr return @@ -69,24 +70,21 @@ func GetEntityData(requestId, userToken string) (result models.EntityQueryResult err = fmt.Errorf("RequestTemplate packageName or entityName illegal ") return } - url := fmt.Sprintf("%s/platform/v1/process/definitions/%s/root-entities", models.Config.Wecube.BaseUrl, requestTemplateObj.ProcDefId) - byteArr, err = HttpGet(url, userToken) - var responseObj models.WorkflowEntityQuery - err = json.Unmarshal(byteArr, &responseObj) + + list, err = GetProcDefService().GetProcDefRootEntities(requestTemplateObj.ProcDefId, userToken, language) if err != nil { - err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) - } else { - result.Status = responseObj.Status - result.Message = responseObj.Message - for _, v := range responseObj.Data { + return + } + if len(list) > 0 { + for _, v := range list { result.Data = append(result.Data, &models.EntityDataObj{Id: v.Id, DisplayName: v.DisplayName, PackageName: requestTemplateObj.PackageName, Entity: requestTemplateObj.EntityName}) } } return } -func ProcessDataPreview(requestTemplateId, entityDataId, userToken string) (result models.EntityTreeResult, err error) { - requestTemplateObj, getTemplateErr := GetSimpleRequestTemplate(requestTemplateId) +func ProcessDataPreview(requestTemplateId, entityDataId, userToken, language string) (result *models.EntityTreeData, err error) { + requestTemplateObj, getTemplateErr := GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplateId) if getTemplateErr != nil { err = getTemplateErr return @@ -95,24 +93,7 @@ func ProcessDataPreview(requestTemplateId, entityDataId, userToken string) (resu err = fmt.Errorf("RequestTemplate proDefId illegal ") return } - req, newReqErr := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/platform/v1/public/process/definitions/%s/preview/entities/%s", models.Config.Wecube.BaseUrl, requestTemplateObj.ProcDefId, entityDataId), nil) - if newReqErr != nil { - err = fmt.Errorf("Try to new http request fail,%s ", newReqErr.Error()) - return - } - req.Header.Set("Authorization", userToken) - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - err = fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) - return - } - b, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(b, &result) - if err != nil { - err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) - } - return + return GetProcDefService().GetProcDefDataPreview(requestTemplateObj.ProcDefId, entityDataId, userToken, language) } // GetRequestCount 工作台请求统计 @@ -249,7 +230,7 @@ func collectSQL(templateType int, user string) (sql string, queryParam []interfa } // DataList 首页工作台数据列表 -func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, user string) (pageInfo models.PageInfo, rowData []*models.PlatformDataObj, err error) { +func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, user, language string) (pageInfo models.PageInfo, rowData []*models.PlatformDataObj, err error) { // 先拼接查询条件 var templateType int var sql string @@ -275,7 +256,7 @@ func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, sql, queryParam = pendingRequestSQL(templateType, userRolesFilterSql, userRolesFilterParam) } else if param.Type == 2 { sql, queryParam = pendingTaskSQL(templateType, userRolesFilterSql, userRolesFilterParam, roleFilterSql) - pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatTaskSQL(where, sql), true) + pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatTaskSQL(where, sql), language, true) return } case "hasProcessed": @@ -283,7 +264,7 @@ func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, sql, queryParam = hasProcessedRequestSQL(templateType, user) } else if param.Type == 2 { sql, queryParam = hasProcessedTaskSQL(templateType, user) - pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatTaskSQL(where, sql), true) + pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatTaskSQL(where, sql), language, true) return } case "submit": @@ -294,12 +275,12 @@ func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, err = fmt.Errorf("request param err,tab:%s", param.Tab) return } - pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatRequestSQL(where, sql), true) + pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatRequestSQL(where, sql), language, true) return } // HistoryList 发布历史 -func HistoryList(param *models.RequestHistoryParam, userRoles []string, userToken, user string) (pageInfo models.PageInfo, rowsData []*models.PlatformDataObj, err error) { +func HistoryList(param *models.RequestHistoryParam, userRoles []string, userToken, user, language string) (pageInfo models.PageInfo, rowsData []*models.PlatformDataObj, err error) { var sql = "select id from request" var queryParam []interface{} where := transHistoryConditionToSQL(param) @@ -309,7 +290,7 @@ func HistoryList(param *models.RequestHistoryParam, userRoles []string, userToke sql = "select id from request where `role` in (" + userRolesFilterSql + ")" queryParam = append(queryParam, userRolesFilterParam...) } - pageInfo, rowsData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, User: user, UserToken: userToken}, getPlatRequestSQL(where, sql), true) + pageInfo, rowsData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, User: user, UserToken: userToken}, getPlatRequestSQL(where, sql), language, true) return } @@ -319,7 +300,7 @@ func Export(w http.ResponseWriter, param *models.RequestHistoryParam, userToken, var sql = "select id from request" var queryParam []interface{} where := transHistoryConditionToSQL(param) - _, rowsData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, User: user, UserToken: userToken}, getPlatRequestSQL(where, sql), false) + _, rowsData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, User: user, UserToken: userToken}, getPlatRequestSQL(where, sql), language, false) if len(rowsData) > 0 { fileName, titles, dataArr := getRequestExportData(language, rowsData) file := xlsx.NewFile() @@ -443,21 +424,21 @@ func getInternationalizationCurNode(language, node string) string { func getInternationalizationStatus(language string, status string) string { if strings.Contains(language, "zh-CN") { switch status { - case string(models.Draft): + case string(models.RequestStatusDraft): return "草稿" - case string(models.Pending): + case string(models.RequestStatusPending): return "等待定版" - case string(models.InProgress): + case string(models.RequestStatusInProgress): return "执行中" - case string(models.InProgressFaulted): + case string(models.RequestStatusInProgressFaulted): return "节点报错" - case string(models.Termination): + case string(models.RequestStatusTermination): return "手动终止" - case string(models.Completed): + case string(models.RequestStatusCompleted): return "成功" - case string(models.InProgressTimeOuted): + case string(models.RequestStatusInProgressTimeOuted): return "节点超时" - case string(models.Faulted): + case string(models.RequestStatusFaulted): return "自动退出" } } @@ -473,7 +454,7 @@ func calcRequestStayTime(dataObject *models.PlatformDataObj) { var err error var reportTime, requestExpectTime, taskCreateTime, taskExpectTime, taskApprovalTime time.Time loc, _ := time.LoadLocation("Local") - if dataObject.Status == string(models.Draft) { + if dataObject.Status == string(models.RequestStatusDraft) { return } // 计算任务停留时长 @@ -499,7 +480,7 @@ func calcRequestStayTime(dataObject *models.PlatformDataObj) { return } // 计算请求停留时长 - if dataObject.Status == string(models.Completed) || dataObject.Status == string(models.Termination) || dataObject.Status == string(models.Faulted) { + if dataObject.Status == string(models.RequestStatusCompleted) || dataObject.Status == string(models.RequestStatusTermination) || dataObject.Status == string(models.RequestStatusFaulted) { updateTime, err := time.ParseInLocation(models.DateTimeFormat, dataObject.UpdatedTime, loc) if err != nil { log.Logger.Error("getRequestRemainDays UpdatedTime err", log.Error(err)) @@ -526,7 +507,7 @@ func getPlatTaskSQL(where, sql string) string { "from request r join request_template rt on r.request_template = rt.id left join task t on r.id = t.request) temp %s and task_id in (%s) ", where, sql) } -func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo models.PageInfo, rowsData []*models.PlatformDataObj, err error) { +func getPlatData(req models.PlatDataParam, newSQL, language string, page bool) (pageInfo models.PageInfo, rowsData []*models.PlatformDataObj, err error) { var operatorObjTypeMap = make(map[string]string) // 排序处理 if req.Param.Sorting != nil { @@ -552,7 +533,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m } if len(rowsData) > 0 { // 操作对象类型,新增模板是录入.历史模板操作对象类型为空,需要全量处理下 - operatorObjTypeMap = getAllCoreProcess(req.UserToken) + operatorObjTypeMap = GetRequestTemplateService().GetAllCoreProcess(req.UserToken, language) // 查询当前用户所有收藏模板记录 collectMap, _ := QueryAllTemplateCollect(req.User) templateMap, _ := getAllRequestTemplate() @@ -575,10 +556,10 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m platformDataObj.CurNode = RequestPending } if platformDataObj.ProcInstanceId != "" { - platformDataObj.Progress, platformDataObj.CurNode = getCurNodeName(platformDataObj.ProcInstanceId, req.UserToken) + platformDataObj.Progress, platformDataObj.CurNode = getCurNodeName(platformDataObj.ProcInstanceId, req.UserToken, language) } if strings.Contains(platformDataObj.Status, "InProgress") && platformDataObj.ProcInstanceId != "" { - newStatus := getInstanceStatus(platformDataObj.ProcInstanceId, req.UserToken) + newStatus := getInstanceStatus(platformDataObj.ProcInstanceId, req.UserToken, language) if newStatus == "InternallyTerminated" { newStatus = "Termination" } @@ -595,7 +576,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m platformDataObj.OperatorObjType = operatorObjTypeMap[platformDataObj.ProcDefKey] } if platformDataObj.OperatorObj == "" && platformDataObj.Cache != "" { - result, _ := GetEntityData(platformDataObj.Id, req.UserToken) + result, _ := GetEntityData(platformDataObj.Id, req.UserToken, language) if len(result.Data) > 0 { var cacheObj models.RequestPreDataDto err = json.Unmarshal([]byte(platformDataObj.Cache), &cacheObj) @@ -621,7 +602,7 @@ func getPlatData(req models.PlatDataParam, newSQL string, page bool) (pageInfo m return } -func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, permission, operator string) (pageInfo models.PageInfo, rowData []*models.RequestTable, err error) { +func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, permission, operator, language string) (pageInfo models.PageInfo, rowData []*models.RequestTable, err error) { rowData = []*models.RequestTable{} if strings.ToLower(permission) == "mgmt" { permission = "MGMT" @@ -662,7 +643,7 @@ func ListRequest(param *models.QueryRequestParam, userRoles []string, userToken, v.HandleRoles = []string{} } if strings.Contains(v.Status, "InProgress") && v.ProcInstanceId != "" { - newStatus := getInstanceStatus(v.ProcInstanceId, userToken) + newStatus := getInstanceStatus(v.ProcInstanceId, userToken, language) if newStatus == "InternallyTerminated" { newStatus = "Termination" } @@ -729,50 +710,55 @@ func calcExpireObj(param *models.ExpireObj) { return } -func getInstanceStatus(instanceId, userToken string) string { - response, err := getProcessInstances(instanceId, userToken) +func getInstanceStatus(instanceId, userToken, language string) string { + processInstance, err := GetProcDefService().GetProcessDefineInstance(instanceId, userToken, language) if err != nil { return "" } - if response.Data.Status != "InProgress" { - return response.Data.Status + if processInstance == nil { + return "" } - status := "InProgress" - for _, v := range response.Data.TaskNodeInstances { - if v.Status == "Faulted" { - status = "InProgress(Faulted)" - break - } - if v.Status == "Timeouted" { - status = "InProgress(Timeouted)" - break + if processInstance.Status != string(models.RequestStatusInProgress) { + return processInstance.Status + } + status := string(models.RequestStatusInProgress) + if len(processInstance.TaskNodeInstances) > 0 { + for _, v := range processInstance.TaskNodeInstances { + if v.Status == string(models.RequestStatusFaulted) { + status = string(models.RequestStatusInProgressFaulted) + break + } + if v.Status == models.ProcDefStatusTimeout { + status = string(models.RequestStatusInProgressTimeOuted) + break + } } } return status } -func getCurNodeName(instanceId, userToken string) (progress int, curNode string) { +func getCurNodeName(instanceId, userToken, language string) (progress int, curNode string) { var total int - response, err := getProcessInstances(instanceId, userToken) - if err != nil || len(response.Data.TaskNodeInstances) == 0 { + processInstance, err := GetProcDefService().GetProcessDefineInstance(instanceId, userToken, language) + if err != nil || processInstance == nil || len(processInstance.TaskNodeInstances) == 0 { return } // 统计完成进度 ,已完成/总数, 编号不为空 - for _, v := range response.Data.TaskNodeInstances { + for _, v := range processInstance.TaskNodeInstances { if v.OrderedNo != "" { - if v.Status == "Completed" { + if v.Status == string(models.RequestStatusCompleted) { progress++ } total++ } } progress = int(math.Floor(float64(progress)/float64(total)*100 + 0.5)) - switch response.Data.Status { + switch processInstance.Status { case "Completed": curNode = CurNodeCompleted return case "InProgress": - for _, v := range response.Data.TaskNodeInstances { + for _, v := range processInstance.TaskNodeInstances { if v.Status == "InProgress" || v.Status == "Timeouted" || v.Status == "Faulted" { curNode = v.NodeName return @@ -782,7 +768,7 @@ func getCurNodeName(instanceId, userToken string) (progress int, curNode string) curNode = "NotStarted" case "Faulted": // 失败状态,筛选成功并且有序号的节点 - list := filterSuccessNode(response.Data.TaskNodeInstances) + list := filterSuccessNode(processInstance.TaskNodeInstances) if len(list) == 0 { return } @@ -792,10 +778,10 @@ func getCurNodeName(instanceId, userToken string) (progress int, curNode string) return default: // 失败状态,显示具体执行失败的节点. filterNode 过滤orderNo为空大节点 - list := filterNode(response.Data.TaskNodeInstances) + list := filterNode(processInstance.TaskNodeInstances) if len(list) == 0 { // 如果都没有序号,找一个NotStarted节点,找不到返回 Completed - for _, v := range response.Data.TaskNodeInstances { + for _, v := range processInstance.TaskNodeInstances { if v.Status == "NotStarted" { curNode = v.NodeName return @@ -816,8 +802,8 @@ func getCurNodeName(instanceId, userToken string) (progress int, curNode string) return } -func filterNode(instances []*models.InstanceStatusQueryNode) []*models.InstanceStatusQueryNode { - var list []*models.InstanceStatusQueryNode +func filterNode(instances []*models.TaskNodeInstances) []*models.TaskNodeInstances { + var list []*models.TaskNodeInstances for _, node := range instances { if node.OrderedNo != "" { list = append(list, node) @@ -826,8 +812,8 @@ func filterNode(instances []*models.InstanceStatusQueryNode) []*models.InstanceS return list } -func filterSuccessNode(instances []*models.InstanceStatusQueryNode) []*models.InstanceStatusQueryNode { - var list []*models.InstanceStatusQueryNode +func filterSuccessNode(instances []*models.TaskNodeInstances) []*models.TaskNodeInstances { + var list []*models.TaskNodeInstances for _, node := range instances { if node.OrderedNo != "" && node.Status == "Completed" { list = append(list, node) @@ -836,36 +822,6 @@ func filterSuccessNode(instances []*models.InstanceStatusQueryNode) []*models.In return list } -// getProcessInstances 获取编排 -func getProcessInstances(instanceId, userToken string) (response models.InstanceStatusQuery, err error) { - var req *http.Request - var resp *http.Response - req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/platform/v1/process/instances/%s", models.Config.Wecube.BaseUrl, instanceId), nil) - if err != nil { - log.Logger.Error("GetInstanceStatus fail", log.String("msg", "new http request fail"), log.Error(err)) - return - } - req.Header.Set("Authorization", userToken) - resp, err = http.DefaultClient.Do(req) - if err != nil { - log.Logger.Error("GetInstanceStatus fail", log.String("msg", "Try to do http request fail"), log.Error(err)) - return - } - b, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(b, &response) - if err != nil { - log.Logger.Error("GetInstanceStatus fail", log.String("msg", "Try to json unmarshal body fail"), log.Error(err)) - return - } - if response.Status != "OK" { - log.Logger.Error("GetInstanceStatus fail", log.String("msg", response.Message)) - err = fmt.Errorf("GetInstanceStatus fail") - return - } - return -} - func calcExpireTime(reportTime string, expireDay int) (expire string) { t, err := time.Parse(models.DateTimeFormat, reportTime) if err != nil { @@ -938,13 +894,13 @@ func GetRequest(requestId string) (result models.RequestTable, err error) { return } -func CreateRequest(param *models.RequestTable, operatorRoles []string, userToken string) error { - requestTemplateObj, err := GetSimpleRequestTemplate(param.RequestTemplate) +func CreateRequest(param *models.RequestTable, operatorRoles []string, userToken, language string) error { + requestTemplateObj, err := GetRequestTemplateService().GetSimpleRequestTemplate(param.RequestTemplate) if err != nil { return err } var actions []*dao.ExecAction - err = SyncProcDefId(requestTemplateObj.Id, requestTemplateObj.ProcDefId, requestTemplateObj.ProcDefName, "", userToken) + err = SyncProcDefId(requestTemplateObj.Id, requestTemplateObj.ProcDefId, requestTemplateObj.ProcDefName, "", userToken, language) if err != nil { return fmt.Errorf("Try to sync proDefId fail,%s ", err.Error()) } @@ -1151,7 +1107,7 @@ func GetRequestRootForm(requestId string) (result models.RequestTemplateFormStru if tmpErr != nil { return result, tmpErr } - requestTemplateObj, _ := GetSimpleRequestTemplate(requestTemplateId) + requestTemplateObj, _ := GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplateId) result.Id = requestTemplateObj.Id result.Name = requestTemplateObj.Name result.PackageName = requestTemplateObj.PackageName @@ -1165,7 +1121,7 @@ func GetRequestRootForm(requestId string) (result models.RequestTemplateFormStru return } -func GetRequestPreData(requestId, entityDataId, userToken string) (result []*models.RequestPreDataTableObj, err error) { +func GetRequestPreData(requestId, entityDataId, userToken, language string) (result []*models.RequestPreDataTableObj, err error) { var requestTables []*models.RequestTable err = dao.X.SQL("select cache from request where id=?", requestId).Find(&requestTables) if err != nil { @@ -1203,15 +1159,15 @@ func GetRequestPreData(requestId, entityDataId, userToken string) (result []*mod if entityDataId == "" { return } - previewData, previewErr := ProcessDataPreview(requestTemplateId, entityDataId, userToken) + previewData, previewErr := ProcessDataPreview(requestTemplateId, entityDataId, userToken, language) if previewErr != nil { return result, previewErr } - if len(previewData.Data.EntityTreeNodes) == 0 { + if len(previewData.EntityTreeNodes) == 0 { return } for _, entity := range result { - for _, tmpData := range previewData.Data.EntityTreeNodes { + for _, tmpData := range previewData.EntityTreeNodes { if tmpData.EntityName == entity.Entity { tmpValueData := make(map[string]interface{}) for _, title := range entity.Title { @@ -1225,13 +1181,13 @@ func GetRequestPreData(requestId, entityDataId, userToken string) (result []*mod } func getItemTemplateTitle(items []*models.FormItemTemplateTable) []*models.RequestPreDataTableObj { - result := []*models.RequestPreDataTableObj{} + var result []*models.RequestPreDataTableObj tmpPackageName := items[0].PackageName tmpEntity := items[0].Entity tmpItemGroup := items[0].ItemGroup tmpItemGroupName := items[0].ItemGroupName - tmpRefEntity := []string{} - tmpItems := []*models.FormItemTemplateTable{} + var tmpRefEntity []string + var tmpItems []*models.FormItemTemplateTable existItemMap := make(map[string]int) for _, v := range items { tmpKey := fmt.Sprintf("%s__%s", v.ItemGroup, v.Name) @@ -1363,7 +1319,7 @@ func sortRequestEntity(param []*models.RequestPreDataTableObj) models.RequestPre return result } -func StartRequest(requestId, operator, userToken string, cacheData models.RequestCacheData) (result models.StartInstanceResultData, err error) { +func StartRequest(requestId, operator, userToken, language string, cacheData models.RequestCacheData) (result *models.StartInstanceResultData, err error) { var requestTemplateTable []*models.RequestTemplateTable dao.X.SQL("select * from request_template where id in (select request_template from request where id=?)", requestId).Find(&requestTemplateTable) if len(requestTemplateTable) == 0 { @@ -1371,57 +1327,34 @@ func StartRequest(requestId, operator, userToken string, cacheData models.Reques } cacheData.ProcDefId = requestTemplateTable[0].ProcDefId cacheData.ProcDefKey = requestTemplateTable[0].ProcDefKey - entityDepMap, tmpErr := AppendUselessEntity(requestTemplateTable[0].Id, userToken, &cacheData) + entityDepMap, tmpErr := AppendUselessEntity(requestTemplateTable[0].Id, userToken, language, &cacheData) if tmpErr != nil { return result, fmt.Errorf("Try to append useless entity fail,%s ", tmpErr.Error()) } - fillBindingWithRequestData(requestId, userToken, &cacheData, entityDepMap) + fillBindingWithRequestData(requestId, userToken, language, &cacheData, entityDepMap) cacheBytes, _ := json.Marshal(cacheData) log.Logger.Info("cacheByte", log.String("cacheBytes", string(cacheBytes))) startParam := BuildRequestProcessData(cacheData) - startParamBytes, tmpErr := json.Marshal(startParam) - if tmpErr != nil { - err = fmt.Errorf("Json marshal cache data fail,%s ", tmpErr.Error()) - return - } - log.Logger.Info("Start request", log.String("param", string(startParamBytes))) - req, newReqErr := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/platform/v1/public/process/instances", models.Config.Wecube.BaseUrl), bytes.NewReader(startParamBytes)) - if newReqErr != nil { - err = fmt.Errorf("Try to new http request fail,%s ", newReqErr.Error()) - return - } - req.Header.Set("Authorization", userToken) - req.Header.Set("Content-Type", "application/json") - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - err = fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) - return - } - var respResult models.StartInstanceResponse - b, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(b, &respResult) + result, err = GetProcDefService().StartProcDefInstances(startParam, userToken, language) if err != nil { - err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) return } - if respResult.Status != "OK" { - err = fmt.Errorf("Start instance fail,%s ", respResult.Message) + if result == nil { + err = fmt.Errorf("StartProcDefInstances response empty") return } - result = respResult.Data nowTime := time.Now().Format(models.DateTimeFormat) expireTime := calcExpireTime(nowTime, requestTemplateTable[0].ExpireDay) - _, err = dao.X.Exec("update request set handler=?,proc_instance_id=?,proc_instance_key=?,confirm_time=?,expire_time=?,status=?,bind_cache=?,updated_by=?,updated_time=? where id=?", operator, strconv.Itoa(result.Id), result.ProcInstKey, nowTime, expireTime, respResult.Data.Status, string(cacheBytes), operator, nowTime, requestId) + _, err = dao.X.Exec("update request set handler=?,proc_instance_id=?,proc_instance_key=?,confirm_time=?,expire_time=?,status=?,bind_cache=?,updated_by=?,updated_time=? where id=?", operator, strconv.Itoa(result.Id), result.ProcInstKey, nowTime, expireTime, result.Status, string(cacheBytes), operator, nowTime, requestId) return } -func UpdateRequestStatus(requestId, status, operator, userToken, description string) error { +func UpdateRequestStatus(requestId, status, operator, userToken, language, description string) error { var err error var request models.RequestTable nowTime := time.Now().Format(models.DateTimeFormat) if status == "Pending" { - bindData, bindErr := GetRequestPreBindData(requestId, userToken) + bindData, bindErr := GetRequestPreBindData(requestId, userToken, language) if bindErr != nil { return fmt.Errorf("Try to build bind data fail,%s ", bindErr.Error()) } @@ -1429,7 +1362,7 @@ func UpdateRequestStatus(requestId, status, operator, userToken, description str bindCache := string(bindCacheBytes) _, err = dao.X.Exec("update request set status=?,reporter=?,report_time=?,bind_cache=?,updated_by=?,updated_time=?,rollback_desc=null,revoke_flag=0 where id=?", status, operator, nowTime, bindCache, operator, nowTime, requestId) if err == nil { - notifyRoleMail(requestId) + notifyRoleMail(requestId, userToken, language) } } else if status == "Draft" { request, err = GetSimpleRequest(requestId) @@ -1444,7 +1377,7 @@ func UpdateRequestStatus(requestId, status, operator, userToken, description str return err } -func fillBindingWithRequestData(requestId, userToken string, cacheData *models.RequestCacheData, existDepMap map[string][]string) { +func fillBindingWithRequestData(requestId, userToken, language string, cacheData *models.RequestCacheData, existDepMap map[string][]string) { var items []*models.FormItemTemplateTable dao.X.SQL("select * from form_item_template where form_template in (select form_template from request_template where id in (select request_template from request where id=?)) order by entity,sort", requestId).Find(&items) itemMap := make(map[string][]string) @@ -1479,7 +1412,7 @@ func fillBindingWithRequestData(requestId, userToken string, cacheData *models.R } entityOidMap := make(map[string]int) dataIdOidMap := make(map[string]string) - matchEntityRoot(requestId, userToken, cacheData) + matchEntityRoot(requestId, userToken, language, cacheData) if cacheData.RootEntityValue.EntityDataOp != "create" { dataIdOidMap[cacheData.RootEntityValue.EntityDataId] = cacheData.RootEntityValue.Oid } @@ -1595,7 +1528,7 @@ func getEntityNameFromAttrDefId(attrDefId, attrName string) string { return attrName } -func matchEntityRoot(requestId, userToken string, cacheData *models.RequestCacheData) { +func matchEntityRoot(requestId, userToken, language string, cacheData *models.RequestCacheData) { for _, taskNode := range cacheData.TaskNodeBindInfos { existFlag := false for _, entityValue := range taskNode.BoundEntityValues { @@ -1622,7 +1555,7 @@ func matchEntityRoot(requestId, userToken string, cacheData *models.RequestCache } } if cacheData.RootEntityValue.Oid != "" && cacheData.RootEntityValue.EntityName == "" { - entityQueryResult, entityQueryErr := GetEntityData(requestId, userToken) + entityQueryResult, entityQueryErr := GetEntityData(requestId, userToken, language) if entityQueryErr != nil { log.Logger.Error("Try to fill root entity data fail", log.Error(entityQueryErr)) } else { @@ -1661,35 +1594,15 @@ func listToSet(input []string, itemMap map[string]int) []string { return result } -func RequestTermination(requestId, operator, userToken string) error { +func RequestTermination(requestId, operator, userToken, language string) error { requestObj, err := GetRequest(requestId) if err != nil { return err } param := models.TerminateInstanceParam{ProcInstId: requestObj.ProcInstanceId, ProcInstKey: requestObj.ProcInstanceKey} - paramBytes, tmpErr := json.Marshal(param) - if tmpErr != nil { - return fmt.Errorf("Json marshal param data fail,%s ", tmpErr.Error()) - } - req, newReqErr := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/platform/v1/public/process/instances/%s/terminations", models.Config.Wecube.BaseUrl, requestObj.ProcInstanceId), bytes.NewReader(paramBytes)) - if newReqErr != nil { - return fmt.Errorf("Try to new http request fail,%s ", newReqErr.Error()) - } - req.Header.Set("Authorization", userToken) - req.Header.Set("Content-Type", "application/json") - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - return fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) - } - var respResult models.StartInstanceResponse - b, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(b, &respResult) + err = GetProcDefService().TerminationsProcDefInstance(param, userToken, language) if err != nil { - return fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) - } - if respResult.Status != "OK" { - return fmt.Errorf("Terminate instance fail,%s ", respResult.Message) + return err } nowTime := time.Now().Format(models.DateTimeFormat) _, err = dao.X.Exec("update request set status='Termination',updated_by=?,updated_time=? where id=?", operator, nowTime, requestId) @@ -1720,7 +1633,7 @@ func GetCmdbReferenceData(attrId, userToken string, param models.QueryRequestPar return } -func GetRequestPreBindData(requestId, userToken string) (result models.RequestCacheData, err error) { +func GetRequestPreBindData(requestId, userToken, language string) (result models.RequestCacheData, err error) { var requestTable []*models.RequestTable err = dao.X.SQL("select * from request where id=?", requestId).Find(&requestTable) if err != nil { @@ -1732,14 +1645,14 @@ func GetRequestPreBindData(requestId, userToken string) (result models.RequestCa if requestTable[0].Cache == "" { return result, fmt.Errorf("Can not find request cache data with id:%s ", requestId) } - processNodes, processErr := GetProcessNodesByProc(models.RequestTemplateTable{Id: requestTable[0].RequestTemplate}, userToken, "bind") + processNodes, processErr := GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: requestTable[0].RequestTemplate}, userToken, language, "bind") if processErr != nil { return result, processErr } entityDefIdMap := make(map[string]string) entityBindMap := make(map[string][]string) for _, v := range processNodes { - tmpBoundEntities := []string{} + var tmpBoundEntities []string for _, vv := range v.BoundEntities { if vv == nil { continue @@ -1936,7 +1849,7 @@ func getPendingRequestData(request *models.RequestTable) *models.TaskQueryObj { return taskQueryObj } -func GetRequestDetailV2(requestId, userToken string) (result models.RequestDetail, err error) { +func GetRequestDetailV2(requestId, userToken, language string) (result models.RequestDetail, err error) { // get request var requests []*models.RequestTable var taskQueryList []*models.TaskQueryObj @@ -1946,7 +1859,7 @@ func GetRequestDetailV2(requestId, userToken string) (result models.RequestDetai return result, fmt.Errorf("Can not find request with id:%s ", requestId) } if strings.Contains(requests[0].Status, "InProgress") && requests[0].ProcInstanceId != "" { - newStatus := getInstanceStatus(requests[0].ProcInstanceId, userToken) + newStatus := getInstanceStatus(requests[0].ProcInstanceId, userToken, language) if newStatus == "InternallyTerminated" { newStatus = "Termination" } @@ -1962,7 +1875,7 @@ func GetRequestDetailV2(requestId, userToken string) (result models.RequestDetai } } } - result.Request = getRequestForm(requests[0], userToken) + result.Request = getRequestForm(requests[0], userToken, language) taskQueryList, err = GetRequestTaskListV2(requestId) if err != nil { return @@ -2136,18 +2049,18 @@ func BuildRequestProcessData(input models.RequestCacheData) (result models.Reque return result } -func AppendUselessEntity(requestTemplateId, userToken string, cacheData *models.RequestCacheData) (entityDepMap map[string][]string, err error) { +func AppendUselessEntity(requestTemplateId, userToken, language string, cacheData *models.RequestCacheData) (entityDepMap map[string][]string, err error) { entityDepMap = make(map[string][]string) if cacheData.RootEntityValue.Oid == "" || strings.HasPrefix(cacheData.RootEntityValue.Oid, "tmp") { return entityDepMap, nil } // get core preview data list - preData, preErr := ProcessDataPreview(requestTemplateId, cacheData.RootEntityValue.Oid, userToken) + preData, preErr := ProcessDataPreview(requestTemplateId, cacheData.RootEntityValue.Oid, userToken, language) if preErr != nil { return entityDepMap, fmt.Errorf("Try to get process preview data fail,%s ", preErr.Error()) } // get binding entity data - entityList := []*models.RequestCacheEntityValue{} + var entityList []*models.RequestCacheEntityValue entityExistMap := make(map[string]int) for _, v := range cacheData.TaskNodeBindInfos { for _, vv := range v.BoundEntityValues { @@ -2158,10 +2071,10 @@ func AppendUselessEntity(requestTemplateId, userToken string, cacheData *models. } } // preEntityList is other entity data - preEntityList := []*models.EntityTreeObj{} + var preEntityList []*models.EntityTreeObj rootParent := models.RequestCacheEntityAttrValue{} - rootSucceeding := []string{} - for _, v := range preData.Data.EntityTreeNodes { + var rootSucceeding []string + for _, v := range preData.EntityTreeNodes { if _, b := entityExistMap[v.Id]; !b { preEntityList = append(preEntityList, v) } @@ -2273,7 +2186,7 @@ func listContains(inputList []string, element string) bool { return result } -func notifyRoleMail(requestId string) error { +func notifyRoleMail(requestId, userToken, language string) error { if !models.MailEnable { return nil } @@ -2286,7 +2199,7 @@ func notifyRoleMail(requestId string) error { if len(roleTable) == 0 { return nil } - mailList := getRoleMail(roleTable) + mailList := getRoleMail(roleTable, userToken, language) if len(mailList) == 0 { log.Logger.Warn("Notify role mail break,email is empty", log.String("role", roleTable[0].Id)) return nil @@ -2320,7 +2233,7 @@ func CopyRequest(requestId, createdBy string) (result models.RequestTable, err e return } parentRequest = requestTable[0] - requestTemplate, err = GetSimpleRequestTemplate(parentRequest.RequestTemplate) + requestTemplate, err = GetRequestTemplateService().GetSimpleRequestTemplate(parentRequest.RequestTemplate) if err != nil { return } @@ -2597,10 +2510,11 @@ func getTaskApproveHandler(requestId string, result models.TaskTemplateDto) stri } // GetRequestProgress 请求已创建时,获取请求进度 -func GetRequestProgress(requestId, userToken string) (rowsData []*models.RequestProgressObj, err error) { +func GetRequestProgress(requestId, userToken, language string) (rowsData []*models.RequestProgressObj, err error) { var request models.RequestTable var pendingHandler string var status = int(Completed) //初始化为已完成 + var processInstance *models.ProcessInstance request, err = GetSimpleRequest(requestId) if err != nil { return @@ -2610,7 +2524,7 @@ func GetRequestProgress(requestId, userToken string) (rowsData []*models.Request } else { pendingHandler = GetRequestTemplateManageRole(request.RequestTemplate) } - subRowsData := getCommonRequestProgress(requestId, request.RequestTemplate, userToken) + subRowsData := getCommonRequestProgress(requestId, request.RequestTemplate, language, userToken) switch request.Status { case "Draft": status = int(NotStart) @@ -2656,24 +2570,28 @@ func GetRequestProgress(requestId, userToken string) (rowsData []*models.Request } } } - response, err := getProcessInstances(request.ProcInstanceId, userToken) + processInstance, err = GetProcDefService().GetProcessDefineInstance(request.ProcInstanceId, userToken, language) if err != nil { log.Logger.Error("http getProcessInstances error", log.Error(err)) } + if processInstance == nil { + log.Logger.Error("getProcessDefineInstance nil", log.String("procInstanceId", request.ProcInstanceId)) + return + } // 自动退出 - if response.Data.Status == "Faulted" { + if processInstance.Status == "Faulted" { subRowsData[len(subRowsData)-1].Node = AutoExit subRowsData[len(subRowsData)-1].Status = int(AutoExitStatus) } else { // 手动终止 - if response.Data.Status == "InternallyTerminated" { + if processInstance.Status == "InternallyTerminated" { subRowsData[len(subRowsData)-1].Node = InternallyTerminated subRowsData[len(subRowsData)-1].Status = int(InternallyTerminatedStatus) } // 记录错误节点,如果实例运行中有错误节点,则需要把运行节点展示在列表中并展示对应位置 var exist bool - for _, v := range response.Data.TaskNodeInstances { + for _, v := range processInstance.TaskNodeInstances { exist = false if v.Status == "Faulted" || v.Status == "Timeouted" { for _, rowData := range subRowsData { @@ -2716,10 +2634,10 @@ func GetRequestProgress(requestId, userToken string) (rowsData []*models.Request return } -func getCommonRequestProgress(requestId, templateId, userToken string) (rowsData []*models.RequestProgressObj) { +func getCommonRequestProgress(requestId, templateId, language, userToken string) (rowsData []*models.RequestProgressObj) { var nodeList models.ProcNodeObjList var err error - nodeList, err = GetProcessNodesByProc(models.RequestTemplateTable{Id: templateId}, userToken, "template") + nodeList, err = GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: templateId}, userToken, language, "template") if err != nil { log.Logger.Error("GetProcessNodesByProc err", log.Error(err)) rowsData = append(rowsData, &models.RequestProgressObj{ @@ -2778,63 +2696,17 @@ func getCommonRequestProgress(requestId, templateId, userToken string) (rowsData return } -func GetProcessDefinitions(templateId, userToken string) (rowData *models.DefinitionsData, err error) { +func GetProcessDefinitions(templateId, userToken, language string) (rowData *models.DefinitionsData, err error) { var template models.RequestTemplateTable - var response models.ProcessDefinitionsResponse - var url string - var byteArr []byte - template, err = GetSimpleRequestTemplate(templateId) - if err != nil { - return - } - url = fmt.Sprintf("%s/platform/v1/process/definitions/%s/outline", models.Config.Wecube.BaseUrl, template.ProcDefId) - byteArr, err = HttpGet(url, userToken) + template, err = GetRequestTemplateService().GetSimpleRequestTemplate(templateId) if err != nil { return } - err = json.Unmarshal(byteArr, &response) - if err != nil { - return - } - rowData = response.Data - return -} - -func GetProcessInstance(instanceId, userToken string) (rowData *models.ProcessInstance, err error) { - var byteArr []byte - var response models.ProcessInstanceResponse - url := fmt.Sprintf("%s/platform/v1/process/instances/%s", models.Config.Wecube.BaseUrl, instanceId) - byteArr, err = HttpGet(url, userToken) - if err != nil { - return - } - err = json.Unmarshal(byteArr, &response) - if err != nil { - return - } - rowData = response.Data - return -} - -func HttpGet(url, userToken string) (byteArr []byte, err error) { - req, newReqErr := http.NewRequest(http.MethodGet, url, strings.NewReader("")) - if newReqErr != nil { - err = fmt.Errorf("Try to new http request fail,%s ", newReqErr.Error()) - return - } - req.Header.Set("Authorization", userToken) - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - err = fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) - return - } - byteArr, _ = ioutil.ReadAll(resp.Body) - defer resp.Body.Close() - return + return GetProcDefService().GetProcessDefine(template.ProcDefId, userToken, language) } // getRequestForm 获取请求信息 -func getRequestForm(request *models.RequestTable, userToken string) (form models.RequestForm) { +func getRequestForm(request *models.RequestTable, userToken, language string) (form models.RequestForm) { if request == nil { return } @@ -2873,7 +2745,7 @@ func getRequestForm(request *models.RequestTable, userToken string) (form models form.CurNode = RequestPending } if request.ProcInstanceId != "" { - form.Progress, form.CurNode = getCurNodeName(request.ProcInstanceId, userToken) + form.Progress, form.CurNode = getCurNodeName(request.ProcInstanceId, userToken, language) } _, form.Handler = getRequestHandler(request.Id) return @@ -2918,7 +2790,7 @@ func getRequestHandler(requestId string) (role, handler string) { func getRequestRemainTime(requestId string) (startTime string, effectiveDays int) { request, _ := GetSimpleRequest(requestId) if request.Status == "Draft" || request.Status == "Pending" || request.Status == "Completed" { - requestTemplate, _ := GetSimpleRequestTemplate(request.RequestTemplate) + requestTemplate, _ := GetRequestTemplateService().GetSimpleRequestTemplate(request.RequestTemplate) startTime = request.ReportTime effectiveDays = requestTemplate.ExpireDay return @@ -2937,28 +2809,12 @@ func getRequestRemainTime(requestId string) (startTime string, effectiveDays int } } } - requestTemplate, _ := GetSimpleRequestTemplate(request.RequestTemplate) + requestTemplate, _ := GetRequestTemplateService().GetSimpleRequestTemplate(request.RequestTemplate) startTime = request.CreatedTime effectiveDays = requestTemplate.ExpireDay return } -func GetExecutionNodes(userToken string, procInstanceId, nodeInstanceId string) (data interface{}, err error) { - var response models.ExecutionResponse - var byteArr []byte - var url = fmt.Sprintf("%s/platform/v1/process/instances/%s/tasknodes/%s/context", models.Config.Wecube.BaseUrl, procInstanceId, nodeInstanceId) - byteArr, err = HttpGet(url, userToken) - if err != nil { - return - } - err = json.Unmarshal(byteArr, &response) - if err != nil { - return - } - data = response.Data - return -} - func GetFilterItem(param models.FilterRequestParam) (data *models.FilterItem, err error) { data = &models.FilterItem{ RequestTemplateList: make([]*models.KeyValuePair, 0), @@ -3050,17 +2906,3 @@ func convertArray2Map(arr []string) map[string]bool { } return hashMap } - -func getAllCoreProcess(userToken string) map[string]string { - var processMap = make(map[string]string) - // 查询全部流程 - result, _ := GetCoreProcessListNew(userToken) - if len(result) > 0 { - for _, procDef := range result { - if procDef != nil { - processMap[procDef.ProcDefKey] = procDef.RootEntity.DisplayName - } - } - } - return processMap -} diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 941162d8..765f19cb 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -3,8 +3,6 @@ package service import ( "encoding/json" "fmt" - "io/ioutil" - "net/http" "sort" "strconv" "strings" @@ -25,7 +23,7 @@ type RequestTemplateService struct { operationLogDao dao.OperationLogDao } -func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestParam, userToken, language string, userRoles []string) (pageInfo models.PageInfo, result []*models.RequestTemplateQueryObj, err error) { +func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestParam, commonParam models.CommonParam) (pageInfo models.PageInfo, result []*models.RequestTemplateQueryObj, err error) { var roleMap = make(map[string]*models.SimpleLocalRoleDto) extFilterSql := "" result = []*models.RequestTemplateQueryObj{} @@ -73,7 +71,7 @@ func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestP } var rowData []*models.RequestTemplateTable filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateTable{}, PrimaryKey: "id", Prefix: "t1"}) - userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(commonParam.Roles, "") queryParam = append(userRolesFilterParam, queryParam...) baseSql := fmt.Sprintf("SELECT %s FROM (select * from request_template where del_flag=0 or (del_flag=2 and id not in (select record_id from request_template where del_flag=2 and record_id<>''))) t1 WHERE t1.id in (select request_template from request_template_role where role_type='MGMT' and `role` in ("+userRolesFilterSql+")) %s %s ", queryColumn, extFilterSql, filterSql) if param.Paging { @@ -120,7 +118,7 @@ func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestP } if isQueryMessage { for _, v := range rowData { - tmpErr := SyncProcDefId(v.Id, v.ProcDefId, v.ProcDefName, v.ProcDefKey, userToken) + tmpErr := SyncProcDefId(v.Id, v.ProcDefId, v.ProcDefName, v.ProcDefKey, commonParam.Token, commonParam.Language) if tmpErr != nil { err = fmt.Errorf("Try to sync proDefId fail,%s ", tmpErr.Error()) break @@ -130,7 +128,7 @@ func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestP return } } - roleMap, err = rpc.QueryAllRoles("Y", userToken, language) + roleMap, err = rpc.QueryAllRoles("Y", commonParam.Token, commonParam.Language) if err != nil { return } @@ -168,7 +166,7 @@ func (s RequestTemplateService) UpdateRequestTemplateStatus(requestTemplateId, u requestTemplate := models.RequestTemplateTable{Id: requestTemplateId, Status: status, UpdatedBy: user, UpdatedTime: time.Now().Format(models.DateTimeFormat)} // 状态更新到草稿,需要退回 - if status == string(models.Draft) { + if status == string(models.RequestStatusDraft) { requestTemplate.RollbackDesc = reason } return s.requestTemplateDao.Update(requestTemplate) @@ -178,35 +176,6 @@ func (s RequestTemplateService) GetRequestTemplate(requestTemplateId string) (re return s.requestTemplateDao.Get(requestTemplateId) } -func (s RequestTemplateService) GetCoreProcessListNew(userToken, language string) (processList []*models.ProcDefObj, err error) { - var procDefDtoList []*models.ProcDefDto - var nodesList []*models.DataModel - var entityMap = make(map[string]models.ProcEntity) - processList = make([]*models.ProcDefObj, 0) - procDefDtoList, err = rpc.QueryProcessDefinitionList(userToken, language, models.QueryProcessDefinitionParam{Plugins: []string{"taskman"}, Status: "deployed"}) - if err != nil { - return - } - nodesList, err = rpc.QueryAllModels(userToken, language) - if err != nil { - return - } - entityMap = models.ConvertModelsList2Map(nodesList) - if len(procDefDtoList) > 0 { - for _, dto := range procDefDtoList { - processList = append(processList, &models.ProcDefObj{ - ProcDefId: dto.Id, - ProcDefKey: dto.Key, - ProcDefName: dto.Name, - Status: dto.Status, - RootEntity: entityMap[dto.RootEntity], - CreatedTime: dto.CreatedTime, - }) - } - } - return -} - func (s RequestTemplateService) CheckRequestTemplateRoles(requestTemplateId string, userRoles []string) error { has, err := s.requestTemplateRoleDao.CheckRequestTemplateRoles(requestTemplateId, userRoles) if err != nil { @@ -248,6 +217,20 @@ func (s RequestTemplateService) CreateRequestTemplate(param *models.RequestTempl return } +func (s RequestTemplateService) GetAllCoreProcess(userToken, language string) map[string]string { + var processMap = make(map[string]string) + // 查询全部流程 + result, _ := GetProcDefService().GetCoreProcessListAll(userToken, language) + if len(result) > 0 { + for _, procDef := range result { + if procDef != nil { + processMap[procDef.ProcDefKey] = procDef.RootEntity.DisplayName + } + } + } + return processMap +} + func QueryRequestTemplateGroup(param *models.QueryRequestParam, userRoles []string) (pageInfo models.PageInfo, rowData []*models.RequestTemplateGroupTable, err error) { rowData = []*models.RequestTemplateGroupTable{} filterSql, queryColumn, queryParam := dao.TransFiltersToSQL(param, &models.TransFiltersParam{IsStruct: true, StructObj: models.RequestTemplateGroupTable{}, PrimaryKey: "id"}) @@ -317,158 +300,20 @@ func CheckRequestTemplateGroupRoles(id string, roles []string) error { return nil } -func GetCoreProcessListNew(userToken string) (processList []*models.ProcDefObj, err error) { - processList = []*models.ProcDefObj{} - req, reqErr := http.NewRequest(http.MethodGet, models.Config.Wecube.BaseUrl+"/platform/v1/public/process/definitions?tags="+models.ProcessFetchTabs, nil) - if reqErr != nil { - err = fmt.Errorf("Try to new http request to core fail,%s ", reqErr.Error()) - return - } - req.Header.Set("Authorization", userToken) - http.DefaultClient.CloseIdleConnections() - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - err = fmt.Errorf("Try to do request to core fail,%s ", respErr.Error()) - return - } - var respObj models.ProcQueryResponse - respBytes, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(respBytes, &respObj) - log.Logger.Debug("Get core process list", log.String("body", string(respBytes))) - if err != nil { - err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) - return - } - if respObj.Status != "OK" { - err = fmt.Errorf(respObj.Message) - return - } - processList = respObj.Data - return -} - -func GetCoreProcessListAll(userToken, permission, tags string) (processList []*models.ProcAllDefObj, err error) { - if permission == "" { - permission = "USE" - } - processList = []*models.ProcAllDefObj{} - req, reqErr := http.NewRequest(http.MethodGet, models.Config.Wecube.BaseUrl+fmt.Sprintf("/platform/v1/process/definitions?includeDraft=0&permission=%s&tags=%s", permission, tags), nil) - if reqErr != nil { - err = fmt.Errorf("Try to new http request to core fail,%s ", reqErr.Error()) - return - } - req.Header.Set("Authorization", userToken) - http.DefaultClient.CloseIdleConnections() - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - err = fmt.Errorf("Try to do request to core fail,%s ", respErr.Error()) - return - } - var respObj models.ProcAllQueryResponse - respBytes, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(respBytes, &respObj) - log.Logger.Debug("Get core process list", log.String("body", string(respBytes))) - if err != nil { - err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) - return - } - if respObj.Status != "OK" { - err = fmt.Errorf(respObj.Message) - return - } - processList = respObj.Data - return -} - -func GetProcessNodesByProc(requestTemplateObj models.RequestTemplateTable, userToken string, filterType string) (nodeList models.ProcNodeObjList, err error) { - if requestTemplateObj.ProcDefId == "" { - requestTemplateObj, err = GetSimpleRequestTemplate(requestTemplateObj.Id) - if err != nil { - return - } - } - if requestTemplateObj.ProcDefId == "" { - err = fmt.Errorf("Request template proDefId illegal ") - return - } - nodeList = []*models.ProcNodeObj{} - req, reqErr := http.NewRequest(http.MethodGet, models.Config.Wecube.BaseUrl+"/platform/v1/public/process/definitions/"+requestTemplateObj.ProcDefId+"/tasknodes", nil) - if reqErr != nil { - err = fmt.Errorf("Try to new http request to core fail,%s ", reqErr.Error()) - return - } - req.Header.Set("Authorization", userToken) - http.DefaultClient.CloseIdleConnections() - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - err = fmt.Errorf("Try to do request to core fail,%s ", respErr.Error()) - return - } - var respObj models.ProcNodeQueryResponse - respBytes, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - log.Logger.Debug("platform process task node return", log.String("body", string(respBytes))) - err = json.Unmarshal(respBytes, &respObj) - if err != nil { - err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) - return - } - if respObj.Status != "OK" { - err = fmt.Errorf(respObj.Message) - return - } - for _, v := range respObj.Data { - if v.NodeType != "subProcess" { - continue - } - if filterType == "template" { - if v.TaskCategory != "SUTN" { - continue - } - } else if filterType == "bind" { - if v.DynamicBind == "Y" { - continue - } - } - if v.OrderedNo == "" { - v.OrderedNum = 0 - } else { - v.OrderedNum, _ = strconv.Atoi(v.OrderedNo) - } - nodeList = append(nodeList, v) - } - sort.Sort(nodeList) - return -} - -func getRoleMail(roleList []*models.RoleTable) (mailList []string) { +func getRoleMail(roleList []*models.RoleTable, userToken, language string) (mailList []string) { + var roleMap map[string]*models.SimpleLocalRoleDto + var err error if models.CoreToken.BaseUrl == "" || len(roleList) == 0 { return } - request, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/platform/v1/roles/retrieve", models.CoreToken.BaseUrl), strings.NewReader("")) + roleMap, err = rpc.QueryAllRoles("N", userToken, language) if err != nil { - log.Logger.Error("Get core role key new request fail", log.Error(err)) - return - } - request.Header.Set("Authorization", models.CoreToken.GetCoreToken()) - res, err := http.DefaultClient.Do(request) - if err != nil { - log.Logger.Error("Get core role key ctxhttp request fail", log.Error(err)) - return - } - b, _ := ioutil.ReadAll(res.Body) - res.Body.Close() - var result models.CoreRoleDto - err = json.Unmarshal(b, &result) - if err != nil { - log.Logger.Error("Get core role key json unmarshal result", log.Error(err)) + log.Logger.Error("QueryAllRoles err:%+v", log.Error(err)) return } for _, v := range roleList { tmpMail := "" - for _, vv := range result.Data { + for _, vv := range roleMap { if vv.Name == v.Id { tmpMail = vv.Email break @@ -481,41 +326,20 @@ func getRoleMail(roleList []*models.RoleTable) (mailList []string) { return } -func SyncCoreRole() { +func SyncCoreRole(userToken, language string) { + var roleMap map[string]*models.SimpleLocalRoleDto + var err error if models.CoreToken.BaseUrl == "" { return } - request, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/platform/v1/roles/retrieve", models.CoreToken.BaseUrl), strings.NewReader("")) - if err != nil { - log.Logger.Error("Get core role key new request fail", log.Error(err)) - return - } - request.Header.Set("Authorization", models.CoreToken.GetCoreToken()) - res, err := http.DefaultClient.Do(request) - if err != nil { - log.Logger.Error("Get core role key ctxhttp request fail", log.Error(err)) - return - } - b, _ := ioutil.ReadAll(res.Body) - res.Body.Close() - //log.Logger.Debug("Get core role response", log.String("body", string(b))) - var result models.CoreRoleDto - err = json.Unmarshal(b, &result) - if err != nil { - log.Logger.Error("Get core role key json unmarshal result", log.Error(err)) - return - } - if len(result.Data) == 0 { - log.Logger.Warn("Get core role key fail with no data") - return - } + roleMap, err = rpc.QueryAllRoles("N", userToken, language) var roleTable, addRoleList, delRoleList []*models.RoleTable err = dao.X.SQL("select * from role").Find(&roleTable) if err != nil { log.Logger.Error("Try to sync core role fail", log.Error(err)) return } - for _, v := range result.Data { + for _, v := range roleMap { existFlag := false for _, vv := range roleTable { if v.Name == vv.Id { @@ -524,12 +348,12 @@ func SyncCoreRole() { } } if !existFlag { - addRoleList = append(addRoleList, &models.RoleTable{Id: v.Name, DisplayName: v.DisplayName, CoreId: v.Id, Email: v.Email}) + addRoleList = append(addRoleList, &models.RoleTable{Id: v.Name, DisplayName: v.DisplayName, CoreId: v.ID, Email: v.Email}) } } for _, v := range roleTable { existFlag := false - for _, vv := range result.Data { + for _, vv := range roleMap { if v.Id == vv.Name { existFlag = true break @@ -579,11 +403,11 @@ func getRequestTemplateModifyType(requestTemplate *models.RequestTemplateTable) return true } -func checkProDefId(proDefId, proDefName, proDefKey, userToken string) (exist bool, newProDefId string, err error) { +func checkProDefId(proDefId, proDefName, proDefKey, userToken, language string) (exist bool, newProDefId string, err error) { exist = false var processList []*models.ProcDefObj if proDefKey != "" { - tmpProcessList, tmpErr := GetCoreProcessListNew(userToken) + tmpProcessList, tmpErr := GetProcDefService().GetCoreProcessListNew(userToken, language, "") if tmpErr != nil { err = tmpErr } else { @@ -592,7 +416,7 @@ func checkProDefId(proDefId, proDefName, proDefKey, userToken string) (exist boo } } } else { - allProcessList, tmpErr := GetCoreProcessListAll(userToken, "", "") + allProcessList, tmpErr := GetProcDefService().GetCoreProcessListAll(userToken, language) if tmpErr != nil { err = tmpErr } else { @@ -637,14 +461,14 @@ func checkProDefId(proDefId, proDefName, proDefKey, userToken string) (exist boo return } -func getUpdateNodeDefIdActions(requestTemplateId, userToken string) (actions []*dao.ExecAction) { +func getUpdateNodeDefIdActions(requestTemplateId, userToken, language string) (actions []*dao.ExecAction) { actions = []*dao.ExecAction{} var taskTemplate []*models.TaskTemplateTable dao.X.SQL("select * from task_template where request_template=?", requestTemplateId).Find(&taskTemplate) if len(taskTemplate) == 0 { return actions } - nodeList, _ := GetProcessNodesByProc(models.RequestTemplateTable{Id: requestTemplateId}, userToken, "template") + nodeList, _ := GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: requestTemplateId}, userToken, language, "template") nodeMap := make(map[string]string) for _, v := range nodeList { nodeMap[v.NodeId] = v.NodeDefId @@ -663,9 +487,9 @@ func getUpdateNodeDefIdActions(requestTemplateId, userToken string) (actions []* return actions } -func SyncProcDefId(requestTemplateId, proDefId, proDefName, proDefKey, userToken string) error { +func SyncProcDefId(requestTemplateId, proDefId, proDefName, proDefKey, userToken, language string) error { log.Logger.Info("Start sync process def id") - proExistFlag, newProDefId, err := checkProDefId(proDefId, proDefName, proDefKey, userToken) + proExistFlag, newProDefId, err := checkProDefId(proDefId, proDefName, proDefKey, userToken, language) if err != nil { return err } @@ -683,7 +507,7 @@ func SyncProcDefId(requestTemplateId, proDefId, proDefName, proDefKey, userToken log.Logger.Info("Update requestTemplate proDefId done") actions = []*dao.ExecAction{} } - tmpActions := getUpdateNodeDefIdActions(requestTemplateId, userToken) + tmpActions := getUpdateNodeDefIdActions(requestTemplateId, userToken, language) if len(tmpActions) > 0 { err = dao.Transaction(tmpActions) if err != nil { @@ -725,7 +549,7 @@ func UpdateRequestTemplate(param *models.RequestTemplateUpdateParam) (result mod } func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*dao.ExecAction, err error) { - rtObj, err := GetSimpleRequestTemplate(id) + rtObj, err := GetRequestTemplateService().GetSimpleRequestTemplate(id) if err != nil { return actions, err } @@ -767,9 +591,9 @@ func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*dao.ExecAc return actions, err } -func ListRequestTemplateEntityAttrs(id, userToken string) (result []*models.ProcEntity, err error) { +func ListRequestTemplateEntityAttrs(id, userToken, language string) (result []*models.ProcEntity, err error) { result = []*models.ProcEntity{} - nodes, getNodesErr := GetProcessNodesByProc(models.RequestTemplateTable{Id: id}, userToken, "all") + nodes, getNodesErr := GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: id}, userToken, language, "all") if getNodesErr != nil { err = getNodesErr return @@ -839,7 +663,7 @@ func UpdateRequestTemplateEntityAttrs(id string, attrs []*models.ProcEntityAttri return err } -func GetSimpleRequestTemplate(id string) (result models.RequestTemplateTable, err error) { +func (s RequestTemplateService) GetSimpleRequestTemplate(id string) (result models.RequestTemplateTable, err error) { var requestTemplateTable []*models.RequestTemplateTable err = dao.X.SQL("select * from request_template where id=?", id).Find(&requestTemplateTable) if err != nil { @@ -892,7 +716,7 @@ func getAllRequestTemplate() (templateMap map[string]*models.RequestTemplateTabl } func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { - requestTemplateObj, err := GetSimpleRequestTemplate(requestTemplateId) + requestTemplateObj, err := GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplateId) if err != nil { return err } @@ -963,7 +787,7 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { func ConfirmRequestTemplate(requestTemplateId string) error { var parentId string - requestTemplateObj, err := GetSimpleRequestTemplate(requestTemplateId) + requestTemplateObj, err := GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplateId) if err != nil { return err } @@ -979,7 +803,7 @@ func ConfirmRequestTemplate(requestTemplateId string) error { } nowTime := time.Now().Format(models.DateTimeFormat) if requestTemplateObj.RecordId != "" { - prevRequestTemplateObj, _ := GetSimpleRequestTemplate(requestTemplateObj.RecordId) + prevRequestTemplateObj, _ := GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplateObj.RecordId) parentId = prevRequestTemplateObj.ParentId } version := requestTemplateObj.Version @@ -1127,7 +951,7 @@ func GetRequestTemplateByUser(userRoles []string) (result []*models.UserRequestT } // GetRequestTemplateByUserV2 新的选择模板接口 -func GetRequestTemplateByUserV2(user, userToken string, userRoles []string) (result []*models.UserRequestTemplateQueryObjNew, err error) { +func (s RequestTemplateService) GetRequestTemplateByUserV2(user, userToken, language string, userRoles []string) (result []*models.UserRequestTemplateQueryObjNew, err error) { var operatorObjTypeMap = make(map[string]string) var roleTemplateGroupMap = make(map[string]map[string][]*models.RequestTemplateTableObj) var resultMap = make(map[string]*models.UserRequestTemplateQueryObjNew) @@ -1222,7 +1046,7 @@ func GetRequestTemplateByUserV2(user, userToken string, userRoles []string) (res var collectFlag int // 组装数据 // 操作对象类型,新增模板是录入.历史模板操作对象类型为空,需要全量处理下 - operatorObjTypeMap = getAllCoreProcess(userToken) + operatorObjTypeMap = s.GetAllCoreProcess(userToken, language) if len(requestTemplateTable) > 0 { for _, template := range requestTemplateTable { collectFlag = 0 @@ -1400,7 +1224,7 @@ func getMGmtRequestTemplateRoles() map[string]string { return roleMap } -func QueryUserByRoles(roles []string, userToken string) (result []string, err error) { +func QueryUserByRoles(roles []string, userToken, language string) (result []string, err error) { result = []string{} var roleTable []*models.RoleTable rolesFilterSql, rolesFilterParam := dao.CreateListParams(roles, "") @@ -1413,51 +1237,24 @@ func QueryUserByRoles(roles []string, userToken string) (result []string, err er if v.CoreId == "" { continue } - tmpResult, tmpErr := queryCoreUser(v.CoreId, userToken) + tmpResult, tmpErr := rpc.QueryRolesUsers(v.CoreId, userToken, language) if tmpErr != nil { err = tmpErr break } + if len(tmpResult) == 0 { + continue + } for _, vv := range tmpResult { - if _, b := existMap[vv]; !b { - result = append(result, vv) - existMap[vv] = 1 + if _, b := existMap[vv.UserName]; !b { + result = append(result, vv.UserName) + existMap[vv.UserName] = 1 } } } return } -func queryCoreUser(roleId, userToken string) (result []string, err error) { - request, newRequestErr := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/platform/v1/roles/%s/users", models.CoreToken.BaseUrl, roleId), strings.NewReader("")) - if newRequestErr != nil { - err = fmt.Errorf("Get core role key new request fail:%s ", newRequestErr.Error()) - return - } - request.Header.Set("Authorization", userToken) - res, requestErr := http.DefaultClient.Do(request) - if requestErr != nil { - err = fmt.Errorf("Get core user request fail:%s ", requestErr.Error()) - return - } - b, _ := ioutil.ReadAll(res.Body) - res.Body.Close() - var response models.CoreUserDto - err = json.Unmarshal(b, &response) - if err != nil { - err = fmt.Errorf("Get core user json unmarshal result:%s ", err.Error()) - return - } - if response.Status != "OK" { - err = fmt.Errorf(response.Message) - return - } - for _, v := range response.Data { - result = append(result, v.Username) - } - return -} - func GetRequestTemplateTags(group string) (result []string, err error) { result = []string{} var requestTemplates []*models.RequestTemplateTable @@ -1500,7 +1297,7 @@ func RequestTemplateExport(requestTemplateId string) (result models.RequestTempl return } -func RequestTemplateImport(input models.RequestTemplateExport, userToken, confirmToken, operator string) (templateName, backToken string, err error) { +func RequestTemplateImport(input models.RequestTemplateExport, userToken, language, confirmToken, operator string) (templateName, backToken string, err error) { var actions []*dao.ExecAction var inputVersion = getTemplateVersion(&input.RequestTemplate) var templateList []*models.RequestTemplateTable @@ -1562,7 +1359,7 @@ func RequestTemplateImport(input models.RequestTemplateExport, userToken, confir err = fmt.Errorf("RequestTemplate id illegal ") return } - allProcessList, processErr := GetCoreProcessListAll(userToken, "", "") + allProcessList, processErr := GetProcDefService().GetCoreProcessListAll(userToken, language) if processErr != nil { err = fmt.Errorf("Get core process list fail,%s ", processErr.Error()) return @@ -1579,7 +1376,7 @@ func RequestTemplateImport(input models.RequestTemplateExport, userToken, confir err = fmt.Errorf("Reqeust process:%s can not find! ", input.RequestTemplate.ProcDefName) return } - nodeList, _ := GetProcessNodesByProc(input.RequestTemplate, userToken, "template") + nodeList, _ := GetProcDefService().GetProcessDefineTaskNodes(input.RequestTemplate, userToken, language, "template") for i, v := range input.TaskTemplate { existFlag := false for _, node := range nodeList { diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index ab13c146..d4576657 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -24,6 +24,8 @@ var ( taskService TaskService // 记录 service operationLogService OperationLogService + // 编排 service + procDefService ProcDefService ) func New() (err error) { @@ -44,6 +46,7 @@ func New() (err error) { attachFileService = AttachFileService{attachFileDao: attachFileDao} requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao, requestTemplateRoleDao: requestTemplateRoleDao, operationLogDao: operationLogDao} operationLogService = OperationLogService{operationLogDao: operationLogDao} + procDefService = ProcDefService{} db = engine return } @@ -63,6 +66,11 @@ func GetOperationLogService() OperationLogService { return operationLogService } +// GetProcDefService 获取编排 service +func GetProcDefService() ProcDefService { + return procDefService +} + // transaction 事务处理 func transaction(f func(session *xorm.Session) error) (err error) { session := db.NewSession() diff --git a/taskman-server/service/task_service.go b/taskman-server/service/task_service.go index 37ae7614..5a60d097 100644 --- a/taskman-server/service/task_service.go +++ b/taskman-server/service/task_service.go @@ -1,7 +1,6 @@ package service import ( - "bytes" "encoding/json" "fmt" "github.com/WeBankPartners/go-common-lib/guid" @@ -10,8 +9,7 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "io/ioutil" - "net/http" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/rpc" "strconv" "strings" "time" @@ -609,20 +607,9 @@ func ApproveTask(taskId, operator, userToken string, param models.TaskApprovePar for _, v := range requestParam.Results.Outputs { v.Comment = param.Comment } - requestBytes, _ := json.Marshal(requestParam) - req, newReqErr := http.NewRequest(http.MethodPost, models.Config.Wecube.BaseUrl+callbackUrl, bytes.NewReader(requestBytes)) - if newReqErr != nil { - return fmt.Errorf("Try to new http request fail,%s ", newReqErr.Error()) - } - req.Header.Set("Authorization", userToken) - req.Header.Set("Content-Type", "application/json") - resp, respErr := http.DefaultClient.Do(req) - if respErr != nil { - return fmt.Errorf("Try to do http request fail,%s ", respErr.Error()) - } var respResult models.CallbackResult - b, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() + requestBytes, _ := json.Marshal(requestParam) + b, _ := rpc.HttpPost(models.Config.Wecube.BaseUrl+callbackUrl, userToken, "", requestBytes) log.Logger.Info("Callback response", log.String("body", string(b))) err = json.Unmarshal(b, &respResult) if err != nil { @@ -810,7 +797,7 @@ func buildTaskOperation(taskObj *models.TaskListObj, operator string) { } } -func NotifyTaskMail(taskId string) error { +func NotifyTaskMail(taskId, userToken, language string) error { if !models.MailEnable { return nil } @@ -829,7 +816,7 @@ func NotifyTaskMail(taskId string) error { if len(roleTable) == 0 { return fmt.Errorf("can not find handle role with task:%s ", taskId) } - mailList := getRoleMail(roleTable) + mailList := getRoleMail(roleTable, userToken, language) if len(mailList) == 0 { log.Logger.Warn("Notify task mail break,email is empty", log.String("role", roleTable[0].Id)) return fmt.Errorf("handle role email is empty ") From 2331c11c77b9a8892f1b19c4512278a8d3581faf Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 9 Feb 2024 11:09:55 +0800 Subject: [PATCH 009/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E3=80=81=E8=A1=A8=E5=8D=95=E9=A1=B9=E7=9B=AE=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=8B=86=E5=88=86=E5=88=86=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 1 + taskman-server/api/v1/form/form_template.go | 19 +- .../api/v1/request/request_template.go | 2 +- taskman-server/dao/form_dao.go | 19 +- taskman-server/dao/form_item_templdate_dao.go | 41 +++- taskman-server/dao/form_template_dao.go | 27 ++- taskman-server/dao/request_template_dao.go | 10 +- .../dao/request_template_role_dao.go | 2 +- taskman-server/models/form_item_template.go | 2 +- taskman-server/models/form_template.go | 12 + taskman-server/models/process_defintions.go | 2 +- taskman-server/models/request_template.go | 2 +- taskman-server/models/response.go | 2 +- taskman-server/rpc/proc_def_rpc.go | 4 +- taskman-server/service/form_item_service.go | 7 + .../service/form_item_template_service.go | 7 + taskman-server/service/form_service.go | 7 + .../service/form_template_service.go | 222 ++++++++++-------- taskman-server/service/proc_def_service.go | 22 +- .../service/request_template_group_service.go | 7 + .../service/request_template_service.go | 38 ++- taskman-server/service/service.go | 113 ++++++++- .../service/task_template_role_service.go | 7 + .../service/task_template_service.go | 66 +++++- 24 files changed, 484 insertions(+), 157 deletions(-) create mode 100644 taskman-server/service/form_item_service.go create mode 100644 taskman-server/service/form_item_template_service.go create mode 100644 taskman-server/service/form_service.go create mode 100644 taskman-server/service/request_template_group_service.go create mode 100644 taskman-server/service/task_template_role_service.go diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 630eb4bc..6a5451ae 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -58,6 +58,7 @@ func init() { &handlerFuncObj{Url: "/request-template/enable/:id", Method: "POST", HandlerFunc: request.EnableRequestTemplate}, &handlerFuncObj{Url: "/request-form-template/:id", Method: "GET", HandlerFunc: form.GetRequestFormTemplate}, &handlerFuncObj{Url: "/request-form-template/:id", Method: "POST", HandlerFunc: form.UpdateRequestFormTemplate}, + // &handlerFuncObj{Url: "/request-form-template/:id", Method: "DELETE", HandlerFunc: form.DeleteFormTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplateId/:proNodeId", Method: "GET", HandlerFunc: task.GetTaskTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplateId", Method: "POST", HandlerFunc: task.UpdateTaskTemplate}, diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index d06a45dc..66401d02 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -14,7 +14,7 @@ func GetRequestFormTemplate(c *gin.Context) { middleware.ReturnParamEmptyError(c, "id") return } - result, err := service.GetRequestFormTemplate(id) + result, err := service.GetFormTemplateService().GetRequestFormTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -23,29 +23,30 @@ func GetRequestFormTemplate(c *gin.Context) { } func UpdateRequestFormTemplate(c *gin.Context) { + var param models.FormTemplateDto + var err error + var user = middleware.GetRequestUser(c) id := c.Param("id") if id == "" { middleware.ReturnParamEmptyError(c, "id") return } - var param models.FormTemplateDto if err := c.ShouldBindJSON(¶m); err != nil { middleware.ReturnParamValidateError(c, err) return } - var err error - param.UpdatedBy = middleware.GetRequestUser(c) + param.UpdatedBy = user if param.Id != "" { - err = service.UpdateRequestFormTemplate(param) + err = service.GetFormTemplateService().UpdateRequestFormTemplate(param, id) } else { - err = service.CreateRequestFormTemplate(param, id) + err = service.GetFormTemplateService().CreateRequestFormTemplate(param, id) } if err != nil { middleware.ReturnServerHandleError(c, err) return } - service.SetRequestTemplateToCreated(id, middleware.GetRequestUser(c)) - result, _ := service.GetRequestFormTemplate(id) + service.SetRequestTemplateToCreated(id, user) + result, _ := service.GetFormTemplateService().GetRequestFormTemplate(id) middleware.ReturnData(c, result) } @@ -78,7 +79,7 @@ func ConfirmRequestFormTemplate(c *gin.Context) { func DeleteRequestFormTemplate(c *gin.Context) { id := c.Param("id") - err := service.DeleteRequestFormTemplate(id) + err := service.GetFormTemplateService().DeleteRequestFormTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) } else { diff --git a/taskman-server/api/v1/request/request_template.go b/taskman-server/api/v1/request/request_template.go index ba917ad5..06934c3c 100644 --- a/taskman-server/api/v1/request/request_template.go +++ b/taskman-server/api/v1/request/request_template.go @@ -165,7 +165,7 @@ func CreateRequestTemplate(c *gin.Context) { return } param.CreatedBy = middleware.GetRequestUser(c) - result, err := service.GetRequestTemplateService().CreateRequestTemplate(¶m) + result, err := service.GetRequestTemplateService().CreateRequestTemplate(param) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/dao/form_dao.go b/taskman-server/dao/form_dao.go index 083fbdd8..dd9a23d8 100644 --- a/taskman-server/dao/form_dao.go +++ b/taskman-server/dao/form_dao.go @@ -1,7 +1,24 @@ package dao -import "xorm.io/xorm" +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "xorm.io/xorm" +) type FormDao struct { DB *xorm.Engine } + +func (d FormDao) Delete(formId string) (err error) { + _, err = d.DB.Where("id = ?", formId).Delete(&models.FormItemTemplateTable{}) + return +} + +func (d FormDao) DeleteByFormItemTemplate(session *xorm.Session, formItemTemplate string) (err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + _, err = session.Where("form_item_template = ?", formItemTemplate).Delete(&models.FormTemplateTable{}) + return +} diff --git a/taskman-server/dao/form_item_templdate_dao.go b/taskman-server/dao/form_item_templdate_dao.go index cdbc448f..043597dd 100644 --- a/taskman-server/dao/form_item_templdate_dao.go +++ b/taskman-server/dao/form_item_templdate_dao.go @@ -1,7 +1,46 @@ package dao -import "xorm.io/xorm" +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "xorm.io/xorm" +) type FormItemTemplateDao struct { DB *xorm.Engine } + +func (d FormItemTemplateDao) Add(session *xorm.Session, formItemTemplate *models.FormItemTemplateTable) (affected int64, err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + return session.InsertOne(formItemTemplate) +} + +func (d FormItemTemplateDao) Update(session *xorm.Session, formItemTemplate *models.FormItemTemplateTable) (err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + _, err = d.DB.ID(formItemTemplate.Id).Update(formItemTemplate) + return +} + +func (d FormItemTemplateDao) Get(formItemTemplateId string) (formItemTemplate *models.FormItemTemplateTable, err error) { + _, err = d.DB.ID(formItemTemplateId).Get(&formItemTemplate) + return +} + +func (d FormItemTemplateDao) QueryByFormTemplate(formTemplate string) (formItemTemplate []*models.FormItemTemplateTable, err error) { + err = d.DB.Where("form_template = ?", formTemplate).Find(&formItemTemplate) + return +} + +func (d FormItemTemplateDao) Delete(session *xorm.Session, id string) (err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + _, err = d.DB.Where("id=?", id).Delete(&models.FormItemTemplateTable{}) + return +} diff --git a/taskman-server/dao/form_template_dao.go b/taskman-server/dao/form_template_dao.go index 47bcb41a..2ea7d5de 100644 --- a/taskman-server/dao/form_template_dao.go +++ b/taskman-server/dao/form_template_dao.go @@ -1,7 +1,32 @@ package dao -import "xorm.io/xorm" +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "xorm.io/xorm" +) type FormTemplateDao struct { DB *xorm.Engine } + +func (d FormTemplateDao) Add(session *xorm.Session, formTemplate *models.FormTemplateTable) (affected int64, err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + return session.InsertOne(formTemplate) +} + +func (d FormTemplateDao) Update(session *xorm.Session, formTemplate *models.FormTemplateTable) (err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + _, err = d.DB.ID(formTemplate.Id).Update(formTemplate) + return +} + +func (d FormTemplateDao) Get(formTemplateId string) (formTemplate *models.FormTemplateTable, err error) { + _, err = d.DB.ID(formTemplateId).Get(&formTemplate) + return +} diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index 3f8c23ad..0d7c3417 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -18,12 +18,16 @@ func (d RequestTemplateDao) Add(session *xorm.Session, requestTemplate *models.R return session.InsertOne(requestTemplate) } -func (d RequestTemplateDao) Update(requestTemplate models.RequestTemplateTable) (err error) { - _, err = d.DB.ID(requestTemplate.Id).Update(&requestTemplate) +func (d RequestTemplateDao) Update(session *xorm.Session, requestTemplate *models.RequestTemplateTable) (err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + _, err = d.DB.ID(requestTemplate.Id).Update(requestTemplate) return } func (d RequestTemplateDao) Get(requestTemplateId string) (requestTemplate *models.RequestTemplateTable, err error) { - _, err = d.DB.ID(requestTemplateId).Get(requestTemplate) + _, err = d.DB.ID(requestTemplateId).Get(&requestTemplate) return } diff --git a/taskman-server/dao/request_template_role_dao.go b/taskman-server/dao/request_template_role_dao.go index d2e9947f..e09069bb 100644 --- a/taskman-server/dao/request_template_role_dao.go +++ b/taskman-server/dao/request_template_role_dao.go @@ -19,5 +19,5 @@ func (d RequestTemplateRoleDao) Add(session *xorm.Session, requestTemplateRole * session = d.DB.NewSession() defer session.Close() } - return session.Insert(requestTemplateRole) + return session.InsertOne(requestTemplateRole) } diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index b5cc0705..5e4dff4b 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -5,7 +5,7 @@ type FormItemTemplateTable struct { Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` ItemGroup string `json:"itemGroup" xorm:"item_group"` - ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义,request 请求信息 + ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` FormTemplate string `json:"formTemplate" xorm:"form_template"` DefaultValue string `json:"defaultValue" xorm:"default_value"` diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index deb9fc52..841875a8 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -37,3 +37,15 @@ type TaskFormItemQueryObj struct { AttrDefDataType string `json:"attrDefDataType" xorm:"attr_def_data_type"` ElementType string `json:"elementType" xorm:"element_type"` } + +func CovertFormTemplateDto2Model(dto FormTemplateDto) *FormTemplateTable { + return &FormTemplateTable{ + Id: dto.Id, + Name: dto.Name, + Description: dto.Description, + CreatedBy: dto.UpdatedBy, + CreatedTime: dto.NowTime, + UpdatedBy: dto.UpdatedBy, + UpdatedTime: dto.NowTime, + } +} diff --git a/taskman-server/models/process_defintions.go b/taskman-server/models/process_defintions.go index 5dfa12e7..e578122f 100644 --- a/taskman-server/models/process_defintions.go +++ b/taskman-server/models/process_defintions.go @@ -103,7 +103,7 @@ type ProcNodeObj struct { ServiceName string `json:"serviceName"` OrderedNo string `json:"orderedNo"` OrderedNum int `json:"-"` - DynamicBind string `json:"dynamicbind"` + DynamicBind bool `json:"dynamicBind"` BoundEntities []*ProcEntity `json:"boundEntities"` } diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index 6ca4ac83..678e3b6f 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -191,7 +191,7 @@ func (s RequestTemplateSort) Less(i, j int) bool { return s[i].UpdatedTime > s[j].UpdatedTime } -func ConvertRequestTemplateUpdateParam2RequestTemplate(param *RequestTemplateUpdateParam) *RequestTemplateTable { +func ConvertRequestTemplateUpdateParam2RequestTemplate(param RequestTemplateUpdateParam) *RequestTemplateTable { nowTime := time.Now().Format(DateTimeFormat) return &RequestTemplateTable{ Id: param.Id, diff --git a/taskman-server/models/response.go b/taskman-server/models/response.go index a76e1ba5..9ed791d1 100644 --- a/taskman-server/models/response.go +++ b/taskman-server/models/response.go @@ -78,7 +78,7 @@ type ProcNodeQueryResponse struct { type ProcDefTaskNodesResponse struct { HttpResponseMeta - Data []*ProcDefNode `json:"data"` + Data []*ProcNodeObj `json:"data"` } type CoreProcessQueryResponse struct { diff --git a/taskman-server/rpc/proc_def_rpc.go b/taskman-server/rpc/proc_def_rpc.go index 9f18f208..4ddcec3b 100644 --- a/taskman-server/rpc/proc_def_rpc.go +++ b/taskman-server/rpc/proc_def_rpc.go @@ -80,9 +80,9 @@ func QueryProcessDefinitionList(userToken, language, manageRole string, param mo } // GetProcessDefineTaskNodes 获取编排节点 -func GetProcessDefineTaskNodes(procDefId, userToken, language string) (list []*models.ProcDefNode, err error) { +func GetProcessDefineTaskNodes(procDefId, userToken, language string) (list []*models.ProcNodeObj, err error) { var response models.ProcDefTaskNodesResponse - list = make([]*models.ProcDefNode, 0) + list = make([]*models.ProcNodeObj, 0) byteArr, err := HttpGet(fmt.Sprintf(BaseUrl+pathQueryProcessDefinitionsTaskNodes, procDefId), userToken, language) if err != nil { return diff --git a/taskman-server/service/form_item_service.go b/taskman-server/service/form_item_service.go new file mode 100644 index 00000000..64d3fbb8 --- /dev/null +++ b/taskman-server/service/form_item_service.go @@ -0,0 +1,7 @@ +package service + +import "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + +type FormItemService struct { + formItemDao dao.FormItemDao +} diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go new file mode 100644 index 00000000..4b641007 --- /dev/null +++ b/taskman-server/service/form_item_template_service.go @@ -0,0 +1,7 @@ +package service + +import "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + +type FormItemTemplateService struct { + formItemTemplateDao dao.FormItemTemplateDao +} diff --git a/taskman-server/service/form_service.go b/taskman-server/service/form_service.go new file mode 100644 index 00000000..6511ac80 --- /dev/null +++ b/taskman-server/service/form_service.go @@ -0,0 +1,7 @@ +package service + +import "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + +type FormService struct { + formDao dao.FormDao +} diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index b3b5c489..c1cf6ac8 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -1,141 +1,175 @@ package service import ( - "fmt" "github.com/WeBankPartners/go-common-lib/guid" - "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "strconv" "time" + "xorm.io/xorm" ) type FormTemplateService struct { - formTemplateDao dao.FormTemplateDao + formTemplateDao dao.FormTemplateDao + formItemTemplateDao dao.FormItemTemplateDao + formDao dao.FormDao } -func GetRequestFormTemplate(id string) (result models.FormTemplateDto, err error) { - result = models.FormTemplateDto{Items: []*models.FormItemTemplateTable{}} - requestTemplate, getErr := GetRequestTemplateService().GetSimpleRequestTemplate(id) - if getErr != nil { - err = getErr - return - } - var formTemplateTable []*models.FormTemplateTable - err = dao.X.SQL("select * from form_template where id=?", requestTemplate.FormTemplate).Find(&formTemplateTable) +func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplateDto models.FormTemplateDto) (newId string, err error) { + newId = guid.CreateGuid() + itemIds := guid.CreateGuidList(len(formTemplateDto.Items)) + formTemplateDto.NowTime = time.Now().Format(models.DateTimeFormat) + formTemplateDto.Id = newId + // 添加模板 + _, err = s.formTemplateDao.Add(session, models.CovertFormTemplateDto2Model(formTemplateDto)) if err != nil { - err = fmt.Errorf("Try to query form template table fail,%s ", err.Error()) return } - if len(formTemplateTable) == 0 { - log.Logger.Warn("Can not find any data in form template", log.String("id", id)) - return + // 添加模板项 + for i, item := range formTemplateDto.Items { + item.Id = itemIds[i] + _, err = s.formItemTemplateDao.Add(session, item) + if err != nil { + return + } } - result.ExpireDay = requestTemplate.ExpireDay - result.Id = formTemplateTable[0].Id - result.Name = formTemplateTable[0].Name - result.Description = formTemplateTable[0].Description - result.UpdatedTime = formTemplateTable[0].UpdatedTime - result.UpdatedBy = formTemplateTable[0].UpdatedBy - var formItemTemplate []*models.FormItemTemplateTable - dao.X.SQL("select * from form_item_template where form_template=?", requestTemplate.FormTemplate).Find(&formItemTemplate) - result.Items = formItemTemplate return } -func CreateRequestFormTemplate(param models.FormTemplateDto, requestTemplateId string) error { - param.NowTime = time.Now().Format(models.DateTimeFormat) - insertFormActions, formId := getFormTemplateCreateActions(param) - insertFormActions = append(insertFormActions, &dao.ExecAction{Sql: "update request_template set form_template=?,expire_day=?,description=? where id=?", Param: []interface{}{formId, param.ExpireDay, param.Description, requestTemplateId}}) - return dao.TransactionWithoutForeignCheck(insertFormActions) -} - -func getFormTemplateCreateActions(param models.FormTemplateDto) (actions []*dao.ExecAction, id string) { - param.Id = guid.CreateGuid() - id = param.Id - itemIds := guid.CreateGuidList(len(param.Items)) - insertAction := dao.ExecAction{Sql: "insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?)"} - insertAction.Param = []interface{}{param.Id, param.Name, param.Description, param.UpdatedBy, param.NowTime, param.UpdatedBy, param.NowTime} - actions = append(actions, &insertAction) - for i, item := range param.Items { - tmpAction := dao.ExecAction{Sql: "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} - tmpAction.Param = []interface{}{itemIds[i], id, item.Name, item.Description, item.ItemGroup, item.ItemGroupName, item.DefaultValue, item.Sort, item.PackageName, item.Entity, item.AttrDefId, item.AttrDefName, item.AttrDefDataType, item.ElementType, item.Title, item.Width, item.RefPackageName, item.RefEntity, item.DataOptions, item.Required, item.Regular, item.IsEdit, item.IsView, item.IsOutput, item.InDisplayName, item.IsRefInside, item.Multiple, item.DefaultClear} - actions = append(actions, &tmpAction) +func (s FormTemplateService) UpdateFormTemplate(session *xorm.Session, formTemplateDto models.FormTemplateDto) (err error) { + var formItemTemplateList []*models.FormItemTemplateTable + formTemplateDto.NowTime = time.Now().Format(models.DateTimeFormat) + newItemGuidList := guid.CreateGuidList(len(formTemplateDto.Items)) + formTemplateTable := &models.FormTemplateTable{ + Id: formTemplateDto.Id, + Name: formTemplateDto.Name, + Description: formTemplateDto.Description, + UpdatedBy: formTemplateDto.UpdatedBy, + UpdatedTime: formTemplateDto.UpdatedTime, } - return -} - -func UpdateRequestFormTemplate(param models.FormTemplateDto) error { - param.NowTime = time.Now().Format(models.DateTimeFormat) - updateActions, err := getFormTemplateUpdateActions(param) + // 更新表单模板 + err = s.formTemplateDao.Update(session, formTemplateTable) if err != nil { - return err - } - updateActions = append(updateActions, &dao.ExecAction{Sql: "update request_template set expire_day=?,description=? where form_template=?", Param: []interface{}{param.ExpireDay, param.Description, param.Id}}) - return dao.Transaction(updateActions) -} - -func getFormTemplateUpdateActions(param models.FormTemplateDto) (actions []*dao.ExecAction, err error) { - var formTemplateTable []*models.FormTemplateTable - err = dao.X.SQL("select id,updated_time from form_template where id=?", param.Id).Find(&formTemplateTable) - if err != nil { - err = fmt.Errorf("Try to query form template table fail,%s ", err.Error()) - return - } - if len(formTemplateTable) == 0 { - err = fmt.Errorf("Can not find any form template with id=%s ", param.Id) return } - if param.UpdatedTime != formTemplateTable[0].UpdatedTime { - err = fmt.Errorf("Update time validate fail,please refersh data ") + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplate(formTemplateDto.Id) + if err != nil { return } - updateAction := dao.ExecAction{Sql: "update form_template set name=?,description=?,updated_by=?,updated_time=? where id=?"} - updateAction.Param = []interface{}{param.Name, param.Description, param.UpdatedBy, param.NowTime, param.Id} - actions = append(actions, &updateAction) - newItemGuidList := guid.CreateGuidList(len(param.Items)) - var formItemTemplate []*models.FormItemTemplateTable - dao.X.SQL("select id from form_item_template where form_template=?", param.Id).Find(&formItemTemplate) - for i, inputItem := range param.Items { - tmpAction := dao.ExecAction{} + // 新增or更新表单项模板 + for i, inputItem := range formTemplateDto.Items { if inputItem.Id == "" { inputItem.Id = newItemGuidList[i] - tmpAction.Sql = "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" - tmpAction.Param = []interface{}{inputItem.Id, param.Id, inputItem.Name, inputItem.Description, inputItem.ItemGroup, inputItem.ItemGroupName, inputItem.DefaultValue, inputItem.Sort, inputItem.PackageName, inputItem.Entity, inputItem.AttrDefId, inputItem.AttrDefName, inputItem.AttrDefDataType, inputItem.ElementType, inputItem.Title, inputItem.Width, inputItem.RefPackageName, inputItem.RefEntity, inputItem.DataOptions, inputItem.Required, inputItem.Regular, inputItem.IsEdit, inputItem.IsView, inputItem.IsOutput, inputItem.InDisplayName, inputItem.IsRefInside, inputItem.Multiple, inputItem.DefaultClear} + _, err = s.formItemTemplateDao.Add(session, inputItem) + if err != nil { + return + } } else { - tmpAction.Sql = "update form_item_template set name=?,description=?,item_group=?,item_group_name=?,default_value=?,sort=?,package_name=?,entity=?,attr_def_id=?,attr_def_name=?,attr_def_data_type=?,element_type=?,title=?,width=?,ref_package_name=?,ref_entity=?,data_options=?,required=?,regular=?,is_edit=?,is_view=?,is_output=?,in_display_name=?,is_ref_inside=?,multiple=?,default_clear=? where id=?" - tmpAction.Param = []interface{}{inputItem.Name, inputItem.Description, inputItem.ItemGroup, inputItem.ItemGroupName, inputItem.DefaultValue, inputItem.Sort, inputItem.PackageName, inputItem.Entity, inputItem.AttrDefId, inputItem.AttrDefName, inputItem.AttrDefDataType, inputItem.ElementType, inputItem.Title, inputItem.Width, inputItem.RefPackageName, inputItem.RefEntity, inputItem.DataOptions, inputItem.Required, inputItem.Regular, inputItem.IsEdit, inputItem.IsView, inputItem.IsOutput, inputItem.InDisplayName, inputItem.IsRefInside, inputItem.Multiple, inputItem.DefaultClear, inputItem.Id} + s.formItemTemplateDao.Update(session, inputItem) } - actions = append(actions, &tmpAction) } - for _, existItem := range formItemTemplate { + // 删除表单项&表单项模板 + for _, formItemTemplate := range formItemTemplateList { existFlag := false - for _, inputItem := range param.Items { - if existItem.Id == inputItem.Id { + for _, inputItem := range formTemplateDto.Items { + if formItemTemplate.Id == inputItem.Id { existFlag = true break } } if !existFlag { - actions = append(actions, &dao.ExecAction{Sql: "delete from form_item where form_item_template=?", Param: []interface{}{existItem.Id}}) - actions = append(actions, &dao.ExecAction{Sql: "delete from form_item_template where id=?", Param: []interface{}{existItem.Id}}) + err = s.formDao.DeleteByFormItemTemplate(session, formItemTemplate.FormTemplate) + if err != nil { + return + } + err = s.formItemTemplateDao.Delete(session, formItemTemplate.Id) } } return } -func DeleteRequestFormTemplate(id string) error { - _, err := dao.X.Exec("update form_template set del_flag=1 where id=?", id) - return err +func (s FormTemplateService) GetRequestFormTemplate(id string) (result models.FormTemplateDto, err error) { + var requestTemplate models.RequestTemplateTable + var formTemplate *models.FormTemplateTable + result = models.FormTemplateDto{Items: []*models.FormItemTemplateTable{}} + requestTemplate, err = GetRequestTemplateService().GetSimpleRequestTemplate(id) + if err != nil { + return + } + formTemplate, err = s.formTemplateDao.Get(requestTemplate.GetFormTemplate()) + if err != nil { + return + } + if formTemplate == nil { + return + } + result.ExpireDay = requestTemplate.ExpireDay + result.Id = formTemplate.Id + result.Name = formTemplate.Name + result.Description = formTemplate.Description + result.UpdatedTime = formTemplate.UpdatedTime + result.UpdatedBy = formTemplate.UpdatedBy + result.Items, err = s.formItemTemplateDao.QueryByFormTemplate(requestTemplate.GetFormTemplate()) + return +} + +func (s FormTemplateService) CreateRequestFormTemplate(formTemplateDto models.FormTemplateDto, requestTemplateId string) (err error) { + var requestTemplate *models.RequestTemplateTable + requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) + if err != nil { + return err + } + // 请求模板的处理不是当前用户,不允许操作 + if requestTemplate.Handler != formTemplateDto.UpdatedBy { + return exterror.New().DataPermissionDeny + } + err = transactionWithoutForeignCheck(func(session *xorm.Session) error { + // 添加表单模板 + formTemplateDto.Id, err = s.AddFormTemplate(session, formTemplateDto) + // 更新模板 + err = GetRequestTemplateService().UpdateFormTemplate(session, requestTemplateId, formTemplateDto.Id, formTemplateDto.Description, formTemplateDto.ExpireDay) + if err != nil { + return err + } + return nil + }) + return } -func buildVersionNum(version string) string { - if version == "" { - return "v1" +func (s FormTemplateService) UpdateRequestFormTemplate(formTemplateDto models.FormTemplateDto, requestTemplateId string) (err error) { + // 需要对当前用户进行校验&操作时间进行校验 + var requestTemplate *models.RequestTemplateTable + var formTemplate *models.FormTemplateTable + requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) + if err != nil { + return err } - tmpV, err := strconv.Atoi(version[1:]) + // 请求模板的处理不是当前用户,不允许操作 + if requestTemplate.Handler != formTemplateDto.UpdatedBy { + return exterror.New().DataPermissionDeny + } + formTemplate, err = s.formTemplateDao.Get(formTemplateDto.Id) if err != nil { - return fmt.Sprintf("v%d", time.Now().Unix()) + return err + } + // 前端传递表单模板更新时间必须和数据库一致才能更新 + if formTemplate.UpdatedTime != formTemplateDto.UpdatedTime { + return exterror.New().DealWithAtTheSameTimeError } - return fmt.Sprintf("v%d", tmpV+1) + err = transaction(func(session *xorm.Session) error { + // 更新表单项模板 + err = s.UpdateFormTemplate(session, formTemplateDto) + // 更新模板 + err = GetRequestTemplateService().UpdateFormTemplate(session, requestTemplateId, formTemplateDto.Id, formTemplateDto.Description, formTemplateDto.ExpireDay) + if err != nil { + return err + } + return nil + }) + return +} + +func (s FormTemplateService) DeleteRequestFormTemplate(id string) error { + _, err := dao.X.Exec("update form_template set del_flag=1 where id=?", id) + return err } diff --git a/taskman-server/service/proc_def_service.go b/taskman-server/service/proc_def_service.go index 9f2e58bc..7466d29f 100644 --- a/taskman-server/service/proc_def_service.go +++ b/taskman-server/service/proc_def_service.go @@ -5,7 +5,6 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/rpc" "sort" - "strconv" ) // 编排任务节点 @@ -89,8 +88,7 @@ func (s ProcDefService) GetProcessDefine(procDefId, userToken, language string) // GetProcessDefineTaskNodes 获取编排节点 func (s ProcDefService) GetProcessDefineTaskNodes(requestTemplate models.RequestTemplateTable, userToken, language, filterType string) (nodeList []*models.ProcNodeObj, err error) { - var dynamicBind = "n" - var allTaskNodeList []*models.ProcDefNode + var allTaskNodeList []*models.ProcNodeObj nodeList = make([]*models.ProcNodeObj, 0) if requestTemplate.ProcDefId == "" { requestTemplate, err = GetRequestTemplateService().GetSimpleRequestTemplate(requestTemplate.Id) @@ -121,23 +119,7 @@ func (s ProcDefService) GetProcessDefineTaskNodes(requestTemplate models.Request continue } } - if node.DynamicBind { - dynamicBind = "y" - } - nodeList = append(nodeList, &models.ProcNodeObj{ - NodeId: node.NodeId, - NodeName: node.Name, - NodeType: node.NodeType, - NodeDefId: node.ProcDefId, - TaskCategory: node.NodeType, - RoutineExp: node.RoutineExpression, - ServiceId: node.ServiceName, - ServiceName: node.ServiceName, - OrderedNo: strconv.Itoa(node.OrderedNo), - OrderedNum: node.OrderedNo, - DynamicBind: dynamicBind, - BoundEntities: nil, - }) + nodeList = append(nodeList, node) } sort.Sort(models.ProcNodeObjList(nodeList)) } diff --git a/taskman-server/service/request_template_group_service.go b/taskman-server/service/request_template_group_service.go new file mode 100644 index 00000000..db0620e6 --- /dev/null +++ b/taskman-server/service/request_template_group_service.go @@ -0,0 +1,7 @@ +package service + +import "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + +type RequestTemplateGroupService struct { + requestTemplateGroupDao dao.RequestTemplateGroupDao +} diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 765f19cb..5fc41a85 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -157,19 +157,24 @@ func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestP return } -func (s RequestTemplateService) UpdateRequestTemplateHandler(requestTemplateId, handler string) (err error) { - return s.requestTemplateDao.Update(models.RequestTemplateTable{Id: requestTemplateId, Handler: handler, UpdatedBy: handler, - UpdatedTime: time.Now().Format(models.DateTimeFormat)}) -} - func (s RequestTemplateService) UpdateRequestTemplateStatus(requestTemplateId, user, status, reason string) (err error) { - requestTemplate := models.RequestTemplateTable{Id: requestTemplateId, Status: status, UpdatedBy: user, + requestTemplate := &models.RequestTemplateTable{Id: requestTemplateId, Status: status, UpdatedBy: user, UpdatedTime: time.Now().Format(models.DateTimeFormat)} // 状态更新到草稿,需要退回 if status == string(models.RequestStatusDraft) { requestTemplate.RollbackDesc = reason } - return s.requestTemplateDao.Update(requestTemplate) + return s.requestTemplateDao.Update(nil, requestTemplate) +} + +func (s RequestTemplateService) UpdateRequestTemplateHandler(requestTemplateId, handler string) (err error) { + return s.requestTemplateDao.Update(nil, &models.RequestTemplateTable{Id: requestTemplateId, Handler: handler, UpdatedBy: handler, + UpdatedTime: time.Now().Format(models.DateTimeFormat)}) +} + +func (s RequestTemplateService) UpdateFormTemplate(session *xorm.Session, requestTemplateId, formTemplate, description string, expireDay int) (err error) { + requestTemplate := &models.RequestTemplateTable{Id: requestTemplateId, FormTemplate: &formTemplate, Description: description, ExpireDay: expireDay} + return s.requestTemplateDao.Update(session, requestTemplate) } func (s RequestTemplateService) GetRequestTemplate(requestTemplateId string) (requestTemplate *models.RequestTemplateTable, err error) { @@ -187,7 +192,7 @@ func (s RequestTemplateService) CheckRequestTemplateRoles(requestTemplateId stri return nil } -func (s RequestTemplateService) CreateRequestTemplate(param *models.RequestTemplateUpdateParam) (result models.RequestTemplateQueryObj, err error) { +func (s RequestTemplateService) CreateRequestTemplate(param models.RequestTemplateUpdateParam) (result models.RequestTemplateQueryObj, err error) { newGuid := guid.CreateGuid() param.Id = newGuid result = models.RequestTemplateQueryObj{RequestTemplateTable: param.RequestTemplateTable, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} @@ -592,10 +597,10 @@ func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*dao.ExecAc } func ListRequestTemplateEntityAttrs(id, userToken, language string) (result []*models.ProcEntity, err error) { + var nodes []*models.ProcNodeObj result = []*models.ProcEntity{} - nodes, getNodesErr := GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: id}, userToken, language, "all") - if getNodesErr != nil { - err = getNodesErr + nodes, err = GetProcDefService().GetProcessDefineTaskNodes(models.RequestTemplateTable{Id: id}, userToken, language, "all") + if err != nil { return } if len(nodes) == 0 { @@ -1601,3 +1606,14 @@ func UpdateRequestTemplateParentIdById(templateId, parentId string) (err error) } return } + +func buildVersionNum(version string) string { + if version == "" { + return "v1" + } + tmpV, err := strconv.Atoi(version[1:]) + if err != nil { + return fmt.Sprintf("v%d", time.Now().Unix()) + } + return fmt.Sprintf("v%d", tmpV+1) +} diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index d4576657..588283b0 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -12,20 +12,32 @@ var ( attachFileService AttachFileService // 模板收藏 service collectTemplateService CollectTemplateService + // 表单 service + formService FormService + // 表单项 service + formItemService FormItemService // 表单模板 service formTemplateService FormTemplateService + // 日志记录 service + operationLogService OperationLogService + // 编排 service + procDefService ProcDefService // CMDB service refSelectService RefSelectService // 请求 service requestService RequestService // 请求模板 service requestTemplateService RequestTemplateService + // 请求模板组 service + requestTemplateGroupService RequestTemplateGroupService // 任务 service taskService TaskService - // 记录 service - operationLogService OperationLogService - // 编排 service - procDefService ProcDefService + // 任务模板 service + taskTemplateService TaskTemplateService + // 任务模板角色 + taskTemplateRoleService TaskTemplateRoleService + // 模板表单项 service + formItemTemplateService FormItemTemplateService ) func New() (err error) { @@ -36,17 +48,37 @@ func New() (err error) { return } // 初始化Dao - requestDao := dao.RequestDao{DB: engine} attachFileDao := dao.AttachFileDao{DB: engine} - requestTemplateDao := dao.RequestTemplateDao{DB: engine} - requestTemplateRoleDao := dao.RequestTemplateRoleDao{DB: engine} + collectTemplateDao := dao.CollectTemplateDao{DB: engine} + formDao := dao.FormDao{DB: engine} + formItemDao := dao.FormItemDao{DB: engine} + formItemTemplateDao := dao.FormItemTemplateDao{DB: engine} operationLogDao := dao.OperationLogDao{DB: engine} + formTemplateDao := dao.FormTemplateDao{DB: engine} + requestDao := dao.RequestDao{DB: engine} + requestTemplateDao := dao.RequestTemplateDao{DB: engine} + requestTemplateGroupDao := dao.RequestTemplateGroupDao{DB: engine} + //requestTemplateRoleDao := dao.RequestTemplateRoleDao{DB: engine} + taskDao := dao.TaskDao{DB: engine} + taskTemplateDao := dao.TaskTemplateDao{DB: engine} + taskTemplateRoleDao := dao.TaskTemplateRoleDao{DB: engine} // 初始化Service + collectTemplateService = CollectTemplateService{collectTemplateDao: collectTemplateDao} requestService = RequestService{requestDao: requestDao} attachFileService = AttachFileService{attachFileDao: attachFileDao} - requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao, requestTemplateRoleDao: requestTemplateRoleDao, operationLogDao: operationLogDao} operationLogService = OperationLogService{operationLogDao: operationLogDao} procDefService = ProcDefService{} + refSelectService = RefSelectService{} + requestService = RequestService{requestDao: requestDao} + taskService = TaskService{taskDao: taskDao} + taskTemplateService = TaskTemplateService{taskTemplateDao: taskTemplateDao} + taskTemplateRoleService = TaskTemplateRoleService{taskTemplateRoleDao: taskTemplateRoleDao} + formService = FormService{formDao: formDao} + requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao} + formItemService = FormItemService{formItemDao: formItemDao} + formItemTemplateService = FormItemTemplateService{formItemTemplateDao: formItemTemplateDao} + requestTemplateGroupService = RequestTemplateGroupService{requestTemplateGroupDao: requestTemplateGroupDao} + formTemplateService = FormTemplateService{formTemplateDao: formTemplateDao, formItemTemplateDao: formItemTemplateDao, formDao: formDao} db = engine return } @@ -71,6 +103,56 @@ func GetProcDefService() ProcDefService { return procDefService } +// GetAttachFileService 文件上传 service +func GetAttachFileService() AttachFileService { + return attachFileService +} + +// GetCollectTemplateService 模板收藏 service +func GetCollectTemplateService() CollectTemplateService { + return collectTemplateService +} + +// GetFormService 表单 service +func GetFormService() FormService { + return formService +} + +// GetFormItemService 表单项 service +func GetFormItemService() FormItemService { + return formItemService +} + +// GetFormTemplateService 表单模板 service +func GetFormTemplateService() FormTemplateService { + return formTemplateService +} + +// GetRefSelectService service +func GetRefSelectService() RefSelectService { + return refSelectService +} + +// GetTaskService 任务 service +func GetTaskService() TaskService { + return taskService +} + +// GetTaskTemplateService 获取任务模板 service +func GetTaskTemplateService() TaskTemplateService { + return taskTemplateService +} + +// GetTaskTemplateRoleService 获取任务模板角色 service +func GetTaskTemplateRoleService() TaskTemplateRoleService { + return taskTemplateRoleService +} + +// GetRequestTemplateGroupService 获取请求模板组 service +func GetRequestTemplateGroupService() RequestTemplateGroupService { + return requestTemplateGroupService +} + // transaction 事务处理 func transaction(f func(session *xorm.Session) error) (err error) { session := db.NewSession() @@ -83,3 +165,18 @@ func transaction(f func(session *xorm.Session) error) (err error) { session.Commit() return } + +// transactionWithoutForeignCheck 事务处理 +func transactionWithoutForeignCheck(f func(session *xorm.Session) error) (err error) { + session := db.NewSession() + defer session.Close() + session.Begin() + session.Exec("SET FOREIGN_KEY_CHECKS=0") + err = f(session) + if err != nil { + session.Rollback() + } + session.Commit() + session.Exec("SET FOREIGN_KEY_CHECKS=1") + return +} diff --git a/taskman-server/service/task_template_role_service.go b/taskman-server/service/task_template_role_service.go new file mode 100644 index 00000000..27388328 --- /dev/null +++ b/taskman-server/service/task_template_role_service.go @@ -0,0 +1,7 @@ +package service + +import "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + +type TaskTemplateRoleService struct { + taskTemplateRoleDao dao.TaskTemplateRoleDao +} diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 293d2928..08547724 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -10,7 +10,7 @@ import ( ) type TaskTemplateService struct { - taskTemplateDao dao.TaskTemplateRoleDao + taskTemplateDao dao.TaskTemplateDao } func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models.TaskTemplateDto, err error) { @@ -62,6 +62,21 @@ func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models return } +func getFormTemplateCreateActions(param models.FormTemplateDto) (actions []*dao.ExecAction, id string) { + param.Id = guid.CreateGuid() + id = param.Id + itemIds := guid.CreateGuidList(len(param.Items)) + insertAction := dao.ExecAction{Sql: "insert into form_template(id,name,description,created_by,created_time,updated_by,updated_time) value (?,?,?,?,?,?,?)"} + insertAction.Param = []interface{}{param.Id, param.Name, param.Description, param.UpdatedBy, param.NowTime, param.UpdatedBy, param.NowTime} + actions = append(actions, &insertAction) + for i, item := range param.Items { + tmpAction := dao.ExecAction{Sql: "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"} + tmpAction.Param = []interface{}{itemIds[i], id, item.Name, item.Description, item.ItemGroup, item.ItemGroupName, item.DefaultValue, item.Sort, item.PackageName, item.Entity, item.AttrDefId, item.AttrDefName, item.AttrDefDataType, item.ElementType, item.Title, item.Width, item.RefPackageName, item.RefEntity, item.DataOptions, item.Required, item.Regular, item.IsEdit, item.IsView, item.IsOutput, item.InDisplayName, item.IsRefInside, item.Multiple, item.DefaultClear} + actions = append(actions, &tmpAction) + } + return +} + func CreateTaskTemplate(param models.TaskTemplateDto, requestTemplateId string) error { _, checkExistErr := getSimpleTaskTemplate("", requestTemplateId, param.NodeDefId, "") if checkExistErr == nil { @@ -103,6 +118,55 @@ func UpdateTaskTemplate(param models.TaskTemplateDto) error { return dao.Transaction(actions) } +func getFormTemplateUpdateActions(param models.FormTemplateDto) (actions []*dao.ExecAction, err error) { + var formTemplateTable []*models.FormTemplateTable + err = dao.X.SQL("select id,updated_time from form_template where id=?", param.Id).Find(&formTemplateTable) + if err != nil { + err = fmt.Errorf("Try to query form template table fail,%s ", err.Error()) + return + } + if len(formTemplateTable) == 0 { + err = fmt.Errorf("Can not find any form template with id=%s ", param.Id) + return + } + if param.UpdatedTime != formTemplateTable[0].UpdatedTime { + err = fmt.Errorf("Update time validate fail,please refersh data ") + return + } + updateAction := dao.ExecAction{Sql: "update form_template set name=?,description=?,updated_by=?,updated_time=? where id=?"} + updateAction.Param = []interface{}{param.Name, param.Description, param.UpdatedBy, param.NowTime, param.Id} + actions = append(actions, &updateAction) + newItemGuidList := guid.CreateGuidList(len(param.Items)) + var formItemTemplate []*models.FormItemTemplateTable + dao.X.SQL("select id from form_item_template where form_template=?", param.Id).Find(&formItemTemplate) + for i, inputItem := range param.Items { + tmpAction := dao.ExecAction{} + if inputItem.Id == "" { + inputItem.Id = newItemGuidList[i] + tmpAction.Sql = "insert into form_item_template(id,form_template,name,description,item_group,item_group_name,default_value,sort,package_name,entity,attr_def_id,attr_def_name,attr_def_data_type,element_type,title,width,ref_package_name,ref_entity,data_options,required,regular,is_edit,is_view,is_output,in_display_name,is_ref_inside,multiple,default_clear) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" + tmpAction.Param = []interface{}{inputItem.Id, param.Id, inputItem.Name, inputItem.Description, inputItem.ItemGroup, inputItem.ItemGroupName, inputItem.DefaultValue, inputItem.Sort, inputItem.PackageName, inputItem.Entity, inputItem.AttrDefId, inputItem.AttrDefName, inputItem.AttrDefDataType, inputItem.ElementType, inputItem.Title, inputItem.Width, inputItem.RefPackageName, inputItem.RefEntity, inputItem.DataOptions, inputItem.Required, inputItem.Regular, inputItem.IsEdit, inputItem.IsView, inputItem.IsOutput, inputItem.InDisplayName, inputItem.IsRefInside, inputItem.Multiple, inputItem.DefaultClear} + } else { + tmpAction.Sql = "update form_item_template set name=?,description=?,item_group=?,item_group_name=?,default_value=?,sort=?,package_name=?,entity=?,attr_def_id=?,attr_def_name=?,attr_def_data_type=?,element_type=?,title=?,width=?,ref_package_name=?,ref_entity=?,data_options=?,required=?,regular=?,is_edit=?,is_view=?,is_output=?,in_display_name=?,is_ref_inside=?,multiple=?,default_clear=? where id=?" + tmpAction.Param = []interface{}{inputItem.Name, inputItem.Description, inputItem.ItemGroup, inputItem.ItemGroupName, inputItem.DefaultValue, inputItem.Sort, inputItem.PackageName, inputItem.Entity, inputItem.AttrDefId, inputItem.AttrDefName, inputItem.AttrDefDataType, inputItem.ElementType, inputItem.Title, inputItem.Width, inputItem.RefPackageName, inputItem.RefEntity, inputItem.DataOptions, inputItem.Required, inputItem.Regular, inputItem.IsEdit, inputItem.IsView, inputItem.IsOutput, inputItem.InDisplayName, inputItem.IsRefInside, inputItem.Multiple, inputItem.DefaultClear, inputItem.Id} + } + actions = append(actions, &tmpAction) + } + for _, existItem := range formItemTemplate { + existFlag := false + for _, inputItem := range param.Items { + if existItem.Id == inputItem.Id { + existFlag = true + break + } + } + if !existFlag { + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item where form_item_template=?", Param: []interface{}{existItem.Id}}) + actions = append(actions, &dao.ExecAction{Sql: "delete from form_item_template where id=?", Param: []interface{}{existItem.Id}}) + } + } + return +} + func getSimpleTaskTemplate(id, requestTemplate, proNodeId, nodeId string) (result models.TaskTemplateTable, err error) { var taskTemplateTable []*models.TaskTemplateTable baseSql := "select * from task_template where 1=1 " From 1fff623de6844a7f0563e7114d7815811689b22c Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 9 Feb 2024 11:40:20 +0800 Subject: [PATCH 010/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E3=80=81=E8=A1=A8=E5=8D=95=E9=A1=B9=E7=9B=AE=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=8B=86=E5=88=86=E5=88=86=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dao/request_template_role_dao.go | 2 +- taskman-server/models/request_template.go | 68 +++++++++---------- taskman-server/service/form_service.go | 3 +- taskman-server/service/service.go | 27 ++------ .../service/task_template_role_service.go | 7 -- .../service/task_template_service.go | 3 +- 6 files changed, 43 insertions(+), 67 deletions(-) delete mode 100644 taskman-server/service/task_template_role_service.go diff --git a/taskman-server/dao/request_template_role_dao.go b/taskman-server/dao/request_template_role_dao.go index e09069bb..59636132 100644 --- a/taskman-server/dao/request_template_role_dao.go +++ b/taskman-server/dao/request_template_role_dao.go @@ -11,7 +11,7 @@ type RequestTemplateRoleDao struct { func (d RequestTemplateRoleDao) CheckRequestTemplateRoles(requestTemplateId string, userRoles []string) (bool, error) { return d.DB.Table(models.RequestTemplateRoleTable{}.TableName()).Where("request_template=?", requestTemplateId).And("role_type=?", - "MGMT").In("role", userRoles).Exist() + models.RolePermissionMGMT).In("role", userRoles).Exist() } func (d RequestTemplateRoleDao) Add(session *xorm.Session, requestTemplateRole *models.RequestTemplateRoleTable) (affected int64, err error) { diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index 678e3b6f..0cd7031b 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -5,40 +5,40 @@ import ( ) type RequestTemplateTable struct { - Id string `json:"id" xorm:"id"` - Group string `json:"group" xorm:"group"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` - FormTemplate *string `json:"formTemplate" xorm:"form_template"` // 此处定义成指针类型原因: request_template表插入数据, - // form_template字段为""也会被插入,又是外键就会报错 - Tags string `json:"tags" xorm:"tags"` - Status string `json:"status" xorm:"status"` - RecordId string `json:"recordId" xorm:"record_id"` - Version string `json:"version" xorm:"version"` - ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` - PackageName string `json:"packageName" xorm:"package_name"` - EntityName string `json:"entityName" xorm:"entity_name"` - ProcDefKey string `json:"procDefKey" xorm:"proc_def_key"` - ProcDefId string `json:"procDefId" xorm:"proc_def_id"` - ProcDefName string `json:"procDefName" xorm:"proc_def_name"` - CreatedBy string `json:"createdBy" xorm:"created_by"` - CreatedTime string `json:"createdTime" xorm:"created_time"` - UpdatedBy string `json:"updatedBy" xorm:"updated_by"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - EntityAttrs string `json:"entityAttrs" xorm:"entity_attrs"` - ExpireDay int `json:"expireDay" xorm:"expire_day"` - Handler string `json:"handler" xorm:"handler"` - DelFlag int `json:"delFlag" xorm:"del_flag"` - Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 - OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 - ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID - ApproveBy string `json:"approveBy" xorm:"approve_by"` // 模板发布审批人 - PendingSwitch bool `json:"pendingSwitch" xorm:"pending_switch"` // 是否加入确认定版流程 - PendingRole string `json:"pendingRole" xorm:"pending_role"` // 定版角色 - PendingHandler string `json:"pendingHandler" xorm:"pending_handler"` // 定版处理人 - ConfirmSwitch bool `json:"confirmSwitch" xorm:"confirm_switch"` // 是否加入确认流程 - ConfirmExpireDay int `json:"confirmExpireDay" xorm:"confirm_expire_day"` // 是否加入确认流程 - RollbackDesc string `json:"rollbackDesc" xorm:"rollback_desc"` // 退回理由 + Id string `json:"id" xorm:"id"` + Group string `json:"group" xorm:"group"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + FormTemplate *string `json:"formTemplate" xorm:"form_template"` // 此处定义成指针类型原因: request_template表插入数据,form_template字段为""也会被插入,又是外键就会报错 + DataFormTemplate *string `json:"dataFormTemplate" xorm:"data_form_template"` + Tags string `json:"tags" xorm:"tags"` + Status string `json:"status" xorm:"status"` + RecordId string `json:"recordId" xorm:"record_id"` + Version string `json:"version" xorm:"version"` + ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` + PackageName string `json:"packageName" xorm:"package_name"` + EntityName string `json:"entityName" xorm:"entity_name"` + ProcDefKey string `json:"procDefKey" xorm:"proc_def_key"` + ProcDefId string `json:"procDefId" xorm:"proc_def_id"` + ProcDefName string `json:"procDefName" xorm:"proc_def_name"` + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + EntityAttrs string `json:"entityAttrs" xorm:"entity_attrs"` + ExpireDay int `json:"expireDay" xorm:"expire_day"` + Handler string `json:"handler" xorm:"handler"` + DelFlag int `json:"delFlag" xorm:"del_flag"` + Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 + OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 + ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID + ApproveBy string `json:"approveBy" xorm:"approve_by"` // 模板发布审批人 + PendingSwitch bool `json:"pendingSwitch" xorm:"pending_switch"` // 是否加入确认定版流程 + PendingRole string `json:"pendingRole" xorm:"pending_role"` // 定版角色 + PendingHandler string `json:"pendingHandler" xorm:"pending_handler"` // 定版处理人 + ConfirmSwitch bool `json:"confirmSwitch" xorm:"confirm_switch"` // 是否加入确认流程 + ConfirmExpireDay int `json:"confirmExpireDay" xorm:"confirm_expire_day"` // 是否加入确认流程 + RollbackDesc string `json:"rollbackDesc" xorm:"rollback_desc"` // 退回理由 } func (RequestTemplateTable) TableName() string { diff --git a/taskman-server/service/form_service.go b/taskman-server/service/form_service.go index 6511ac80..5e75e620 100644 --- a/taskman-server/service/form_service.go +++ b/taskman-server/service/form_service.go @@ -3,5 +3,6 @@ package service import "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" type FormService struct { - formDao dao.FormDao + formDao dao.FormDao + formItemDao dao.FormItemDao } diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index 588283b0..a499a274 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -14,8 +14,6 @@ var ( collectTemplateService CollectTemplateService // 表单 service formService FormService - // 表单项 service - formItemService FormItemService // 表单模板 service formTemplateService FormTemplateService // 日志记录 service @@ -34,10 +32,6 @@ var ( taskService TaskService // 任务模板 service taskTemplateService TaskTemplateService - // 任务模板角色 - taskTemplateRoleService TaskTemplateRoleService - // 模板表单项 service - formItemTemplateService FormItemTemplateService ) func New() (err error) { @@ -58,7 +52,7 @@ func New() (err error) { requestDao := dao.RequestDao{DB: engine} requestTemplateDao := dao.RequestTemplateDao{DB: engine} requestTemplateGroupDao := dao.RequestTemplateGroupDao{DB: engine} - //requestTemplateRoleDao := dao.RequestTemplateRoleDao{DB: engine} + requestTemplateRoleDao := dao.RequestTemplateRoleDao{DB: engine} taskDao := dao.TaskDao{DB: engine} taskTemplateDao := dao.TaskTemplateDao{DB: engine} taskTemplateRoleDao := dao.TaskTemplateRoleDao{DB: engine} @@ -71,12 +65,9 @@ func New() (err error) { refSelectService = RefSelectService{} requestService = RequestService{requestDao: requestDao} taskService = TaskService{taskDao: taskDao} - taskTemplateService = TaskTemplateService{taskTemplateDao: taskTemplateDao} - taskTemplateRoleService = TaskTemplateRoleService{taskTemplateRoleDao: taskTemplateRoleDao} - formService = FormService{formDao: formDao} - requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao} - formItemService = FormItemService{formItemDao: formItemDao} - formItemTemplateService = FormItemTemplateService{formItemTemplateDao: formItemTemplateDao} + taskTemplateService = TaskTemplateService{taskTemplateDao: taskTemplateDao, taskTemplateRoleDao: taskTemplateRoleDao} + formService = FormService{formDao: formDao, formItemDao: formItemDao} + requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao, operationLogDao: operationLogDao, requestTemplateRoleDao: requestTemplateRoleDao} requestTemplateGroupService = RequestTemplateGroupService{requestTemplateGroupDao: requestTemplateGroupDao} formTemplateService = FormTemplateService{formTemplateDao: formTemplateDao, formItemTemplateDao: formItemTemplateDao, formDao: formDao} db = engine @@ -118,11 +109,6 @@ func GetFormService() FormService { return formService } -// GetFormItemService 表单项 service -func GetFormItemService() FormItemService { - return formItemService -} - // GetFormTemplateService 表单模板 service func GetFormTemplateService() FormTemplateService { return formTemplateService @@ -143,11 +129,6 @@ func GetTaskTemplateService() TaskTemplateService { return taskTemplateService } -// GetTaskTemplateRoleService 获取任务模板角色 service -func GetTaskTemplateRoleService() TaskTemplateRoleService { - return taskTemplateRoleService -} - // GetRequestTemplateGroupService 获取请求模板组 service func GetRequestTemplateGroupService() RequestTemplateGroupService { return requestTemplateGroupService diff --git a/taskman-server/service/task_template_role_service.go b/taskman-server/service/task_template_role_service.go deleted file mode 100644 index 27388328..00000000 --- a/taskman-server/service/task_template_role_service.go +++ /dev/null @@ -1,7 +0,0 @@ -package service - -import "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" - -type TaskTemplateRoleService struct { - taskTemplateRoleDao dao.TaskTemplateRoleDao -} diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 08547724..9f5978c6 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -10,7 +10,8 @@ import ( ) type TaskTemplateService struct { - taskTemplateDao dao.TaskTemplateDao + taskTemplateDao dao.TaskTemplateDao + taskTemplateRoleDao dao.TaskTemplateRoleDao } func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models.TaskTemplateDto, err error) { From 4828ce387acc91f89fb2a9c8ece4f4f52e07656b Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 9 Feb 2024 13:08:08 +0800 Subject: [PATCH 011/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E3=80=81=E8=A1=A8=E5=8D=95=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/dao/form_item_templdate_dao.go | 4 +++- taskman-server/dao/form_template_dao.go | 18 ++++++++++++++---- taskman-server/models/request_template.go | 8 +++++++- .../service/form_template_service.go | 4 ++++ 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/taskman-server/dao/form_item_templdate_dao.go b/taskman-server/dao/form_item_templdate_dao.go index 043597dd..6b0440b2 100644 --- a/taskman-server/dao/form_item_templdate_dao.go +++ b/taskman-server/dao/form_item_templdate_dao.go @@ -27,11 +27,13 @@ func (d FormItemTemplateDao) Update(session *xorm.Session, formItemTemplate *mod } func (d FormItemTemplateDao) Get(formItemTemplateId string) (formItemTemplate *models.FormItemTemplateTable, err error) { - _, err = d.DB.ID(formItemTemplateId).Get(&formItemTemplate) + formItemTemplate = &models.FormItemTemplateTable{} + _, err = d.DB.ID(formItemTemplateId).Get(formItemTemplate) return } func (d FormItemTemplateDao) QueryByFormTemplate(formTemplate string) (formItemTemplate []*models.FormItemTemplateTable, err error) { + formItemTemplate = []*models.FormItemTemplateTable{} err = d.DB.Where("form_template = ?", formTemplate).Find(&formItemTemplate) return } diff --git a/taskman-server/dao/form_template_dao.go b/taskman-server/dao/form_template_dao.go index 2ea7d5de..6b5559d5 100644 --- a/taskman-server/dao/form_template_dao.go +++ b/taskman-server/dao/form_template_dao.go @@ -22,11 +22,21 @@ func (d FormTemplateDao) Update(session *xorm.Session, formTemplate *models.Form session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.ID(formTemplate.Id).Update(formTemplate) + _, err = d.DB.Where("id=?", formTemplate.Id).Update(formTemplate) return } -func (d FormTemplateDao) Get(formTemplateId string) (formTemplate *models.FormTemplateTable, err error) { - _, err = d.DB.ID(formTemplateId).Get(&formTemplate) - return +func (d FormTemplateDao) Get(formTemplateId string) (*models.FormTemplateTable, error) { + var formTemplate *models.FormTemplateTable + var found bool + var err error + formTemplate = &models.FormTemplateTable{} + found, err = d.DB.Where("id=?", formTemplateId).Get(formTemplate) + if err != nil { + return nil, err + } + if found { + return formTemplate, nil + } + return nil, nil } diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index 0cd7031b..a83e4c62 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -46,10 +46,16 @@ func (RequestTemplateTable) TableName() string { } func (r RequestTemplateTable) GetFormTemplate() string { + if r.FormTemplate == nil { + return "" + } return *r.FormTemplate } func (r RequestTemplateTable) SetFormTemplate(formTemplate string) { - *r.FormTemplate = formTemplate + if formTemplate == "" { + return + } + r.FormTemplate = &formTemplate } // CollectDataObj 收藏数据项 diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index c1cf6ac8..4e57b1b5 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -1,6 +1,7 @@ package service import ( + "fmt" "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" @@ -152,6 +153,9 @@ func (s FormTemplateService) UpdateRequestFormTemplate(formTemplateDto models.Fo if err != nil { return err } + if formTemplate == nil { + return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param id is invalid")) + } // 前端传递表单模板更新时间必须和数据库一致才能更新 if formTemplate.UpdatedTime != formTemplateDto.UpdatedTime { return exterror.New().DealWithAtTheSameTimeError From 70ab161dea9c98470049998364d25c851e973d10 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 9 Feb 2024 13:17:30 +0800 Subject: [PATCH 012/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E3=80=81=E8=A1=A8=E5=8D=95=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/dao/form_item_templdate_dao.go | 15 ++++++++++++--- taskman-server/dao/request_template_dao.go | 16 +++++++++++++--- taskman-server/service/form_template_service.go | 12 +++++++++--- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/taskman-server/dao/form_item_templdate_dao.go b/taskman-server/dao/form_item_templdate_dao.go index 6b0440b2..a54acf8b 100644 --- a/taskman-server/dao/form_item_templdate_dao.go +++ b/taskman-server/dao/form_item_templdate_dao.go @@ -26,10 +26,19 @@ func (d FormItemTemplateDao) Update(session *xorm.Session, formItemTemplate *mod return } -func (d FormItemTemplateDao) Get(formItemTemplateId string) (formItemTemplate *models.FormItemTemplateTable, err error) { +func (d FormItemTemplateDao) Get(formItemTemplateId string) (*models.FormItemTemplateTable, error) { + var formItemTemplate *models.FormItemTemplateTable + var found bool + var err error formItemTemplate = &models.FormItemTemplateTable{} - _, err = d.DB.ID(formItemTemplateId).Get(formItemTemplate) - return + found, err = d.DB.Where("id=?", formItemTemplateId).Get(formItemTemplate) + if err != nil { + return nil, err + } + if found { + return formItemTemplate, nil + } + return nil, nil } func (d FormItemTemplateDao) QueryByFormTemplate(formTemplate string) (formItemTemplate []*models.FormItemTemplateTable, err error) { diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index 0d7c3417..e1fdcf82 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -27,7 +27,17 @@ func (d RequestTemplateDao) Update(session *xorm.Session, requestTemplate *model return } -func (d RequestTemplateDao) Get(requestTemplateId string) (requestTemplate *models.RequestTemplateTable, err error) { - _, err = d.DB.ID(requestTemplateId).Get(&requestTemplate) - return +func (d RequestTemplateDao) Get(requestTemplateId string) (*models.RequestTemplateTable, error) { + var requestTemplate *models.RequestTemplateTable + var found bool + var err error + requestTemplate = &models.RequestTemplateTable{} + found, err = d.DB.Where("id=?", requestTemplateId).Get(requestTemplate) + if err != nil { + return nil, err + } + if found { + return requestTemplate, nil + } + return nil, nil } diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index 4e57b1b5..f9d16f0c 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -120,6 +120,9 @@ func (s FormTemplateService) CreateRequestFormTemplate(formTemplateDto models.Fo if err != nil { return err } + if requestTemplate == nil { + return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param id is invalid")) + } // 请求模板的处理不是当前用户,不允许操作 if requestTemplate.Handler != formTemplateDto.UpdatedBy { return exterror.New().DataPermissionDeny @@ -143,7 +146,10 @@ func (s FormTemplateService) UpdateRequestFormTemplate(formTemplateDto models.Fo var formTemplate *models.FormTemplateTable requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) if err != nil { - return err + return + } + if requestTemplate == nil { + return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param id is invalid")) } // 请求模板的处理不是当前用户,不允许操作 if requestTemplate.Handler != formTemplateDto.UpdatedBy { @@ -151,10 +157,10 @@ func (s FormTemplateService) UpdateRequestFormTemplate(formTemplateDto models.Fo } formTemplate, err = s.formTemplateDao.Get(formTemplateDto.Id) if err != nil { - return err + return } if formTemplate == nil { - return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param id is invalid")) + return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param form_template_id is invalid")) } // 前端传递表单模板更新时间必须和数据库一致才能更新 if formTemplate.UpdatedTime != formTemplateDto.UpdatedTime { From 9f2e5a4b0e95a5e549e983a3871226c99f9a70e7 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Sat, 10 Feb 2024 04:34:58 +0800 Subject: [PATCH 013/618] =?UTF-8?q?go=20mod=20=E7=89=88=E6=9C=AC=E5=8D=87?= =?UTF-8?q?=E7=BA=A7=E5=88=B0=201.18=20&=20xorm=E7=89=88=E6=9C=AC=E5=8D=87?= =?UTF-8?q?=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/dao/db.go | 6 + ...ldate_dao.go => form_item_template_dao.go} | 2 +- taskman-server/dao/form_template_dao.go | 27 +- taskman-server/dao/request_template_dao.go | 41 +- .../dao/request_template_role_dao.go | 5 +- taskman-server/go.mod | 44 +- taskman-server/go.sum | 512 +- taskman-server/models/approve.go | 2 +- taskman-server/models/attach_file.go | 2 +- taskman-server/models/cmdb.go | 2 +- taskman-server/models/collect_template.go | 2 +- taskman-server/models/form.go | 2 +- taskman-server/models/form_item.go | 2 +- taskman-server/models/form_item_template.go | 2 +- taskman-server/models/form_template.go | 4 +- taskman-server/models/operation_log.go | 2 +- taskman-server/models/request.go | 6 +- taskman-server/models/request_approve_role.go | 2 +- taskman-server/models/request_template.go | 85 +- .../models/request_template_group.go | 2 +- .../models/request_template_role.go | 2 +- taskman-server/models/role.go | 2 +- taskman-server/models/task.go | 4 +- taskman-server/models/task_approve_role.go | 2 +- taskman-server/models/task_template.go | 6 +- taskman-server/models/wecube.go | 2 +- .../service/form_template_service.go | 17 +- .../service/request_template_service.go | 16 +- taskman-server/service/service.go | 10 +- .../go-common-lib/cipher/password.go | 152 - .../go-common-lib/cipher/rsa.go | 103 - .../go-common-lib/file_server/minio.go | 77 - .../WeBankPartners/go-common-lib/guid/rand.go | 37 - .../go-common-lib/logger/zap.go | 60 - .../WeBankPartners/go-common-lib/smtp/auth.go | 110 - .../WeBankPartners/go-common-lib/smtp/func.go | 124 - .../WeBankPartners/go-common-lib/smtp/smtp.go | 430 - .../go-common-lib/token/wecube.go | 225 - .../github.com/dgrijalva/jwt-go/.gitignore | 4 - .../github.com/dgrijalva/jwt-go/.travis.yml | 13 - .../github.com/dgrijalva/jwt-go/LICENSE | 8 - .../dgrijalva/jwt-go/MIGRATION_GUIDE.md | 97 - .../github.com/dgrijalva/jwt-go/README.md | 100 - .../dgrijalva/jwt-go/VERSION_HISTORY.md | 118 - .../github.com/dgrijalva/jwt-go/claims.go | 134 - .../vendor/github.com/dgrijalva/jwt-go/doc.go | 4 - .../github.com/dgrijalva/jwt-go/ecdsa.go | 148 - .../dgrijalva/jwt-go/ecdsa_utils.go | 67 - .../github.com/dgrijalva/jwt-go/errors.go | 59 - .../github.com/dgrijalva/jwt-go/hmac.go | 95 - .../github.com/dgrijalva/jwt-go/map_claims.go | 94 - .../github.com/dgrijalva/jwt-go/none.go | 52 - .../github.com/dgrijalva/jwt-go/parser.go | 148 - .../vendor/github.com/dgrijalva/jwt-go/rsa.go | 101 - .../github.com/dgrijalva/jwt-go/rsa_pss.go | 126 - .../github.com/dgrijalva/jwt-go/rsa_utils.go | 101 - .../dgrijalva/jwt-go/signing_method.go | 35 - .../github.com/dgrijalva/jwt-go/token.go | 108 - .../github.com/dustin/go-humanize/.travis.yml | 21 - .../github.com/dustin/go-humanize/LICENSE | 21 - .../dustin/go-humanize/README.markdown | 124 - .../github.com/dustin/go-humanize/big.go | 31 - .../github.com/dustin/go-humanize/bigbytes.go | 173 - .../github.com/dustin/go-humanize/bytes.go | 143 - .../github.com/dustin/go-humanize/comma.go | 116 - .../github.com/dustin/go-humanize/commaf.go | 40 - .../github.com/dustin/go-humanize/ftoa.go | 46 - .../github.com/dustin/go-humanize/humanize.go | 8 - .../github.com/dustin/go-humanize/number.go | 192 - .../github.com/dustin/go-humanize/ordinals.go | 25 - .../github.com/dustin/go-humanize/si.go | 123 - .../github.com/dustin/go-humanize/times.go | 117 - .../github.com/gin-contrib/sse/.travis.yml | 26 - .../vendor/github.com/gin-contrib/sse/LICENSE | 21 - .../github.com/gin-contrib/sse/README.md | 58 - .../vendor/github.com/gin-contrib/sse/go.mod | 5 - .../vendor/github.com/gin-contrib/sse/go.sum | 7 - .../github.com/gin-contrib/sse/sse-decoder.go | 116 - .../github.com/gin-contrib/sse/sse-encoder.go | 110 - .../github.com/gin-contrib/sse/writer.go | 24 - .../github.com/gin-gonic/gin/.gitignore | 7 - .../github.com/gin-gonic/gin/.travis.yml | 50 - .../github.com/gin-gonic/gin/AUTHORS.md | 233 - .../github.com/gin-gonic/gin/BENCHMARKS.md | 666 - .../github.com/gin-gonic/gin/CHANGELOG.md | 424 - .../gin-gonic/gin/CODE_OF_CONDUCT.md | 46 - .../github.com/gin-gonic/gin/CONTRIBUTING.md | 13 - .../vendor/github.com/gin-gonic/gin/LICENSE | 21 - .../vendor/github.com/gin-gonic/gin/Makefile | 71 - .../vendor/github.com/gin-gonic/gin/README.md | 2217 --- .../vendor/github.com/gin-gonic/gin/auth.go | 91 - .../gin-gonic/gin/binding/binding.go | 118 - .../gin/binding/binding_nomsgpack.go | 112 - .../gin/binding/default_validator.go | 85 - .../github.com/gin-gonic/gin/binding/form.go | 63 - .../gin-gonic/gin/binding/form_mapping.go | 392 - .../gin-gonic/gin/binding/header.go | 34 - .../github.com/gin-gonic/gin/binding/json.go | 56 - .../gin-gonic/gin/binding/msgpack.go | 38 - .../gin/binding/multipart_form_mapping.go | 66 - .../gin-gonic/gin/binding/protobuf.go | 36 - .../github.com/gin-gonic/gin/binding/query.go | 21 - .../github.com/gin-gonic/gin/binding/uri.go | 18 - .../github.com/gin-gonic/gin/binding/xml.go | 33 - .../github.com/gin-gonic/gin/binding/yaml.go | 35 - .../github.com/gin-gonic/gin/codecov.yml | 5 - .../github.com/gin-gonic/gin/context.go | 1178 -- .../gin-gonic/gin/context_appengine.go | 12 - .../vendor/github.com/gin-gonic/gin/debug.go | 103 - .../github.com/gin-gonic/gin/deprecated.go | 21 - .../vendor/github.com/gin-gonic/gin/doc.go | 6 - .../vendor/github.com/gin-gonic/gin/errors.go | 174 - .../vendor/github.com/gin-gonic/gin/fs.go | 45 - .../vendor/github.com/gin-gonic/gin/gin.go | 577 - .../vendor/github.com/gin-gonic/gin/go.mod | 14 - .../vendor/github.com/gin-gonic/gin/go.sum | 52 - .../gin/internal/bytesconv/bytesconv.go | 24 - .../gin-gonic/gin/internal/json/json.go | 23 - .../gin-gonic/gin/internal/json/jsoniter.go | 24 - .../vendor/github.com/gin-gonic/gin/logger.go | 271 - .../vendor/github.com/gin-gonic/gin/mode.go | 92 - .../vendor/github.com/gin-gonic/gin/path.go | 150 - .../github.com/gin-gonic/gin/recovery.go | 171 - .../github.com/gin-gonic/gin/render/data.go | 25 - .../github.com/gin-gonic/gin/render/html.go | 92 - .../github.com/gin-gonic/gin/render/json.go | 193 - .../gin-gonic/gin/render/msgpack.go | 42 - .../gin-gonic/gin/render/protobuf.go | 36 - .../github.com/gin-gonic/gin/render/reader.go | 48 - .../gin-gonic/gin/render/redirect.go | 29 - .../github.com/gin-gonic/gin/render/render.go | 40 - .../github.com/gin-gonic/gin/render/text.go | 41 - .../github.com/gin-gonic/gin/render/xml.go | 28 - .../github.com/gin-gonic/gin/render/yaml.go | 36 - .../gin-gonic/gin/response_writer.go | 126 - .../github.com/gin-gonic/gin/routergroup.go | 230 - .../github.com/gin-gonic/gin/test_helpers.go | 16 - .../vendor/github.com/gin-gonic/gin/tree.go | 831 - .../vendor/github.com/gin-gonic/gin/utils.go | 153 - .../github.com/gin-gonic/gin/version.go | 8 - .../go-playground/locales/.gitignore | 24 - .../go-playground/locales/.travis.yml | 26 - .../github.com/go-playground/locales/LICENSE | 21 - .../go-playground/locales/README.md | 172 - .../locales/currency/currency.go | 308 - .../github.com/go-playground/locales/go.mod | 5 - .../github.com/go-playground/locales/go.sum | 3 - .../github.com/go-playground/locales/logo.png | Bin 37360 -> 0 bytes .../github.com/go-playground/locales/rules.go | 293 - .../universal-translator/.gitignore | 25 - .../universal-translator/.travis.yml | 27 - .../universal-translator/LICENSE | 21 - .../universal-translator/README.md | 89 - .../universal-translator/errors.go | 148 - .../go-playground/universal-translator/go.mod | 5 - .../go-playground/universal-translator/go.sum | 4 - .../universal-translator/import_export.go | 274 - .../universal-translator/logo.png | Bin 16598 -> 0 bytes .../universal-translator/translator.go | 420 - .../universal_translator.go | 113 - .../go-playground/validator/v10/.gitignore | 30 - .../go-playground/validator/v10/.travis.yml | 29 - .../go-playground/validator/v10/LICENSE | 22 - .../go-playground/validator/v10/Makefile | 18 - .../go-playground/validator/v10/README.md | 299 - .../go-playground/validator/v10/baked_in.go | 2285 --- .../go-playground/validator/v10/cache.go | 322 - .../validator/v10/country_codes.go | 162 - .../go-playground/validator/v10/doc.go | 1308 -- .../go-playground/validator/v10/errors.go | 275 - .../validator/v10/field_level.go | 119 - .../go-playground/validator/v10/go.mod | 11 - .../go-playground/validator/v10/go.sum | 28 - .../go-playground/validator/v10/logo.png | Bin 13443 -> 0 bytes .../go-playground/validator/v10/regexes.go | 101 - .../validator/v10/struct_level.go | 175 - .../validator/v10/translations.go | 11 - .../go-playground/validator/v10/util.go | 288 - .../go-playground/validator/v10/validator.go | 477 - .../validator/v10/validator_instance.go | 619 - .../github.com/go-sql-driver/mysql/.gitignore | 9 - .../github.com/go-sql-driver/mysql/AUTHORS | 117 - .../go-sql-driver/mysql/CHANGELOG.md | 232 - .../github.com/go-sql-driver/mysql/LICENSE | 373 - .../github.com/go-sql-driver/mysql/README.md | 520 - .../github.com/go-sql-driver/mysql/auth.go | 425 - .../github.com/go-sql-driver/mysql/buffer.go | 182 - .../go-sql-driver/mysql/collations.go | 265 - .../go-sql-driver/mysql/conncheck.go | 54 - .../go-sql-driver/mysql/conncheck_dummy.go | 17 - .../go-sql-driver/mysql/connection.go | 650 - .../go-sql-driver/mysql/connector.go | 146 - .../github.com/go-sql-driver/mysql/const.go | 174 - .../github.com/go-sql-driver/mysql/driver.go | 107 - .../github.com/go-sql-driver/mysql/dsn.go | 560 - .../github.com/go-sql-driver/mysql/errors.go | 65 - .../github.com/go-sql-driver/mysql/fields.go | 194 - .../github.com/go-sql-driver/mysql/fuzz.go | 24 - .../github.com/go-sql-driver/mysql/go.mod | 3 - .../github.com/go-sql-driver/mysql/infile.go | 182 - .../go-sql-driver/mysql/nulltime.go | 50 - .../go-sql-driver/mysql/nulltime_go113.go | 40 - .../go-sql-driver/mysql/nulltime_legacy.go | 39 - .../github.com/go-sql-driver/mysql/packets.go | 1349 -- .../github.com/go-sql-driver/mysql/result.go | 22 - .../github.com/go-sql-driver/mysql/rows.go | 223 - .../go-sql-driver/mysql/statement.go | 220 - .../go-sql-driver/mysql/transaction.go | 31 - .../github.com/go-sql-driver/mysql/utils.go | 868 - .../github.com/goccy/go-json/.codecov.yml | 32 - .../github.com/goccy/go-json/.gitignore | 2 - .../github.com/goccy/go-json/.golangci.yml | 75 - .../github.com/goccy/go-json/CHANGELOG.md | 236 - .../vendor/github.com/goccy/go-json/LICENSE | 21 - .../vendor/github.com/goccy/go-json/Makefile | 39 - .../vendor/github.com/goccy/go-json/README.md | 529 - .../vendor/github.com/goccy/go-json/color.go | 68 - .../vendor/github.com/goccy/go-json/decode.go | 232 - .../goccy/go-json/docker-compose.yml | 13 - .../vendor/github.com/goccy/go-json/encode.go | 323 - .../vendor/github.com/goccy/go-json/error.go | 39 - .../vendor/github.com/goccy/go-json/go.mod | 3 - .../vendor/github.com/goccy/go-json/go.sum | 0 .../internal/decoder/anonymous_field.go | 37 - .../goccy/go-json/internal/decoder/array.go | 169 - .../goccy/go-json/internal/decoder/bool.go | 78 - .../goccy/go-json/internal/decoder/bytes.go | 177 - .../goccy/go-json/internal/decoder/compile.go | 510 - .../internal/decoder/compile_norace.go | 28 - .../go-json/internal/decoder/compile_race.go | 36 - .../goccy/go-json/internal/decoder/context.go | 254 - .../goccy/go-json/internal/decoder/float.go | 158 - .../goccy/go-json/internal/decoder/func.go | 141 - .../goccy/go-json/internal/decoder/int.go | 242 - .../go-json/internal/decoder/interface.go | 458 - .../goccy/go-json/internal/decoder/map.go | 173 - .../goccy/go-json/internal/decoder/number.go | 108 - .../goccy/go-json/internal/decoder/option.go | 15 - .../goccy/go-json/internal/decoder/ptr.go | 87 - .../goccy/go-json/internal/decoder/slice.go | 294 - .../goccy/go-json/internal/decoder/stream.go | 554 - .../goccy/go-json/internal/decoder/string.go | 361 - .../goccy/go-json/internal/decoder/struct.go | 819 - .../goccy/go-json/internal/decoder/type.go | 29 - .../goccy/go-json/internal/decoder/uint.go | 190 - .../internal/decoder/unmarshal_json.go | 91 - .../internal/decoder/unmarshal_text.go | 280 - .../internal/decoder/wrapped_string.go | 68 - .../goccy/go-json/internal/encoder/compact.go | 286 - .../go-json/internal/encoder/compiler.go | 1569 -- .../internal/encoder/compiler_norace.go | 56 - .../go-json/internal/encoder/compiler_race.go | 65 - .../goccy/go-json/internal/encoder/context.go | 141 - .../goccy/go-json/internal/encoder/encoder.go | 551 - .../goccy/go-json/internal/encoder/indent.go | 211 - .../goccy/go-json/internal/encoder/int.go | 130 - .../goccy/go-json/internal/encoder/map112.go | 8 - .../goccy/go-json/internal/encoder/map113.go | 8 - .../goccy/go-json/internal/encoder/opcode.go | 766 - .../goccy/go-json/internal/encoder/option.go | 41 - .../goccy/go-json/internal/encoder/optype.go | 934 - .../goccy/go-json/internal/encoder/string.go | 640 - .../go-json/internal/encoder/vm/debug_vm.go | 34 - .../goccy/go-json/internal/encoder/vm/hack.go | 9 - .../goccy/go-json/internal/encoder/vm/util.go | 182 - .../goccy/go-json/internal/encoder/vm/vm.go | 5041 ----- .../internal/encoder/vm_color/debug_vm.go | 34 - .../go-json/internal/encoder/vm_color/hack.go | 9 - .../go-json/internal/encoder/vm_color/util.go | 246 - .../go-json/internal/encoder/vm_color/vm.go | 5041 ----- .../encoder/vm_color_indent/debug_vm.go | 34 - .../internal/encoder/vm_color_indent/util.go | 267 - .../internal/encoder/vm_color_indent/vm.go | 5041 ----- .../internal/encoder/vm_indent/debug_vm.go | 34 - .../internal/encoder/vm_indent/hack.go | 9 - .../internal/encoder/vm_indent/util.go | 204 - .../go-json/internal/encoder/vm_indent/vm.go | 5041 ----- .../goccy/go-json/internal/errors/error.go | 157 - .../goccy/go-json/internal/runtime/rtype.go | 263 - .../go-json/internal/runtime/struct_field.go | 87 - .../goccy/go-json/internal/runtime/type.go | 100 - .../vendor/github.com/goccy/go-json/json.go | 366 - .../vendor/github.com/goccy/go-json/option.go | 46 - .../vendor/github.com/golang/protobuf/AUTHORS | 3 - .../github.com/golang/protobuf/CONTRIBUTORS | 3 - .../vendor/github.com/golang/protobuf/LICENSE | 28 - .../github.com/golang/protobuf/proto/clone.go | 253 - .../golang/protobuf/proto/decode.go | 427 - .../golang/protobuf/proto/deprecated.go | 63 - .../golang/protobuf/proto/discard.go | 350 - .../golang/protobuf/proto/encode.go | 203 - .../github.com/golang/protobuf/proto/equal.go | 301 - .../golang/protobuf/proto/extensions.go | 607 - .../github.com/golang/protobuf/proto/lib.go | 965 - .../golang/protobuf/proto/message_set.go | 181 - .../golang/protobuf/proto/pointer_reflect.go | 360 - .../golang/protobuf/proto/pointer_unsafe.go | 313 - .../golang/protobuf/proto/properties.go | 544 - .../golang/protobuf/proto/table_marshal.go | 2776 --- .../golang/protobuf/proto/table_merge.go | 654 - .../golang/protobuf/proto/table_unmarshal.go | 2053 -- .../github.com/golang/protobuf/proto/text.go | 845 - .../golang/protobuf/proto/text_parser.go | 880 - .../github.com/golang/snappy/.gitignore | 16 - .../vendor/github.com/golang/snappy/AUTHORS | 15 - .../github.com/golang/snappy/CONTRIBUTORS | 37 - .../vendor/github.com/golang/snappy/LICENSE | 27 - .../vendor/github.com/golang/snappy/README | 107 - .../vendor/github.com/golang/snappy/decode.go | 237 - .../github.com/golang/snappy/decode_amd64.go | 14 - .../github.com/golang/snappy/decode_amd64.s | 490 - .../github.com/golang/snappy/decode_other.go | 101 - .../vendor/github.com/golang/snappy/encode.go | 285 - .../github.com/golang/snappy/encode_amd64.go | 29 - .../github.com/golang/snappy/encode_amd64.s | 730 - .../github.com/golang/snappy/encode_other.go | 238 - .../vendor/github.com/golang/snappy/snappy.go | 98 - .../vendor/github.com/google/uuid/.travis.yml | 9 - .../github.com/google/uuid/CONTRIBUTING.md | 10 - .../github.com/google/uuid/CONTRIBUTORS | 9 - .../vendor/github.com/google/uuid/LICENSE | 27 - .../vendor/github.com/google/uuid/README.md | 19 - .../vendor/github.com/google/uuid/dce.go | 80 - .../vendor/github.com/google/uuid/doc.go | 12 - .../vendor/github.com/google/uuid/go.mod | 1 - .../vendor/github.com/google/uuid/hash.go | 53 - .../vendor/github.com/google/uuid/marshal.go | 37 - .../vendor/github.com/google/uuid/node.go | 90 - .../vendor/github.com/google/uuid/node_js.go | 12 - .../vendor/github.com/google/uuid/node_net.go | 33 - .../vendor/github.com/google/uuid/sql.go | 59 - .../vendor/github.com/google/uuid/time.go | 123 - .../vendor/github.com/google/uuid/util.go | 43 - .../vendor/github.com/google/uuid/uuid.go | 245 - .../vendor/github.com/google/uuid/version1.go | 44 - .../vendor/github.com/google/uuid/version4.go | 38 - .../github.com/json-iterator/go/.codecov.yml | 3 - .../github.com/json-iterator/go/.gitignore | 4 - .../github.com/json-iterator/go/.travis.yml | 14 - .../github.com/json-iterator/go/Gopkg.lock | 21 - .../github.com/json-iterator/go/Gopkg.toml | 26 - .../github.com/json-iterator/go/LICENSE | 21 - .../github.com/json-iterator/go/README.md | 87 - .../github.com/json-iterator/go/adapter.go | 150 - .../vendor/github.com/json-iterator/go/any.go | 325 - .../github.com/json-iterator/go/any_array.go | 278 - .../github.com/json-iterator/go/any_bool.go | 137 - .../github.com/json-iterator/go/any_float.go | 83 - .../github.com/json-iterator/go/any_int32.go | 74 - .../github.com/json-iterator/go/any_int64.go | 74 - .../json-iterator/go/any_invalid.go | 82 - .../github.com/json-iterator/go/any_nil.go | 69 - .../github.com/json-iterator/go/any_number.go | 123 - .../github.com/json-iterator/go/any_object.go | 374 - .../github.com/json-iterator/go/any_str.go | 166 - .../github.com/json-iterator/go/any_uint32.go | 74 - .../github.com/json-iterator/go/any_uint64.go | 74 - .../github.com/json-iterator/go/build.sh | 12 - .../github.com/json-iterator/go/config.go | 375 - .../go/fuzzy_mode_convert_table.md | 7 - .../vendor/github.com/json-iterator/go/go.mod | 11 - .../vendor/github.com/json-iterator/go/go.sum | 15 - .../github.com/json-iterator/go/iter.go | 349 - .../github.com/json-iterator/go/iter_array.go | 64 - .../github.com/json-iterator/go/iter_float.go | 342 - .../github.com/json-iterator/go/iter_int.go | 346 - .../json-iterator/go/iter_object.go | 267 - .../github.com/json-iterator/go/iter_skip.go | 130 - .../json-iterator/go/iter_skip_sloppy.go | 163 - .../json-iterator/go/iter_skip_strict.go | 99 - .../github.com/json-iterator/go/iter_str.go | 215 - .../github.com/json-iterator/go/jsoniter.go | 18 - .../github.com/json-iterator/go/pool.go | 42 - .../github.com/json-iterator/go/reflect.go | 337 - .../json-iterator/go/reflect_array.go | 104 - .../json-iterator/go/reflect_dynamic.go | 70 - .../json-iterator/go/reflect_extension.go | 483 - .../json-iterator/go/reflect_json_number.go | 112 - .../go/reflect_json_raw_message.go | 76 - .../json-iterator/go/reflect_map.go | 346 - .../json-iterator/go/reflect_marshaler.go | 225 - .../json-iterator/go/reflect_native.go | 453 - .../json-iterator/go/reflect_optional.go | 129 - .../json-iterator/go/reflect_slice.go | 99 - .../go/reflect_struct_decoder.go | 1097 -- .../go/reflect_struct_encoder.go | 211 - .../github.com/json-iterator/go/stream.go | 210 - .../json-iterator/go/stream_float.go | 111 - .../github.com/json-iterator/go/stream_int.go | 190 - .../github.com/json-iterator/go/stream_str.go | 372 - .../github.com/json-iterator/go/test.sh | 12 - .../github.com/klauspost/compress/LICENSE | 292 - .../klauspost/compress/s2/.gitignore | 15 - .../github.com/klauspost/compress/s2/LICENSE | 28 - .../klauspost/compress/s2/README.md | 717 - .../klauspost/compress/s2/decode.go | 565 - .../klauspost/compress/s2/decode_amd64.s | 571 - .../klauspost/compress/s2/decode_arm64.s | 574 - .../klauspost/compress/s2/decode_asm.go | 17 - .../klauspost/compress/s2/decode_other.go | 267 - .../klauspost/compress/s2/encode.go | 1172 -- .../klauspost/compress/s2/encode_all.go | 456 - .../klauspost/compress/s2/encode_amd64.go | 142 - .../klauspost/compress/s2/encode_best.go | 604 - .../klauspost/compress/s2/encode_better.go | 431 - .../klauspost/compress/s2/encode_go.go | 298 - .../compress/s2/encodeblock_amd64.go | 189 - .../klauspost/compress/s2/encodeblock_amd64.s | 15678 ---------------- .../github.com/klauspost/compress/s2/s2.go | 139 - .../github.com/klauspost/cpuid/.gitignore | 24 - .../github.com/klauspost/cpuid/.travis.yml | 46 - .../klauspost/cpuid/CONTRIBUTING.txt | 35 - .../vendor/github.com/klauspost/cpuid/LICENSE | 22 - .../github.com/klauspost/cpuid/README.md | 191 - .../github.com/klauspost/cpuid/cpuid.go | 1504 -- .../github.com/klauspost/cpuid/cpuid_386.s | 42 - .../github.com/klauspost/cpuid/cpuid_amd64.s | 42 - .../github.com/klauspost/cpuid/cpuid_arm64.s | 26 - .../klauspost/cpuid/detect_arm64.go | 219 - .../klauspost/cpuid/detect_intel.go | 33 - .../github.com/klauspost/cpuid/detect_ref.go | 14 - .../vendor/github.com/klauspost/cpuid/go.mod | 3 - .../github.com/leodido/go-urn/.gitignore | 11 - .../github.com/leodido/go-urn/.travis.yml | 18 - .../vendor/github.com/leodido/go-urn/LICENSE | 21 - .../github.com/leodido/go-urn/README.md | 55 - .../vendor/github.com/leodido/go-urn/go.mod | 5 - .../vendor/github.com/leodido/go-urn/go.sum | 11 - .../github.com/leodido/go-urn/machine.go | 1691 -- .../github.com/leodido/go-urn/machine.go.rl | 159 - .../vendor/github.com/leodido/go-urn/makefile | 39 - .../vendor/github.com/leodido/go-urn/urn.go | 63 - .../github.com/mattn/go-isatty/.travis.yml | 14 - .../vendor/github.com/mattn/go-isatty/LICENSE | 9 - .../github.com/mattn/go-isatty/README.md | 50 - .../vendor/github.com/mattn/go-isatty/doc.go | 2 - .../vendor/github.com/mattn/go-isatty/go.mod | 5 - .../vendor/github.com/mattn/go-isatty/go.sum | 2 - .../github.com/mattn/go-isatty/go.test.sh | 12 - .../github.com/mattn/go-isatty/isatty_bsd.go | 18 - .../mattn/go-isatty/isatty_others.go | 15 - .../mattn/go-isatty/isatty_plan9.go | 22 - .../mattn/go-isatty/isatty_solaris.go | 22 - .../mattn/go-isatty/isatty_tcgets.go | 18 - .../mattn/go-isatty/isatty_windows.go | 125 - .../github.com/mattn/go-isatty/renovate.json | 8 - .../vendor/github.com/minio/md5-simd/LICENSE | 202 - .../github.com/minio/md5-simd/README.md | 196 - .../minio/md5-simd/block-generic.go | 132 - .../github.com/minio/md5-simd/block16_amd64.s | 227 - .../github.com/minio/md5-simd/block8_amd64.s | 279 - .../github.com/minio/md5-simd/block_amd64.go | 199 - .../vendor/github.com/minio/md5-simd/go.mod | 7 - .../vendor/github.com/minio/md5-simd/go.sum | 2 - .../minio/md5-simd/md5-digest_amd64.go | 178 - .../minio/md5-simd/md5-server_amd64.go | 307 - .../minio/md5-simd/md5-server_fallback.go | 12 - .../minio/md5-simd/md5-util_amd64.go | 70 - .../vendor/github.com/minio/md5-simd/md5.go | 57 - .../github.com/minio/minio-go/v7/.gitignore | 4 - .../minio/minio-go/v7/.golangci.yml | 16 - .../vendor/github.com/minio/minio-go/v7/CNAME | 1 - .../minio/minio-go/v7/CONTRIBUTING.md | 23 - .../github.com/minio/minio-go/v7/LICENSE | 202 - .../minio/minio-go/v7/MAINTAINERS.md | 35 - .../github.com/minio/minio-go/v7/Makefile | 35 - .../github.com/minio/minio-go/v7/NOTICE | 9 - .../github.com/minio/minio-go/v7/README.md | 251 - .../minio/minio-go/v7/README_zh_CN.md | 260 - .../minio-go/v7/api-bucket-encryption.go | 134 - .../minio/minio-go/v7/api-bucket-lifecycle.go | 147 - .../minio-go/v7/api-bucket-notification.go | 255 - .../minio/minio-go/v7/api-bucket-policy.go | 142 - .../minio-go/v7/api-bucket-replication.go | 259 - .../minio/minio-go/v7/api-bucket-tagging.go | 135 - .../minio-go/v7/api-bucket-versioning.go | 137 - .../minio/minio-go/v7/api-compose-object.go | 592 - .../minio/minio-go/v7/api-copy-object.go | 77 - .../minio/minio-go/v7/api-datatypes.go | 177 - .../minio/minio-go/v7/api-error-response.go | 271 - .../minio/minio-go/v7/api-get-object-acl.go | 151 - .../minio/minio-go/v7/api-get-object-file.go | 127 - .../minio/minio-go/v7/api-get-object.go | 681 - .../minio/minio-go/v7/api-get-options.go | 140 - .../github.com/minio/minio-go/v7/api-list.go | 973 - .../minio-go/v7/api-object-legal-hold.go | 176 - .../minio/minio-go/v7/api-object-lock.go | 241 - .../minio/minio-go/v7/api-object-retention.go | 165 - .../minio/minio-go/v7/api-object-tagging.go | 157 - .../minio/minio-go/v7/api-presigned.go | 216 - .../minio/minio-go/v7/api-put-bucket.go | 123 - .../minio-go/v7/api-put-object-common.go | 150 - .../v7/api-put-object-file-context.go | 64 - .../minio-go/v7/api-put-object-multipart.go | 396 - .../minio-go/v7/api-put-object-streaming.go | 489 - .../minio/minio-go/v7/api-put-object.go | 383 - .../minio-go/v7/api-putobject-snowball.go | 215 - .../minio/minio-go/v7/api-remove.go | 467 - .../minio/minio-go/v7/api-restore.go | 182 - .../minio/minio-go/v7/api-s3-datatypes.go | 361 - .../minio/minio-go/v7/api-select.go | 758 - .../github.com/minio/minio-go/v7/api-stat.go | 127 - .../github.com/minio/minio-go/v7/api.go | 976 - .../minio/minio-go/v7/bucket-cache.go | 253 - .../minio/minio-go/v7/code_of_conduct.md | 80 - .../github.com/minio/minio-go/v7/constants.go | 101 - .../github.com/minio/minio-go/v7/core.go | 133 - .../minio/minio-go/v7/functional_tests.go | 11816 ------------ .../github.com/minio/minio-go/v7/go.mod | 28 - .../github.com/minio/minio-go/v7/go.sum | 79 - .../minio/minio-go/v7/hook-reader.go | 85 - .../v7/pkg/credentials/assume_role.go | 214 - .../minio-go/v7/pkg/credentials/chain.go | 89 - .../v7/pkg/credentials/config.json.sample | 17 - .../v7/pkg/credentials/credentials.go | 192 - .../v7/pkg/credentials/credentials.sample | 12 - .../minio/minio-go/v7/pkg/credentials/doc.go | 62 - .../minio-go/v7/pkg/credentials/env_aws.go | 71 - .../minio-go/v7/pkg/credentials/env_minio.go | 68 - .../pkg/credentials/file_aws_credentials.go | 120 - .../v7/pkg/credentials/file_minio_client.go | 135 - .../minio-go/v7/pkg/credentials/iam_aws.go | 370 - .../v7/pkg/credentials/signature-type.go | 77 - .../minio-go/v7/pkg/credentials/static.go | 67 - .../v7/pkg/credentials/sts-tls-identity.go | 192 - .../v7/pkg/credentials/sts_client_grants.go | 162 - .../v7/pkg/credentials/sts_ldap_identity.go | 188 - .../v7/pkg/credentials/sts_web_identity.go | 186 - .../minio-go/v7/pkg/encrypt/server-side.go | 198 - .../minio-go/v7/pkg/lifecycle/lifecycle.go | 451 - .../minio-go/v7/pkg/notification/info.go | 78 - .../v7/pkg/notification/notification.go | 395 - .../v7/pkg/replication/replication.go | 731 - .../minio/minio-go/v7/pkg/s3utils/utils.go | 392 - .../minio/minio-go/v7/pkg/set/stringset.go | 200 - .../pkg/signer/request-signature-streaming.go | 306 - .../v7/pkg/signer/request-signature-v2.go | 317 - .../v7/pkg/signer/request-signature-v4.go | 318 - .../minio/minio-go/v7/pkg/signer/utils.go | 59 - .../minio/minio-go/v7/pkg/sse/sse.go | 66 - .../minio/minio-go/v7/pkg/tags/tags.go | 341 - .../minio/minio-go/v7/post-policy.go | 327 - .../minio/minio-go/v7/retry-continous.go | 69 - .../github.com/minio/minio-go/v7/retry.go | 124 - .../minio/minio-go/v7/s3-endpoints.go | 57 - .../github.com/minio/minio-go/v7/s3-error.go | 61 - .../github.com/minio/minio-go/v7/transport.go | 83 - .../github.com/minio/minio-go/v7/utils.go | 630 - .../github.com/minio/sha256-simd/.gitignore | 1 - .../github.com/minio/sha256-simd/.travis.yml | 25 - .../github.com/minio/sha256-simd/LICENSE | 202 - .../github.com/minio/sha256-simd/README.md | 133 - .../github.com/minio/sha256-simd/appveyor.yml | 32 - .../github.com/minio/sha256-simd/cpuid.go | 119 - .../github.com/minio/sha256-simd/cpuid_386.go | 24 - .../github.com/minio/sha256-simd/cpuid_386.s | 53 - .../minio/sha256-simd/cpuid_amd64.go | 24 - .../minio/sha256-simd/cpuid_amd64.s | 53 - .../github.com/minio/sha256-simd/cpuid_arm.go | 32 - .../minio/sha256-simd/cpuid_linux_arm64.go | 49 - .../minio/sha256-simd/cpuid_other.go | 34 - .../github.com/minio/sha256-simd/go.mod | 3 - .../github.com/minio/sha256-simd/sha256.go | 409 - .../sha256-simd/sha256blockAvx2_amd64.go | 22 - .../minio/sha256-simd/sha256blockAvx2_amd64.s | 1449 -- .../sha256-simd/sha256blockAvx512_amd64.asm | 686 - .../sha256-simd/sha256blockAvx512_amd64.go | 500 - .../sha256-simd/sha256blockAvx512_amd64.s | 267 - .../minio/sha256-simd/sha256blockAvx_amd64.go | 22 - .../minio/sha256-simd/sha256blockAvx_amd64.s | 408 - .../minio/sha256-simd/sha256blockSha_amd64.go | 6 - .../minio/sha256-simd/sha256blockSha_amd64.s | 266 - .../sha256-simd/sha256blockSsse_amd64.go | 22 - .../minio/sha256-simd/sha256blockSsse_amd64.s | 429 - .../minio/sha256-simd/sha256block_amd64.go | 53 - .../minio/sha256-simd/sha256block_arm64.go | 37 - .../minio/sha256-simd/sha256block_arm64.s | 192 - .../minio/sha256-simd/sha256block_other.go | 25 - .../minio/sha256-simd/test-architectures.sh | 15 - .../github.com/mitchellh/go-homedir/LICENSE | 21 - .../github.com/mitchellh/go-homedir/README.md | 14 - .../github.com/mitchellh/go-homedir/go.mod | 1 - .../mitchellh/go-homedir/homedir.go | 167 - .../modern-go/concurrent/.gitignore | 1 - .../modern-go/concurrent/.travis.yml | 14 - .../github.com/modern-go/concurrent/LICENSE | 201 - .../github.com/modern-go/concurrent/README.md | 49 - .../modern-go/concurrent/executor.go | 14 - .../modern-go/concurrent/go_above_19.go | 15 - .../modern-go/concurrent/go_below_19.go | 33 - .../github.com/modern-go/concurrent/log.go | 13 - .../github.com/modern-go/concurrent/test.sh | 12 - .../concurrent/unbounded_executor.go | 119 - .../github.com/modern-go/reflect2/.gitignore | 2 - .../github.com/modern-go/reflect2/.travis.yml | 15 - .../github.com/modern-go/reflect2/Gopkg.lock | 15 - .../github.com/modern-go/reflect2/Gopkg.toml | 35 - .../github.com/modern-go/reflect2/LICENSE | 201 - .../github.com/modern-go/reflect2/README.md | 71 - .../modern-go/reflect2/go_above_17.go | 8 - .../modern-go/reflect2/go_above_19.go | 14 - .../modern-go/reflect2/go_below_17.go | 9 - .../modern-go/reflect2/go_below_19.go | 14 - .../github.com/modern-go/reflect2/reflect2.go | 298 - .../modern-go/reflect2/reflect2_amd64.s | 0 .../modern-go/reflect2/reflect2_kind.go | 30 - .../modern-go/reflect2/relfect2_386.s | 0 .../modern-go/reflect2/relfect2_amd64p32.s | 0 .../modern-go/reflect2/relfect2_arm.s | 0 .../modern-go/reflect2/relfect2_arm64.s | 0 .../modern-go/reflect2/relfect2_mips64x.s | 0 .../modern-go/reflect2/relfect2_mipsx.s | 0 .../modern-go/reflect2/relfect2_ppc64x.s | 0 .../modern-go/reflect2/relfect2_s390x.s | 0 .../modern-go/reflect2/safe_field.go | 58 - .../github.com/modern-go/reflect2/safe_map.go | 101 - .../modern-go/reflect2/safe_slice.go | 92 - .../modern-go/reflect2/safe_struct.go | 29 - .../modern-go/reflect2/safe_type.go | 78 - .../github.com/modern-go/reflect2/test.sh | 12 - .../github.com/modern-go/reflect2/type_map.go | 113 - .../modern-go/reflect2/unsafe_array.go | 65 - .../modern-go/reflect2/unsafe_eface.go | 59 - .../modern-go/reflect2/unsafe_field.go | 74 - .../modern-go/reflect2/unsafe_iface.go | 64 - .../modern-go/reflect2/unsafe_link.go | 70 - .../modern-go/reflect2/unsafe_map.go | 138 - .../modern-go/reflect2/unsafe_ptr.go | 46 - .../modern-go/reflect2/unsafe_slice.go | 177 - .../modern-go/reflect2/unsafe_struct.go | 59 - .../modern-go/reflect2/unsafe_type.go | 85 - .../vendor/github.com/rs/xid/.appveyor.yml | 27 - .../vendor/github.com/rs/xid/.travis.yml | 8 - .../vendor/github.com/rs/xid/LICENSE | 19 - .../vendor/github.com/rs/xid/README.md | 112 - .../vendor/github.com/rs/xid/go.mod | 1 - .../vendor/github.com/rs/xid/hostid_darwin.go | 9 - .../github.com/rs/xid/hostid_fallback.go | 9 - .../github.com/rs/xid/hostid_freebsd.go | 9 - .../vendor/github.com/rs/xid/hostid_linux.go | 10 - .../github.com/rs/xid/hostid_windows.go | 38 - taskman-server/vendor/github.com/rs/xid/id.go | 365 - .../github.com/sirupsen/logrus/.gitignore | 4 - .../github.com/sirupsen/logrus/.golangci.yml | 40 - .../github.com/sirupsen/logrus/.travis.yml | 15 - .../github.com/sirupsen/logrus/CHANGELOG.md | 259 - .../vendor/github.com/sirupsen/logrus/LICENSE | 21 - .../github.com/sirupsen/logrus/README.md | 513 - .../github.com/sirupsen/logrus/alt_exit.go | 76 - .../github.com/sirupsen/logrus/appveyor.yml | 14 - .../github.com/sirupsen/logrus/buffer_pool.go | 52 - .../vendor/github.com/sirupsen/logrus/doc.go | 26 - .../github.com/sirupsen/logrus/entry.go | 431 - .../github.com/sirupsen/logrus/exported.go | 270 - .../github.com/sirupsen/logrus/formatter.go | 78 - .../vendor/github.com/sirupsen/logrus/go.mod | 10 - .../vendor/github.com/sirupsen/logrus/go.sum | 8 - .../github.com/sirupsen/logrus/hooks.go | 34 - .../sirupsen/logrus/json_formatter.go | 128 - .../github.com/sirupsen/logrus/logger.go | 404 - .../github.com/sirupsen/logrus/logrus.go | 186 - .../logrus/terminal_check_appengine.go | 11 - .../sirupsen/logrus/terminal_check_bsd.go | 13 - .../sirupsen/logrus/terminal_check_js.go | 7 - .../logrus/terminal_check_no_terminal.go | 11 - .../logrus/terminal_check_notappengine.go | 17 - .../sirupsen/logrus/terminal_check_solaris.go | 11 - .../sirupsen/logrus/terminal_check_unix.go | 13 - .../sirupsen/logrus/terminal_check_windows.go | 27 - .../sirupsen/logrus/text_formatter.go | 339 - .../github.com/sirupsen/logrus/writer.go | 70 - .../github.com/syndtr/goleveldb/LICENSE | 24 - .../syndtr/goleveldb/leveldb/batch.go | 349 - .../syndtr/goleveldb/leveldb/cache/cache.go | 704 - .../syndtr/goleveldb/leveldb/cache/lru.go | 195 - .../syndtr/goleveldb/leveldb/comparer.go | 67 - .../leveldb/comparer/bytes_comparer.go | 51 - .../goleveldb/leveldb/comparer/comparer.go | 57 - .../github.com/syndtr/goleveldb/leveldb/db.go | 1179 -- .../syndtr/goleveldb/leveldb/db_compaction.go | 854 - .../syndtr/goleveldb/leveldb/db_iter.go | 360 - .../syndtr/goleveldb/leveldb/db_snapshot.go | 187 - .../syndtr/goleveldb/leveldb/db_state.go | 239 - .../goleveldb/leveldb/db_transaction.go | 329 - .../syndtr/goleveldb/leveldb/db_util.go | 102 - .../syndtr/goleveldb/leveldb/db_write.go | 464 - .../syndtr/goleveldb/leveldb/doc.go | 92 - .../syndtr/goleveldb/leveldb/errors.go | 20 - .../syndtr/goleveldb/leveldb/errors/errors.go | 78 - .../syndtr/goleveldb/leveldb/filter.go | 31 - .../syndtr/goleveldb/leveldb/filter/bloom.go | 116 - .../syndtr/goleveldb/leveldb/filter/filter.go | 60 - .../goleveldb/leveldb/iterator/array_iter.go | 184 - .../leveldb/iterator/indexed_iter.go | 242 - .../syndtr/goleveldb/leveldb/iterator/iter.go | 132 - .../goleveldb/leveldb/iterator/merged_iter.go | 304 - .../goleveldb/leveldb/journal/journal.go | 524 - .../syndtr/goleveldb/leveldb/key.go | 143 - .../syndtr/goleveldb/leveldb/memdb/memdb.go | 479 - .../syndtr/goleveldb/leveldb/opt/options.go | 697 - .../syndtr/goleveldb/leveldb/options.go | 107 - .../syndtr/goleveldb/leveldb/session.go | 210 - .../goleveldb/leveldb/session_compaction.go | 302 - .../goleveldb/leveldb/session_record.go | 323 - .../syndtr/goleveldb/leveldb/session_util.go | 271 - .../syndtr/goleveldb/leveldb/storage.go | 63 - .../goleveldb/leveldb/storage/file_storage.go | 671 - .../leveldb/storage/file_storage_nacl.go | 34 - .../leveldb/storage/file_storage_plan9.go | 63 - .../leveldb/storage/file_storage_solaris.go | 81 - .../leveldb/storage/file_storage_unix.go | 98 - .../leveldb/storage/file_storage_windows.go | 78 - .../goleveldb/leveldb/storage/mem_storage.go | 222 - .../goleveldb/leveldb/storage/storage.go | 187 - .../syndtr/goleveldb/leveldb/table.go | 531 - .../syndtr/goleveldb/leveldb/table/reader.go | 1139 -- .../syndtr/goleveldb/leveldb/table/table.go | 177 - .../syndtr/goleveldb/leveldb/table/writer.go | 375 - .../syndtr/goleveldb/leveldb/util.go | 98 - .../syndtr/goleveldb/leveldb/util/buffer.go | 293 - .../goleveldb/leveldb/util/buffer_pool.go | 239 - .../syndtr/goleveldb/leveldb/util/crc32.go | 30 - .../syndtr/goleveldb/leveldb/util/hash.go | 48 - .../syndtr/goleveldb/leveldb/util/range.go | 32 - .../syndtr/goleveldb/leveldb/util/util.go | 73 - .../syndtr/goleveldb/leveldb/version.go | 528 - .../vendor/github.com/tealeg/xlsx/.gitignore | 6 - .../vendor/github.com/tealeg/xlsx/.travis.yml | 14 - .../vendor/github.com/tealeg/xlsx/AUTHORS.txt | 54 - .../github.com/tealeg/xlsx/CODE_OF_CONDUCT.md | 46 - .../vendor/github.com/tealeg/xlsx/LICENSE | 29 - .../vendor/github.com/tealeg/xlsx/README.org | 102 - .../vendor/github.com/tealeg/xlsx/cell.go | 418 - .../vendor/github.com/tealeg/xlsx/col.go | 121 - .../github.com/tealeg/xlsx/data_validation.go | 189 - .../vendor/github.com/tealeg/xlsx/date.go | 147 - .../vendor/github.com/tealeg/xlsx/doc.go | 11 - .../vendor/github.com/tealeg/xlsx/file.go | 414 - .../github.com/tealeg/xlsx/format_code.go | 644 - .../vendor/github.com/tealeg/xlsx/go.mod | 8 - .../vendor/github.com/tealeg/xlsx/go.sum | 7 - .../vendor/github.com/tealeg/xlsx/hsl.go | 145 - .../vendor/github.com/tealeg/xlsx/lib.go | 1131 -- .../vendor/github.com/tealeg/xlsx/read.go | 132 - .../vendor/github.com/tealeg/xlsx/reftable.go | 77 - .../vendor/github.com/tealeg/xlsx/row.go | 27 - .../vendor/github.com/tealeg/xlsx/sheet.go | 454 - .../github.com/tealeg/xlsx/stream_cell.go | 51 - .../github.com/tealeg/xlsx/stream_file.go | 400 - .../tealeg/xlsx/stream_file_builder.go | 417 - .../github.com/tealeg/xlsx/stream_style.go | 130 - .../vendor/github.com/tealeg/xlsx/style.go | 203 - .../github.com/tealeg/xlsx/templates.go | 339 - .../vendor/github.com/tealeg/xlsx/theme.go | 47 - .../vendor/github.com/tealeg/xlsx/write.go | 153 - .../github.com/tealeg/xlsx/xmlContentTypes.go | 50 - .../tealeg/xlsx/xmlSharedStrings.go | 32 - .../vendor/github.com/tealeg/xlsx/xmlStyle.go | 959 - .../vendor/github.com/tealeg/xlsx/xmlTheme.go | 55 - .../github.com/tealeg/xlsx/xmlWorkbook.go | 213 - .../github.com/tealeg/xlsx/xmlWorksheet.go | 422 - .../ugorji/go/codec/0_importpath.go | 7 - .../vendor/github.com/ugorji/go/codec/LICENSE | 22 - .../vendor/github.com/ugorji/go/codec/binc.go | 1219 -- .../github.com/ugorji/go/codec/build.sh | 272 - .../vendor/github.com/ugorji/go/codec/cbor.go | 846 - .../github.com/ugorji/go/codec/codecgen.go | 13 - .../github.com/ugorji/go/codec/decode.go | 2034 -- .../vendor/github.com/ugorji/go/codec/doc.go | 226 - .../github.com/ugorji/go/codec/encode.go | 1373 -- .../ugorji/go/codec/fast-path.generated.go | 8950 --------- .../ugorji/go/codec/fast-path.go.tmpl | 503 - .../ugorji/go/codec/fast-path.not.go | 41 - .../github.com/ugorji/go/codec/float.go | 313 - .../ugorji/go/codec/gen-dec-array.go.tmpl | 90 - .../ugorji/go/codec/gen-dec-map.go.tmpl | 53 - .../ugorji/go/codec/gen-enc-chan.go.tmpl | 27 - .../ugorji/go/codec/gen-helper.generated.go | 273 - .../ugorji/go/codec/gen-helper.go.tmpl | 241 - .../ugorji/go/codec/gen.generated.go | 187 - .../vendor/github.com/ugorji/go/codec/gen.go | 2339 --- .../vendor/github.com/ugorji/go/codec/go.mod | 5 - .../go/codec/goversion_arrayof_gte_go15.go | 14 - .../go/codec/goversion_arrayof_lt_go15.go | 14 - .../go/codec/goversion_fmt_time_gte_go15.go | 12 - .../go/codec/goversion_fmt_time_lt_go15.go | 15 - .../go/codec/goversion_makemap_gte_go19.go | 15 - .../go/codec/goversion_makemap_lt_go19.go | 12 - .../go/codec/goversion_maprange_gte_go112.go | 44 - .../go/codec/goversion_maprange_lt_go112.go | 47 - ...version_unexportedembeddedptr_gte_go110.go | 8 - ...oversion_unexportedembeddedptr_lt_go110.go | 8 - .../go/codec/goversion_unsupported_lt_go14.go | 17 - .../go/codec/goversion_vendor_eq_go15.go | 10 - .../go/codec/goversion_vendor_eq_go16.go | 10 - .../go/codec/goversion_vendor_gte_go17.go | 8 - .../go/codec/goversion_vendor_lt_go15.go | 8 - .../github.com/ugorji/go/codec/helper.go | 2682 --- .../github.com/ugorji/go/codec/helper.s | 0 .../ugorji/go/codec/helper_internal.go | 124 - .../ugorji/go/codec/helper_not_unsafe.go | 409 - .../ugorji/go/codec/helper_unsafe.go | 867 - .../vendor/github.com/ugorji/go/codec/json.go | 1493 -- .../ugorji/go/codec/mammoth-test.go.tmpl | 162 - .../ugorji/go/codec/mammoth2-test.go.tmpl | 94 - .../github.com/ugorji/go/codec/msgpack.go | 1108 -- .../github.com/ugorji/go/codec/prebuild.go | 136 - .../github.com/ugorji/go/codec/reader.go | 1017 - .../ugorji/go/codec/register_ext.go | 38 - .../vendor/github.com/ugorji/go/codec/rpc.go | 222 - .../github.com/ugorji/go/codec/simple.go | 647 - .../ugorji/go/codec/sort-slice.generated.go | 266 - .../ugorji/go/codec/sort-slice.go.tmpl | 64 - .../ugorji/go/codec/test-cbor-goldens.json | 639 - .../vendor/github.com/ugorji/go/codec/test.py | 126 - .../github.com/ugorji/go/codec/writer.go | 267 - .../vendor/go.uber.org/atomic/.codecov.yml | 19 - .../vendor/go.uber.org/atomic/.gitignore | 12 - .../vendor/go.uber.org/atomic/.travis.yml | 27 - .../vendor/go.uber.org/atomic/CHANGELOG.md | 76 - .../vendor/go.uber.org/atomic/LICENSE.txt | 19 - .../vendor/go.uber.org/atomic/Makefile | 78 - .../vendor/go.uber.org/atomic/README.md | 63 - .../vendor/go.uber.org/atomic/bool.go | 81 - .../vendor/go.uber.org/atomic/bool_ext.go | 53 - .../vendor/go.uber.org/atomic/doc.go | 23 - .../vendor/go.uber.org/atomic/duration.go | 82 - .../vendor/go.uber.org/atomic/duration_ext.go | 40 - .../vendor/go.uber.org/atomic/error.go | 51 - .../vendor/go.uber.org/atomic/error_ext.go | 39 - .../vendor/go.uber.org/atomic/float64.go | 76 - .../vendor/go.uber.org/atomic/float64_ext.go | 47 - .../vendor/go.uber.org/atomic/gen.go | 26 - .../vendor/go.uber.org/atomic/go.mod | 8 - .../vendor/go.uber.org/atomic/go.sum | 9 - .../vendor/go.uber.org/atomic/int32.go | 102 - .../vendor/go.uber.org/atomic/int64.go | 102 - .../vendor/go.uber.org/atomic/nocmp.go | 35 - .../vendor/go.uber.org/atomic/string.go | 54 - .../vendor/go.uber.org/atomic/string_ext.go | 43 - .../vendor/go.uber.org/atomic/uint32.go | 102 - .../vendor/go.uber.org/atomic/uint64.go | 102 - .../vendor/go.uber.org/atomic/value.go | 31 - .../vendor/go.uber.org/multierr/.codecov.yml | 15 - .../vendor/go.uber.org/multierr/.gitignore | 4 - .../vendor/go.uber.org/multierr/.travis.yml | 23 - .../vendor/go.uber.org/multierr/CHANGELOG.md | 60 - .../vendor/go.uber.org/multierr/LICENSE.txt | 19 - .../vendor/go.uber.org/multierr/Makefile | 42 - .../vendor/go.uber.org/multierr/README.md | 23 - .../vendor/go.uber.org/multierr/error.go | 449 - .../vendor/go.uber.org/multierr/glide.yaml | 8 - .../vendor/go.uber.org/multierr/go.mod | 8 - .../vendor/go.uber.org/multierr/go.sum | 11 - .../vendor/go.uber.org/multierr/go113.go | 52 - .../vendor/go.uber.org/zap/.codecov.yml | 17 - .../vendor/go.uber.org/zap/.gitignore | 32 - .../vendor/go.uber.org/zap/.readme.tmpl | 109 - .../vendor/go.uber.org/zap/CHANGELOG.md | 504 - .../vendor/go.uber.org/zap/CODE_OF_CONDUCT.md | 75 - .../vendor/go.uber.org/zap/CONTRIBUTING.md | 75 - taskman-server/vendor/go.uber.org/zap/FAQ.md | 164 - .../vendor/go.uber.org/zap/LICENSE.txt | 19 - .../vendor/go.uber.org/zap/Makefile | 73 - .../vendor/go.uber.org/zap/README.md | 134 - .../vendor/go.uber.org/zap/array.go | 320 - .../vendor/go.uber.org/zap/buffer/buffer.go | 141 - .../vendor/go.uber.org/zap/buffer/pool.go | 49 - .../vendor/go.uber.org/zap/checklicense.sh | 17 - .../vendor/go.uber.org/zap/config.go | 264 - taskman-server/vendor/go.uber.org/zap/doc.go | 113 - .../vendor/go.uber.org/zap/encoder.go | 79 - .../vendor/go.uber.org/zap/error.go | 80 - .../vendor/go.uber.org/zap/field.go | 549 - taskman-server/vendor/go.uber.org/zap/flag.go | 39 - .../vendor/go.uber.org/zap/glide.yaml | 34 - .../vendor/go.uber.org/zap/global.go | 168 - .../vendor/go.uber.org/zap/global_go112.go | 26 - .../vendor/go.uber.org/zap/global_prego112.go | 26 - taskman-server/vendor/go.uber.org/zap/go.mod | 14 - taskman-server/vendor/go.uber.org/zap/go.sum | 46 - .../vendor/go.uber.org/zap/http_handler.go | 132 - .../zap/internal/bufferpool/bufferpool.go | 31 - .../go.uber.org/zap/internal/color/color.go | 44 - .../go.uber.org/zap/internal/exit/exit.go | 64 - .../vendor/go.uber.org/zap/level.go | 132 - .../vendor/go.uber.org/zap/logger.go | 348 - .../vendor/go.uber.org/zap/options.go | 148 - taskman-server/vendor/go.uber.org/zap/sink.go | 161 - .../vendor/go.uber.org/zap/stacktrace.go | 85 - .../vendor/go.uber.org/zap/sugar.go | 315 - taskman-server/vendor/go.uber.org/zap/time.go | 27 - .../vendor/go.uber.org/zap/writer.go | 99 - .../zap/zapcore/buffered_write_syncer.go | 188 - .../vendor/go.uber.org/zap/zapcore/clock.go | 50 - .../zap/zapcore/console_encoder.go | 161 - .../vendor/go.uber.org/zap/zapcore/core.go | 113 - .../vendor/go.uber.org/zap/zapcore/doc.go | 24 - .../vendor/go.uber.org/zap/zapcore/encoder.go | 443 - .../vendor/go.uber.org/zap/zapcore/entry.go | 262 - .../vendor/go.uber.org/zap/zapcore/error.go | 132 - .../vendor/go.uber.org/zap/zapcore/field.go | 233 - .../vendor/go.uber.org/zap/zapcore/hook.go | 68 - .../go.uber.org/zap/zapcore/increase_level.go | 66 - .../go.uber.org/zap/zapcore/json_encoder.go | 534 - .../vendor/go.uber.org/zap/zapcore/level.go | 175 - .../go.uber.org/zap/zapcore/level_strings.go | 46 - .../go.uber.org/zap/zapcore/marshaler.go | 61 - .../go.uber.org/zap/zapcore/memory_encoder.go | 179 - .../vendor/go.uber.org/zap/zapcore/sampler.go | 210 - .../vendor/go.uber.org/zap/zapcore/tee.go | 81 - .../go.uber.org/zap/zapcore/write_syncer.go | 122 - .../vendor/golang.org/x/crypto/AUTHORS | 3 - .../vendor/golang.org/x/crypto/CONTRIBUTORS | 3 - .../vendor/golang.org/x/crypto/LICENSE | 27 - .../vendor/golang.org/x/crypto/PATENTS | 22 - .../golang.org/x/crypto/argon2/argon2.go | 285 - .../golang.org/x/crypto/argon2/blake2b.go | 53 - .../x/crypto/argon2/blamka_amd64.go | 61 - .../golang.org/x/crypto/argon2/blamka_amd64.s | 244 - .../x/crypto/argon2/blamka_generic.go | 163 - .../golang.org/x/crypto/argon2/blamka_ref.go | 16 - .../golang.org/x/crypto/blake2b/blake2b.go | 291 - .../x/crypto/blake2b/blake2bAVX2_amd64.go | 38 - .../x/crypto/blake2b/blake2bAVX2_amd64.s | 745 - .../x/crypto/blake2b/blake2b_amd64.go | 25 - .../x/crypto/blake2b/blake2b_amd64.s | 279 - .../x/crypto/blake2b/blake2b_generic.go | 182 - .../x/crypto/blake2b/blake2b_ref.go | 12 - .../golang.org/x/crypto/blake2b/blake2x.go | 177 - .../golang.org/x/crypto/blake2b/register.go | 33 - .../vendor/golang.org/x/crypto/sha3/doc.go | 66 - .../vendor/golang.org/x/crypto/sha3/hashes.go | 97 - .../x/crypto/sha3/hashes_generic.go | 28 - .../golang.org/x/crypto/sha3/keccakf.go | 413 - .../golang.org/x/crypto/sha3/keccakf_amd64.go | 14 - .../golang.org/x/crypto/sha3/keccakf_amd64.s | 391 - .../golang.org/x/crypto/sha3/register.go | 19 - .../vendor/golang.org/x/crypto/sha3/sha3.go | 193 - .../golang.org/x/crypto/sha3/sha3_s390x.go | 285 - .../golang.org/x/crypto/sha3/sha3_s390x.s | 34 - .../vendor/golang.org/x/crypto/sha3/shake.go | 173 - .../golang.org/x/crypto/sha3/shake_generic.go | 20 - .../vendor/golang.org/x/crypto/sha3/xor.go | 24 - .../golang.org/x/crypto/sha3/xor_generic.go | 28 - .../golang.org/x/crypto/sha3/xor_unaligned.go | 68 - .../vendor/golang.org/x/net/AUTHORS | 3 - .../vendor/golang.org/x/net/CONTRIBUTORS | 3 - .../vendor/golang.org/x/net/LICENSE | 27 - .../vendor/golang.org/x/net/PATENTS | 22 - .../golang.org/x/net/http/httpguts/guts.go | 50 - .../golang.org/x/net/http/httpguts/httplex.go | 346 - .../golang.org/x/net/idna/idna10.0.0.go | 735 - .../vendor/golang.org/x/net/idna/idna9.0.0.go | 683 - .../vendor/golang.org/x/net/idna/punycode.go | 203 - .../golang.org/x/net/idna/tables10.0.0.go | 4560 ----- .../golang.org/x/net/idna/tables11.0.0.go | 4654 ----- .../golang.org/x/net/idna/tables12.0.0.go | 4734 ----- .../golang.org/x/net/idna/tables13.0.0.go | 4840 ----- .../golang.org/x/net/idna/tables9.0.0.go | 4487 ----- .../vendor/golang.org/x/net/idna/trie.go | 72 - .../vendor/golang.org/x/net/idna/trieval.go | 119 - .../golang.org/x/net/publicsuffix/list.go | 181 - .../golang.org/x/net/publicsuffix/table.go | 10435 ---------- .../vendor/golang.org/x/sys/AUTHORS | 3 - .../vendor/golang.org/x/sys/CONTRIBUTORS | 3 - .../vendor/golang.org/x/sys/LICENSE | 27 - .../vendor/golang.org/x/sys/PATENTS | 22 - .../golang.org/x/sys/cpu/asm_aix_ppc64.s | 18 - .../vendor/golang.org/x/sys/cpu/byteorder.go | 65 - .../vendor/golang.org/x/sys/cpu/cpu.go | 286 - .../vendor/golang.org/x/sys/cpu/cpu_aix.go | 34 - .../vendor/golang.org/x/sys/cpu/cpu_arm.go | 73 - .../vendor/golang.org/x/sys/cpu/cpu_arm64.go | 172 - .../vendor/golang.org/x/sys/cpu/cpu_arm64.s | 32 - .../golang.org/x/sys/cpu/cpu_gc_arm64.go | 12 - .../golang.org/x/sys/cpu/cpu_gc_s390x.go | 22 - .../vendor/golang.org/x/sys/cpu/cpu_gc_x86.go | 21 - .../golang.org/x/sys/cpu/cpu_gccgo_arm64.go | 12 - .../golang.org/x/sys/cpu/cpu_gccgo_s390x.go | 23 - .../golang.org/x/sys/cpu/cpu_gccgo_x86.c | 43 - .../golang.org/x/sys/cpu/cpu_gccgo_x86.go | 33 - .../vendor/golang.org/x/sys/cpu/cpu_linux.go | 16 - .../golang.org/x/sys/cpu/cpu_linux_arm.go | 39 - .../golang.org/x/sys/cpu/cpu_linux_arm64.go | 71 - .../golang.org/x/sys/cpu/cpu_linux_mips64x.go | 24 - .../golang.org/x/sys/cpu/cpu_linux_noinit.go | 10 - .../golang.org/x/sys/cpu/cpu_linux_ppc64x.go | 32 - .../golang.org/x/sys/cpu/cpu_linux_s390x.go | 40 - .../golang.org/x/sys/cpu/cpu_mips64x.go | 16 - .../vendor/golang.org/x/sys/cpu/cpu_mipsx.go | 12 - .../golang.org/x/sys/cpu/cpu_netbsd_arm64.go | 173 - .../golang.org/x/sys/cpu/cpu_other_arm.go | 10 - .../golang.org/x/sys/cpu/cpu_other_arm64.go | 10 - .../golang.org/x/sys/cpu/cpu_other_mips64x.go | 13 - .../vendor/golang.org/x/sys/cpu/cpu_ppc64x.go | 17 - .../golang.org/x/sys/cpu/cpu_riscv64.go | 12 - .../vendor/golang.org/x/sys/cpu/cpu_s390x.go | 172 - .../vendor/golang.org/x/sys/cpu/cpu_s390x.s | 58 - .../vendor/golang.org/x/sys/cpu/cpu_wasm.go | 18 - .../vendor/golang.org/x/sys/cpu/cpu_x86.go | 142 - .../vendor/golang.org/x/sys/cpu/cpu_x86.s | 52 - .../vendor/golang.org/x/sys/cpu/cpu_zos.go | 10 - .../golang.org/x/sys/cpu/cpu_zos_s390x.go | 25 - .../golang.org/x/sys/cpu/hwcap_linux.go | 56 - .../golang.org/x/sys/cpu/syscall_aix_gccgo.go | 27 - .../x/sys/cpu/syscall_aix_ppc64_gc.go | 36 - .../sys/internal/unsafeheader/unsafeheader.go | 30 - .../vendor/golang.org/x/sys/unix/.gitignore | 2 - .../vendor/golang.org/x/sys/unix/README.md | 184 - .../golang.org/x/sys/unix/affinity_linux.go | 86 - .../vendor/golang.org/x/sys/unix/aliases.go | 15 - .../golang.org/x/sys/unix/asm_aix_ppc64.s | 18 - .../golang.org/x/sys/unix/asm_bsd_386.s | 29 - .../golang.org/x/sys/unix/asm_bsd_amd64.s | 29 - .../golang.org/x/sys/unix/asm_bsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_bsd_arm64.s | 29 - .../golang.org/x/sys/unix/asm_linux_386.s | 66 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 58 - .../golang.org/x/sys/unix/asm_linux_arm.s | 57 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 53 - .../golang.org/x/sys/unix/asm_linux_mips64x.s | 57 - .../golang.org/x/sys/unix/asm_linux_mipsx.s | 55 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 45 - .../golang.org/x/sys/unix/asm_linux_riscv64.s | 49 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 57 - .../x/sys/unix/asm_openbsd_mips64.s | 30 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 18 - .../golang.org/x/sys/unix/asm_zos_s390x.s | 426 - .../golang.org/x/sys/unix/bluetooth_linux.go | 36 - .../golang.org/x/sys/unix/cap_freebsd.go | 196 - .../vendor/golang.org/x/sys/unix/constants.go | 14 - .../golang.org/x/sys/unix/dev_aix_ppc.go | 27 - .../golang.org/x/sys/unix/dev_aix_ppc64.go | 29 - .../golang.org/x/sys/unix/dev_darwin.go | 24 - .../golang.org/x/sys/unix/dev_dragonfly.go | 30 - .../golang.org/x/sys/unix/dev_freebsd.go | 30 - .../vendor/golang.org/x/sys/unix/dev_linux.go | 42 - .../golang.org/x/sys/unix/dev_netbsd.go | 29 - .../golang.org/x/sys/unix/dev_openbsd.go | 29 - .../vendor/golang.org/x/sys/unix/dev_zos.go | 29 - .../vendor/golang.org/x/sys/unix/dirent.go | 103 - .../golang.org/x/sys/unix/endian_big.go | 10 - .../golang.org/x/sys/unix/endian_little.go | 10 - .../vendor/golang.org/x/sys/unix/env_unix.go | 32 - .../vendor/golang.org/x/sys/unix/epoll_zos.go | 221 - .../x/sys/unix/errors_freebsd_386.go | 233 - .../x/sys/unix/errors_freebsd_amd64.go | 233 - .../x/sys/unix/errors_freebsd_arm.go | 226 - .../x/sys/unix/errors_freebsd_arm64.go | 17 - .../vendor/golang.org/x/sys/unix/fcntl.go | 37 - .../golang.org/x/sys/unix/fcntl_darwin.go | 24 - .../x/sys/unix/fcntl_linux_32bit.go | 14 - .../vendor/golang.org/x/sys/unix/fdset.go | 30 - .../golang.org/x/sys/unix/fstatfs_zos.go | 164 - .../vendor/golang.org/x/sys/unix/gccgo.go | 60 - .../vendor/golang.org/x/sys/unix/gccgo_c.c | 45 - .../x/sys/unix/gccgo_linux_amd64.go | 21 - .../vendor/golang.org/x/sys/unix/ioctl.go | 75 - .../golang.org/x/sys/unix/ioctl_linux.go | 196 - .../vendor/golang.org/x/sys/unix/ioctl_zos.go | 74 - .../vendor/golang.org/x/sys/unix/mkall.sh | 231 - .../vendor/golang.org/x/sys/unix/mkerrors.sh | 758 - .../golang.org/x/sys/unix/pagesize_unix.go | 16 - .../golang.org/x/sys/unix/pledge_openbsd.go | 163 - .../golang.org/x/sys/unix/ptrace_darwin.go | 12 - .../golang.org/x/sys/unix/ptrace_ios.go | 12 - .../vendor/golang.org/x/sys/unix/race.go | 31 - .../vendor/golang.org/x/sys/unix/race0.go | 26 - .../x/sys/unix/readdirent_getdents.go | 13 - .../x/sys/unix/readdirent_getdirentries.go | 20 - .../x/sys/unix/sockcmsg_dragonfly.go | 16 - .../golang.org/x/sys/unix/sockcmsg_linux.go | 36 - .../golang.org/x/sys/unix/sockcmsg_unix.go | 93 - .../x/sys/unix/sockcmsg_unix_other.go | 47 - .../vendor/golang.org/x/sys/unix/str.go | 27 - .../vendor/golang.org/x/sys/unix/syscall.go | 95 - .../golang.org/x/sys/unix/syscall_aix.go | 553 - .../golang.org/x/sys/unix/syscall_aix_ppc.go | 54 - .../x/sys/unix/syscall_aix_ppc64.go | 85 - .../golang.org/x/sys/unix/syscall_bsd.go | 664 - .../x/sys/unix/syscall_darwin.1_12.go | 32 - .../x/sys/unix/syscall_darwin.1_13.go | 108 - .../golang.org/x/sys/unix/syscall_darwin.go | 688 - .../x/sys/unix/syscall_darwin_amd64.go | 51 - .../x/sys/unix/syscall_darwin_arm64.go | 51 - .../x/sys/unix/syscall_darwin_libSystem.go | 27 - .../x/sys/unix/syscall_dragonfly.go | 541 - .../x/sys/unix/syscall_dragonfly_amd64.go | 57 - .../golang.org/x/sys/unix/syscall_freebsd.go | 872 - .../x/sys/unix/syscall_freebsd_386.go | 67 - .../x/sys/unix/syscall_freebsd_amd64.go | 67 - .../x/sys/unix/syscall_freebsd_arm.go | 63 - .../x/sys/unix/syscall_freebsd_arm64.go | 63 - .../golang.org/x/sys/unix/syscall_illumos.go | 178 - .../golang.org/x/sys/unix/syscall_linux.go | 2400 --- .../x/sys/unix/syscall_linux_386.go | 392 - .../x/sys/unix/syscall_linux_amd64.go | 199 - .../x/sys/unix/syscall_linux_amd64_gc.go | 13 - .../x/sys/unix/syscall_linux_arm.go | 291 - .../x/sys/unix/syscall_linux_arm64.go | 250 - .../golang.org/x/sys/unix/syscall_linux_gc.go | 15 - .../x/sys/unix/syscall_linux_gc_386.go | 17 - .../x/sys/unix/syscall_linux_gc_arm.go | 14 - .../x/sys/unix/syscall_linux_gccgo_386.go | 31 - .../x/sys/unix/syscall_linux_gccgo_arm.go | 21 - .../x/sys/unix/syscall_linux_mips64x.go | 235 - .../x/sys/unix/syscall_linux_mipsx.go | 243 - .../x/sys/unix/syscall_linux_ppc.go | 276 - .../x/sys/unix/syscall_linux_ppc64x.go | 161 - .../x/sys/unix/syscall_linux_riscv64.go | 235 - .../x/sys/unix/syscall_linux_s390x.go | 347 - .../x/sys/unix/syscall_linux_sparc64.go | 156 - .../golang.org/x/sys/unix/syscall_netbsd.go | 618 - .../x/sys/unix/syscall_netbsd_386.go | 38 - .../x/sys/unix/syscall_netbsd_amd64.go | 38 - .../x/sys/unix/syscall_netbsd_arm.go | 38 - .../x/sys/unix/syscall_netbsd_arm64.go | 38 - .../golang.org/x/sys/unix/syscall_openbsd.go | 390 - .../x/sys/unix/syscall_openbsd_386.go | 42 - .../x/sys/unix/syscall_openbsd_amd64.go | 42 - .../x/sys/unix/syscall_openbsd_arm.go | 42 - .../x/sys/unix/syscall_openbsd_arm64.go | 42 - .../x/sys/unix/syscall_openbsd_mips64.go | 35 - .../golang.org/x/sys/unix/syscall_solaris.go | 746 - .../x/sys/unix/syscall_solaris_amd64.go | 28 - .../golang.org/x/sys/unix/syscall_unix.go | 431 - .../golang.org/x/sys/unix/syscall_unix_gc.go | 18 - .../x/sys/unix/syscall_unix_gc_ppc64x.go | 25 - .../x/sys/unix/syscall_zos_s390x.go | 1829 -- .../golang.org/x/sys/unix/timestruct.go | 77 - .../golang.org/x/sys/unix/unveil_openbsd.go | 42 - .../vendor/golang.org/x/sys/unix/xattr_bsd.go | 241 - .../golang.org/x/sys/unix/zerrors_aix_ppc.go | 1385 -- .../x/sys/unix/zerrors_aix_ppc64.go | 1386 -- .../x/sys/unix/zerrors_darwin_amd64.go | 1860 -- .../x/sys/unix/zerrors_darwin_arm64.go | 1860 -- .../x/sys/unix/zerrors_dragonfly_amd64.go | 1738 -- .../x/sys/unix/zerrors_freebsd_386.go | 1943 -- .../x/sys/unix/zerrors_freebsd_amd64.go | 1942 -- .../x/sys/unix/zerrors_freebsd_arm.go | 1841 -- .../x/sys/unix/zerrors_freebsd_arm64.go | 1943 -- .../golang.org/x/sys/unix/zerrors_linux.go | 2917 --- .../x/sys/unix/zerrors_linux_386.go | 820 - .../x/sys/unix/zerrors_linux_amd64.go | 820 - .../x/sys/unix/zerrors_linux_arm.go | 826 - .../x/sys/unix/zerrors_linux_arm64.go | 817 - .../x/sys/unix/zerrors_linux_mips.go | 827 - .../x/sys/unix/zerrors_linux_mips64.go | 827 - .../x/sys/unix/zerrors_linux_mips64le.go | 827 - .../x/sys/unix/zerrors_linux_mipsle.go | 827 - .../x/sys/unix/zerrors_linux_ppc.go | 879 - .../x/sys/unix/zerrors_linux_ppc64.go | 883 - .../x/sys/unix/zerrors_linux_ppc64le.go | 883 - .../x/sys/unix/zerrors_linux_riscv64.go | 807 - .../x/sys/unix/zerrors_linux_s390x.go | 882 - .../x/sys/unix/zerrors_linux_sparc64.go | 877 - .../x/sys/unix/zerrors_netbsd_386.go | 1780 -- .../x/sys/unix/zerrors_netbsd_amd64.go | 1770 -- .../x/sys/unix/zerrors_netbsd_arm.go | 1759 -- .../x/sys/unix/zerrors_netbsd_arm64.go | 1770 -- .../x/sys/unix/zerrors_openbsd_386.go | 1665 -- .../x/sys/unix/zerrors_openbsd_amd64.go | 1775 -- .../x/sys/unix/zerrors_openbsd_arm.go | 1667 -- .../x/sys/unix/zerrors_openbsd_arm64.go | 1798 -- .../x/sys/unix/zerrors_openbsd_mips64.go | 1863 -- .../x/sys/unix/zerrors_solaris_amd64.go | 1557 -- .../x/sys/unix/zerrors_zos_s390x.go | 860 - .../x/sys/unix/zptrace_armnn_linux.go | 42 - .../x/sys/unix/zptrace_linux_arm64.go | 17 - .../x/sys/unix/zptrace_mipsnn_linux.go | 51 - .../x/sys/unix/zptrace_mipsnnle_linux.go | 51 - .../x/sys/unix/zptrace_x86_linux.go | 81 - .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1485 -- .../x/sys/unix/zsyscall_aix_ppc64.go | 1443 -- .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 1192 -- .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 1070 -- .../x/sys/unix/zsyscall_darwin_amd64.1_13.go | 40 - .../x/sys/unix/zsyscall_darwin_amd64.1_13.s | 25 - .../x/sys/unix/zsyscall_darwin_amd64.go | 2431 --- .../x/sys/unix/zsyscall_darwin_amd64.s | 859 - .../x/sys/unix/zsyscall_darwin_arm64.1_13.go | 40 - .../x/sys/unix/zsyscall_darwin_arm64.1_13.s | 25 - .../x/sys/unix/zsyscall_darwin_arm64.go | 2431 --- .../x/sys/unix/zsyscall_darwin_arm64.s | 859 - .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1679 -- .../x/sys/unix/zsyscall_freebsd_386.go | 2016 -- .../x/sys/unix/zsyscall_freebsd_amd64.go | 2016 -- .../x/sys/unix/zsyscall_freebsd_arm.go | 2016 -- .../x/sys/unix/zsyscall_freebsd_arm64.go | 2016 -- .../x/sys/unix/zsyscall_illumos_amd64.go | 128 - .../golang.org/x/sys/unix/zsyscall_linux.go | 1944 -- .../x/sys/unix/zsyscall_linux_386.go | 579 - .../x/sys/unix/zsyscall_linux_amd64.go | 746 - .../x/sys/unix/zsyscall_linux_arm.go | 716 - .../x/sys/unix/zsyscall_linux_arm64.go | 603 - .../x/sys/unix/zsyscall_linux_mips.go | 759 - .../x/sys/unix/zsyscall_linux_mips64.go | 730 - .../x/sys/unix/zsyscall_linux_mips64le.go | 730 - .../x/sys/unix/zsyscall_linux_mipsle.go | 759 - .../x/sys/unix/zsyscall_linux_ppc.go | 762 - .../x/sys/unix/zsyscall_linux_ppc64.go | 808 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 808 - .../x/sys/unix/zsyscall_linux_riscv64.go | 583 - .../x/sys/unix/zsyscall_linux_s390x.go | 578 - .../x/sys/unix/zsyscall_linux_sparc64.go | 741 - .../x/sys/unix/zsyscall_netbsd_386.go | 1862 -- .../x/sys/unix/zsyscall_netbsd_amd64.go | 1862 -- .../x/sys/unix/zsyscall_netbsd_arm.go | 1862 -- .../x/sys/unix/zsyscall_netbsd_arm64.go | 1862 -- .../x/sys/unix/zsyscall_openbsd_386.go | 1693 -- .../x/sys/unix/zsyscall_openbsd_amd64.go | 1693 -- .../x/sys/unix/zsyscall_openbsd_arm.go | 1693 -- .../x/sys/unix/zsyscall_openbsd_arm64.go | 1693 -- .../x/sys/unix/zsyscall_openbsd_mips64.go | 1693 -- .../x/sys/unix/zsyscall_solaris_amd64.go | 1983 -- .../x/sys/unix/zsyscall_zos_s390x.go | 1255 -- .../x/sys/unix/zsysctl_openbsd_386.go | 274 - .../x/sys/unix/zsysctl_openbsd_amd64.go | 272 - .../x/sys/unix/zsysctl_openbsd_arm.go | 274 - .../x/sys/unix/zsysctl_openbsd_arm64.go | 276 - .../x/sys/unix/zsysctl_openbsd_mips64.go | 280 - .../x/sys/unix/zsysnum_darwin_amd64.go | 440 - .../x/sys/unix/zsysnum_darwin_arm64.go | 438 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 317 - .../x/sys/unix/zsysnum_freebsd_386.go | 397 - .../x/sys/unix/zsysnum_freebsd_amd64.go | 397 - .../x/sys/unix/zsysnum_freebsd_arm.go | 397 - .../x/sys/unix/zsysnum_freebsd_arm64.go | 397 - .../x/sys/unix/zsysnum_linux_386.go | 442 - .../x/sys/unix/zsysnum_linux_amd64.go | 364 - .../x/sys/unix/zsysnum_linux_arm.go | 406 - .../x/sys/unix/zsysnum_linux_arm64.go | 309 - .../x/sys/unix/zsysnum_linux_mips.go | 427 - .../x/sys/unix/zsysnum_linux_mips64.go | 357 - .../x/sys/unix/zsysnum_linux_mips64le.go | 357 - .../x/sys/unix/zsysnum_linux_mipsle.go | 427 - .../x/sys/unix/zsysnum_linux_ppc.go | 434 - .../x/sys/unix/zsysnum_linux_ppc64.go | 406 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 406 - .../x/sys/unix/zsysnum_linux_riscv64.go | 308 - .../x/sys/unix/zsysnum_linux_s390x.go | 371 - .../x/sys/unix/zsysnum_linux_sparc64.go | 385 - .../x/sys/unix/zsysnum_netbsd_386.go | 275 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 275 - .../x/sys/unix/zsysnum_netbsd_arm.go | 275 - .../x/sys/unix/zsysnum_netbsd_arm64.go | 275 - .../x/sys/unix/zsysnum_openbsd_386.go | 219 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 219 - .../x/sys/unix/zsysnum_openbsd_arm.go | 219 - .../x/sys/unix/zsysnum_openbsd_arm64.go | 218 - .../x/sys/unix/zsysnum_openbsd_mips64.go | 221 - .../x/sys/unix/zsysnum_zos_s390x.go | 2670 --- .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 354 - .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 358 - .../x/sys/unix/ztypes_darwin_amd64.go | 537 - .../x/sys/unix/ztypes_darwin_arm64.go | 537 - .../x/sys/unix/ztypes_dragonfly_amd64.go | 474 - .../x/sys/unix/ztypes_freebsd_386.go | 721 - .../x/sys/unix/ztypes_freebsd_amd64.go | 724 - .../x/sys/unix/ztypes_freebsd_arm.go | 705 - .../x/sys/unix/ztypes_freebsd_arm64.go | 702 - .../x/sys/unix/ztypes_illumos_amd64.go | 40 - .../golang.org/x/sys/unix/ztypes_linux.go | 3907 ---- .../golang.org/x/sys/unix/ztypes_linux_386.go | 632 - .../x/sys/unix/ztypes_linux_amd64.go | 650 - .../golang.org/x/sys/unix/ztypes_linux_arm.go | 627 - .../x/sys/unix/ztypes_linux_arm64.go | 629 - .../x/sys/unix/ztypes_linux_mips.go | 633 - .../x/sys/unix/ztypes_linux_mips64.go | 632 - .../x/sys/unix/ztypes_linux_mips64le.go | 632 - .../x/sys/unix/ztypes_linux_mipsle.go | 633 - .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 639 - .../x/sys/unix/ztypes_linux_ppc64.go | 639 - .../x/sys/unix/ztypes_linux_ppc64le.go | 639 - .../x/sys/unix/ztypes_linux_riscv64.go | 657 - .../x/sys/unix/ztypes_linux_s390x.go | 653 - .../x/sys/unix/ztypes_linux_sparc64.go | 634 - .../x/sys/unix/ztypes_netbsd_386.go | 502 - .../x/sys/unix/ztypes_netbsd_amd64.go | 510 - .../x/sys/unix/ztypes_netbsd_arm.go | 507 - .../x/sys/unix/ztypes_netbsd_arm64.go | 510 - .../x/sys/unix/ztypes_openbsd_386.go | 575 - .../x/sys/unix/ztypes_openbsd_amd64.go | 575 - .../x/sys/unix/ztypes_openbsd_arm.go | 576 - .../x/sys/unix/ztypes_openbsd_arm64.go | 569 - .../x/sys/unix/ztypes_openbsd_mips64.go | 569 - .../x/sys/unix/ztypes_solaris_amd64.go | 442 - .../golang.org/x/sys/unix/ztypes_zos_s390x.go | 406 - .../golang.org/x/sys/windows/aliases.go | 13 - .../golang.org/x/sys/windows/dll_windows.go | 416 - .../vendor/golang.org/x/sys/windows/empty.s | 9 - .../golang.org/x/sys/windows/env_windows.go | 54 - .../golang.org/x/sys/windows/eventlog.go | 20 - .../golang.org/x/sys/windows/exec_windows.go | 195 - .../x/sys/windows/memory_windows.go | 37 - .../golang.org/x/sys/windows/mkerrors.bash | 70 - .../x/sys/windows/mkknownfolderids.bash | 27 - .../golang.org/x/sys/windows/mksyscall.go | 9 - .../vendor/golang.org/x/sys/windows/race.go | 30 - .../vendor/golang.org/x/sys/windows/race0.go | 25 - .../x/sys/windows/security_windows.go | 1443 -- .../golang.org/x/sys/windows/service.go | 237 - .../x/sys/windows/setupapierrors_windows.go | 100 - .../vendor/golang.org/x/sys/windows/str.go | 22 - .../golang.org/x/sys/windows/syscall.go | 112 - .../x/sys/windows/syscall_windows.go | 1672 -- .../golang.org/x/sys/windows/types_windows.go | 2775 --- .../x/sys/windows/types_windows_386.go | 35 - .../x/sys/windows/types_windows_amd64.go | 34 - .../x/sys/windows/types_windows_arm.go | 35 - .../x/sys/windows/types_windows_arm64.go | 34 - .../x/sys/windows/zerrors_windows.go | 9468 ---------- .../x/sys/windows/zknownfolderids_windows.go | 149 - .../x/sys/windows/zsyscall_windows.go | 3652 ---- .../vendor/golang.org/x/text/AUTHORS | 3 - .../vendor/golang.org/x/text/CONTRIBUTORS | 3 - .../vendor/golang.org/x/text/LICENSE | 27 - .../vendor/golang.org/x/text/PATENTS | 22 - .../x/text/secure/bidirule/bidirule.go | 336 - .../x/text/secure/bidirule/bidirule10.0.0.go | 12 - .../x/text/secure/bidirule/bidirule9.0.0.go | 15 - .../golang.org/x/text/transform/transform.go | 709 - .../golang.org/x/text/unicode/bidi/bidi.go | 359 - .../golang.org/x/text/unicode/bidi/bracket.go | 335 - .../golang.org/x/text/unicode/bidi/core.go | 1071 -- .../golang.org/x/text/unicode/bidi/prop.go | 206 - .../x/text/unicode/bidi/tables10.0.0.go | 1816 -- .../x/text/unicode/bidi/tables11.0.0.go | 1888 -- .../x/text/unicode/bidi/tables12.0.0.go | 1924 -- .../x/text/unicode/bidi/tables13.0.0.go | 1956 -- .../x/text/unicode/bidi/tables9.0.0.go | 1782 -- .../golang.org/x/text/unicode/bidi/trieval.go | 60 - .../x/text/unicode/norm/composition.go | 512 - .../x/text/unicode/norm/forminfo.go | 278 - .../golang.org/x/text/unicode/norm/input.go | 109 - .../golang.org/x/text/unicode/norm/iter.go | 458 - .../x/text/unicode/norm/normalize.go | 609 - .../x/text/unicode/norm/readwriter.go | 125 - .../x/text/unicode/norm/tables10.0.0.go | 7658 -------- .../x/text/unicode/norm/tables11.0.0.go | 7694 -------- .../x/text/unicode/norm/tables12.0.0.go | 7711 -------- .../x/text/unicode/norm/tables13.0.0.go | 7761 -------- .../x/text/unicode/norm/tables9.0.0.go | 7638 -------- .../x/text/unicode/norm/transform.go | 88 - .../golang.org/x/text/unicode/norm/trie.go | 54 - .../vendor/gopkg.in/ini.v1/.gitignore | 6 - taskman-server/vendor/gopkg.in/ini.v1/LICENSE | 191 - .../vendor/gopkg.in/ini.v1/Makefile | 15 - .../vendor/gopkg.in/ini.v1/README.md | 43 - .../vendor/gopkg.in/ini.v1/codecov.yml | 9 - .../vendor/gopkg.in/ini.v1/data_source.go | 76 - .../vendor/gopkg.in/ini.v1/deprecated.go | 25 - .../vendor/gopkg.in/ini.v1/error.go | 34 - taskman-server/vendor/gopkg.in/ini.v1/file.go | 509 - .../vendor/gopkg.in/ini.v1/helper.go | 24 - taskman-server/vendor/gopkg.in/ini.v1/ini.go | 168 - taskman-server/vendor/gopkg.in/ini.v1/key.go | 829 - .../vendor/gopkg.in/ini.v1/parser.go | 535 - .../vendor/gopkg.in/ini.v1/section.go | 256 - .../vendor/gopkg.in/ini.v1/struct.go | 729 - .../natefinch/lumberjack.v2/.gitignore | 23 - .../natefinch/lumberjack.v2/.travis.yml | 6 - .../gopkg.in/natefinch/lumberjack.v2/LICENSE | 21 - .../natefinch/lumberjack.v2/README.md | 179 - .../gopkg.in/natefinch/lumberjack.v2/chown.go | 11 - .../natefinch/lumberjack.v2/chown_linux.go | 19 - .../natefinch/lumberjack.v2/lumberjack.go | 541 - .../vendor/gopkg.in/yaml.v2/.travis.yml | 16 - .../vendor/gopkg.in/yaml.v2/LICENSE | 201 - .../vendor/gopkg.in/yaml.v2/LICENSE.libyaml | 31 - taskman-server/vendor/gopkg.in/yaml.v2/NOTICE | 13 - .../vendor/gopkg.in/yaml.v2/README.md | 133 - .../vendor/gopkg.in/yaml.v2/apic.go | 739 - .../vendor/gopkg.in/yaml.v2/decode.go | 815 - .../vendor/gopkg.in/yaml.v2/emitterc.go | 1685 -- .../vendor/gopkg.in/yaml.v2/encode.go | 390 - taskman-server/vendor/gopkg.in/yaml.v2/go.mod | 5 - .../vendor/gopkg.in/yaml.v2/parserc.go | 1095 -- .../vendor/gopkg.in/yaml.v2/readerc.go | 412 - .../vendor/gopkg.in/yaml.v2/resolve.go | 258 - .../vendor/gopkg.in/yaml.v2/scannerc.go | 2711 --- .../vendor/gopkg.in/yaml.v2/sorter.go | 113 - .../vendor/gopkg.in/yaml.v2/writerc.go | 26 - .../vendor/gopkg.in/yaml.v2/yaml.go | 466 - .../vendor/gopkg.in/yaml.v2/yamlh.go | 739 - .../vendor/gopkg.in/yaml.v2/yamlprivateh.go | 173 - taskman-server/vendor/modules.txt | 157 - .../vendor/xorm.io/builder/.drone.yml | 21 - .../vendor/xorm.io/builder/.gitignore | 1 - taskman-server/vendor/xorm.io/builder/LICENSE | 27 - .../vendor/xorm.io/builder/README.md | 206 - .../vendor/xorm.io/builder/builder.go | 321 - .../vendor/xorm.io/builder/builder_delete.go | 27 - .../vendor/xorm.io/builder/builder_insert.go | 149 - .../vendor/xorm.io/builder/builder_join.go | 42 - .../vendor/xorm.io/builder/builder_limit.go | 103 - .../vendor/xorm.io/builder/builder_select.go | 158 - .../xorm.io/builder/builder_set_operations.go | 51 - .../vendor/xorm.io/builder/builder_update.go | 57 - taskman-server/vendor/xorm.io/builder/cond.go | 38 - .../vendor/xorm.io/builder/cond_and.go | 61 - .../vendor/xorm.io/builder/cond_between.go | 65 - .../vendor/xorm.io/builder/cond_compare.go | 160 - .../vendor/xorm.io/builder/cond_eq.go | 117 - .../vendor/xorm.io/builder/cond_expr.go | 43 - .../vendor/xorm.io/builder/cond_if.go | 49 - .../vendor/xorm.io/builder/cond_in.go | 237 - .../vendor/xorm.io/builder/cond_like.go | 41 - .../vendor/xorm.io/builder/cond_neq.go | 94 - .../vendor/xorm.io/builder/cond_not.go | 77 - .../vendor/xorm.io/builder/cond_notin.go | 234 - .../vendor/xorm.io/builder/cond_null.go | 59 - .../vendor/xorm.io/builder/cond_or.go | 69 - taskman-server/vendor/xorm.io/builder/doc.go | 120 - .../vendor/xorm.io/builder/error.go | 40 - taskman-server/vendor/xorm.io/builder/go.mod | 8 - taskman-server/vendor/xorm.io/builder/go.sum | 9 - taskman-server/vendor/xorm.io/builder/sql.go | 168 - .../vendor/xorm.io/builder/writer.go | 42 - taskman-server/vendor/xorm.io/core/.drone.yml | 33 - taskman-server/vendor/xorm.io/core/.gitignore | 1 - taskman-server/vendor/xorm.io/core/LICENSE | 27 - taskman-server/vendor/xorm.io/core/README.md | 118 - .../vendor/xorm.io/core/benchmark.sh | 1 - taskman-server/vendor/xorm.io/core/cache.go | 95 - taskman-server/vendor/xorm.io/core/column.go | 166 - .../vendor/xorm.io/core/converstion.go | 12 - taskman-server/vendor/xorm.io/core/db.go | 227 - taskman-server/vendor/xorm.io/core/dialect.go | 327 - taskman-server/vendor/xorm.io/core/driver.go | 31 - taskman-server/vendor/xorm.io/core/error.go | 14 - taskman-server/vendor/xorm.io/core/filter.go | 93 - taskman-server/vendor/xorm.io/core/go.mod | 8 - taskman-server/vendor/xorm.io/core/go.sum | 20 - taskman-server/vendor/xorm.io/core/ilogger.go | 37 - taskman-server/vendor/xorm.io/core/index.go | 72 - taskman-server/vendor/xorm.io/core/mapper.go | 258 - taskman-server/vendor/xorm.io/core/pk.go | 30 - taskman-server/vendor/xorm.io/core/rows.go | 338 - taskman-server/vendor/xorm.io/core/scan.go | 66 - taskman-server/vendor/xorm.io/core/stmt.go | 166 - taskman-server/vendor/xorm.io/core/table.go | 155 - taskman-server/vendor/xorm.io/core/tx.go | 153 - taskman-server/vendor/xorm.io/core/type.go | 325 - .../vendor/xorm.io/xorm/.changelog.yml | 53 - taskman-server/vendor/xorm.io/xorm/.drone.yml | 401 - taskman-server/vendor/xorm.io/xorm/.gitignore | 40 - .../vendor/xorm.io/xorm/.revive.toml | 29 - .../vendor/xorm.io/xorm/CHANGELOG.md | 344 - .../vendor/xorm.io/xorm/CONTRIBUTING.md | 87 - taskman-server/vendor/xorm.io/xorm/LICENSE | 27 - taskman-server/vendor/xorm.io/xorm/Makefile | 258 - taskman-server/vendor/xorm.io/xorm/README.md | 488 - .../vendor/xorm.io/xorm/README_CN.md | 480 - .../vendor/xorm.io/xorm/caches/cache.go | 99 - .../vendor/xorm.io/xorm/caches/encode.go | 65 - .../vendor/xorm.io/xorm/caches/leveldb.go | 99 - .../vendor/xorm.io/xorm/caches/lru.go | 282 - .../vendor/xorm.io/xorm/caches/manager.go | 60 - .../xorm.io/xorm/caches/memory_store.go | 49 - .../xorm.io/xorm/contexts/context_cache.go | 30 - .../vendor/xorm.io/xorm/contexts/hook.go | 81 - .../vendor/xorm.io/xorm/convert/bool.go | 51 - .../vendor/xorm.io/xorm/convert/conversion.go | 391 - .../vendor/xorm.io/xorm/convert/float.go | 142 - .../vendor/xorm.io/xorm/convert/int.go | 178 - .../vendor/xorm.io/xorm/convert/interface.go | 49 - .../vendor/xorm.io/xorm/convert/scanner.go | 19 - .../vendor/xorm.io/xorm/convert/string.go | 75 - .../vendor/xorm.io/xorm/convert/time.go | 117 - taskman-server/vendor/xorm.io/xorm/core/db.go | 308 - .../vendor/xorm.io/xorm/core/error.go | 14 - .../vendor/xorm.io/xorm/core/interface.go | 22 - .../vendor/xorm.io/xorm/core/rows.go | 346 - .../vendor/xorm.io/xorm/core/scan.go | 70 - .../vendor/xorm.io/xorm/core/stmt.go | 213 - taskman-server/vendor/xorm.io/xorm/core/tx.go | 238 - .../vendor/xorm.io/xorm/dialects/dialect.go | 330 - .../vendor/xorm.io/xorm/dialects/driver.go | 85 - .../vendor/xorm.io/xorm/dialects/filter.go | 76 - .../xorm.io/xorm/dialects/gen_reserved.sh | 6 - .../vendor/xorm.io/xorm/dialects/mssql.go | 727 - .../vendor/xorm.io/xorm/dialects/mysql.go | 814 - .../vendor/xorm.io/xorm/dialects/oracle.go | 928 - .../xorm.io/xorm/dialects/pg_reserved.txt | 746 - .../vendor/xorm.io/xorm/dialects/postgres.go | 1495 -- .../vendor/xorm.io/xorm/dialects/quote.go | 15 - .../vendor/xorm.io/xorm/dialects/sqlite3.go | 572 - .../xorm.io/xorm/dialects/table_name.go | 89 - .../vendor/xorm.io/xorm/dialects/time.go | 61 - taskman-server/vendor/xorm.io/xorm/doc.go | 234 - taskman-server/vendor/xorm.io/xorm/engine.go | 1328 -- .../vendor/xorm.io/xorm/engine_group.go | 267 - .../xorm.io/xorm/engine_group_policy.go | 118 - taskman-server/vendor/xorm.io/xorm/error.go | 26 - taskman-server/vendor/xorm.io/xorm/go.mod | 19 - taskman-server/vendor/xorm.io/xorm/go.sum | 573 - .../vendor/xorm.io/xorm/interface.go | 133 - .../xorm.io/xorm/internal/json/gojson.go | 28 - .../vendor/xorm.io/xorm/internal/json/json.go | 31 - .../xorm.io/xorm/internal/json/jsoniter.go | 28 - .../xorm.io/xorm/internal/statements/cache.go | 81 - .../xorm/internal/statements/column_map.go | 66 - .../xorm.io/xorm/internal/statements/expr.go | 94 - .../xorm/internal/statements/insert.go | 260 - .../xorm.io/xorm/internal/statements/pk.go | 98 - .../xorm.io/xorm/internal/statements/query.go | 462 - .../xorm/internal/statements/statement.go | 1032 - .../internal/statements/statement_args.go | 134 - .../xorm/internal/statements/update.go | 308 - .../xorm/internal/statements/values.go | 171 - .../xorm.io/xorm/internal/utils/name.go | 14 - .../vendor/xorm.io/xorm/internal/utils/new.go | 25 - .../xorm.io/xorm/internal/utils/reflect.go | 14 - .../xorm.io/xorm/internal/utils/slice.go | 22 - .../vendor/xorm.io/xorm/internal/utils/sql.go | 20 - .../xorm.io/xorm/internal/utils/strings.go | 32 - .../xorm.io/xorm/internal/utils/zero.go | 151 - .../vendor/xorm.io/xorm/log/logger.go | 208 - .../vendor/xorm.io/xorm/log/logger_context.go | 116 - .../vendor/xorm.io/xorm/log/syslogger.go | 87 - .../vendor/xorm.io/xorm/names/mapper.go | 281 - .../vendor/xorm.io/xorm/names/table_name.go | 57 - .../vendor/xorm.io/xorm/processors.go | 144 - taskman-server/vendor/xorm.io/xorm/rows.go | 143 - taskman-server/vendor/xorm.io/xorm/scan.go | 320 - .../vendor/xorm.io/xorm/schemas/column.go | 110 - .../vendor/xorm.io/xorm/schemas/index.go | 72 - .../vendor/xorm.io/xorm/schemas/pk.go | 46 - .../vendor/xorm.io/xorm/schemas/quote.go | 242 - .../vendor/xorm.io/xorm/schemas/table.go | 178 - .../vendor/xorm.io/xorm/schemas/type.go | 353 - .../vendor/xorm.io/xorm/schemas/version.go | 12 - taskman-server/vendor/xorm.io/xorm/session.go | 745 - .../vendor/xorm.io/xorm/session_cols.go | 143 - .../vendor/xorm.io/xorm/session_cond.go | 55 - .../vendor/xorm.io/xorm/session_delete.go | 268 - .../vendor/xorm.io/xorm/session_exist.go | 32 - .../vendor/xorm.io/xorm/session_find.go | 482 - .../vendor/xorm.io/xorm/session_get.go | 376 - .../vendor/xorm.io/xorm/session_insert.go | 671 - .../vendor/xorm.io/xorm/session_iterate.go | 105 - .../vendor/xorm.io/xorm/session_query.go | 154 - .../vendor/xorm.io/xorm/session_raw.go | 128 - .../vendor/xorm.io/xorm/session_schema.go | 508 - .../vendor/xorm.io/xorm/session_stats.go | 81 - .../vendor/xorm.io/xorm/session_tx.go | 91 - .../vendor/xorm.io/xorm/session_update.go | 551 - .../vendor/xorm.io/xorm/tags/parser.go | 332 - .../vendor/xorm.io/xorm/tags/tag.go | 400 - 1551 files changed, 244 insertions(+), 543853 deletions(-) rename taskman-server/dao/{form_item_templdate_dao.go => form_item_template_dao.go} (95%) delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/password.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/rsa.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/file_server/minio.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/guid/rand.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/logger/zap.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/auth.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/func.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/smtp.go delete mode 100644 taskman-server/vendor/github.com/WeBankPartners/go-common-lib/token/wecube.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/.gitignore delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/.travis.yml delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/LICENSE delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/README.md delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/claims.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/doc.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/errors.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/hmac.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/map_claims.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/none.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/parser.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/signing_method.go delete mode 100644 taskman-server/vendor/github.com/dgrijalva/jwt-go/token.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/.travis.yml delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/LICENSE delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/README.markdown delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/big.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/bigbytes.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/bytes.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/comma.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/commaf.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/ftoa.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/humanize.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/number.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/ordinals.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/si.go delete mode 100644 taskman-server/vendor/github.com/dustin/go-humanize/times.go delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/.travis.yml delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/LICENSE delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/README.md delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/go.mod delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/go.sum delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/sse-decoder.go delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/sse-encoder.go delete mode 100644 taskman-server/vendor/github.com/gin-contrib/sse/writer.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/.gitignore delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/.travis.yml delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/AUTHORS.md delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/BENCHMARKS.md delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/CHANGELOG.md delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/CODE_OF_CONDUCT.md delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/CONTRIBUTING.md delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/LICENSE delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/Makefile delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/README.md delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/auth.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/binding.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/default_validator.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/form.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/form_mapping.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/header.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/json.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/msgpack.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/protobuf.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/query.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/uri.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/xml.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/binding/yaml.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/codecov.yml delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/context.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/context_appengine.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/debug.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/deprecated.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/doc.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/errors.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/fs.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/gin.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/go.mod delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/go.sum delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/internal/json/json.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/logger.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/mode.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/path.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/recovery.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/data.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/html.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/json.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/msgpack.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/protobuf.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/reader.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/redirect.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/render.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/text.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/xml.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/render/yaml.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/response_writer.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/routergroup.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/test_helpers.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/tree.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/utils.go delete mode 100644 taskman-server/vendor/github.com/gin-gonic/gin/version.go delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/.gitignore delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/.travis.yml delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/LICENSE delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/README.md delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/currency/currency.go delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/go.mod delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/go.sum delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/logo.png delete mode 100644 taskman-server/vendor/github.com/go-playground/locales/rules.go delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/.gitignore delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/.travis.yml delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/LICENSE delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/README.md delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/errors.go delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/go.mod delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/go.sum delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/import_export.go delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/logo.png delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/translator.go delete mode 100644 taskman-server/vendor/github.com/go-playground/universal-translator/universal_translator.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/.gitignore delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/.travis.yml delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/LICENSE delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/Makefile delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/README.md delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/baked_in.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/cache.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/country_codes.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/doc.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/errors.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/field_level.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/go.mod delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/go.sum delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/logo.png delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/regexes.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/struct_level.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/translations.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/util.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/validator.go delete mode 100644 taskman-server/vendor/github.com/go-playground/validator/v10/validator_instance.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/.gitignore delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/AUTHORS delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/LICENSE delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/README.md delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/auth.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/buffer.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/collations.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck_dummy.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/connection.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/connector.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/const.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/driver.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/dsn.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/errors.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/fields.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/fuzz.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/go.mod delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/infile.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_go113.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_legacy.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/packets.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/result.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/rows.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/statement.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/transaction.go delete mode 100644 taskman-server/vendor/github.com/go-sql-driver/mysql/utils.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/.codecov.yml delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/.gitignore delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/.golangci.yml delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/CHANGELOG.md delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/LICENSE delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/Makefile delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/README.md delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/color.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/decode.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/docker-compose.yml delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/encode.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/error.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/go.mod delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/go.sum delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/anonymous_field.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/array.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bool.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bytes.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_norace.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_race.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/context.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/float.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/func.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/int.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/interface.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/map.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/number.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/option.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/ptr.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/slice.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/stream.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/string.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/struct.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/type.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/uint.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_json.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_text.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/decoder/wrapped_string.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compact.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_norace.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_race.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/context.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/encoder.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/indent.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/int.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map112.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map113.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/opcode.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/option.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/optype.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/string.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/debug_vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/hack.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/util.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/debug_vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/hack.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/util.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/debug_vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/util.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/debug_vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/hack.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/util.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/vm.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/errors/error.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/runtime/rtype.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/runtime/struct_field.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/internal/runtime/type.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/json.go delete mode 100644 taskman-server/vendor/github.com/goccy/go-json/option.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/AUTHORS delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/CONTRIBUTORS delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/LICENSE delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/clone.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/decode.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/deprecated.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/discard.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/encode.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/equal.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/extensions.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/lib.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/message_set.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/pointer_reflect.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/properties.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/table_marshal.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/table_merge.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/table_unmarshal.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/text.go delete mode 100644 taskman-server/vendor/github.com/golang/protobuf/proto/text_parser.go delete mode 100644 taskman-server/vendor/github.com/golang/snappy/.gitignore delete mode 100644 taskman-server/vendor/github.com/golang/snappy/AUTHORS delete mode 100644 taskman-server/vendor/github.com/golang/snappy/CONTRIBUTORS delete mode 100644 taskman-server/vendor/github.com/golang/snappy/LICENSE delete mode 100644 taskman-server/vendor/github.com/golang/snappy/README delete mode 100644 taskman-server/vendor/github.com/golang/snappy/decode.go delete mode 100644 taskman-server/vendor/github.com/golang/snappy/decode_amd64.go delete mode 100644 taskman-server/vendor/github.com/golang/snappy/decode_amd64.s delete mode 100644 taskman-server/vendor/github.com/golang/snappy/decode_other.go delete mode 100644 taskman-server/vendor/github.com/golang/snappy/encode.go delete mode 100644 taskman-server/vendor/github.com/golang/snappy/encode_amd64.go delete mode 100644 taskman-server/vendor/github.com/golang/snappy/encode_amd64.s delete mode 100644 taskman-server/vendor/github.com/golang/snappy/encode_other.go delete mode 100644 taskman-server/vendor/github.com/golang/snappy/snappy.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/.travis.yml delete mode 100644 taskman-server/vendor/github.com/google/uuid/CONTRIBUTING.md delete mode 100644 taskman-server/vendor/github.com/google/uuid/CONTRIBUTORS delete mode 100644 taskman-server/vendor/github.com/google/uuid/LICENSE delete mode 100644 taskman-server/vendor/github.com/google/uuid/README.md delete mode 100644 taskman-server/vendor/github.com/google/uuid/dce.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/doc.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/go.mod delete mode 100644 taskman-server/vendor/github.com/google/uuid/hash.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/marshal.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/node.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/node_js.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/node_net.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/sql.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/time.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/util.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/uuid.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/version1.go delete mode 100644 taskman-server/vendor/github.com/google/uuid/version4.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/.codecov.yml delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/.gitignore delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/.travis.yml delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/Gopkg.lock delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/Gopkg.toml delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/LICENSE delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/README.md delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/adapter.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_array.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_bool.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_float.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_int32.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_int64.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_invalid.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_nil.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_number.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_object.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_str.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_uint32.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/any_uint64.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/build.sh delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/config.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/go.mod delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/go.sum delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_array.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_float.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_int.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_object.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_skip.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_skip_sloppy.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_skip_strict.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/iter_str.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/jsoniter.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/pool.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_array.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_dynamic.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_extension.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_json_number.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_json_raw_message.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_map.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_marshaler.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_native.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_optional.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_slice.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_struct_decoder.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/reflect_struct_encoder.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/stream.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/stream_float.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/stream_int.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/stream_str.go delete mode 100644 taskman-server/vendor/github.com/json-iterator/go/test.sh delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/LICENSE delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/.gitignore delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/LICENSE delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/README.md delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/decode.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/decode_amd64.s delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/decode_arm64.s delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/decode_asm.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/decode_other.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encode.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encode_all.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encode_amd64.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encode_best.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encode_better.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encode_go.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.go delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.s delete mode 100644 taskman-server/vendor/github.com/klauspost/compress/s2/s2.go delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/.gitignore delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/.travis.yml delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/CONTRIBUTING.txt delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/LICENSE delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/README.md delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/cpuid.go delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/cpuid_386.s delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/cpuid_amd64.s delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/cpuid_arm64.s delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/detect_arm64.go delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/detect_intel.go delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/detect_ref.go delete mode 100644 taskman-server/vendor/github.com/klauspost/cpuid/go.mod delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/.gitignore delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/.travis.yml delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/LICENSE delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/README.md delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/go.mod delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/go.sum delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/machine.go delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/machine.go.rl delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/makefile delete mode 100644 taskman-server/vendor/github.com/leodido/go-urn/urn.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/.travis.yml delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/LICENSE delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/README.md delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/doc.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/go.mod delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/go.sum delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/go.test.sh delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/isatty_bsd.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/isatty_others.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/isatty_plan9.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/isatty_solaris.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/isatty_tcgets.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/isatty_windows.go delete mode 100644 taskman-server/vendor/github.com/mattn/go-isatty/renovate.json delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/LICENSE delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/README.md delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/block-generic.go delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/block16_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/block8_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/block_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/go.mod delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/go.sum delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/md5-digest_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/md5-server_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/md5-server_fallback.go delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/md5-util_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/md5-simd/md5.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/.gitignore delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/.golangci.yml delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/CNAME delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/CONTRIBUTING.md delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/LICENSE delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/MAINTAINERS.md delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/Makefile delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/NOTICE delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/README.md delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/README_zh_CN.md delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-bucket-encryption.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-bucket-lifecycle.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-bucket-notification.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-bucket-policy.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-bucket-replication.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-bucket-tagging.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-bucket-versioning.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-compose-object.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-copy-object.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-datatypes.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-error-response.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-get-object-acl.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-get-object-file.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-get-object.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-get-options.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-list.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-object-legal-hold.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-object-lock.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-object-retention.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-object-tagging.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-presigned.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-put-bucket.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-put-object-common.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-put-object-file-context.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-put-object-multipart.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-put-object-streaming.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-put-object.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-putobject-snowball.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-remove.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-restore.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-s3-datatypes.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-select.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api-stat.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/api.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/bucket-cache.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/code_of_conduct.md delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/constants.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/core.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/functional_tests.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/go.mod delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/go.sum delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/hook-reader.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/assume_role.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/chain.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/config.json.sample delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/credentials.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/credentials.sample delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/doc.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/env_aws.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/env_minio.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/file_aws_credentials.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/file_minio_client.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/iam_aws.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/signature-type.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/static.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/sts-tls-identity.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/sts_client_grants.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/sts_ldap_identity.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/credentials/sts_web_identity.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/encrypt/server-side.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/lifecycle/lifecycle.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/notification/info.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/notification/notification.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/replication/replication.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/s3utils/utils.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/set/stringset.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/signer/request-signature-streaming.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/signer/request-signature-v2.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/signer/request-signature-v4.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/signer/utils.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/sse/sse.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/pkg/tags/tags.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/post-policy.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/retry-continous.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/retry.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/s3-endpoints.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/s3-error.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/transport.go delete mode 100644 taskman-server/vendor/github.com/minio/minio-go/v7/utils.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/.gitignore delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/.travis.yml delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/LICENSE delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/README.md delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/appveyor.yml delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid_386.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid_386.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid_arm.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid_linux_arm64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/cpuid_other.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/go.mod delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockAvx2_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockAvx2_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockAvx512_amd64.asm delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockAvx512_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockAvx512_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockAvx_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockAvx_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockSha_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockSha_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockSsse_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256blockSsse_amd64.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256block_amd64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256block_arm64.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256block_arm64.s delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/sha256block_other.go delete mode 100644 taskman-server/vendor/github.com/minio/sha256-simd/test-architectures.sh delete mode 100644 taskman-server/vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 taskman-server/vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 taskman-server/vendor/github.com/mitchellh/go-homedir/go.mod delete mode 100644 taskman-server/vendor/github.com/mitchellh/go-homedir/homedir.go delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/.gitignore delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/.travis.yml delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/LICENSE delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/README.md delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/executor.go delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/go_above_19.go delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/go_below_19.go delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/log.go delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/test.sh delete mode 100644 taskman-server/vendor/github.com/modern-go/concurrent/unbounded_executor.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/.gitignore delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/.travis.yml delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/Gopkg.lock delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/Gopkg.toml delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/LICENSE delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/README.md delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/go_above_17.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/go_above_19.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/go_below_17.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/go_below_19.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/reflect2.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/reflect2_amd64.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/reflect2_kind.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_386.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_amd64p32.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_arm.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_arm64.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_mips64x.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_mipsx.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_ppc64x.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/relfect2_s390x.s delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/safe_field.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/safe_map.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/safe_slice.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/safe_struct.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/safe_type.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/test.sh delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/type_map.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_array.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_eface.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_field.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_iface.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_link.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_map.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_ptr.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_slice.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_struct.go delete mode 100644 taskman-server/vendor/github.com/modern-go/reflect2/unsafe_type.go delete mode 100644 taskman-server/vendor/github.com/rs/xid/.appveyor.yml delete mode 100644 taskman-server/vendor/github.com/rs/xid/.travis.yml delete mode 100644 taskman-server/vendor/github.com/rs/xid/LICENSE delete mode 100644 taskman-server/vendor/github.com/rs/xid/README.md delete mode 100644 taskman-server/vendor/github.com/rs/xid/go.mod delete mode 100644 taskman-server/vendor/github.com/rs/xid/hostid_darwin.go delete mode 100644 taskman-server/vendor/github.com/rs/xid/hostid_fallback.go delete mode 100644 taskman-server/vendor/github.com/rs/xid/hostid_freebsd.go delete mode 100644 taskman-server/vendor/github.com/rs/xid/hostid_linux.go delete mode 100644 taskman-server/vendor/github.com/rs/xid/hostid_windows.go delete mode 100644 taskman-server/vendor/github.com/rs/xid/id.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/.gitignore delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/.golangci.yml delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/.travis.yml delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/CHANGELOG.md delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/LICENSE delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/README.md delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/alt_exit.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/appveyor.yml delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/buffer_pool.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/doc.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/entry.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/exported.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/formatter.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/go.mod delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/go.sum delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/hooks.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/json_formatter.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/logger.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/logrus.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_js.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_unix.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/terminal_check_windows.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/text_formatter.go delete mode 100644 taskman-server/vendor/github.com/sirupsen/logrus/writer.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/LICENSE delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/batch.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/cache/cache.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/cache/lru.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/comparer.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/comparer/bytes_comparer.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/comparer/comparer.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db_compaction.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db_iter.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db_snapshot.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db_state.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db_transaction.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db_util.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/db_write.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/doc.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/errors.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/errors/errors.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/filter.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/filter/bloom.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/filter/filter.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/iterator/iter.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/journal/journal.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/key.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/opt/options.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/options.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/session.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/session_compaction.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/session_record.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/session_util.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/file_storage_nacl.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/file_storage_plan9.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/file_storage_solaris.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/file_storage_unix.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/file_storage_windows.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/storage/storage.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/table.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/table/reader.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/table/table.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/table/writer.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/util.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/util/buffer.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/util/buffer_pool.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/util/crc32.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/util/hash.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/util/range.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/util/util.go delete mode 100644 taskman-server/vendor/github.com/syndtr/goleveldb/leveldb/version.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/.gitignore delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/.travis.yml delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/AUTHORS.txt delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/CODE_OF_CONDUCT.md delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/LICENSE delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/README.org delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/cell.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/col.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/data_validation.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/date.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/doc.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/file.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/format_code.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/go.mod delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/go.sum delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/hsl.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/lib.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/read.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/reftable.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/row.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/sheet.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/stream_cell.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/stream_file.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/stream_file_builder.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/stream_style.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/style.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/templates.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/theme.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/write.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/xmlContentTypes.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/xmlSharedStrings.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/xmlStyle.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/xmlTheme.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/xmlWorkbook.go delete mode 100644 taskman-server/vendor/github.com/tealeg/xlsx/xmlWorksheet.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/0_importpath.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/LICENSE delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/binc.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/build.sh delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/cbor.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/codecgen.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/decode.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/doc.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/encode.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/fast-path.generated.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/fast-path.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/fast-path.not.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/float.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/gen-dec-array.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/gen-dec-map.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/gen-enc-chan.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/gen-helper.generated.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/gen-helper.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/gen.generated.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/gen.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/go.mod delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_arrayof_gte_go15.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_arrayof_lt_go15.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_fmt_time_gte_go15.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_fmt_time_lt_go15.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_makemap_gte_go19.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_makemap_lt_go19.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_maprange_gte_go112.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_maprange_lt_go112.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_gte_go110.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_lt_go110.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_unsupported_lt_go14.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go15.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_vendor_gte_go17.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/goversion_vendor_lt_go15.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/helper.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/helper.s delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/helper_internal.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/helper_unsafe.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/json.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/mammoth-test.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/mammoth2-test.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/msgpack.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/prebuild.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/reader.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/register_ext.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/rpc.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/simple.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/sort-slice.generated.go delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/sort-slice.go.tmpl delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/test-cbor-goldens.json delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/test.py delete mode 100644 taskman-server/vendor/github.com/ugorji/go/codec/writer.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/.codecov.yml delete mode 100644 taskman-server/vendor/go.uber.org/atomic/.gitignore delete mode 100644 taskman-server/vendor/go.uber.org/atomic/.travis.yml delete mode 100644 taskman-server/vendor/go.uber.org/atomic/CHANGELOG.md delete mode 100644 taskman-server/vendor/go.uber.org/atomic/LICENSE.txt delete mode 100644 taskman-server/vendor/go.uber.org/atomic/Makefile delete mode 100644 taskman-server/vendor/go.uber.org/atomic/README.md delete mode 100644 taskman-server/vendor/go.uber.org/atomic/bool.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/bool_ext.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/doc.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/duration.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/duration_ext.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/error.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/error_ext.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/float64.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/float64_ext.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/gen.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/go.mod delete mode 100644 taskman-server/vendor/go.uber.org/atomic/go.sum delete mode 100644 taskman-server/vendor/go.uber.org/atomic/int32.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/int64.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/nocmp.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/string.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/string_ext.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/uint32.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/uint64.go delete mode 100644 taskman-server/vendor/go.uber.org/atomic/value.go delete mode 100644 taskman-server/vendor/go.uber.org/multierr/.codecov.yml delete mode 100644 taskman-server/vendor/go.uber.org/multierr/.gitignore delete mode 100644 taskman-server/vendor/go.uber.org/multierr/.travis.yml delete mode 100644 taskman-server/vendor/go.uber.org/multierr/CHANGELOG.md delete mode 100644 taskman-server/vendor/go.uber.org/multierr/LICENSE.txt delete mode 100644 taskman-server/vendor/go.uber.org/multierr/Makefile delete mode 100644 taskman-server/vendor/go.uber.org/multierr/README.md delete mode 100644 taskman-server/vendor/go.uber.org/multierr/error.go delete mode 100644 taskman-server/vendor/go.uber.org/multierr/glide.yaml delete mode 100644 taskman-server/vendor/go.uber.org/multierr/go.mod delete mode 100644 taskman-server/vendor/go.uber.org/multierr/go.sum delete mode 100644 taskman-server/vendor/go.uber.org/multierr/go113.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/.codecov.yml delete mode 100644 taskman-server/vendor/go.uber.org/zap/.gitignore delete mode 100644 taskman-server/vendor/go.uber.org/zap/.readme.tmpl delete mode 100644 taskman-server/vendor/go.uber.org/zap/CHANGELOG.md delete mode 100644 taskman-server/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md delete mode 100644 taskman-server/vendor/go.uber.org/zap/CONTRIBUTING.md delete mode 100644 taskman-server/vendor/go.uber.org/zap/FAQ.md delete mode 100644 taskman-server/vendor/go.uber.org/zap/LICENSE.txt delete mode 100644 taskman-server/vendor/go.uber.org/zap/Makefile delete mode 100644 taskman-server/vendor/go.uber.org/zap/README.md delete mode 100644 taskman-server/vendor/go.uber.org/zap/array.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/buffer/buffer.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/buffer/pool.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/checklicense.sh delete mode 100644 taskman-server/vendor/go.uber.org/zap/config.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/doc.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/encoder.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/error.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/field.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/flag.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/glide.yaml delete mode 100644 taskman-server/vendor/go.uber.org/zap/global.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/global_go112.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/global_prego112.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/go.mod delete mode 100644 taskman-server/vendor/go.uber.org/zap/go.sum delete mode 100644 taskman-server/vendor/go.uber.org/zap/http_handler.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/internal/color/color.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/internal/exit/exit.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/level.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/logger.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/options.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/sink.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/stacktrace.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/sugar.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/time.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/writer.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/clock.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/console_encoder.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/core.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/doc.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/encoder.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/entry.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/error.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/field.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/hook.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/increase_level.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/json_encoder.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/level.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/level_strings.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/marshaler.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/memory_encoder.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/sampler.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/tee.go delete mode 100644 taskman-server/vendor/go.uber.org/zap/zapcore/write_syncer.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/AUTHORS delete mode 100644 taskman-server/vendor/golang.org/x/crypto/CONTRIBUTORS delete mode 100644 taskman-server/vendor/golang.org/x/crypto/LICENSE delete mode 100644 taskman-server/vendor/golang.org/x/crypto/PATENTS delete mode 100644 taskman-server/vendor/golang.org/x/crypto/argon2/argon2.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/argon2/blake2b.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/argon2/blamka_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/argon2/blamka_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/crypto/argon2/blamka_generic.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/argon2/blamka_ref.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2b.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/blake2x.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/blake2b/register.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/doc.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/hashes.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/hashes_generic.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/keccakf.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/keccakf_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/keccakf_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/register.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/sha3.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/sha3_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/sha3_s390x.s delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/shake.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/shake_generic.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/xor.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/xor_generic.go delete mode 100644 taskman-server/vendor/golang.org/x/crypto/sha3/xor_unaligned.go delete mode 100644 taskman-server/vendor/golang.org/x/net/AUTHORS delete mode 100644 taskman-server/vendor/golang.org/x/net/CONTRIBUTORS delete mode 100644 taskman-server/vendor/golang.org/x/net/LICENSE delete mode 100644 taskman-server/vendor/golang.org/x/net/PATENTS delete mode 100644 taskman-server/vendor/golang.org/x/net/http/httpguts/guts.go delete mode 100644 taskman-server/vendor/golang.org/x/net/http/httpguts/httplex.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/idna10.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/idna9.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/punycode.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/tables10.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/tables11.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/tables12.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/tables13.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/tables9.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/trie.go delete mode 100644 taskman-server/vendor/golang.org/x/net/idna/trieval.go delete mode 100644 taskman-server/vendor/golang.org/x/net/publicsuffix/list.go delete mode 100644 taskman-server/vendor/golang.org/x/net/publicsuffix/table.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/AUTHORS delete mode 100644 taskman-server/vendor/golang.org/x/sys/CONTRIBUTORS delete mode 100644 taskman-server/vendor/golang.org/x/sys/LICENSE delete mode 100644 taskman-server/vendor/golang.org/x/sys/PATENTS delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/byteorder.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_aix.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_arm64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_linux_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_mips64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_mipsx.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_other_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_ppc64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_riscv64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_s390x.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_wasm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_x86.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_x86.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_zos.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/cpu_zos_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/hwcap_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/.gitignore delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/README.md delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/affinity_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/aliases.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_bsd_386.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_bsd_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_bsd_arm.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_bsd_arm64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_386.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_arm.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_arm64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_linux_s390x.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/asm_zos_s390x.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/bluetooth_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/cap_freebsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/constants.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_aix_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_darwin.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_dragonfly.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_freebsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_netbsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_openbsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dev_zos.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/dirent.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/endian_big.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/endian_little.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/env_unix.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/epoll_zos.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/errors_freebsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/errors_freebsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/fcntl.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/fcntl_darwin.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/fdset.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/fstatfs_zos.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/gccgo.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/gccgo_c.c delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ioctl.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ioctl_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ioctl_zos.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/mkall.sh delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/mkerrors.sh delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/pagesize_unix.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/pledge_openbsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ptrace_darwin.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ptrace_ios.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/race.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/race0.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/readdirent_getdents.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/sockcmsg_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/sockcmsg_unix.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/str.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_aix.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_aix_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_bsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_darwin.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_dragonfly.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_freebsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_illumos.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_gc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_netbsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_openbsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_openbsd_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_solaris.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_unix.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_unix_gc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/timestruct.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/unveil_openbsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/xattr_bsd.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zptrace_linux_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zptrace_x86_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_illumos_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/aliases.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/dll_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/empty.s delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/env_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/eventlog.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/exec_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/memory_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/mkerrors.bash delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/mkknownfolderids.bash delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/mksyscall.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/race.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/race0.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/security_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/service.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/setupapierrors_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/str.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/syscall.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/syscall_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/types_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/types_windows_386.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/types_windows_amd64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/types_windows_arm.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/types_windows_arm64.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/zerrors_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/zknownfolderids_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/sys/windows/zsyscall_windows.go delete mode 100644 taskman-server/vendor/golang.org/x/text/AUTHORS delete mode 100644 taskman-server/vendor/golang.org/x/text/CONTRIBUTORS delete mode 100644 taskman-server/vendor/golang.org/x/text/LICENSE delete mode 100644 taskman-server/vendor/golang.org/x/text/PATENTS delete mode 100644 taskman-server/vendor/golang.org/x/text/secure/bidirule/bidirule.go delete mode 100644 taskman-server/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/transform/transform.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/bidi.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/bracket.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/core.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/prop.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/bidi/trieval.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/composition.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/forminfo.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/input.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/iter.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/normalize.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/readwriter.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/transform.go delete mode 100644 taskman-server/vendor/golang.org/x/text/unicode/norm/trie.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/.gitignore delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/LICENSE delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/Makefile delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/README.md delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/codecov.yml delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/data_source.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/deprecated.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/error.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/file.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/helper.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/ini.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/key.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/parser.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/section.go delete mode 100644 taskman-server/vendor/gopkg.in/ini.v1/struct.go delete mode 100644 taskman-server/vendor/gopkg.in/natefinch/lumberjack.v2/.gitignore delete mode 100644 taskman-server/vendor/gopkg.in/natefinch/lumberjack.v2/.travis.yml delete mode 100644 taskman-server/vendor/gopkg.in/natefinch/lumberjack.v2/LICENSE delete mode 100644 taskman-server/vendor/gopkg.in/natefinch/lumberjack.v2/README.md delete mode 100644 taskman-server/vendor/gopkg.in/natefinch/lumberjack.v2/chown.go delete mode 100644 taskman-server/vendor/gopkg.in/natefinch/lumberjack.v2/chown_linux.go delete mode 100644 taskman-server/vendor/gopkg.in/natefinch/lumberjack.v2/lumberjack.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/.travis.yml delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/LICENSE delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/LICENSE.libyaml delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/NOTICE delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/README.md delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/apic.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/decode.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/emitterc.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/encode.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/go.mod delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/parserc.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/readerc.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/resolve.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/scannerc.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/sorter.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/writerc.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/yaml.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/yamlh.go delete mode 100644 taskman-server/vendor/gopkg.in/yaml.v2/yamlprivateh.go delete mode 100644 taskman-server/vendor/modules.txt delete mode 100644 taskman-server/vendor/xorm.io/builder/.drone.yml delete mode 100644 taskman-server/vendor/xorm.io/builder/.gitignore delete mode 100644 taskman-server/vendor/xorm.io/builder/LICENSE delete mode 100644 taskman-server/vendor/xorm.io/builder/README.md delete mode 100644 taskman-server/vendor/xorm.io/builder/builder.go delete mode 100644 taskman-server/vendor/xorm.io/builder/builder_delete.go delete mode 100644 taskman-server/vendor/xorm.io/builder/builder_insert.go delete mode 100644 taskman-server/vendor/xorm.io/builder/builder_join.go delete mode 100644 taskman-server/vendor/xorm.io/builder/builder_limit.go delete mode 100644 taskman-server/vendor/xorm.io/builder/builder_select.go delete mode 100644 taskman-server/vendor/xorm.io/builder/builder_set_operations.go delete mode 100644 taskman-server/vendor/xorm.io/builder/builder_update.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_and.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_between.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_compare.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_eq.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_expr.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_if.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_in.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_like.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_neq.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_not.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_notin.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_null.go delete mode 100644 taskman-server/vendor/xorm.io/builder/cond_or.go delete mode 100644 taskman-server/vendor/xorm.io/builder/doc.go delete mode 100644 taskman-server/vendor/xorm.io/builder/error.go delete mode 100644 taskman-server/vendor/xorm.io/builder/go.mod delete mode 100644 taskman-server/vendor/xorm.io/builder/go.sum delete mode 100644 taskman-server/vendor/xorm.io/builder/sql.go delete mode 100644 taskman-server/vendor/xorm.io/builder/writer.go delete mode 100644 taskman-server/vendor/xorm.io/core/.drone.yml delete mode 100644 taskman-server/vendor/xorm.io/core/.gitignore delete mode 100644 taskman-server/vendor/xorm.io/core/LICENSE delete mode 100644 taskman-server/vendor/xorm.io/core/README.md delete mode 100644 taskman-server/vendor/xorm.io/core/benchmark.sh delete mode 100644 taskman-server/vendor/xorm.io/core/cache.go delete mode 100644 taskman-server/vendor/xorm.io/core/column.go delete mode 100644 taskman-server/vendor/xorm.io/core/converstion.go delete mode 100644 taskman-server/vendor/xorm.io/core/db.go delete mode 100644 taskman-server/vendor/xorm.io/core/dialect.go delete mode 100644 taskman-server/vendor/xorm.io/core/driver.go delete mode 100644 taskman-server/vendor/xorm.io/core/error.go delete mode 100644 taskman-server/vendor/xorm.io/core/filter.go delete mode 100644 taskman-server/vendor/xorm.io/core/go.mod delete mode 100644 taskman-server/vendor/xorm.io/core/go.sum delete mode 100644 taskman-server/vendor/xorm.io/core/ilogger.go delete mode 100644 taskman-server/vendor/xorm.io/core/index.go delete mode 100644 taskman-server/vendor/xorm.io/core/mapper.go delete mode 100644 taskman-server/vendor/xorm.io/core/pk.go delete mode 100644 taskman-server/vendor/xorm.io/core/rows.go delete mode 100644 taskman-server/vendor/xorm.io/core/scan.go delete mode 100644 taskman-server/vendor/xorm.io/core/stmt.go delete mode 100644 taskman-server/vendor/xorm.io/core/table.go delete mode 100644 taskman-server/vendor/xorm.io/core/tx.go delete mode 100644 taskman-server/vendor/xorm.io/core/type.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/.changelog.yml delete mode 100644 taskman-server/vendor/xorm.io/xorm/.drone.yml delete mode 100644 taskman-server/vendor/xorm.io/xorm/.gitignore delete mode 100644 taskman-server/vendor/xorm.io/xorm/.revive.toml delete mode 100644 taskman-server/vendor/xorm.io/xorm/CHANGELOG.md delete mode 100644 taskman-server/vendor/xorm.io/xorm/CONTRIBUTING.md delete mode 100644 taskman-server/vendor/xorm.io/xorm/LICENSE delete mode 100644 taskman-server/vendor/xorm.io/xorm/Makefile delete mode 100644 taskman-server/vendor/xorm.io/xorm/README.md delete mode 100644 taskman-server/vendor/xorm.io/xorm/README_CN.md delete mode 100644 taskman-server/vendor/xorm.io/xorm/caches/cache.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/caches/encode.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/caches/leveldb.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/caches/lru.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/caches/manager.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/caches/memory_store.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/contexts/context_cache.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/contexts/hook.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/bool.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/conversion.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/float.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/int.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/interface.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/scanner.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/string.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/convert/time.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/core/db.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/core/error.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/core/interface.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/core/rows.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/core/scan.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/core/stmt.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/core/tx.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/dialect.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/driver.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/filter.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/gen_reserved.sh delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/mssql.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/mysql.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/oracle.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/pg_reserved.txt delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/postgres.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/quote.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/sqlite3.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/table_name.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/dialects/time.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/doc.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/engine.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/engine_group.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/engine_group_policy.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/error.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/go.mod delete mode 100644 taskman-server/vendor/xorm.io/xorm/go.sum delete mode 100644 taskman-server/vendor/xorm.io/xorm/interface.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/json/gojson.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/json/json.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/json/jsoniter.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/cache.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/column_map.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/expr.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/insert.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/pk.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/query.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/statement.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/statement_args.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/update.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/statements/values.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/utils/name.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/utils/new.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/utils/reflect.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/utils/slice.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/utils/sql.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/utils/strings.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/internal/utils/zero.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/log/logger.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/log/logger_context.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/log/syslogger.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/names/mapper.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/names/table_name.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/processors.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/rows.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/scan.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/schemas/column.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/schemas/index.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/schemas/pk.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/schemas/quote.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/schemas/table.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/schemas/type.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/schemas/version.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_cols.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_cond.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_delete.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_exist.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_find.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_get.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_insert.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_iterate.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_query.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_raw.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_schema.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_stats.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_tx.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/session_update.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/tags/parser.go delete mode 100644 taskman-server/vendor/xorm.io/xorm/tags/tag.go diff --git a/taskman-server/dao/db.go b/taskman-server/dao/db.go index e7a60ee6..b189d72c 100644 --- a/taskman-server/dao/db.go +++ b/taskman-server/dao/db.go @@ -42,6 +42,12 @@ func InitDatabase() (engine *xorm.Engine, err error) { return } +// logExecuteSql 打印执行sql +func logExecuteSql(session *xorm.Session, module, method string, objectParam interface{}, affected int64, err error) { + sql, param := session.LastSQL() + log.DatabaseLogger.Debug(fmt.Sprintf("%s exec %s sql", module, method), log.String("sql", sql), log.JsonObj("param", param), log.JsonObj("objectParam", objectParam), log.Int64("affected", affected), log.Error(err)) +} + type dbLogger struct { LogLevel xorm_log.LogLevel ShowSql bool diff --git a/taskman-server/dao/form_item_templdate_dao.go b/taskman-server/dao/form_item_template_dao.go similarity index 95% rename from taskman-server/dao/form_item_templdate_dao.go rename to taskman-server/dao/form_item_template_dao.go index a54acf8b..623d9544 100644 --- a/taskman-server/dao/form_item_templdate_dao.go +++ b/taskman-server/dao/form_item_template_dao.go @@ -52,6 +52,6 @@ func (d FormItemTemplateDao) Delete(session *xorm.Session, id string) (err error session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.Where("id=?", id).Delete(&models.FormItemTemplateTable{}) + _, err = d.DB.ID(id).Delete(&models.FormItemTemplateTable{}) return } diff --git a/taskman-server/dao/form_template_dao.go b/taskman-server/dao/form_template_dao.go index 6b5559d5..94d418bb 100644 --- a/taskman-server/dao/form_template_dao.go +++ b/taskman-server/dao/form_template_dao.go @@ -14,15 +14,27 @@ func (d FormTemplateDao) Add(session *xorm.Session, formTemplate *models.FormTem session = d.DB.NewSession() defer session.Close() } - return session.InsertOne(formTemplate) + affected, err = session.Insert(formTemplate) + // 打印日志 + logExecuteSql(session, "FormTemplateDao", "Add", formTemplate, affected, err) + return } func (d FormTemplateDao) Update(session *xorm.Session, formTemplate *models.FormTemplateTable) (err error) { + var affected int64 if session == nil { session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.Where("id=?", formTemplate.Id).Update(formTemplate) + if formTemplate == nil || formTemplate.Id == "" { + return + } + affected, err = session.ID(formTemplate.Id).Update(formTemplate) + // 打印日志 + logExecuteSql(session, "FormTemplateDao", "Update", formTemplate, affected, err) + if err != nil { + return + } return } @@ -31,7 +43,7 @@ func (d FormTemplateDao) Get(formTemplateId string) (*models.FormTemplateTable, var found bool var err error formTemplate = &models.FormTemplateTable{} - found, err = d.DB.Where("id=?", formTemplateId).Get(formTemplate) + found, err = d.DB.ID(formTemplateId).Get(formTemplate) if err != nil { return nil, err } @@ -40,3 +52,12 @@ func (d FormTemplateDao) Get(formTemplateId string) (*models.FormTemplateTable, } return nil, nil } + +func (d FormTemplateDao) Delete(session *xorm.Session, id string) (err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + _, err = d.DB.ID(id).Delete(&models.FormItemTemplateTable{}) + return +} diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index e1fdcf82..e165f97a 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -1,6 +1,7 @@ package dao import ( + "database/sql" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "xorm.io/xorm" ) @@ -15,15 +16,49 @@ func (d RequestTemplateDao) Add(session *xorm.Session, requestTemplate *models.R session = d.DB.NewSession() defer session.Close() } - return session.InsertOne(requestTemplate) + affected, err = session.Insert(requestTemplate) + // 打印日志 + logExecuteSql(session, "RequestTemplateDao", "Add", requestTemplate, affected, err) + return +} + +// AddBasicInfo 添加模板基础信息(此处用SQL形式添加,由于RequestTemplateTable中包含外键字段,外键form_template传递"",新增数据会报错) +func (d RequestTemplateDao) AddBasicInfo(session *xorm.Session, template *models.RequestTemplateTable) (affected int64, err error) { + var result sql.Result + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + result, err = session.Exec("insert into request_template(id,`group`,name,description,tags,package_name,entity_name,proc_def_key,proc_def_id,"+ + "proc_def_name,expire_day,handler,created_by,created_time,updated_by,updated_time,type,operator_obj_type,parent_id,approve_by,pending_switch,"+ + "pending_role,pending_handler,confirm_switch,confirm_expire_day,rollback_desc) value (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", template.Id, + template.Group, template.Name, template.Description, template.Tags, template.PackageName, template.EntityName, template.ProcDefKey, template.ProcDefId, + template.ProcDefName, template.ExpireDay, template.Handler, template.CreatedBy, template.CreatedTime, template.UpdatedBy, template.UpdatedTime, template.OperatorObjType, + template.Id, template.ApproveBy, template.PendingSwitch, template.PendingRole, template.PendingHandler, template.ConfirmSwitch, template.ConfirmExpireDay, template.RollbackDesc) + if err != nil { + return + } + affected, err = result.RowsAffected() + return } func (d RequestTemplateDao) Update(session *xorm.Session, requestTemplate *models.RequestTemplateTable) (err error) { + var affected int64 if session == nil { session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.ID(requestTemplate.Id).Update(requestTemplate) + if requestTemplate == nil || requestTemplate.Id == "" { + return + } + // 由于RequestTemplateTable里面包含version字段,此处需要去掉xorm自带版本校验 + session.NoVersionCheck() + affected, err = session.ID(requestTemplate.Id).Update(requestTemplate) + // 打印日志 + logExecuteSql(session, "RequestTemplateDao", "Update", requestTemplate, affected, err) + if err != nil { + return + } return } @@ -32,7 +67,7 @@ func (d RequestTemplateDao) Get(requestTemplateId string) (*models.RequestTempla var found bool var err error requestTemplate = &models.RequestTemplateTable{} - found, err = d.DB.Where("id=?", requestTemplateId).Get(requestTemplate) + found, err = d.DB.ID(requestTemplateId).Get(requestTemplate) if err != nil { return nil, err } diff --git a/taskman-server/dao/request_template_role_dao.go b/taskman-server/dao/request_template_role_dao.go index 59636132..d77ce67c 100644 --- a/taskman-server/dao/request_template_role_dao.go +++ b/taskman-server/dao/request_template_role_dao.go @@ -19,5 +19,8 @@ func (d RequestTemplateRoleDao) Add(session *xorm.Session, requestTemplateRole * session = d.DB.NewSession() defer session.Close() } - return session.InsertOne(requestTemplateRole) + affected, err = session.Insert(requestTemplateRole) + // 打印日志 + logExecuteSql(session, "RequestTemplateRoleDao", "Add", requestTemplateRole, affected, err) + return } diff --git a/taskman-server/go.mod b/taskman-server/go.mod index 96414683..b6ac223e 100644 --- a/taskman-server/go.mod +++ b/taskman-server/go.mod @@ -1,13 +1,51 @@ module github.com/WeBankPartners/wecube-plugins-taskman/taskman-server -go 1.16 +go 1.18 require ( github.com/WeBankPartners/go-common-lib v1.0.7 github.com/gin-gonic/gin v1.7.4 - github.com/go-sql-driver/mysql v1.6.0 + github.com/go-sql-driver/mysql v1.7.0 github.com/tealeg/xlsx v1.0.5 go.uber.org/zap v1.19.0 xorm.io/core v0.7.3 - xorm.io/xorm v1.2.3 + xorm.io/xorm v1.3.8 +) + +require ( + github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect + github.com/dustin/go-humanize v1.0.0 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.13.0 // indirect + github.com/go-playground/universal-translator v0.17.0 // indirect + github.com/go-playground/validator/v10 v10.4.1 // indirect + github.com/goccy/go-json v0.8.1 // indirect + github.com/golang/protobuf v1.3.3 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/compress v1.13.5 // indirect + github.com/klauspost/cpuid v1.3.1 // indirect + github.com/leodido/go-urn v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.16 // indirect + github.com/minio/md5-simd v1.1.0 // indirect + github.com/minio/minio-go/v7 v7.0.15 // indirect + github.com/minio/sha256-simd v0.1.1 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/rs/xid v1.2.1 // indirect + github.com/sirupsen/logrus v1.8.1 // indirect + github.com/syndtr/goleveldb v1.0.0 // indirect + github.com/ugorji/go/codec v1.1.7 // indirect + go.uber.org/atomic v1.7.0 // indirect + go.uber.org/multierr v1.6.0 // indirect + golang.org/x/crypto v0.12.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.11.0 // indirect + golang.org/x/text v0.12.0 // indirect + gopkg.in/ini.v1 v1.57.0 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect + gopkg.in/yaml.v2 v2.2.8 // indirect + xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect ) diff --git a/taskman-server/go.sum b/taskman-server/go.sum index faa469ae..0c0af5fe 100644 --- a/taskman-server/go.sum +++ b/taskman-server/go.sum @@ -1,84 +1,23 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:lSA0F4e9A2NcQSqGqTOXqu2aRi/XEQxDCBwM8yJtE6s= gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:EXuID2Zs0pAQhH8yz+DNjUbjppKQzKFAn28TMYPB6IU= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.4.1 h1:GaI7EiDXDRfa8VshkTj7Fym7ha+y8/XxIgD2okUIjLw= github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= -github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= -github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= -github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= -github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= github.com/WeBankPartners/go-common-lib v1.0.7 h1:MzMsNfsYdkkIVszF8vbHSnptnqu3saYcQiIi8UjJZHc= github.com/WeBankPartners/go-common-lib v1.0.7/go.mod h1:wTYOF5NSO0e9Isov/aD4i+ZwSe0GFG8Vdm0nRKr4so8= -github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= -github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= -github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= -github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= -github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= -github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= -github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/denisenkom/go-mssqldb v0.10.0/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= -github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= -github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= -github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= -github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= -github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.7.4 h1:QmUZXrvJ9qZ3GfWvQ+2wnW/1ePrTEJqPKMYEU3lD/DM= github.com/gin-gonic/gin v1.7.4/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= @@ -87,544 +26,177 @@ github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD87 github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= -github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= -github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/goccy/go-json v0.7.4 h1:B44qRUFwz/vxPKPISQ1KhvzRi9kZ28RAf6YtjriBZ5k= -github.com/goccy/go-json v0.7.4/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/goccy/go-json v0.8.1 h1:4/Wjm0JIJaTDm8K1KcGrLHJoa8EsJ13YWeX+6Kfq6uI= +github.com/goccy/go-json v0.8.1/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= -github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= -github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= -github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= -github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= -github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA= -github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE= -github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s= -github.com/jackc/pgconn v1.4.0/go.mod h1:Y2O3ZDF0q4mMacyWV3AstPJpeHXWGEetiFttmq5lahk= -github.com/jackc/pgconn v1.5.0/go.mod h1:QeD3lBfpTFe8WUnPZWN5KY/mB8FGMIYRdd8P8Jr0fAI= -github.com/jackc/pgconn v1.5.1-0.20200601181101-fa742c524853/go.mod h1:QeD3lBfpTFe8WUnPZWN5KY/mB8FGMIYRdd8P8Jr0fAI= -github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= -github.com/jackc/pgconn v1.8.1/go.mod h1:JV6m6b6jhjdmzchES0drzCcYcAHS1OPD5xu3OZ/lE2g= -github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY= -github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= -github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= -github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= -github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg= -github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgservicefile v0.0.0-20200307190119-3430c5407db8/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= -github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= -github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= -github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= -github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= -github.com/jackc/pgtype v1.2.0/go.mod h1:5m2OfMh1wTK7x+Fk952IDmI4nw3nPrvtQdM0ZT4WpC0= -github.com/jackc/pgtype v1.3.1-0.20200510190516-8cd94a14c75a/go.mod h1:vaogEUkALtxZMCH411K+tKzNpwzCKU+AnPzBKZ+I+Po= -github.com/jackc/pgtype v1.3.1-0.20200606141011-f6355165a91c/go.mod h1:cvk9Bgu/VzJ9/lxTO5R5sf80p0DiucVtN7ZxvaC4GmQ= -github.com/jackc/pgtype v1.7.0/go.mod h1:ZnHF+rMePVqDKaOfJVI4Q8IVvAQMryDlDkZnKOI75BE= -github.com/jackc/pgtype v1.8.0/go.mod h1:PqDKcEBtllAtk/2p6z6SHdXW5UB+MhE75tUol2OKexE= -github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= -github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM= -github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= -github.com/jackc/pgx/v4 v4.5.0/go.mod h1:EpAKPLdnTorwmPUUsqrPxy5fphV18j9q3wrfRXgo+kA= -github.com/jackc/pgx/v4 v4.6.1-0.20200510190926-94ba730bb1e9/go.mod h1:t3/cdRQl6fOLDxqtlyhe9UWgfIi9R8+8v8GKV5TRA/o= -github.com/jackc/pgx/v4 v4.6.1-0.20200606145419-4e5062306904/go.mod h1:ZDaNWkt9sW1JMiNn0kdYBaLelIhw7Pg4qd+Vk6tw7Hg= -github.com/jackc/pgx/v4 v4.11.0/go.mod h1:i62xJgdrtVDsnL3U8ekyrQXEwGNTRoG7/8r+CIdYfcc= -github.com/jackc/pgx/v4 v4.12.0/go.mod h1:fE547h6VulLPA3kySjfnSG/e2D861g/50JlVUa/ub60= -github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v1.1.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v1.1.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= -github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.13.5 h1:9O69jUPDcsT9fEm74W92rZL9FQY7rCdaXVneq+yyzl4= github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/klauspost/cpuid v1.2.3/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/cpuid v1.3.1 h1:5JNjFYYQrZeKRJ0734q51WCEEn2huer72Dc7K+R/b6s= github.com/klauspost/cpuid v1.3.1/go.mod h1:bYW4mA6ZgKPob1/Dlai2LviZJO7KGI3uoWLd42rAQw4= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= -github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= -github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= -github.com/mattn/go-sqlite3 v1.14.8 h1:gDp86IdQsN/xWjIEmr9MF6o9mpksUgh0fu+9ByFxzIU= -github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= github.com/minio/md5-simd v1.1.0 h1:QPfiOqlZH+Cj9teu0t9b1nTBfPbyTl16Of5MeuShdK4= github.com/minio/md5-simd v1.1.0/go.mod h1:XpBqgZULrMYD3R+M28PcmP0CkI7PEMzB3U77ZrKZ0Gw= github.com/minio/minio-go/v7 v7.0.15 h1:r9/NhjJ+nXYrIYvbObhvc1wPj3YH1iDpJzz61uRKLyY= github.com/minio/minio-go/v7 v7.0.15/go.mod h1:pUV0Pc+hPd1nccgmzQF/EXh48l/Z/yps6QPF1aaie4g= github.com/minio/sha256-simd v0.1.1 h1:5QHSlgo3nt5yKOJrC7W8w7X+NFl8cMPZm96iu8kKUJU= github.com/minio/sha256-simd v0.1.1/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM= -github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= -github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= -github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= -github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= -github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= -github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= -github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= -github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= -github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= -github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= -github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= -github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= -github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= -github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA= -github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= -github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= -github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= -github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= -github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= -github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= -github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rs/xid v1.2.1 h1:mhH9Nq+C1fY2l1XIpgxIiUOfNpRBYH1kKcr+qfKgjRc= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= -github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= -github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= -github.com/shopspring/decimal v0.0.0-20200227202807-02e2044944cc/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= -github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= -github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= -github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE= github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ= github.com/tealeg/xlsx v1.0.5 h1:+f8oFmvY8Gw1iUXzPk+kz+4GpbDZPK1FhPiQRd+ypgE= github.com/tealeg/xlsx v1.0.5/go.mod h1:btRS8dz54TDnvKNosuAqxrM1QgN1udgk9O34bDCnORM= -github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= -github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0= -go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= -go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= -go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= -go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= -go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.19.0 h1:mZQZefskPPCMIBCSEH0v2/iUqqLrYtaeqwD6FUGUnFE= go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e h1:gsTQYXdTw2Gq7RBsWvlQ91b+aEQ6bXFUngBGuR8sPpI= -golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 h1:M8tBwCtWD/cZV9DZpFYRUgaymAYAr+aIUTWzDaM3uPs= -golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= -gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= gopkg.in/ini.v1 v1.57.0 h1:9unxIsFcTt4I55uWluz+UmL95q4kdJ0buvQ1ZIqVQww= gopkg.in/ini.v1 v1.57.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -lukechampine.com/uint128 v1.1.1 h1:pnxCASz787iMf+02ssImqk6OLt+Z5QHMoZyUXR4z6JU= -lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= -modernc.org/cc/v3 v3.33.6 h1:r63dgSzVzRxUpAJFPQWHy1QeZeY1ydNENUDaBx1GqYc= -modernc.org/cc/v3 v3.33.6/go.mod h1:iPJg1pkwXqAV16SNgFBVYmggfMg6xhs+2oiO0vclK3g= -modernc.org/ccgo/v3 v3.9.5 h1:dEuUSf8WN51rDkprFuAqjfchKEzN0WttP/Py3enBwjk= -modernc.org/ccgo/v3 v3.9.5/go.mod h1:umuo2EP2oDSBnD3ckjaVUXMrmeAw8C8OSICVa0iFf60= -modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM= -modernc.org/libc v1.7.13-0.20210308123627-12f642a52bb8/go.mod h1:U1eq8YWr/Kc1RWCMFUWEdkTg8OTcfLw2kY8EDwl039w= -modernc.org/libc v1.9.8/go.mod h1:U1eq8YWr/Kc1RWCMFUWEdkTg8OTcfLw2kY8EDwl039w= -modernc.org/libc v1.9.11 h1:QUxZMs48Ahg2F7SN41aERvMfGLY2HU/ADnB9DC4Yts8= -modernc.org/libc v1.9.11/go.mod h1:NyF3tsA5ArIjJ83XB0JlqhjTabTCHm9aX4XMPHyQn0Q= -modernc.org/mathutil v1.1.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= -modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= -modernc.org/mathutil v1.4.0 h1:GCjoRaBew8ECCKINQA2nYjzvufFW9YiEuuB+rQ9bn2E= -modernc.org/mathutil v1.4.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= -modernc.org/memory v1.0.4 h1:utMBrFcpnQDdNsmM6asmyH/FM9TqLPS7XF7otpJmrwM= -modernc.org/memory v1.0.4/go.mod h1:nV2OApxradM3/OVbs2/0OsP6nPfakXpi50C7dcoHXlc= -modernc.org/opt v0.1.1 h1:/0RX92k9vwVeDXj+Xn23DKp2VJubL7k8qNffND6qn3A= -modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= -modernc.org/sqlite v1.11.2 h1:ShWQpeD3ag/bmx6TqidBlIWonWmQaSQKls3aenCbt+w= -modernc.org/sqlite v1.11.2/go.mod h1:+mhs/P1ONd+6G7hcAs6irwDi/bjTQ7nLW6LHRBsEa3A= -modernc.org/strutil v1.1.1 h1:xv+J1BXY3Opl2ALrBwyfEikFAj8pmqcpnfmuwUwcozs= -modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw= -modernc.org/tcl v1.5.5/go.mod h1:ADkaTUuwukkrlhqwERyq0SM8OvyXo7+TjFz7yAF56EI= -modernc.org/token v1.0.0 h1:a0jaWiNMDhDUtqOj09wvjWWAqd3q7WpBulmL9H2egsk= -modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= -modernc.org/z v1.0.1/go.mod h1:8/SRk5C/HgiQWCgXdfpb+1RvhORdkz5sw72d3jjtyqA= -sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= -sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= -xorm.io/builder v0.3.9 h1:Sd65/LdWyO7LR8+Cbd+e7mm3sK/7U9k0jS3999IDHMc= -xorm.io/builder v0.3.9/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI= +modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw= +modernc.org/ccgo/v3 v3.16.13 h1:Mkgdzl46i5F/CNR/Kj80Ri59hC8TKAhZrYSaqvkwzUw= +modernc.org/libc v1.22.2 h1:4U7v51GyhlWqQmwCHj28Rdq2Yzwk55ovjFrdPjs8Hb0= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/memory v1.4.0 h1:crykUfNSnMAXaOJnnxcSzbUGMqkLWjklJKkBK2nwZwk= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/sqlite v1.20.4 h1:J8+m2trkN+KKoE7jglyHYYYiaq5xmz2HoHJIiBlRzbE= +modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY= +modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg= +xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 h1:bvLlAPW1ZMTWA32LuZMBEGHAUOcATZjzHcotf3SWweM= +xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE= xorm.io/core v0.7.3 h1:W8ws1PlrnkS1CZU1YWaYLMQcQilwAmQXU0BJDJon+H0= xorm.io/core v0.7.3/go.mod h1:jJfd0UAEzZ4t87nbQYtVjmqpIODugN6PD2D9E+dJvdM= -xorm.io/xorm v1.2.3 h1:ZsVtQEsfkA31bbe8lhrP5cZKUjrxXQQO5tsr7Tf/0eo= -xorm.io/xorm v1.2.3/go.mod h1:fTG8tSjk6O1BYxwuohZUK+S1glnRycsCF05L1qQyEU0= +xorm.io/xorm v1.3.8 h1:CJmplmWqfSRpLWSPMmqz+so8toBp3m7ehuRehIWedZo= +xorm.io/xorm v1.3.8/go.mod h1:LsCCffeeYp63ssk0pKumP6l96WZcHix7ChpurcLNuMw= diff --git a/taskman-server/models/approve.go b/taskman-server/models/approve.go index 44c9be1e..46e48b0b 100644 --- a/taskman-server/models/approve.go +++ b/taskman-server/models/approve.go @@ -2,7 +2,7 @@ package models // RequestApproveTable 请求审批表 type RequestApproveTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Request string `json:"request" xorm:"request"` // 请求ID Name string `json:"name" xorm:"name"` // 审批名称 ExpireDay string `json:"expireDay" xorm:"expire_day"` // 审批时效 diff --git a/taskman-server/models/attach_file.go b/taskman-server/models/attach_file.go index 1bf2b7de..3c04eeb0 100644 --- a/taskman-server/models/attach_file.go +++ b/taskman-server/models/attach_file.go @@ -1,7 +1,7 @@ package models type AttachFileTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` S3BucketName string `json:"s3BucketName" xorm:"s3_bucket_name"` S3KeyName string `json:"s3KeyName" xorm:"s3_key_name"` diff --git a/taskman-server/models/cmdb.go b/taskman-server/models/cmdb.go index 6505f17f..8d5a8f39 100644 --- a/taskman-server/models/cmdb.go +++ b/taskman-server/models/cmdb.go @@ -1,7 +1,7 @@ package models type SysCiTypeAttrTable struct { - Id string `json:"ciTypeAttrId" xorm:"id"` + Id string `json:"ciTypeAttrId" xorm:"'id' pk"` CiType string `json:"ciTypeId" xorm:"ci_type"` Name string `json:"propertyName" xorm:"name"` DisplayNameTmp string `json:"displayName" xorm:"-"` diff --git a/taskman-server/models/collect_template.go b/taskman-server/models/collect_template.go index 080105cb..7e9a1769 100644 --- a/taskman-server/models/collect_template.go +++ b/taskman-server/models/collect_template.go @@ -2,7 +2,7 @@ package models // CollectTemplateTable 收藏模板 type CollectTemplateTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` RequestTemplate string `json:"requestTemplate" xorm:"request_template"` // 收藏模板ID User string `json:"user" xorm:"user"` // 收藏用户 Role string `json:"role" xorm:"role"` // 收藏模板时角色 diff --git a/taskman-server/models/form.go b/taskman-server/models/form.go index b9b35e8f..9da7407d 100644 --- a/taskman-server/models/form.go +++ b/taskman-server/models/form.go @@ -1,7 +1,7 @@ package models type FormTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` FormTemplate string `json:"formTemplate" xorm:"form_template"` diff --git a/taskman-server/models/form_item.go b/taskman-server/models/form_item.go index b881d7ba..708809ff 100644 --- a/taskman-server/models/form_item.go +++ b/taskman-server/models/form_item.go @@ -1,7 +1,7 @@ package models type FormItemTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Form string `json:"form" xorm:"form"` FormItemTemplate string `json:"formItemTemplate" xorm:"form_item_template"` Name string `json:"name" xorm:"name"` diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index 5e4dff4b..3614cb4a 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -1,7 +1,7 @@ package models type FormItemTemplateTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` ItemGroup string `json:"itemGroup" xorm:"item_group"` diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index 841875a8..8980519b 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -1,7 +1,7 @@ package models type FormTemplateTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` CreatedBy string `json:"createdBy" xorm:"created_by"` @@ -27,7 +27,7 @@ type FormTemplateDto struct { } type TaskFormItemQueryObj struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Form string `json:"form" xorm:"form"` FormItemTemplate string `json:"formItemTemplate" xorm:"form_item_template"` Name string `json:"name" xorm:"name"` diff --git a/taskman-server/models/operation_log.go b/taskman-server/models/operation_log.go index f09afb2c..44b51952 100644 --- a/taskman-server/models/operation_log.go +++ b/taskman-server/models/operation_log.go @@ -6,7 +6,7 @@ import ( ) type OperationLogTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Request string `json:"request" xorm:"request"` RequestName string `json:"requestName" xorm:"request_name"` RequestTemplate string `json:"requestTemplate" xorm:"request_template"` diff --git a/taskman-server/models/request.go b/taskman-server/models/request.go index 5e55ccda..8851229e 100644 --- a/taskman-server/models/request.go +++ b/taskman-server/models/request.go @@ -3,7 +3,7 @@ package models import "strings" type RequestTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Form string `json:"form" xorm:"form"` RequestTemplate string `json:"requestTemplate" xorm:"request_template"` @@ -56,7 +56,7 @@ type PlatformData struct { // PlatformDataObj 工作台返回数据 type PlatformDataObj struct { - Id string `json:"id" xorm:"id"` // 请求ID + Id string `json:"id" xorm:"'id' pk"` // 请求ID Name string `json:"name" xorm:"name"` // 请求名称 TemplateId string `json:"templateId" xorm:"template_id"` // 模板ID TemplateName string `json:"templateName" xorm:"template_name"` // 使用模板名称 @@ -273,7 +273,7 @@ func (q KeyValueSort) Swap(i, j int) { } type FilterObj struct { - Id string `json:"id" xorm:"id"` // requestID + Id string `json:"id" xorm:"'id' pk"` // requestID TemplateId string `json:"templateId" xorm:"template_id"` // 模板IDa TemplateName string `json:"templateName" xorm:"template_name"` // 模板名称 Version string `json:"version" xorm:"version"` // 模板版本 diff --git a/taskman-server/models/request_approve_role.go b/taskman-server/models/request_approve_role.go index 3c4d55bd..9165002e 100644 --- a/taskman-server/models/request_approve_role.go +++ b/taskman-server/models/request_approve_role.go @@ -2,7 +2,7 @@ package models // RequestApproveRoleTable 请求审批角色表 type RequestApproveRoleTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` RequestApprove string `json:"requestApprove" xorm:"request_approve"` // 请求审批ID Role string `json:"role" xorm:"role"` // 角色 handler string `json:"handler" xorm:"handler"` // 处理人 diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index a83e4c62..514b5610 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -5,63 +5,50 @@ import ( ) type RequestTemplateTable struct { - Id string `json:"id" xorm:"id"` - Group string `json:"group" xorm:"group"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` - FormTemplate *string `json:"formTemplate" xorm:"form_template"` // 此处定义成指针类型原因: request_template表插入数据,form_template字段为""也会被插入,又是外键就会报错 - DataFormTemplate *string `json:"dataFormTemplate" xorm:"data_form_template"` - Tags string `json:"tags" xorm:"tags"` - Status string `json:"status" xorm:"status"` - RecordId string `json:"recordId" xorm:"record_id"` - Version string `json:"version" xorm:"version"` - ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` - PackageName string `json:"packageName" xorm:"package_name"` - EntityName string `json:"entityName" xorm:"entity_name"` - ProcDefKey string `json:"procDefKey" xorm:"proc_def_key"` - ProcDefId string `json:"procDefId" xorm:"proc_def_id"` - ProcDefName string `json:"procDefName" xorm:"proc_def_name"` - CreatedBy string `json:"createdBy" xorm:"created_by"` - CreatedTime string `json:"createdTime" xorm:"created_time"` - UpdatedBy string `json:"updatedBy" xorm:"updated_by"` - UpdatedTime string `json:"updatedTime" xorm:"updated_time"` - EntityAttrs string `json:"entityAttrs" xorm:"entity_attrs"` - ExpireDay int `json:"expireDay" xorm:"expire_day"` - Handler string `json:"handler" xorm:"handler"` - DelFlag int `json:"delFlag" xorm:"del_flag"` - Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 - OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 - ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID - ApproveBy string `json:"approveBy" xorm:"approve_by"` // 模板发布审批人 - PendingSwitch bool `json:"pendingSwitch" xorm:"pending_switch"` // 是否加入确认定版流程 - PendingRole string `json:"pendingRole" xorm:"pending_role"` // 定版角色 - PendingHandler string `json:"pendingHandler" xorm:"pending_handler"` // 定版处理人 - ConfirmSwitch bool `json:"confirmSwitch" xorm:"confirm_switch"` // 是否加入确认流程 - ConfirmExpireDay int `json:"confirmExpireDay" xorm:"confirm_expire_day"` // 是否加入确认流程 - RollbackDesc string `json:"rollbackDesc" xorm:"rollback_desc"` // 退回理由 + Id string `json:"id" xorm:"'id' pk"` + Group string `json:"group" xorm:"group"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + FormTemplate string `json:"formTemplate" xorm:"form_template"` // 此处定义成指针类型原因: request_template表插入数据,form_template字段为""也会被插入,又是外键就会报错 + DataFormTemplate string `json:"dataFormTemplate" xorm:"data_form_template"` + Tags string `json:"tags" xorm:"tags"` + Status string `json:"status" xorm:"status"` + RecordId string `json:"recordId" xorm:"record_id"` + Version string `json:"version" xorm:"version"` + ConfirmTime string `json:"confirmTime" xorm:"confirm_time"` + PackageName string `json:"packageName" xorm:"package_name"` + EntityName string `json:"entityName" xorm:"entity_name"` + ProcDefKey string `json:"procDefKey" xorm:"proc_def_key"` + ProcDefId string `json:"procDefId" xorm:"proc_def_id"` + ProcDefName string `json:"procDefName" xorm:"proc_def_name"` + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` + EntityAttrs string `json:"entityAttrs" xorm:"entity_attrs"` + ExpireDay int `json:"expireDay" xorm:"expire_day"` + Handler string `json:"handler" xorm:"handler"` + DelFlag int `json:"delFlag" xorm:"del_flag"` + Type int `json:"type" xorm:"type"` // 请求类型, 0表示请求,1表示发布 + OperatorObjType string `json:"operatorObjType" xorm:"operator_obj_type"` // 操作对象类型 + ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID + ApproveBy string `json:"approveBy" xorm:"approve_by"` // 模板发布审批人 + PendingSwitch bool `json:"pendingSwitch" xorm:"pending_switch"` // 是否加入确认定版流程 + PendingRole string `json:"pendingRole" xorm:"pending_role"` // 定版角色 + PendingHandler string `json:"pendingHandler" xorm:"pending_handler"` // 定版处理人 + ConfirmSwitch bool `json:"confirmSwitch" xorm:"confirm_switch"` // 是否加入确认流程 + ConfirmExpireDay int `json:"confirmExpireDay" xorm:"confirm_expire_day"` // 是否加入确认流程 + RollbackDesc string `json:"rollbackDesc" xorm:"rollback_desc"` // 退回理由 } func (RequestTemplateTable) TableName() string { return "request_template" } -func (r RequestTemplateTable) GetFormTemplate() string { - if r.FormTemplate == nil { - return "" - } - return *r.FormTemplate -} -func (r RequestTemplateTable) SetFormTemplate(formTemplate string) { - if formTemplate == "" { - return - } - r.FormTemplate = &formTemplate -} - // CollectDataObj 收藏数据项 type CollectDataObj struct { ParentId string `json:"parentId" xorm:"parent_id"` // 父类ID - Id string `json:"id" xorm:"id"` // 模版ID + Id string `json:"id" xorm:"'id' pk"` // 模版ID Name string `json:"name" xorm:"name"` // 模版名称 Version string `json:"version" xorm:"version"` // 模版名称 Status int `json:"status" xorm:"status"` // 模版状态: 1可使用 2已禁用 3权限被移除 @@ -115,7 +102,7 @@ type UserRequestTemplateQueryObj struct { } type RequestTemplateTableObj struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Version string `json:"version" xorm:"version"` Tags string `json:"tags" xorm:"tags"` diff --git a/taskman-server/models/request_template_group.go b/taskman-server/models/request_template_group.go index f4ca01ad..92e149ce 100644 --- a/taskman-server/models/request_template_group.go +++ b/taskman-server/models/request_template_group.go @@ -1,7 +1,7 @@ package models type RequestTemplateGroupTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name" binding:"required"` Description string `json:"description" xorm:"description"` ManageRole string `json:"manageRole" xorm:"manage_role" binding:"required"` diff --git a/taskman-server/models/request_template_role.go b/taskman-server/models/request_template_role.go index a632ee4c..59fad875 100644 --- a/taskman-server/models/request_template_role.go +++ b/taskman-server/models/request_template_role.go @@ -1,7 +1,7 @@ package models type RequestTemplateRoleTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` RequestTemplate string `json:"requestTemplate" xorm:"request_template"` Role string `json:"role" xorm:"role"` RoleType string `json:"roleType" xorm:"role_type"` diff --git a/taskman-server/models/role.go b/taskman-server/models/role.go index 965d5c64..e35ccc4a 100644 --- a/taskman-server/models/role.go +++ b/taskman-server/models/role.go @@ -1,7 +1,7 @@ package models type RoleTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` DisplayName string `json:"displayName" xorm:"display_name"` UpdatedTime string `json:"updatedTime" xorm:"updated_time"` CoreId string `json:"coreId" xorm:"core_id"` diff --git a/taskman-server/models/task.go b/taskman-server/models/task.go index b811466d..03e1e1a8 100644 --- a/taskman-server/models/task.go +++ b/taskman-server/models/task.go @@ -1,7 +1,7 @@ package models type TaskTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` Form string `json:"form" xorm:"form"` @@ -43,7 +43,7 @@ type TaskTable struct { } type TaskListObj struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` Status string `json:"status" xorm:"status"` diff --git a/taskman-server/models/task_approve_role.go b/taskman-server/models/task_approve_role.go index ce51b98a..c86dbf5c 100644 --- a/taskman-server/models/task_approve_role.go +++ b/taskman-server/models/task_approve_role.go @@ -2,7 +2,7 @@ package models // TaskApproveRoleTable 任务审批表 type TaskApproveRoleTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Task string `json:"task" xorm:"task"` // 任务审批ID Role string `json:"role" xorm:"role"` // 角色 handler string `json:"handler" xorm:"handler"` // 处理人 diff --git a/taskman-server/models/task_template.go b/taskman-server/models/task_template.go index 6ea0cea8..fd1d4c2a 100644 --- a/taskman-server/models/task_template.go +++ b/taskman-server/models/task_template.go @@ -1,7 +1,7 @@ package models type TaskTemplateTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` FormTemplate string `json:"formTemplate" xorm:"form_template"` @@ -19,13 +19,13 @@ type TaskTemplateTable struct { } type TaskTemplateVo struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` Handler string `json:"handler" xorm:"handler"` Role string `json:"role" xorm:"role"` } type TaskTemplateRoleTable struct { - Id string `json:"id" xorm:"id"` + Id string `json:"id" xorm:"'id' pk"` TaskTemplate string `json:"taskTemplate" xorm:"task_template"` Role string `json:"role" xorm:"role"` RoleType string `json:"roleType" xorm:"role_type"` diff --git a/taskman-server/models/wecube.go b/taskman-server/models/wecube.go index b4fe2b13..d4116dd8 100644 --- a/taskman-server/models/wecube.go +++ b/taskman-server/models/wecube.go @@ -24,7 +24,7 @@ type SyncDataModelResponse struct { } type SyncDataModelCiType struct { - Name string `json:"name" xorm:"id"` + Name string `json:"name" xorm:"'id' pk"` DisplayName string `json:"displayName" xorm:"display_name"` Description string `json:"description" xorm:"description"` Attributes []*SyncDataModelCiAttr `json:"attributes" xorm:"-"` diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index f9d16f0c..2ce2a0c7 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -29,6 +29,7 @@ func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplate // 添加模板项 for i, item := range formTemplateDto.Items { item.Id = itemIds[i] + item.FormTemplate = newId _, err = s.formItemTemplateDao.Add(session, item) if err != nil { return @@ -97,7 +98,7 @@ func (s FormTemplateService) GetRequestFormTemplate(id string) (result models.Fo if err != nil { return } - formTemplate, err = s.formTemplateDao.Get(requestTemplate.GetFormTemplate()) + formTemplate, err = s.formTemplateDao.Get(requestTemplate.FormTemplate) if err != nil { return } @@ -110,7 +111,7 @@ func (s FormTemplateService) GetRequestFormTemplate(id string) (result models.Fo result.Description = formTemplate.Description result.UpdatedTime = formTemplate.UpdatedTime result.UpdatedBy = formTemplate.UpdatedBy - result.Items, err = s.formItemTemplateDao.QueryByFormTemplate(requestTemplate.GetFormTemplate()) + result.Items, err = s.formItemTemplateDao.QueryByFormTemplate(requestTemplate.FormTemplate) return } @@ -130,8 +131,11 @@ func (s FormTemplateService) CreateRequestFormTemplate(formTemplateDto models.Fo err = transactionWithoutForeignCheck(func(session *xorm.Session) error { // 添加表单模板 formTemplateDto.Id, err = s.AddFormTemplate(session, formTemplateDto) + if err != nil { + return err + } // 更新模板 - err = GetRequestTemplateService().UpdateFormTemplate(session, requestTemplateId, formTemplateDto.Id, formTemplateDto.Description, formTemplateDto.ExpireDay) + err = GetRequestTemplateService().UpdateRequestTemplate(session, requestTemplateId, formTemplateDto.Id, formTemplateDto.Description, formTemplateDto.ExpireDay) if err != nil { return err } @@ -166,11 +170,14 @@ func (s FormTemplateService) UpdateRequestFormTemplate(formTemplateDto models.Fo if formTemplate.UpdatedTime != formTemplateDto.UpdatedTime { return exterror.New().DealWithAtTheSameTimeError } - err = transaction(func(session *xorm.Session) error { + err = transactionWithoutForeignCheck(func(session *xorm.Session) error { // 更新表单项模板 err = s.UpdateFormTemplate(session, formTemplateDto) + if err != nil { + return err + } // 更新模板 - err = GetRequestTemplateService().UpdateFormTemplate(session, requestTemplateId, formTemplateDto.Id, formTemplateDto.Description, formTemplateDto.ExpireDay) + err = GetRequestTemplateService().UpdateRequestTemplate(session, requestTemplateId, formTemplateDto.Id, formTemplateDto.Description, formTemplateDto.ExpireDay) if err != nil { return err } diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 5fc41a85..ec8d2559 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -172,8 +172,8 @@ func (s RequestTemplateService) UpdateRequestTemplateHandler(requestTemplateId, UpdatedTime: time.Now().Format(models.DateTimeFormat)}) } -func (s RequestTemplateService) UpdateFormTemplate(session *xorm.Session, requestTemplateId, formTemplate, description string, expireDay int) (err error) { - requestTemplate := &models.RequestTemplateTable{Id: requestTemplateId, FormTemplate: &formTemplate, Description: description, ExpireDay: expireDay} +func (s RequestTemplateService) UpdateRequestTemplate(session *xorm.Session, requestTemplateId, formTemplate, description string, expireDay int) (err error) { + requestTemplate := &models.RequestTemplateTable{Id: requestTemplateId, FormTemplate: formTemplate, Description: description, ExpireDay: expireDay} return s.requestTemplateDao.Update(session, requestTemplate) } @@ -199,7 +199,7 @@ func (s RequestTemplateService) CreateRequestTemplate(param models.RequestTempla result.Id = newGuid err = transaction(func(session *xorm.Session) error { var err error - _, err = s.requestTemplateDao.Add(session, models.ConvertRequestTemplateUpdateParam2RequestTemplate(param)) + _, err = s.requestTemplateDao.AddBasicInfo(session, models.ConvertRequestTemplateUpdateParam2RequestTemplate(param)) if err != nil { return err } @@ -563,7 +563,7 @@ func DeleteRequestTemplate(id string, getActionFlag bool) (actions []*dao.ExecAc } var taskTemplateTable []*models.TaskTemplateTable dao.X.SQL("select id,form_template from task_template where request_template=?", id).Find(&taskTemplateTable) - formTemplateIds := []string{rtObj.GetFormTemplate()} + formTemplateIds := []string{rtObj.FormTemplate} for _, v := range taskTemplateTable { formTemplateIds = append(formTemplateIds, v.FormTemplate) } @@ -754,7 +754,7 @@ func ForkConfirmRequestTemplate(requestTemplateId, operator string) error { "'' as confirm_time,expire_day,handler,type,operator_obj_type,'%s' as parent_id from request_template where id='%s'", newRequestTemplateId, newRequestFormTemplateId, operator, nowTime, operator, nowTime, requestTemplateObj.Id, version, requestTemplateObj.Id, requestTemplateObj.ParentId)}) } - newRequestFormActions, tmpErr := getFormCopyActions(requestTemplateObj.GetFormTemplate(), newRequestFormTemplateId) + newRequestFormActions, tmpErr := getFormCopyActions(requestTemplateObj.FormTemplate, newRequestFormTemplateId) if tmpErr != nil { return fmt.Errorf("Try to copy request form fail,%s ", tmpErr.Error()) } @@ -796,7 +796,7 @@ func ConfirmRequestTemplate(requestTemplateId string) error { if err != nil { return err } - if requestTemplateObj.GetFormTemplate() == "" { + if requestTemplateObj.FormTemplate == "" { return fmt.Errorf("Please config request template form ") } if requestTemplateObj.Status == "confirm" { @@ -1466,8 +1466,8 @@ func createNewImportTemplate(input models.RequestTemplateExport, recordId string historyFormTemplateId := formTemplate.Id formTemplate.Id = guid.CreateGuid() // 修改模板里面的 formTemplateId - if input.RequestTemplate.GetFormTemplate() == historyFormTemplateId { - input.RequestTemplate.SetFormTemplate(formTemplate.Id) + if input.RequestTemplate.FormTemplate == historyFormTemplateId { + input.RequestTemplate.FormTemplate = formTemplate.Id } for _, formItemTemplate := range input.FormItemTemplate { formItemTemplate.Id = guid.CreateGuid() diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index a499a274..0680a090 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -143,7 +143,10 @@ func transaction(f func(session *xorm.Session) error) (err error) { if err != nil { session.Rollback() } - session.Commit() + err = session.Commit() + if err != nil { + return + } return } @@ -157,7 +160,10 @@ func transactionWithoutForeignCheck(f func(session *xorm.Session) error) (err er if err != nil { session.Rollback() } - session.Commit() + err = session.Commit() + if err != nil { + return + } session.Exec("SET FOREIGN_KEY_CHECKS=1") return } diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/password.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/password.go deleted file mode 100644 index b7e7223b..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/password.go +++ /dev/null @@ -1,152 +0,0 @@ -package cipher - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/md5" - "encoding/hex" - "fmt" - "math/rand" - "strings" - "time" -) - -var ( - passwordLength = 12 - digitalBytes = []byte("0123456789") - lettersBytes = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - DEFALT_CIPHER = "CIPHER_A" - CIPHER_MAP = map[string]string{"CIPHER_A": "{cipher_a}"} -) - -func Md5Encode(rawData string) string { - data := []byte(rawData) - return fmt.Sprintf("%x", md5.Sum(data)) -} - -func PKCS7Padding(ciphertext []byte, blockSize int) []byte { - padding := blockSize - len(ciphertext)%blockSize - padtext := bytes.Repeat([]byte{byte(padding)}, padding) - return append(ciphertext, padtext...) -} - -func PKCS7UnPadding(origData []byte) []byte { - length := len(origData) - unpadding := int(origData[length-1]) - if length > unpadding { - return origData[:(length - unpadding)] - } - return []byte{} -} - -func AesEncode(key string, rawData string) (string, error) { - bytesRawKey := []byte(key) - block, err := aes.NewCipher(bytesRawKey) - if err != nil { - return "", err - } - blockSize := block.BlockSize() - origData := PKCS7Padding([]byte(rawData), blockSize) - blockMode := cipher.NewCBCEncrypter(block, bytesRawKey[:blockSize]) - crypted := make([]byte, len([]byte(origData))) - blockMode.CryptBlocks(crypted, origData) - return hex.EncodeToString(crypted), nil -} - -func AesDecode(key string, encryptData string) (password string, err error) { - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("%v", r) - } - }() - - bytesRawKey := []byte(key) - bytesRawData, _ := hex.DecodeString(encryptData) - block, err := aes.NewCipher(bytesRawKey) - if err != nil { - return - } - blockSize := block.BlockSize() - blockMode := cipher.NewCBCDecrypter(block, bytesRawKey[:blockSize]) - origData := make([]byte, len(bytesRawData)) - blockMode.CryptBlocks(origData, bytesRawData) - origData = PKCS7UnPadding(origData) - if len(origData) == 0 { - err = fmt.Errorf("password wrong") - return - } - - password = string(origData) - return -} - -func CreateRandomPassword() string { - var result []byte - r := rand.New(rand.NewSource(time.Now().UnixNano())) - for i := 0; i < passwordLength-4; i++ { - result = append(result, lettersBytes[r.Intn(len(lettersBytes))]) - } - for i := 0; i < 4; i++ { - result = append(result, digitalBytes[r.Intn(len(digitalBytes))]) - } - return string(result) -} - -func AesEnPassword(seed, password string) (string, error) { - md5sum := Md5Encode(seed) - enPassword, err := AesEncode(md5sum[0:16], password) - if err != nil { - return "", err - } - return enPassword, nil -} - -func AesDePassword(seed, password string) (string, error) { - md5sum := Md5Encode(seed) - dePassword, err := AesDecode(md5sum[0:16], password) - if err != nil { - return "", err - } - return dePassword, nil -} - -func AesEnPasswordByGuid(guid, seed, password, cipher string) (string, error) { - if seed == "" { - return password, nil - } - for _, _cipher := range CIPHER_MAP { - if strings.HasPrefix(password, _cipher) { - return password, nil - } - } - if cipher == "" { - cipher = DEFALT_CIPHER - } - md5sum := Md5Encode(guid + seed) - enPassword, err := AesEncode(md5sum[0:16], password) - if err != nil { - return "", err - } - return CIPHER_MAP[cipher] + enPassword, nil -} - -func AesDePasswordByGuid(guid, seed, password string) (string, error) { - var cipher string - for _, _cipher := range CIPHER_MAP { - if strings.HasPrefix(password, _cipher) { - cipher = _cipher - break - } - } - if cipher == "" { - return password, nil - } - password = password[len(cipher):] - md5sum := Md5Encode(guid + seed) - dePassword, err := AesDecode(md5sum[0:16], password) - if err != nil { - return "", err - } - return dePassword, nil -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/rsa.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/rsa.go deleted file mode 100644 index d6d19517..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/cipher/rsa.go +++ /dev/null @@ -1,103 +0,0 @@ -package cipher - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/pem" - "fmt" - "math/big" - "strings" -) - -func DecryptRsa(inputString, rsaPemContent string) (string, error) { - if !strings.HasPrefix(strings.ToLower(inputString), "rsa@") { - return inputString, nil - } - inputString = inputString[4:] - result := inputString - inputBytes, err := base64.StdEncoding.DecodeString(inputString) - if err != nil { - err = fmt.Errorf("Input string format to base64 fail,%s ", err.Error()) - return inputString, err - } - block, _ := pem.Decode([]byte(rsaPemContent)) - privateKeyInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes) - if err != nil { - err = fmt.Errorf("Parse private key fail,%s ", err.Error()) - return result, err - } - privateKey := privateKeyInterface.(*rsa.PrivateKey) - decodeBytes, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, inputBytes) - if err != nil { - err = fmt.Errorf("Decode fail,%s ", err.Error()) - return result, err - } - result = string(decodeBytes) - return result, nil -} - -func RSAEncryptByPrivate(orgidata []byte, privatekey string) ([]byte, error) { - decodeBytes, err := base64.StdEncoding.DecodeString(privatekey) - if err != nil { - return nil, fmt.Errorf("RSASign private key is bad") - } - - privInterface, err := x509.ParsePKCS8PrivateKey(decodeBytes) - if err != nil { - return nil, err - } - - priv := privInterface.(*rsa.PrivateKey) - - k := (priv.N.BitLen() + 7) / 8 - tLen := len(orgidata) - em := make([]byte, k) - em[1] = 1 - for i := 2; i < k-tLen-1; i++ { - em[i] = 0xff - } - copy(em[k-tLen:k], orgidata) - c := new(big.Int).SetBytes(em) - if c.Cmp(priv.N) > 0 { - return nil, nil - } - var m *big.Int - var ir *big.Int - if priv.Precomputed.Dp == nil { - m = new(big.Int).Exp(c, priv.D, priv.N) - } else { - // We have the precalculated values needed for the CRT. - m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0]) - m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1]) - m.Sub(m, m2) - if m.Sign() < 0 { - m.Add(m, priv.Primes[0]) - } - m.Mul(m, priv.Precomputed.Qinv) - m.Mod(m, priv.Primes[0]) - m.Mul(m, priv.Primes[1]) - m.Add(m, m2) - - for i, values := range priv.Precomputed.CRTValues { - prime := priv.Primes[2+i] - m2.Exp(c, values.Exp, prime) - m2.Sub(m2, m) - m2.Mul(m2, values.Coeff) - m2.Mod(m2, prime) - if m2.Sign() < 0 { - m2.Add(m2, prime) - } - m2.Mul(m2, values.R) - m.Add(m, m2) - } - } - - if ir != nil { - // Unblind. - m.Mul(m, ir) - m.Mod(m, priv.N) - } - return m.Bytes(), nil -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/file_server/minio.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/file_server/minio.go deleted file mode 100644 index ef5cdb57..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/file_server/minio.go +++ /dev/null @@ -1,77 +0,0 @@ -package file_server - -import ( - "bytes" - "context" - "fmt" - "github.com/minio/minio-go/v7" - "github.com/minio/minio-go/v7/pkg/credentials" - "io/ioutil" -) - -type MinioServer struct { - ServerAddress string `json:"server_address"` - AccessKey string `json:"access_key"` - SecretKey string `json:"secret_key"` - SSL bool `json:"ssl"` - Client *minio.Client `json:"client"` -} - -type MinioParam struct { - Ctx context.Context `json:"ctx"` - Bucket string `json:"bucket"` - ObjectName string `json:"object_name"` - FileContent []byte `json:"file_content"` -} - -func (m *MinioServer) Init() error { - minioClient, err := minio.New(m.ServerAddress, &minio.Options{ - Creds: credentials.NewStaticV4(m.AccessKey, m.SecretKey, ""), - Secure: m.SSL, - }) - if err == nil { - m.Client = minioClient - } - return err -} - -func (m *MinioServer) Upload(param MinioParam) error { - err := m.Client.MakeBucket(param.Ctx, param.Bucket, minio.MakeBucketOptions{Region: ""}) - if err != nil { - exists, errBucketExists := m.Client.BucketExists(param.Ctx, param.Bucket) - if errBucketExists != nil { - return fmt.Errorf("Check bucket if exist fail,%s ", errBucketExists.Error()) - } - if !exists { - return fmt.Errorf("Bucket:%s is not exist ", param.Bucket) - } - } - - info, putErr := m.Client.PutObject(param.Ctx, param.Bucket, param.ObjectName, bytes.NewReader(param.FileContent), int64(len(param.FileContent)), minio.PutObjectOptions{}) - if putErr != nil { - return fmt.Errorf("Upload minio file fail,%s ", putErr.Error()) - } - fmt.Printf("info key:%s \n", info.Key) - return nil -} - -func (m *MinioServer) Download(param MinioParam) (result []byte, err error) { - obj, getErr := m.Client.GetObject(param.Ctx, param.Bucket, param.ObjectName, minio.GetObjectOptions{}) - if getErr != nil { - err = fmt.Errorf("Download file fail,%s ", getErr.Error()) - return result, err - } - result, err = ioutil.ReadAll(obj) - if err != nil { - err = fmt.Errorf("Read file content fail,%s ", err.Error()) - } - return result, err -} - -func (m *MinioServer) Remove(param MinioParam) error { - err := m.Client.RemoveObject(param.Ctx, param.Bucket, param.ObjectName, minio.RemoveObjectOptions{ForceDelete: true}) - if err != nil { - err = fmt.Errorf("Remove file:%s/%s fail,%s ", param.Bucket, param.ObjectName, err.Error()) - } - return err -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/guid/rand.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/guid/rand.go deleted file mode 100644 index 85c1e2b2..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/guid/rand.go +++ /dev/null @@ -1,37 +0,0 @@ -package guid - -import ( - "crypto/rand" - "fmt" - "sort" - "time" -) - -func CreateGuid() string { - b := make([]byte, 16) - rand.Read(b) - return fmt.Sprintf("%x%x", uint32(time.Now().Unix()), b[4:8]) -} - -func CreateGuidList(num int) []string { - var guidList guidSortList - for i := 0; i < num; i++ { - guidList = append(guidList, CreateGuid()) - } - sort.Sort(guidList) - return guidList -} - -type guidSortList []string - -func (l guidSortList) Len() int { - return len(l) -} - -func (l guidSortList) Swap(i, j int) { - l[i], l[j] = l[j], l[i] -} - -func (l guidSortList) Less(i, j int) bool { - return l[i] < l[j] -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/logger/zap.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/logger/zap.go deleted file mode 100644 index d5d893cd..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/logger/zap.go +++ /dev/null @@ -1,60 +0,0 @@ -package logger - -import ( - "go.uber.org/zap" - "go.uber.org/zap/zapcore" - "gopkg.in/natefinch/lumberjack.v2" - "strings" - "time" -) - -var levelStringList = []string{"debug", "info", "warn", "error"} - -type LogConfig struct { - Name string - FilePath string - LogLevel string - ArchiveMaxSize int - ArchiveMaxBackup int - ArchiveMaxDay int - Compress bool -} - -func InitArchiveZapLogger(config LogConfig) *zap.Logger { - config.LogLevel = strings.ToLower(config.LogLevel) - var level int - for i, v := range levelStringList { - if v == config.LogLevel { - level = i - 1 - break - } - } - zapLevel := zap.NewAtomicLevel() - zapLevel.SetLevel(zapcore.Level(level)) - hook := lumberjack.Logger{ - Filename: config.FilePath, - MaxSize: config.ArchiveMaxSize, - MaxBackups: config.ArchiveMaxBackup, - MaxAge: config.ArchiveMaxDay, - Compress: config.Compress, - } - encoderConfig := zapcore.EncoderConfig{ - TimeKey: "time", - LevelKey: "level", - NameKey: "logger", - CallerKey: "caller", - MessageKey: "msg", - StacktraceKey: "stacktrace", - LineEnding: zapcore.DefaultLineEnding, - EncodeLevel: zapcore.LowercaseLevelEncoder, - EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString(t.Format("2006-01-02 15:04:05")) - }, - EncodeDuration: zapcore.SecondsDurationEncoder, - EncodeCaller: zapcore.ShortCallerEncoder, - } - core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderConfig), zapcore.NewMultiWriteSyncer(zapcore.AddSync(&hook)), zapLevel) - zapLogger := zap.New(core, zap.AddCaller(), zap.Development()) - zapLogger.Info("Success init " + config.Name + " log !!") - return zapLogger -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/auth.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/auth.go deleted file mode 100644 index fd1a472f..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/auth.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package smtp - -import ( - "crypto/hmac" - "crypto/md5" - "errors" - "fmt" -) - -// Auth is implemented by an SMTP authentication mechanism. -type Auth interface { - // Start begins an authentication with a server. - // It returns the name of the authentication protocol - // and optionally data to include in the initial AUTH message - // sent to the server. It can return proto == "" to indicate - // that the authentication should be skipped. - // If it returns a non-nil error, the SMTP client aborts - // the authentication attempt and closes the connection. - Start(server *ServerInfo) (proto string, toServer []byte, err error) - - // Next continues the authentication. The server has just sent - // the fromServer data. If more is true, the server expects a - // response, which Next should return as toServer; otherwise - // Next should return toServer == nil. - // If Next returns a non-nil error, the SMTP client aborts - // the authentication attempt and closes the connection. - Next(fromServer []byte, more bool) (toServer []byte, err error) -} - -// ServerInfo records information about an SMTP server. -type ServerInfo struct { - Name string // SMTP server name - TLS bool // using TLS, with valid certificate for Name - Auth []string // advertised authentication mechanisms -} - -type plainAuth struct { - identity, username, password string - host string -} - -// PlainAuth returns an Auth that implements the PLAIN authentication -// mechanism as defined in RFC 4616. The returned Auth uses the given -// username and password to authenticate to host and act as identity. -// Usually identity should be the empty string, to act as username. -// -// PlainAuth will only send the credentials if the connection is using TLS -// or is connected to localhost. Otherwise authentication will fail with an -// error, without sending the credentials. -func PlainAuth(identity, username, password, host string) Auth { - return &plainAuth{identity, username, password, host} -} - -func isLocalhost(name string) bool { - return name == "localhost" || name == "127.0.0.1" || name == "::1" -} - -func (a *plainAuth) Start(server *ServerInfo) (string, []byte, error) { - // Must have TLS, or else localhost server. - // Note: If TLS is not true, then we can't trust ANYTHING in ServerInfo. - // In particular, it doesn't matter if the server advertises PLAIN auth. - // That might just be the attacker saying - // "it's ok, you can trust me with your password." - if !server.TLS && !isLocalhost(server.Name) { - return "", nil, errors.New("unencrypted connection") - } - if server.Name != a.host { - return "", nil, errors.New("wrong host name") - } - resp := []byte(a.identity + "\x00" + a.username + "\x00" + a.password) - return "PLAIN", resp, nil -} - -func (a *plainAuth) Next(fromServer []byte, more bool) ([]byte, error) { - if more { - // We've already sent everything. - return nil, errors.New("unexpected server challenge") - } - return nil, nil -} - -type cramMD5Auth struct { - username, secret string -} - -// CRAMMD5Auth returns an Auth that implements the CRAM-MD5 authentication -// mechanism as defined in RFC 2195. -// The returned Auth uses the given username and secret to authenticate -// to the server using the challenge-response mechanism. -func CRAMMD5Auth(username, secret string) Auth { - return &cramMD5Auth{username, secret} -} - -func (a *cramMD5Auth) Start(server *ServerInfo) (string, []byte, error) { - return "CRAM-MD5", nil, nil -} - -func (a *cramMD5Auth) Next(fromServer []byte, more bool) ([]byte, error) { - if more { - d := hmac.New(md5.New, []byte(a.secret)) - d.Write(fromServer) - s := make([]byte, 0, d.Size()) - return []byte(fmt.Sprintf("%s %x", a.username, d.Sum(s))), nil - } - return nil, nil -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/func.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/func.go deleted file mode 100644 index b53293b6..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/func.go +++ /dev/null @@ -1,124 +0,0 @@ -package smtp - -import ( - "bytes" - "crypto/tls" - "fmt" - "regexp" - "strings" -) - -type MailSender struct { - SenderName string - SenderMail string - AuthServer string - AuthPassword string - SSL bool - Auth Auth -} - -func (ms *MailSender) Init() error { - if ms.AuthServer == "" || ms.SenderMail == "" { - return fmt.Errorf("Mail server and sender can not empty ") - } - if !verifyMailAddress(ms.SenderMail) { - return fmt.Errorf("Sender mail:%s validate fail ", ms.SenderMail) - } - if !strings.Contains(ms.AuthServer, ":") { - if ms.SSL { - ms.AuthServer = ms.AuthServer + ":465" - } else { - ms.AuthServer = ms.AuthServer + ":25" - } - } - ms.Auth = PlainAuth("", ms.SenderMail, ms.AuthPassword, ms.AuthServer) - return nil -} - -func (ms *MailSender) Send(subject, content string, addressee []string) error { - var err error - if subject == "" { - return fmt.Errorf("Mail subject can not empty ") - } - if len(addressee) == 0 { - return fmt.Errorf("Mail addressee can not empty ") - } - for _, to := range addressee { - if !verifyMailAddress(to) { - err = fmt.Errorf("Mail:%s validate fail ", to) - break - } - } - if err != nil { - return err - } - if ms.SSL { - err = ms.sendTLSMail(subject, content, addressee) - } else { - err = SendMail(ms.AuthServer, ms.Auth, ms.SenderMail, addressee, mailQQMessage(addressee, subject, content, ms.SenderName, ms.SenderMail)) - } - return err -} - -func (ms *MailSender) sendTLSMail(subject, content string, addressee []string) error { - tlsConfig := &tls.Config{ - InsecureSkipVerify: true, - ServerName: ms.AuthServer, - } - conn, err := tls.Dial("tcp", ms.AuthServer, tlsConfig) - if err != nil { - return fmt.Errorf("tls dial error: %v", err) - } - client, newClientErr := NewClient(conn, ms.AuthServer) - if newClientErr != nil { - return fmt.Errorf("smtp new client error: %v", newClientErr) - } - defer client.Close() - if b, _ := client.Extension("AUTH"); b { - err = client.Auth(ms.Auth) - if err != nil { - return fmt.Errorf("client auth error: %v", err) - } - } - err = client.Mail(ms.SenderMail) - if err != nil { - return fmt.Errorf("client mail set from error: %v", err) - } - for _, to := range addressee { - if err = client.Rcpt(to); err != nil { - return fmt.Errorf("client rcpt %s error: %v", to, err) - } - } - w, err := client.Data() - if err != nil { - return fmt.Errorf("client data init error: %v", err) - } - _, err = w.Write(mailQQMessage(addressee, subject, content, ms.SenderName, ms.SenderMail)) - if err != nil { - return fmt.Errorf("write message error: %v", err) - } - w.Close() - err = client.Quit() - if err != nil { - return fmt.Errorf("client quit error: %v", err) - } - return err -} - -func mailQQMessage(addressee []string, subject, content, senderName, senderMail string) []byte { - var buff bytes.Buffer - buff.WriteString("To:") - buff.WriteString(strings.Join(addressee, ",")) - buff.WriteString("\r\nFrom:") - buff.WriteString(senderName + "<" + senderMail + ">") - buff.WriteString("\r\nSubject:") - buff.WriteString(subject) - buff.WriteString("\r\nContent-Type:text/plain;charset=UTF-8\r\n\r\n") - buff.WriteString(content) - return buff.Bytes() -} - -func verifyMailAddress(mailString string) bool { - reg := regexp.MustCompile(`\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`) - return reg.MatchString(mailString) -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/smtp.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/smtp.go deleted file mode 100644 index 956fbf69..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/smtp/smtp.go +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321. -// It also implements the following extensions: -// 8BITMIME RFC 1652 -// AUTH RFC 2554 -// STARTTLS RFC 3207 -// Additional extensions may be handled by clients. -// -// The smtp package is frozen and is not accepting new features. -// Some external packages provide more functionality. See: -// -// https://godoc.org/?q=smtp -package smtp - -import ( - "crypto/tls" - "encoding/base64" - "errors" - "fmt" - "io" - "net" - "net/textproto" - "strings" -) - -// A Client represents a client connection to an SMTP server. -type Client struct { - // Text is the textproto.Conn used by the Client. It is exported to allow for - // clients to add extensions. - Text *textproto.Conn - // keep a reference to the connection so it can be used to create a TLS - // connection later - conn net.Conn - // whether the Client is using TLS - tls bool - serverName string - // map of supported extensions - ext map[string]string - // supported auth mechanisms - auth []string - localName string // the name to use in HELO/EHLO - didHello bool // whether we've said HELO/EHLO - helloError error // the error from the hello -} - -// Dial returns a new Client connected to an SMTP server at addr. -// The addr must include a port, as in "mail.example.com:smtp". -func Dial(addr string) (*Client, error) { - conn, err := net.Dial("tcp", addr) - if err != nil { - return nil, err - } - host, _, _ := net.SplitHostPort(addr) - return NewClient(conn, host) -} - -// NewClient returns a new Client using an existing connection and host as a -// server name to be used when authenticating. -func NewClient(conn net.Conn, host string) (*Client, error) { - text := textproto.NewConn(conn) - _, _, err := text.ReadResponse(220) - if err != nil { - text.Close() - return nil, err - } - c := &Client{Text: text, conn: conn, serverName: host, localName: "localhost"} - _, c.tls = conn.(*tls.Conn) - return c, nil -} - -// Close closes the connection. -func (c *Client) Close() error { - return c.Text.Close() -} - -// hello runs a hello exchange if needed. -func (c *Client) hello() error { - if !c.didHello { - c.didHello = true - err := c.ehlo() - if err != nil { - c.helloError = c.helo() - } - } - return c.helloError -} - -// Hello sends a HELO or EHLO to the server as the given host name. -// Calling this method is only necessary if the client needs control -// over the host name used. The client will introduce itself as "localhost" -// automatically otherwise. If Hello is called, it must be called before -// any of the other methods. -func (c *Client) Hello(localName string) error { - if err := validateLine(localName); err != nil { - return err - } - if c.didHello { - return errors.New("smtp: Hello called after other methods") - } - c.localName = localName - return c.hello() -} - -// cmd is a convenience function that sends a command and returns the response -func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) { - id, err := c.Text.Cmd(format, args...) - if err != nil { - return 0, "", err - } - c.Text.StartResponse(id) - defer c.Text.EndResponse(id) - code, msg, err := c.Text.ReadResponse(expectCode) - return code, msg, err -} - -// helo sends the HELO greeting to the server. It should be used only when the -// server does not support ehlo. -func (c *Client) helo() error { - c.ext = nil - _, _, err := c.cmd(250, "HELO %s", c.localName) - return err -} - -// ehlo sends the EHLO (extended hello) greeting to the server. It -// should be the preferred greeting for servers that support it. -func (c *Client) ehlo() error { - _, msg, err := c.cmd(250, "EHLO %s", c.localName) - if err != nil { - return err - } - ext := make(map[string]string) - extList := strings.Split(msg, "\n") - if len(extList) > 1 { - extList = extList[1:] - for _, line := range extList { - args := strings.SplitN(line, " ", 2) - if len(args) > 1 { - ext[args[0]] = args[1] - } else { - ext[args[0]] = "" - } - } - } - if mechs, ok := ext["AUTH"]; ok { - c.auth = strings.Split(mechs, " ") - } - c.ext = ext - return err -} - -// StartTLS sends the STARTTLS command and encrypts all further communication. -// Only servers that advertise the STARTTLS extension support this function. -func (c *Client) StartTLS(config *tls.Config) error { - if err := c.hello(); err != nil { - return err - } - _, _, err := c.cmd(220, "STARTTLS") - if err != nil { - return err - } - c.conn = tls.Client(c.conn, config) - c.Text = textproto.NewConn(c.conn) - c.tls = true - return c.ehlo() -} - -// TLSConnectionState returns the client's TLS connection state. -// The return values are their zero values if StartTLS did -// not succeed. -func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool) { - tc, ok := c.conn.(*tls.Conn) - if !ok { - return - } - return tc.ConnectionState(), true -} - -// Verify checks the validity of an email address on the server. -// If Verify returns nil, the address is valid. A non-nil return -// does not necessarily indicate an invalid address. Many servers -// will not verify addresses for security reasons. -func (c *Client) Verify(addr string) error { - if err := validateLine(addr); err != nil { - return err - } - if err := c.hello(); err != nil { - return err - } - _, _, err := c.cmd(250, "VRFY %s", addr) - return err -} - -// Auth authenticates a client using the provided authentication mechanism. -// A failed authentication closes the connection. -// Only servers that advertise the AUTH extension support this function. -func (c *Client) Auth(a Auth) error { - if err := c.hello(); err != nil { - return err - } - encoding := base64.StdEncoding - mech, resp, err := a.Start(&ServerInfo{c.serverName, c.tls, c.auth}) - if err != nil { - c.Quit() - return err - } - resp64 := make([]byte, encoding.EncodedLen(len(resp))) - encoding.Encode(resp64, resp) - code, msg64, err := c.cmd(0, strings.TrimSpace(fmt.Sprintf("AUTH %s %s", mech, resp64))) - for err == nil { - var msg []byte - switch code { - case 334: - msg, err = encoding.DecodeString(msg64) - case 235: - // the last message isn't base64 because it isn't a challenge - msg = []byte(msg64) - default: - err = &textproto.Error{Code: code, Msg: msg64} - } - if err == nil { - resp, err = a.Next(msg, code == 334) - } - if err != nil { - // abort the AUTH - c.cmd(501, "*") - c.Quit() - break - } - if resp == nil { - break - } - resp64 = make([]byte, encoding.EncodedLen(len(resp))) - encoding.Encode(resp64, resp) - code, msg64, err = c.cmd(0, string(resp64)) - } - return err -} - -// Mail issues a MAIL command to the server using the provided email address. -// If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME -// parameter. -// This initiates a mail transaction and is followed by one or more Rcpt calls. -func (c *Client) Mail(from string) error { - if err := validateLine(from); err != nil { - return err - } - if err := c.hello(); err != nil { - return err - } - cmdStr := "MAIL FROM:<%s>" - if c.ext != nil { - if _, ok := c.ext["8BITMIME"]; ok { - cmdStr += " BODY=8BITMIME" - } - } - _, _, err := c.cmd(250, cmdStr, from) - return err -} - -// Rcpt issues a RCPT command to the server using the provided email address. -// A call to Rcpt must be preceded by a call to Mail and may be followed by -// a Data call or another Rcpt call. -func (c *Client) Rcpt(to string) error { - if err := validateLine(to); err != nil { - return err - } - _, _, err := c.cmd(25, "RCPT TO:<%s>", to) - return err -} - -type dataCloser struct { - c *Client - io.WriteCloser -} - -func (d *dataCloser) Close() error { - d.WriteCloser.Close() - _, _, err := d.c.Text.ReadResponse(250) - return err -} - -// Data issues a DATA command to the server and returns a writer that -// can be used to write the mail headers and body. The caller should -// close the writer before calling any more methods on c. A call to -// Data must be preceded by one or more calls to Rcpt. -func (c *Client) Data() (io.WriteCloser, error) { - _, _, err := c.cmd(354, "DATA") - if err != nil { - return nil, err - } - return &dataCloser{c, c.Text.DotWriter()}, nil -} - -var testHookStartTLS func(*tls.Config) // nil, except for tests - -// SendMail connects to the server at addr, switches to TLS if -// possible, authenticates with the optional mechanism a if possible, -// and then sends an email from address from, to addresses to, with -// message msg. -// The addr must include a port, as in "mail.example.com:smtp". -// -// The addresses in the to parameter are the SMTP RCPT addresses. -// -// The msg parameter should be an RFC 822-style email with headers -// first, a blank line, and then the message body. The lines of msg -// should be CRLF terminated. The msg headers should usually include -// fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" -// messages is accomplished by including an email address in the to -// parameter but not including it in the msg headers. -// -// The SendMail function and the net/smtp package are low-level -// mechanisms and provide no support for DKIM signing, MIME -// attachments (see the mime/multipart package), or other mail -// functionality. Higher-level packages exist outside of the standard -// library. -func SendMail(addr string, a Auth, from string, to []string, msg []byte) error { - if err := validateLine(from); err != nil { - return err - } - for _, recp := range to { - if err := validateLine(recp); err != nil { - return err - } - } - c, err := Dial(addr) - if err != nil { - return err - } - defer c.Close() - if err = c.hello(); err != nil { - return err - } - //if ok, _ := c.Extension("STARTTLS"); ok { - // config := &tls.Config{ServerName: c.serverName} - // if testHookStartTLS != nil { - // testHookStartTLS(config) - // } - // if err = c.StartTLS(config); err != nil { - // return err - // } - //} - if a != nil && c.ext != nil { - if _, ok := c.ext["AUTH"]; !ok { - return errors.New("smtp: server doesn't support AUTH") - } - if err = c.Auth(a); err != nil { - return err - } - } - if err = c.Mail(from); err != nil { - return err - } - for _, addr := range to { - if err = c.Rcpt(addr); err != nil { - return err - } - } - w, err := c.Data() - if err != nil { - return err - } - _, err = w.Write(msg) - if err != nil { - return err - } - err = w.Close() - if err != nil { - return err - } - return c.Quit() -} - -// Extension reports whether an extension is support by the server. -// The extension name is case-insensitive. If the extension is supported, -// Extension also returns a string that contains any parameters the -// server specifies for the extension. -func (c *Client) Extension(ext string) (bool, string) { - if err := c.hello(); err != nil { - return false, "" - } - if c.ext == nil { - return false, "" - } - ext = strings.ToUpper(ext) - param, ok := c.ext[ext] - return ok, param -} - -// Reset sends the RSET command to the server, aborting the current mail -// transaction. -func (c *Client) Reset() error { - if err := c.hello(); err != nil { - return err - } - _, _, err := c.cmd(250, "RSET") - return err -} - -// Noop sends the NOOP command to the server. It does nothing but check -// that the connection to the server is okay. -func (c *Client) Noop() error { - if err := c.hello(); err != nil { - return err - } - _, _, err := c.cmd(250, "NOOP") - return err -} - -// Quit sends the QUIT command and closes the connection to the server. -func (c *Client) Quit() error { - if err := c.hello(); err != nil { - return err - } - _, _, err := c.cmd(221, "QUIT") - if err != nil { - return err - } - return c.Text.Close() -} - -// validateLine checks to see if a line has CR or LF as per RFC 5321 -func validateLine(line string) error { - if strings.ContainsAny(line, "\n\r") { - return errors.New("smtp: A line must not contain CR or LF") - } - return nil -} diff --git a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/token/wecube.go b/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/token/wecube.go deleted file mode 100644 index 14ce4599..00000000 --- a/taskman-server/vendor/github.com/WeBankPartners/go-common-lib/token/wecube.go +++ /dev/null @@ -1,225 +0,0 @@ -package token - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "github.com/WeBankPartners/go-common-lib/cipher" - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "log" - "net/http" - "strconv" - "strings" - "time" -) - -var ( - coreRefreshToken string - coreRefreshTokenExpTime time.Time - coreRequestToken string - coreRequestTokenExpTime time.Time - requestCoreNonce = "monitor" - defaultSignedKey = "Platform+Auth+Server+Secret" -) - -type requestToken struct { - Password string `json:"password"` - Username string `json:"username"` - Nonce string `json:"nonce"` - ClientType string `json:"clientType"` -} - -type responseObj struct { - Status string `json:"status"` - Message string `json:"message"` - Data []*responseDataObj `json:"data"` -} - -type responseDataObj struct { - Expiration string `json:"expiration"` - Token string `json:"token"` - TokenType string `json:"tokenType"` -} - -type CoreToken struct { - BaseUrl string - JwtSigningKey string - SubSystemCode string - SubSystemKey string -} - -func (c *CoreToken) refreshToken() error { - req, err := http.NewRequest(http.MethodGet, c.BaseUrl+"/auth/v1/api/token", strings.NewReader("")) - if err != nil { - return fmt.Errorf("http new request fail,%s ", err.Error()) - } - req.Header.Set("Authorization", coreRefreshToken) - resp, err := http.DefaultClient.Do(req) - if err != nil { - return fmt.Errorf("http response fail,%s ", err.Error()) - } - var respObj responseObj - bodyBytes, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(bodyBytes, &respObj) - if err != nil { - return fmt.Errorf("http response body json unmarshal fail,%s ", err.Error()) - } - for _, v := range respObj.Data { - if len(v.Expiration) > 10 { - v.Expiration = v.Expiration[:10] - } - expInt, _ := strconv.ParseInt(v.Expiration, 10, 64) - if v.TokenType == "refreshToken" { - coreRefreshToken = "Bearer " + v.Token - coreRefreshTokenExpTime = time.Unix(expInt, 0) - } - if v.TokenType == "accessToken" { - coreRequestToken = "Bearer " + v.Token - coreRequestTokenExpTime = time.Unix(expInt, 0) - } - } - return nil -} - -func (c *CoreToken) requestCoreToken(rsaKey string) error { - encryptBytes, err := cipher.RSAEncryptByPrivate([]byte(fmt.Sprintf("%s:%s", c.SubSystemCode, requestCoreNonce)), rsaKey) - encryptString := base64.StdEncoding.EncodeToString(encryptBytes) - if err != nil { - return err - } - postParam := requestToken{Username: c.SubSystemCode, Nonce: requestCoreNonce, ClientType: "SUB_SYSTEM", Password: encryptString} - postBytes, _ := json.Marshal(postParam) - fmt.Printf("param: %s \n", string(postBytes)) - req, err := http.NewRequest(http.MethodPost, c.BaseUrl+"/auth/v1/api/login", bytes.NewReader(postBytes)) - if err != nil { - return fmt.Errorf("http new request fail,%s ", err.Error()) - } - resp, err := http.DefaultClient.Do(req) - if err != nil { - return fmt.Errorf("http response fail, %s ", err.Error()) - } - var respObj responseObj - bodyBytes, _ := ioutil.ReadAll(resp.Body) - resp.Body.Close() - err = json.Unmarshal(bodyBytes, &respObj) - if err != nil { - return fmt.Errorf("http response body read fail,%s ", err.Error()) - } - for _, v := range respObj.Data { - if len(v.Expiration) > 10 { - v.Expiration = v.Expiration[:10] - } - expInt, _ := strconv.ParseInt(v.Expiration, 10, 64) - if v.TokenType == "refreshToken" { - coreRefreshToken = "Bearer " + v.Token - coreRefreshTokenExpTime = time.Unix(expInt, 0) - } - if v.TokenType == "accessToken" { - coreRequestToken = "Bearer " + v.Token - coreRequestTokenExpTime = time.Unix(expInt, 0) - } - } - return nil -} - -func (c *CoreToken) InitCoreToken() { - err := c.requestCoreToken(c.SubSystemKey) - if err != nil { - log.Printf("Init core token fail,error: %s ", err.Error()) - } else { - log.Println("Init core token success") - } -} - -func (c *CoreToken) GetCoreToken() string { - if c.BaseUrl == "" { - return "" - } - if coreRequestTokenExpTime.Unix() > time.Now().Unix() && coreRequestToken != "" { - return coreRequestToken - } - if coreRefreshTokenExpTime.Unix() > time.Now().Unix() && coreRefreshToken != "" { - err := c.refreshToken() - if err != nil { - log.Printf("Refresh token fail,%s ", err.Error()) - } else { - return coreRequestToken - } - } - err := c.requestCoreToken(c.SubSystemKey) - if err != nil { - log.Printf("Try to init core token fail,%s ", err.Error()) - } - return coreRefreshToken -} - -type JwtToken struct { - User string `json:"user"` - Expire int64 `json:"expire"` - Roles []string `json:"roles"` -} - -func DecodeJwtToken(token, key string) (result JwtToken, err error) { - if strings.HasPrefix(token, "Bearer") { - token = token[7:] - } - if key == "" || strings.HasPrefix(key, "{{") { - key = defaultSignedKey - } - keyBytes, err := ioutil.ReadAll(base64.NewDecoder(base64.RawStdEncoding, bytes.NewBufferString(key))) - if err != nil { - return result, fmt.Errorf("Decode core token fail,base64 decode error,%s ", err.Error()) - } - pToken, err := jwt.Parse(token, func(*jwt.Token) (interface{}, error) { - return keyBytes, nil - }) - if err != nil { - return result, fmt.Errorf("Decode core token fail,jwt parse error,%s ", err.Error()) - } - claimMap, ok := pToken.Claims.(jwt.MapClaims) - if !ok { - return result, fmt.Errorf("Decode core token fail,claims to map error,%s ", err.Error()) - } - result.User = fmt.Sprintf("%s", claimMap["sub"]) - result.Expire, err = strconv.ParseInt(fmt.Sprintf("%.0f", claimMap["exp"]), 10, 64) - if err != nil { - return result, fmt.Errorf("Decode core token fail,parse expire to int64 error,%s ", err.Error()) - } - roleListString := fmt.Sprintf("%s", claimMap["authority"]) - roleListString = roleListString[1 : len(roleListString)-1] - if strings.Contains(roleListString, ",") { - result.Roles = strings.Split(roleListString, ",") - } else if strings.Contains(roleListString, " ") { - result.Roles = strings.Split(roleListString, " ") - } else { - result.Roles = []string{roleListString} - } - return result, nil -} - -type AuthClaims struct { - Authority []string `json:"authority"` - jwt.StandardClaims -} - -func CreateJwtToken(user, key string, expire int64, permission []string) (signedToken string, err error) { - var keyBytes []byte - if key == "" || strings.HasPrefix(key, "{{") { - key = defaultSignedKey - } - keyBytes, err = ioutil.ReadAll(base64.NewDecoder(base64.RawStdEncoding, bytes.NewBufferString("Platform+Auth+Server+Secret"))) - if err != nil { - err = fmt.Errorf("Create token error with decode sign key:%s \n", err.Error()) - return - } - newClaims := AuthClaims{StandardClaims: jwt.StandardClaims{ExpiresAt: expire, Subject: user}, Authority: permission} - newToken := jwt.NewWithClaims(jwt.SigningMethodHS256, newClaims) - signedToken, err = newToken.SignedString(keyBytes) - if err != nil { - err = fmt.Errorf("Create token error with sign in key:%s \n", err.Error()) - } - return -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/.gitignore b/taskman-server/vendor/github.com/dgrijalva/jwt-go/.gitignore deleted file mode 100644 index 80bed650..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -bin - - diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/.travis.yml b/taskman-server/vendor/github.com/dgrijalva/jwt-go/.travis.yml deleted file mode 100644 index 1027f56c..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -script: - - go vet ./... - - go test -v ./... - -go: - - 1.3 - - 1.4 - - 1.5 - - 1.6 - - 1.7 - - tip diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/LICENSE b/taskman-server/vendor/github.com/dgrijalva/jwt-go/LICENSE deleted file mode 100644 index df83a9c2..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -Copyright (c) 2012 Dave Grijalva - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/taskman-server/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md deleted file mode 100644 index 7fc1f793..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md +++ /dev/null @@ -1,97 +0,0 @@ -## Migration Guide from v2 -> v3 - -Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. - -### `Token.Claims` is now an interface type - -The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. - -`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. - -The old example for parsing a token looked like this.. - -```go - if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { - fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) - } -``` - -is now directly mapped to... - -```go - if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { - claims := token.Claims.(jwt.MapClaims) - fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) - } -``` - -`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. - -```go - type MyCustomClaims struct { - User string - *StandardClaims - } - - if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { - claims := token.Claims.(*MyCustomClaims) - fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) - } -``` - -### `ParseFromRequest` has been moved - -To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. - -`Extractors` do the work of picking the token string out of a request. The interface is simple and composable. - -This simple parsing example: - -```go - if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { - fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) - } -``` - -is directly mapped to: - -```go - if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil { - claims := token.Claims.(jwt.MapClaims) - fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) - } -``` - -There are several concrete `Extractor` types provided for your convenience: - -* `HeaderExtractor` will search a list of headers until one contains content. -* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. -* `MultiExtractor` will try a list of `Extractors` in order until one returns content. -* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. -* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument -* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header - - -### RSA signing methods no longer accept `[]byte` keys - -Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. - -To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. - -```go - func keyLookupFunc(*Token) (interface{}, error) { - // Don't forget to validate the alg is what you expect: - if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } - - // Look up key - key, err := lookupPublicKey(token.Header["kid"]) - if err != nil { - return nil, err - } - - // Unpack key from PEM encoded PKCS8 - return jwt.ParseRSAPublicKeyFromPEM(key) - } -``` diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/README.md b/taskman-server/vendor/github.com/dgrijalva/jwt-go/README.md deleted file mode 100644 index d358d881..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/README.md +++ /dev/null @@ -1,100 +0,0 @@ -# jwt-go - -[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) -[![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go) - -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) - -**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3. - -**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail. - -**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. - -## What the heck is a JWT? - -JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. - -In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. - -The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. - -The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own. - -## What's in the box? - -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. - -## Examples - -See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage: - -* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac) -* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac) -* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples) - -## Extensions - -This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`. - -Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go - -## Compliance - -This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: - -* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. - -## Project Status & Versioning - -This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). - -This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). - -While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning. - -**BREAKING CHANGES:*** -* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. - -## Usage Tips - -### Signing vs Encryption - -A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: - -* The author of the token was in the possession of the signing secret -* The data has not been modified since it was signed - -It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. - -### Choosing a Signing Method - -There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. - -Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. - -Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. - -### Signing Methods and Key Types - -Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: - -* The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation - -### JWT and OAuth - -It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. - -Without going too far down the rabbit hole, here's a description of the interaction of these technologies: - -* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. -* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. -* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. - -## More - -Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). - -The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/taskman-server/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md deleted file mode 100644 index 63702983..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md +++ /dev/null @@ -1,118 +0,0 @@ -## `jwt-go` Version History - -#### 3.2.0 - -* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation -* HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate -* Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before. -* Deprecated `ParseFromRequestWithClaims` to simplify API in the future. - -#### 3.1.0 - -* Improvements to `jwt` command line tool -* Added `SkipClaimsValidation` option to `Parser` -* Documentation updates - -#### 3.0.0 - -* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code - * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. - * `ParseFromRequest` has been moved to `request` subpackage and usage has changed - * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. -* Other Additions and Changes - * Added `Claims` interface type to allow users to decode the claims into a custom type - * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. - * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage - * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` - * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. - * Added several new, more specific, validation errors to error type bitmask - * Moved examples from README to executable example files - * Signing method registry is now thread safe - * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) - -#### 2.7.0 - -This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. - -* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying -* Error text for expired tokens includes how long it's been expired -* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` -* Documentation updates - -#### 2.6.0 - -* Exposed inner error within ValidationError -* Fixed validation errors when using UseJSONNumber flag -* Added several unit tests - -#### 2.5.0 - -* Added support for signing method none. You shouldn't use this. The API tries to make this clear. -* Updated/fixed some documentation -* Added more helpful error message when trying to parse tokens that begin with `BEARER ` - -#### 2.4.0 - -* Added new type, Parser, to allow for configuration of various parsing parameters - * You can now specify a list of valid signing methods. Anything outside this set will be rejected. - * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON -* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) -* Fixed some bugs with ECDSA parsing - -#### 2.3.0 - -* Added support for ECDSA signing methods -* Added support for RSA PSS signing methods (requires go v1.4) - -#### 2.2.0 - -* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. - -#### 2.1.0 - -Backwards compatible API change that was missed in 2.0.0. - -* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` - -#### 2.0.0 - -There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. - -The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. - -It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. - -* **Compatibility Breaking Changes** - * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` - * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` - * `KeyFunc` now returns `interface{}` instead of `[]byte` - * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key - * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key -* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodHS256` - * Added public package global `SigningMethodHS384` - * Added public package global `SigningMethodHS512` -* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodRS256` - * Added public package global `SigningMethodRS384` - * Added public package global `SigningMethodRS512` -* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. -* Refactored the RSA implementation to be easier to read -* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` - -#### 1.0.2 - -* Fixed bug in parsing public keys from certificates -* Added more tests around the parsing of keys for RS256 -* Code refactoring in RS256 implementation. No functional changes - -#### 1.0.1 - -* Fixed panic if RS256 signing method was passed an invalid key - -#### 1.0.0 - -* First versioned release -* API stabilized -* Supports creating, signing, parsing, and validating JWT tokens -* Supports RS256 and HS256 signing methods \ No newline at end of file diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/claims.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/claims.go deleted file mode 100644 index f0228f02..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/claims.go +++ /dev/null @@ -1,134 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// For a type to be a Claims object, it must just have a Valid method that determines -// if the token is invalid for any supported reason -type Claims interface { - Valid() error -} - -// Structured version of Claims Section, as referenced at -// https://tools.ietf.org/html/rfc7519#section-4.1 -// See examples for how to use this with your own claim types -type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if c.VerifyExpiresAt(now, false) == false { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("token is expired by %v", delta) - vErr.Errors |= ValidationErrorExpired - } - - if c.VerifyIssuedAt(now, false) == false { - vErr.Inner = fmt.Errorf("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if c.VerifyNotBefore(now, false) == false { - vErr.Inner = fmt.Errorf("token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud(c.Audience, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - return verifyExp(c.ExpiresAt, cmp, req) -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - return verifyIat(c.IssuedAt, cmp, req) -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - return verifyNbf(c.NotBefore, cmp, req) -} - -// ----- helpers - -func verifyAud(aud string, cmp string, required bool) bool { - if aud == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyExp(exp int64, now int64, required bool) bool { - if exp == 0 { - return !required - } - return now <= exp -} - -func verifyIat(iat int64, now int64, required bool) bool { - if iat == 0 { - return !required - } - return now >= iat -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyNbf(nbf int64, now int64, required bool) bool { - if nbf == 0 { - return !required - } - return now >= nbf -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/doc.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/doc.go deleted file mode 100644 index a86dc1a3..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html -// -// See README.md for more info. -package jwt diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa.go deleted file mode 100644 index f9773812..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "errors" - "math/big" -) - -var ( - // Sadly this is missing from crypto/ecdsa compared to crypto/rsa - ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") -) - -// Implements the ECDSA family of signing methods signing methods -// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int - CurveBits int -} - -// Specific instances for EC256 and company -var ( - SigningMethodES256 *SigningMethodECDSA - SigningMethodES384 *SigningMethodECDSA - SigningMethodES512 *SigningMethodECDSA -) - -func init() { - // ES256 - SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} - RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { - return SigningMethodES256 - }) - - // ES384 - SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} - RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { - return SigningMethodES384 - }) - - // ES512 - SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} - RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { - return SigningMethodES512 - }) -} - -func (m *SigningMethodECDSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - // Get the key - var ecdsaKey *ecdsa.PublicKey - switch k := key.(type) { - case *ecdsa.PublicKey: - ecdsaKey = k - default: - return ErrInvalidKeyType - } - - if len(sig) != 2*m.KeySize { - return ErrECDSAVerification - } - - r := big.NewInt(0).SetBytes(sig[:m.KeySize]) - s := big.NewInt(0).SetBytes(sig[m.KeySize:]) - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { - return nil - } else { - return ErrECDSAVerification - } -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { - // Get the key - var ecdsaKey *ecdsa.PrivateKey - switch k := key.(type) { - case *ecdsa.PrivateKey: - ecdsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return r, s - if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { - curveBits := ecdsaKey.Curve.Params().BitSize - - if m.CurveBits != curveBits { - return "", ErrInvalidKey - } - - keyBytes := curveBits / 8 - if curveBits%8 > 0 { - keyBytes += 1 - } - - // We serialize the outpus (r and s) into big-endian byte arrays and pad - // them with zeros on the left to make sure the sizes work out. Both arrays - // must be keyBytes long, and the output must be 2*keyBytes long. - rBytes := r.Bytes() - rBytesPadded := make([]byte, keyBytes) - copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) - - sBytes := s.Bytes() - sBytesPadded := make([]byte, keyBytes) - copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) - - out := append(rBytesPadded, sBytesPadded...) - - return EncodeSegment(out), nil - } else { - return "", err - } -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go deleted file mode 100644 index d19624b7..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go +++ /dev/null @@ -1,67 +0,0 @@ -package jwt - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") -) - -// Parse PEM encoded Elliptic Curve Private Key Structure -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { - return nil, err - } - - var pkey *ecdsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { - return nil, ErrNotECPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *ecdsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { - return nil, ErrNotECPublicKey - } - - return pkey, nil -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/errors.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/errors.go deleted file mode 100644 index 1c93024a..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/errors.go +++ /dev/null @@ -1,59 +0,0 @@ -package jwt - -import ( - "errors" -) - -// Error constants -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") -) - -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// Helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// The error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text -} - -// Validation error is an error type -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" - } -} - -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/hmac.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/hmac.go deleted file mode 100644 index addbe5d4..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/hmac.go +++ /dev/null @@ -1,95 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/hmac" - "errors" -) - -// Implements the HMAC-SHA family of signing methods signing methods -// Expects key type of []byte for both signing and validation -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash -} - -// Specific instances for HS256 and company -var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC - ErrSignatureInvalid = errors.New("signature is invalid") -) - -func init() { - // HS256 - SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { - return SigningMethodHS256 - }) - - // HS384 - SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { - return SigningMethodHS384 - }) - - // HS512 - SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { - return SigningMethodHS512 - }) -} - -func (m *SigningMethodHMAC) Alg() string { - return m.Name -} - -// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. -func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { - // Verify the key is the right type - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKeyType - } - - // Decode signature, for comparison - sig, err := DecodeSegment(signature) - if err != nil { - return err - } - - // Can we use the specified hashing method? - if !m.Hash.Available() { - return ErrHashUnavailable - } - - // This signing method is symmetric, so we validate the signature - // by reproducing the signature from the signing string and key, then - // comparing that against the provided signature. - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - if !hmac.Equal(sig, hasher.Sum(nil)) { - return ErrSignatureInvalid - } - - // No validation errors. Signature is good. - return nil -} - -// Implements the Sign method from SigningMethod for this signing method. -// Key must be []byte -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { - if keyBytes, ok := key.([]byte); ok { - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - - return EncodeSegment(hasher.Sum(nil)), nil - } - - return "", ErrInvalidKeyType -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/map_claims.go deleted file mode 100644 index 291213c4..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/map_claims.go +++ /dev/null @@ -1,94 +0,0 @@ -package jwt - -import ( - "encoding/json" - "errors" - // "fmt" -) - -// Claims type that uses the map[string]interface{} for JSON decoding -// This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - aud, _ := m["aud"].(string) - return verifyAud(aud, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - switch exp := m["exp"].(type) { - case float64: - return verifyExp(int64(exp), cmp, req) - case json.Number: - v, _ := exp.Int64() - return verifyExp(v, cmp, req) - } - return req == false -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - switch iat := m["iat"].(type) { - case float64: - return verifyIat(int64(iat), cmp, req) - case json.Number: - v, _ := iat.Int64() - return verifyIat(v, cmp, req) - } - return req == false -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - switch nbf := m["nbf"].(type) { - case float64: - return verifyNbf(int64(nbf), cmp, req) - case json.Number: - v, _ := nbf.Int64() - return verifyNbf(v, cmp, req) - } - return req == false -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if m.VerifyExpiresAt(now, false) == false { - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if m.VerifyIssuedAt(now, false) == false { - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if m.VerifyNotBefore(now, false) == false { - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/none.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/none.go deleted file mode 100644 index f04d189d..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/none.go +++ /dev/null @@ -1,52 +0,0 @@ -package jwt - -// Implements the none signing method. This is required by the spec -// but you probably should never use it. -var SigningMethodNone *signingMethodNone - -const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" - -var NoneSignatureTypeDisallowedError error - -type signingMethodNone struct{} -type unsafeNoneMagicConstant string - -func init() { - SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) - - RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { - return SigningMethodNone - }) -} - -func (m *signingMethodNone) Alg() string { - return "none" -} - -// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { - // Key must be UnsafeAllowNoneSignatureType to prevent accidentally - // accepting 'none' signing method - if _, ok := key.(unsafeNoneMagicConstant); !ok { - return NoneSignatureTypeDisallowedError - } - // If signing method is none, signature must be an empty string - if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) - } - - // Accept 'none' signing method. - return nil -} - -// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { - if _, ok := key.(unsafeNoneMagicConstant); ok { - return "", nil - } - return "", NoneSignatureTypeDisallowedError -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/parser.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/parser.go deleted file mode 100644 index d6901d9a..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/parser.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type Parser struct { - ValidMethods []string // If populated, only these methods will be considered valid - UseJSONNumber bool // Use JSON Number format in JSON decoder - SkipClaimsValidation bool // Skip claims validation during token parsing -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) -} - -func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - token, parts, err := p.ParseUnverified(tokenString, claims) - if err != nil { - return token, err - } - - // Verify signing method is in the required set - if p.ValidMethods != nil { - var signingMethodValid = false - var alg = token.Method.Alg() - for _, m := range p.ValidMethods { - if m == alg { - signingMethodValid = true - break - } - } - if !signingMethodValid { - // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) - } - } - - // Lookup key - var key interface{} - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) - } - if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} - } - - vErr := &ValidationError{} - - // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } - } - } - - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid - } - - if vErr.valid() { - token.Valid = true - return token, nil - } - - return token, vErr -} - -// WARNING: Don't use this method unless you know what you're doing -// -// This method parses the token but doesn't validate the signature. It's only -// ever useful in cases where you know the signature is valid (because it has -// been checked previously in the stack) and you want to extract values from -// it. -func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { - parts = strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) - } - - token = &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) - } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - token.Claims = claims - - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - // Handle decode error - if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) - } - } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) - } - - return token, parts, nil -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa.go deleted file mode 100644 index e4caf1ca..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSA family of signing methods signing methods -// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation -type SigningMethodRSA struct { - Name string - Hash crypto.Hash -} - -// Specific instances for RS256 and company -var ( - SigningMethodRS256 *SigningMethodRSA - SigningMethodRS384 *SigningMethodRSA - SigningMethodRS512 *SigningMethodRSA -) - -func init() { - // RS256 - SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { - return SigningMethodRS256 - }) - - // RS384 - SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { - return SigningMethodRS384 - }) - - // RS512 - SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { - return SigningMethodRS512 - }) -} - -func (m *SigningMethodRSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - var ok bool - - if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return ErrInvalidKeyType - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) -} - -// Implements the Sign method from SigningMethod -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - var ok bool - - // Validate type of key - if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return "", ErrInvalidKey - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go deleted file mode 100644 index 10ee9db8..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go +++ /dev/null @@ -1,126 +0,0 @@ -// +build go1.4 - -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSAPSS family of signing methods signing methods -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions -} - -// Specific instances for RS/PS and company -var ( - SigningMethodPS256 *SigningMethodRSAPSS - SigningMethodPS384 *SigningMethodRSAPSS - SigningMethodPS512 *SigningMethodRSAPSS -) - -func init() { - // PS256 - SigningMethodPS256 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA256, - }, - } - RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { - return SigningMethodPS256 - }) - - // PS384 - SigningMethodPS384 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA384, - }, - } - RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { - return SigningMethodPS384 - }) - - // PS512 - SigningMethodPS512 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA512, - }, - } - RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { - return SigningMethodPS512 - }) -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - switch k := key.(type) { - case *rsa.PublicKey: - rsaKey = k - default: - return ErrInvalidKey - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - - switch k := key.(type) { - case *rsa.PrivateKey: - rsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go deleted file mode 100644 index a5ababf9..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") - ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") -) - -// Parse PEM encoded PKCS1 or PKCS8 private key -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 private key protected with password -func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - - var blockDecrypted []byte - if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { - return nil, err - } - - if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/signing_method.go deleted file mode 100644 index ed1f212b..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/signing_method.go +++ /dev/null @@ -1,35 +0,0 @@ -package jwt - -import ( - "sync" -) - -var signingMethods = map[string]func() SigningMethod{} -var signingMethodLock = new(sync.RWMutex) - -// Implement SigningMethod to add new methods for signing or verifying tokens. -type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') -} - -// Register the "alg" name and a factory function for signing method. -// This is typically done during init() in the method's implementation -func RegisterSigningMethod(alg string, f func() SigningMethod) { - signingMethodLock.Lock() - defer signingMethodLock.Unlock() - - signingMethods[alg] = f -} - -// Get a signing method from an "alg" string -func GetSigningMethod(alg string) (method SigningMethod) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - if methodF, ok := signingMethods[alg]; ok { - method = methodF() - } - return -} diff --git a/taskman-server/vendor/github.com/dgrijalva/jwt-go/token.go b/taskman-server/vendor/github.com/dgrijalva/jwt-go/token.go deleted file mode 100644 index d637e086..00000000 --- a/taskman-server/vendor/github.com/dgrijalva/jwt-go/token.go +++ /dev/null @@ -1,108 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" - "time" -) - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Parse methods use this callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// A JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// Create a new Token. Takes a signing method -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// Get the complete, signed token -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// Generate the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - parts := make([]string, 2) - for i, _ := range parts { - var jsonValue []byte - if i == 0 { - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - } else { - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - } - - parts[i] = EncodeSegment(jsonValue) - } - return strings.Join(parts, "."), nil -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return new(Parser).Parse(tokenString, keyFunc) -} - -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) -} - -// Encode JWT specific base64url encoding with padding stripped -func EncodeSegment(seg []byte) string { - return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") -} - -// Decode JWT specific base64url encoding with padding stripped -func DecodeSegment(seg string) ([]byte, error) { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - - return base64.URLEncoding.DecodeString(seg) -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/.travis.yml b/taskman-server/vendor/github.com/dustin/go-humanize/.travis.yml deleted file mode 100644 index ba95cdd1..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -sudo: false -language: go -go: - - 1.3.x - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - master -matrix: - allow_failures: - - go: master - fast_finish: true -install: - - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d -s .) - - go tool vet . - - go test -v -race ./... diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/LICENSE b/taskman-server/vendor/github.com/dustin/go-humanize/LICENSE deleted file mode 100644 index 8d9a94a9..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2005-2008 Dustin Sallings - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/README.markdown b/taskman-server/vendor/github.com/dustin/go-humanize/README.markdown deleted file mode 100644 index 91b4ae56..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/README.markdown +++ /dev/null @@ -1,124 +0,0 @@ -# Humane Units [![Build Status](https://travis-ci.org/dustin/go-humanize.svg?branch=master)](https://travis-ci.org/dustin/go-humanize) [![GoDoc](https://godoc.org/github.com/dustin/go-humanize?status.svg)](https://godoc.org/github.com/dustin/go-humanize) - -Just a few functions for helping humanize times and sizes. - -`go get` it as `github.com/dustin/go-humanize`, import it as -`"github.com/dustin/go-humanize"`, use it as `humanize`. - -See [godoc](https://godoc.org/github.com/dustin/go-humanize) for -complete documentation. - -## Sizes - -This lets you take numbers like `82854982` and convert them to useful -strings like, `83 MB` or `79 MiB` (whichever you prefer). - -Example: - -```go -fmt.Printf("That file is %s.", humanize.Bytes(82854982)) // That file is 83 MB. -``` - -## Times - -This lets you take a `time.Time` and spit it out in relative terms. -For example, `12 seconds ago` or `3 days from now`. - -Example: - -```go -fmt.Printf("This was touched %s.", humanize.Time(someTimeInstance)) // This was touched 7 hours ago. -``` - -Thanks to Kyle Lemons for the time implementation from an IRC -conversation one day. It's pretty neat. - -## Ordinals - -From a [mailing list discussion][odisc] where a user wanted to be able -to label ordinals. - - 0 -> 0th - 1 -> 1st - 2 -> 2nd - 3 -> 3rd - 4 -> 4th - [...] - -Example: - -```go -fmt.Printf("You're my %s best friend.", humanize.Ordinal(193)) // You are my 193rd best friend. -``` - -## Commas - -Want to shove commas into numbers? Be my guest. - - 0 -> 0 - 100 -> 100 - 1000 -> 1,000 - 1000000000 -> 1,000,000,000 - -100000 -> -100,000 - -Example: - -```go -fmt.Printf("You owe $%s.\n", humanize.Comma(6582491)) // You owe $6,582,491. -``` - -## Ftoa - -Nicer float64 formatter that removes trailing zeros. - -```go -fmt.Printf("%f", 2.24) // 2.240000 -fmt.Printf("%s", humanize.Ftoa(2.24)) // 2.24 -fmt.Printf("%f", 2.0) // 2.000000 -fmt.Printf("%s", humanize.Ftoa(2.0)) // 2 -``` - -## SI notation - -Format numbers with [SI notation][sinotation]. - -Example: - -```go -humanize.SI(0.00000000223, "M") // 2.23 nM -``` - -## English-specific functions - -The following functions are in the `humanize/english` subpackage. - -### Plurals - -Simple English pluralization - -```go -english.PluralWord(1, "object", "") // object -english.PluralWord(42, "object", "") // objects -english.PluralWord(2, "bus", "") // buses -english.PluralWord(99, "locus", "loci") // loci - -english.Plural(1, "object", "") // 1 object -english.Plural(42, "object", "") // 42 objects -english.Plural(2, "bus", "") // 2 buses -english.Plural(99, "locus", "loci") // 99 loci -``` - -### Word series - -Format comma-separated words lists with conjuctions: - -```go -english.WordSeries([]string{"foo"}, "and") // foo -english.WordSeries([]string{"foo", "bar"}, "and") // foo and bar -english.WordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar and baz - -english.OxfordWordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar, and baz -``` - -[odisc]: https://groups.google.com/d/topic/golang-nuts/l8NhI74jl-4/discussion -[sinotation]: http://en.wikipedia.org/wiki/Metric_prefix diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/big.go b/taskman-server/vendor/github.com/dustin/go-humanize/big.go deleted file mode 100644 index f49dc337..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/big.go +++ /dev/null @@ -1,31 +0,0 @@ -package humanize - -import ( - "math/big" -) - -// order of magnitude (to a max order) -func oomm(n, b *big.Int, maxmag int) (float64, int) { - mag := 0 - m := &big.Int{} - for n.Cmp(b) >= 0 { - n.DivMod(n, b, m) - mag++ - if mag == maxmag && maxmag >= 0 { - break - } - } - return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag -} - -// total order of magnitude -// (same as above, but with no upper limit) -func oom(n, b *big.Int) (float64, int) { - mag := 0 - m := &big.Int{} - for n.Cmp(b) >= 0 { - n.DivMod(n, b, m) - mag++ - } - return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/bigbytes.go b/taskman-server/vendor/github.com/dustin/go-humanize/bigbytes.go deleted file mode 100644 index 1a2bf617..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/bigbytes.go +++ /dev/null @@ -1,173 +0,0 @@ -package humanize - -import ( - "fmt" - "math/big" - "strings" - "unicode" -) - -var ( - bigIECExp = big.NewInt(1024) - - // BigByte is one byte in bit.Ints - BigByte = big.NewInt(1) - // BigKiByte is 1,024 bytes in bit.Ints - BigKiByte = (&big.Int{}).Mul(BigByte, bigIECExp) - // BigMiByte is 1,024 k bytes in bit.Ints - BigMiByte = (&big.Int{}).Mul(BigKiByte, bigIECExp) - // BigGiByte is 1,024 m bytes in bit.Ints - BigGiByte = (&big.Int{}).Mul(BigMiByte, bigIECExp) - // BigTiByte is 1,024 g bytes in bit.Ints - BigTiByte = (&big.Int{}).Mul(BigGiByte, bigIECExp) - // BigPiByte is 1,024 t bytes in bit.Ints - BigPiByte = (&big.Int{}).Mul(BigTiByte, bigIECExp) - // BigEiByte is 1,024 p bytes in bit.Ints - BigEiByte = (&big.Int{}).Mul(BigPiByte, bigIECExp) - // BigZiByte is 1,024 e bytes in bit.Ints - BigZiByte = (&big.Int{}).Mul(BigEiByte, bigIECExp) - // BigYiByte is 1,024 z bytes in bit.Ints - BigYiByte = (&big.Int{}).Mul(BigZiByte, bigIECExp) -) - -var ( - bigSIExp = big.NewInt(1000) - - // BigSIByte is one SI byte in big.Ints - BigSIByte = big.NewInt(1) - // BigKByte is 1,000 SI bytes in big.Ints - BigKByte = (&big.Int{}).Mul(BigSIByte, bigSIExp) - // BigMByte is 1,000 SI k bytes in big.Ints - BigMByte = (&big.Int{}).Mul(BigKByte, bigSIExp) - // BigGByte is 1,000 SI m bytes in big.Ints - BigGByte = (&big.Int{}).Mul(BigMByte, bigSIExp) - // BigTByte is 1,000 SI g bytes in big.Ints - BigTByte = (&big.Int{}).Mul(BigGByte, bigSIExp) - // BigPByte is 1,000 SI t bytes in big.Ints - BigPByte = (&big.Int{}).Mul(BigTByte, bigSIExp) - // BigEByte is 1,000 SI p bytes in big.Ints - BigEByte = (&big.Int{}).Mul(BigPByte, bigSIExp) - // BigZByte is 1,000 SI e bytes in big.Ints - BigZByte = (&big.Int{}).Mul(BigEByte, bigSIExp) - // BigYByte is 1,000 SI z bytes in big.Ints - BigYByte = (&big.Int{}).Mul(BigZByte, bigSIExp) -) - -var bigBytesSizeTable = map[string]*big.Int{ - "b": BigByte, - "kib": BigKiByte, - "kb": BigKByte, - "mib": BigMiByte, - "mb": BigMByte, - "gib": BigGiByte, - "gb": BigGByte, - "tib": BigTiByte, - "tb": BigTByte, - "pib": BigPiByte, - "pb": BigPByte, - "eib": BigEiByte, - "eb": BigEByte, - "zib": BigZiByte, - "zb": BigZByte, - "yib": BigYiByte, - "yb": BigYByte, - // Without suffix - "": BigByte, - "ki": BigKiByte, - "k": BigKByte, - "mi": BigMiByte, - "m": BigMByte, - "gi": BigGiByte, - "g": BigGByte, - "ti": BigTiByte, - "t": BigTByte, - "pi": BigPiByte, - "p": BigPByte, - "ei": BigEiByte, - "e": BigEByte, - "z": BigZByte, - "zi": BigZiByte, - "y": BigYByte, - "yi": BigYiByte, -} - -var ten = big.NewInt(10) - -func humanateBigBytes(s, base *big.Int, sizes []string) string { - if s.Cmp(ten) < 0 { - return fmt.Sprintf("%d B", s) - } - c := (&big.Int{}).Set(s) - val, mag := oomm(c, base, len(sizes)-1) - suffix := sizes[mag] - f := "%.0f %s" - if val < 10 { - f = "%.1f %s" - } - - return fmt.Sprintf(f, val, suffix) - -} - -// BigBytes produces a human readable representation of an SI size. -// -// See also: ParseBigBytes. -// -// BigBytes(82854982) -> 83 MB -func BigBytes(s *big.Int) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} - return humanateBigBytes(s, bigSIExp, sizes) -} - -// BigIBytes produces a human readable representation of an IEC size. -// -// See also: ParseBigBytes. -// -// BigIBytes(82854982) -> 79 MiB -func BigIBytes(s *big.Int) string { - sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} - return humanateBigBytes(s, bigIECExp, sizes) -} - -// ParseBigBytes parses a string representation of bytes into the number -// of bytes it represents. -// -// See also: BigBytes, BigIBytes. -// -// ParseBigBytes("42 MB") -> 42000000, nil -// ParseBigBytes("42 mib") -> 44040192, nil -func ParseBigBytes(s string) (*big.Int, error) { - lastDigit := 0 - hasComma := false - for _, r := range s { - if !(unicode.IsDigit(r) || r == '.' || r == ',') { - break - } - if r == ',' { - hasComma = true - } - lastDigit++ - } - - num := s[:lastDigit] - if hasComma { - num = strings.Replace(num, ",", "", -1) - } - - val := &big.Rat{} - _, err := fmt.Sscanf(num, "%f", val) - if err != nil { - return nil, err - } - - extra := strings.ToLower(strings.TrimSpace(s[lastDigit:])) - if m, ok := bigBytesSizeTable[extra]; ok { - mv := (&big.Rat{}).SetInt(m) - val.Mul(val, mv) - rv := &big.Int{} - rv.Div(val.Num(), val.Denom()) - return rv, nil - } - - return nil, fmt.Errorf("unhandled size name: %v", extra) -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/bytes.go b/taskman-server/vendor/github.com/dustin/go-humanize/bytes.go deleted file mode 100644 index 0b498f48..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/bytes.go +++ /dev/null @@ -1,143 +0,0 @@ -package humanize - -import ( - "fmt" - "math" - "strconv" - "strings" - "unicode" -) - -// IEC Sizes. -// kibis of bits -const ( - Byte = 1 << (iota * 10) - KiByte - MiByte - GiByte - TiByte - PiByte - EiByte -) - -// SI Sizes. -const ( - IByte = 1 - KByte = IByte * 1000 - MByte = KByte * 1000 - GByte = MByte * 1000 - TByte = GByte * 1000 - PByte = TByte * 1000 - EByte = PByte * 1000 -) - -var bytesSizeTable = map[string]uint64{ - "b": Byte, - "kib": KiByte, - "kb": KByte, - "mib": MiByte, - "mb": MByte, - "gib": GiByte, - "gb": GByte, - "tib": TiByte, - "tb": TByte, - "pib": PiByte, - "pb": PByte, - "eib": EiByte, - "eb": EByte, - // Without suffix - "": Byte, - "ki": KiByte, - "k": KByte, - "mi": MiByte, - "m": MByte, - "gi": GiByte, - "g": GByte, - "ti": TiByte, - "t": TByte, - "pi": PiByte, - "p": PByte, - "ei": EiByte, - "e": EByte, -} - -func logn(n, b float64) float64 { - return math.Log(n) / math.Log(b) -} - -func humanateBytes(s uint64, base float64, sizes []string) string { - if s < 10 { - return fmt.Sprintf("%d B", s) - } - e := math.Floor(logn(float64(s), base)) - suffix := sizes[int(e)] - val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10 - f := "%.0f %s" - if val < 10 { - f = "%.1f %s" - } - - return fmt.Sprintf(f, val, suffix) -} - -// Bytes produces a human readable representation of an SI size. -// -// See also: ParseBytes. -// -// Bytes(82854982) -> 83 MB -func Bytes(s uint64) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"} - return humanateBytes(s, 1000, sizes) -} - -// IBytes produces a human readable representation of an IEC size. -// -// See also: ParseBytes. -// -// IBytes(82854982) -> 79 MiB -func IBytes(s uint64) string { - sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"} - return humanateBytes(s, 1024, sizes) -} - -// ParseBytes parses a string representation of bytes into the number -// of bytes it represents. -// -// See Also: Bytes, IBytes. -// -// ParseBytes("42 MB") -> 42000000, nil -// ParseBytes("42 mib") -> 44040192, nil -func ParseBytes(s string) (uint64, error) { - lastDigit := 0 - hasComma := false - for _, r := range s { - if !(unicode.IsDigit(r) || r == '.' || r == ',') { - break - } - if r == ',' { - hasComma = true - } - lastDigit++ - } - - num := s[:lastDigit] - if hasComma { - num = strings.Replace(num, ",", "", -1) - } - - f, err := strconv.ParseFloat(num, 64) - if err != nil { - return 0, err - } - - extra := strings.ToLower(strings.TrimSpace(s[lastDigit:])) - if m, ok := bytesSizeTable[extra]; ok { - f *= float64(m) - if f >= math.MaxUint64 { - return 0, fmt.Errorf("too large: %v", s) - } - return uint64(f), nil - } - - return 0, fmt.Errorf("unhandled size name: %v", extra) -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/comma.go b/taskman-server/vendor/github.com/dustin/go-humanize/comma.go deleted file mode 100644 index 520ae3e5..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/comma.go +++ /dev/null @@ -1,116 +0,0 @@ -package humanize - -import ( - "bytes" - "math" - "math/big" - "strconv" - "strings" -) - -// Comma produces a string form of the given number in base 10 with -// commas after every three orders of magnitude. -// -// e.g. Comma(834142) -> 834,142 -func Comma(v int64) string { - sign := "" - - // Min int64 can't be negated to a usable value, so it has to be special cased. - if v == math.MinInt64 { - return "-9,223,372,036,854,775,808" - } - - if v < 0 { - sign = "-" - v = 0 - v - } - - parts := []string{"", "", "", "", "", "", ""} - j := len(parts) - 1 - - for v > 999 { - parts[j] = strconv.FormatInt(v%1000, 10) - switch len(parts[j]) { - case 2: - parts[j] = "0" + parts[j] - case 1: - parts[j] = "00" + parts[j] - } - v = v / 1000 - j-- - } - parts[j] = strconv.Itoa(int(v)) - return sign + strings.Join(parts[j:], ",") -} - -// Commaf produces a string form of the given number in base 10 with -// commas after every three orders of magnitude. -// -// e.g. Commaf(834142.32) -> 834,142.32 -func Commaf(v float64) string { - buf := &bytes.Buffer{} - if v < 0 { - buf.Write([]byte{'-'}) - v = 0 - v - } - - comma := []byte{','} - - parts := strings.Split(strconv.FormatFloat(v, 'f', -1, 64), ".") - pos := 0 - if len(parts[0])%3 != 0 { - pos += len(parts[0]) % 3 - buf.WriteString(parts[0][:pos]) - buf.Write(comma) - } - for ; pos < len(parts[0]); pos += 3 { - buf.WriteString(parts[0][pos : pos+3]) - buf.Write(comma) - } - buf.Truncate(buf.Len() - 1) - - if len(parts) > 1 { - buf.Write([]byte{'.'}) - buf.WriteString(parts[1]) - } - return buf.String() -} - -// CommafWithDigits works like the Commaf but limits the resulting -// string to the given number of decimal places. -// -// e.g. CommafWithDigits(834142.32, 1) -> 834,142.3 -func CommafWithDigits(f float64, decimals int) string { - return stripTrailingDigits(Commaf(f), decimals) -} - -// BigComma produces a string form of the given big.Int in base 10 -// with commas after every three orders of magnitude. -func BigComma(b *big.Int) string { - sign := "" - if b.Sign() < 0 { - sign = "-" - b.Abs(b) - } - - athousand := big.NewInt(1000) - c := (&big.Int{}).Set(b) - _, m := oom(c, athousand) - parts := make([]string, m+1) - j := len(parts) - 1 - - mod := &big.Int{} - for b.Cmp(athousand) >= 0 { - b.DivMod(b, athousand, mod) - parts[j] = strconv.FormatInt(mod.Int64(), 10) - switch len(parts[j]) { - case 2: - parts[j] = "0" + parts[j] - case 1: - parts[j] = "00" + parts[j] - } - j-- - } - parts[j] = strconv.Itoa(int(b.Int64())) - return sign + strings.Join(parts[j:], ",") -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/commaf.go b/taskman-server/vendor/github.com/dustin/go-humanize/commaf.go deleted file mode 100644 index 620690de..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/commaf.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build go1.6 - -package humanize - -import ( - "bytes" - "math/big" - "strings" -) - -// BigCommaf produces a string form of the given big.Float in base 10 -// with commas after every three orders of magnitude. -func BigCommaf(v *big.Float) string { - buf := &bytes.Buffer{} - if v.Sign() < 0 { - buf.Write([]byte{'-'}) - v.Abs(v) - } - - comma := []byte{','} - - parts := strings.Split(v.Text('f', -1), ".") - pos := 0 - if len(parts[0])%3 != 0 { - pos += len(parts[0]) % 3 - buf.WriteString(parts[0][:pos]) - buf.Write(comma) - } - for ; pos < len(parts[0]); pos += 3 { - buf.WriteString(parts[0][pos : pos+3]) - buf.Write(comma) - } - buf.Truncate(buf.Len() - 1) - - if len(parts) > 1 { - buf.Write([]byte{'.'}) - buf.WriteString(parts[1]) - } - return buf.String() -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/ftoa.go b/taskman-server/vendor/github.com/dustin/go-humanize/ftoa.go deleted file mode 100644 index 1c62b640..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/ftoa.go +++ /dev/null @@ -1,46 +0,0 @@ -package humanize - -import ( - "strconv" - "strings" -) - -func stripTrailingZeros(s string) string { - offset := len(s) - 1 - for offset > 0 { - if s[offset] == '.' { - offset-- - break - } - if s[offset] != '0' { - break - } - offset-- - } - return s[:offset+1] -} - -func stripTrailingDigits(s string, digits int) string { - if i := strings.Index(s, "."); i >= 0 { - if digits <= 0 { - return s[:i] - } - i++ - if i+digits >= len(s) { - return s - } - return s[:i+digits] - } - return s -} - -// Ftoa converts a float to a string with no trailing zeros. -func Ftoa(num float64) string { - return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64)) -} - -// FtoaWithDigits converts a float to a string but limits the resulting string -// to the given number of decimal places, and no trailing zeros. -func FtoaWithDigits(num float64, digits int) string { - return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits)) -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/humanize.go b/taskman-server/vendor/github.com/dustin/go-humanize/humanize.go deleted file mode 100644 index a2c2da31..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/humanize.go +++ /dev/null @@ -1,8 +0,0 @@ -/* -Package humanize converts boring ugly numbers to human-friendly strings and back. - -Durations can be turned into strings such as "3 days ago", numbers -representing sizes like 82854982 into useful strings like, "83 MB" or -"79 MiB" (whichever you prefer). -*/ -package humanize diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/number.go b/taskman-server/vendor/github.com/dustin/go-humanize/number.go deleted file mode 100644 index dec61865..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/number.go +++ /dev/null @@ -1,192 +0,0 @@ -package humanize - -/* -Slightly adapted from the source to fit go-humanize. - -Author: https://github.com/gorhill -Source: https://gist.github.com/gorhill/5285193 - -*/ - -import ( - "math" - "strconv" -) - -var ( - renderFloatPrecisionMultipliers = [...]float64{ - 1, - 10, - 100, - 1000, - 10000, - 100000, - 1000000, - 10000000, - 100000000, - 1000000000, - } - - renderFloatPrecisionRounders = [...]float64{ - 0.5, - 0.05, - 0.005, - 0.0005, - 0.00005, - 0.000005, - 0.0000005, - 0.00000005, - 0.000000005, - 0.0000000005, - } -) - -// FormatFloat produces a formatted number as string based on the following user-specified criteria: -// * thousands separator -// * decimal separator -// * decimal precision -// -// Usage: s := RenderFloat(format, n) -// The format parameter tells how to render the number n. -// -// See examples: http://play.golang.org/p/LXc1Ddm1lJ -// -// Examples of format strings, given n = 12345.6789: -// "#,###.##" => "12,345.67" -// "#,###." => "12,345" -// "#,###" => "12345,678" -// "#\u202F###,##" => "12 345,68" -// "#.###,###### => 12.345,678900 -// "" (aka default format) => 12,345.67 -// -// The highest precision allowed is 9 digits after the decimal symbol. -// There is also a version for integer number, FormatInteger(), -// which is convenient for calls within template. -func FormatFloat(format string, n float64) string { - // Special cases: - // NaN = "NaN" - // +Inf = "+Infinity" - // -Inf = "-Infinity" - if math.IsNaN(n) { - return "NaN" - } - if n > math.MaxFloat64 { - return "Infinity" - } - if n < -math.MaxFloat64 { - return "-Infinity" - } - - // default format - precision := 2 - decimalStr := "." - thousandStr := "," - positiveStr := "" - negativeStr := "-" - - if len(format) > 0 { - format := []rune(format) - - // If there is an explicit format directive, - // then default values are these: - precision = 9 - thousandStr = "" - - // collect indices of meaningful formatting directives - formatIndx := []int{} - for i, char := range format { - if char != '#' && char != '0' { - formatIndx = append(formatIndx, i) - } - } - - if len(formatIndx) > 0 { - // Directive at index 0: - // Must be a '+' - // Raise an error if not the case - // index: 0123456789 - // +0.000,000 - // +000,000.0 - // +0000.00 - // +0000 - if formatIndx[0] == 0 { - if format[formatIndx[0]] != '+' { - panic("RenderFloat(): invalid positive sign directive") - } - positiveStr = "+" - formatIndx = formatIndx[1:] - } - - // Two directives: - // First is thousands separator - // Raise an error if not followed by 3-digit - // 0123456789 - // 0.000,000 - // 000,000.00 - if len(formatIndx) == 2 { - if (formatIndx[1] - formatIndx[0]) != 4 { - panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers") - } - thousandStr = string(format[formatIndx[0]]) - formatIndx = formatIndx[1:] - } - - // One directive: - // Directive is decimal separator - // The number of digit-specifier following the separator indicates wanted precision - // 0123456789 - // 0.00 - // 000,0000 - if len(formatIndx) == 1 { - decimalStr = string(format[formatIndx[0]]) - precision = len(format) - formatIndx[0] - 1 - } - } - } - - // generate sign part - var signStr string - if n >= 0.000000001 { - signStr = positiveStr - } else if n <= -0.000000001 { - signStr = negativeStr - n = -n - } else { - signStr = "" - n = 0.0 - } - - // split number into integer and fractional parts - intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision]) - - // generate integer part string - intStr := strconv.FormatInt(int64(intf), 10) - - // add thousand separator if required - if len(thousandStr) > 0 { - for i := len(intStr); i > 3; { - i -= 3 - intStr = intStr[:i] + thousandStr + intStr[i:] - } - } - - // no fractional part, we can leave now - if precision == 0 { - return signStr + intStr - } - - // generate fractional part - fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision])) - // may need padding - if len(fracStr) < precision { - fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr - } - - return signStr + intStr + decimalStr + fracStr -} - -// FormatInteger produces a formatted number as string. -// See FormatFloat. -func FormatInteger(format string, n int) string { - return FormatFloat(format, float64(n)) -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/ordinals.go b/taskman-server/vendor/github.com/dustin/go-humanize/ordinals.go deleted file mode 100644 index 43d88a86..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/ordinals.go +++ /dev/null @@ -1,25 +0,0 @@ -package humanize - -import "strconv" - -// Ordinal gives you the input number in a rank/ordinal format. -// -// Ordinal(3) -> 3rd -func Ordinal(x int) string { - suffix := "th" - switch x % 10 { - case 1: - if x%100 != 11 { - suffix = "st" - } - case 2: - if x%100 != 12 { - suffix = "nd" - } - case 3: - if x%100 != 13 { - suffix = "rd" - } - } - return strconv.Itoa(x) + suffix -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/si.go b/taskman-server/vendor/github.com/dustin/go-humanize/si.go deleted file mode 100644 index ae659e0e..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/si.go +++ /dev/null @@ -1,123 +0,0 @@ -package humanize - -import ( - "errors" - "math" - "regexp" - "strconv" -) - -var siPrefixTable = map[float64]string{ - -24: "y", // yocto - -21: "z", // zepto - -18: "a", // atto - -15: "f", // femto - -12: "p", // pico - -9: "n", // nano - -6: "µ", // micro - -3: "m", // milli - 0: "", - 3: "k", // kilo - 6: "M", // mega - 9: "G", // giga - 12: "T", // tera - 15: "P", // peta - 18: "E", // exa - 21: "Z", // zetta - 24: "Y", // yotta -} - -var revSIPrefixTable = revfmap(siPrefixTable) - -// revfmap reverses the map and precomputes the power multiplier -func revfmap(in map[float64]string) map[string]float64 { - rv := map[string]float64{} - for k, v := range in { - rv[v] = math.Pow(10, k) - } - return rv -} - -var riParseRegex *regexp.Regexp - -func init() { - ri := `^([\-0-9.]+)\s?([` - for _, v := range siPrefixTable { - ri += v - } - ri += `]?)(.*)` - - riParseRegex = regexp.MustCompile(ri) -} - -// ComputeSI finds the most appropriate SI prefix for the given number -// and returns the prefix along with the value adjusted to be within -// that prefix. -// -// See also: SI, ParseSI. -// -// e.g. ComputeSI(2.2345e-12) -> (2.2345, "p") -func ComputeSI(input float64) (float64, string) { - if input == 0 { - return 0, "" - } - mag := math.Abs(input) - exponent := math.Floor(logn(mag, 10)) - exponent = math.Floor(exponent/3) * 3 - - value := mag / math.Pow(10, exponent) - - // Handle special case where value is exactly 1000.0 - // Should return 1 M instead of 1000 k - if value == 1000.0 { - exponent += 3 - value = mag / math.Pow(10, exponent) - } - - value = math.Copysign(value, input) - - prefix := siPrefixTable[exponent] - return value, prefix -} - -// SI returns a string with default formatting. -// -// SI uses Ftoa to format float value, removing trailing zeros. -// -// See also: ComputeSI, ParseSI. -// -// e.g. SI(1000000, "B") -> 1 MB -// e.g. SI(2.2345e-12, "F") -> 2.2345 pF -func SI(input float64, unit string) string { - value, prefix := ComputeSI(input) - return Ftoa(value) + " " + prefix + unit -} - -// SIWithDigits works like SI but limits the resulting string to the -// given number of decimal places. -// -// e.g. SIWithDigits(1000000, 0, "B") -> 1 MB -// e.g. SIWithDigits(2.2345e-12, 2, "F") -> 2.23 pF -func SIWithDigits(input float64, decimals int, unit string) string { - value, prefix := ComputeSI(input) - return FtoaWithDigits(value, decimals) + " " + prefix + unit -} - -var errInvalid = errors.New("invalid input") - -// ParseSI parses an SI string back into the number and unit. -// -// See also: SI, ComputeSI. -// -// e.g. ParseSI("2.2345 pF") -> (2.2345e-12, "F", nil) -func ParseSI(input string) (float64, string, error) { - found := riParseRegex.FindStringSubmatch(input) - if len(found) != 4 { - return 0, "", errInvalid - } - mag := revSIPrefixTable[found[2]] - unit := found[3] - - base, err := strconv.ParseFloat(found[1], 64) - return base * mag, unit, err -} diff --git a/taskman-server/vendor/github.com/dustin/go-humanize/times.go b/taskman-server/vendor/github.com/dustin/go-humanize/times.go deleted file mode 100644 index dd3fbf5e..00000000 --- a/taskman-server/vendor/github.com/dustin/go-humanize/times.go +++ /dev/null @@ -1,117 +0,0 @@ -package humanize - -import ( - "fmt" - "math" - "sort" - "time" -) - -// Seconds-based time units -const ( - Day = 24 * time.Hour - Week = 7 * Day - Month = 30 * Day - Year = 12 * Month - LongTime = 37 * Year -) - -// Time formats a time into a relative string. -// -// Time(someT) -> "3 weeks ago" -func Time(then time.Time) string { - return RelTime(then, time.Now(), "ago", "from now") -} - -// A RelTimeMagnitude struct contains a relative time point at which -// the relative format of time will switch to a new format string. A -// slice of these in ascending order by their "D" field is passed to -// CustomRelTime to format durations. -// -// The Format field is a string that may contain a "%s" which will be -// replaced with the appropriate signed label (e.g. "ago" or "from -// now") and a "%d" that will be replaced by the quantity. -// -// The DivBy field is the amount of time the time difference must be -// divided by in order to display correctly. -// -// e.g. if D is 2*time.Minute and you want to display "%d minutes %s" -// DivBy should be time.Minute so whatever the duration is will be -// expressed in minutes. -type RelTimeMagnitude struct { - D time.Duration - Format string - DivBy time.Duration -} - -var defaultMagnitudes = []RelTimeMagnitude{ - {time.Second, "now", time.Second}, - {2 * time.Second, "1 second %s", 1}, - {time.Minute, "%d seconds %s", time.Second}, - {2 * time.Minute, "1 minute %s", 1}, - {time.Hour, "%d minutes %s", time.Minute}, - {2 * time.Hour, "1 hour %s", 1}, - {Day, "%d hours %s", time.Hour}, - {2 * Day, "1 day %s", 1}, - {Week, "%d days %s", Day}, - {2 * Week, "1 week %s", 1}, - {Month, "%d weeks %s", Week}, - {2 * Month, "1 month %s", 1}, - {Year, "%d months %s", Month}, - {18 * Month, "1 year %s", 1}, - {2 * Year, "2 years %s", 1}, - {LongTime, "%d years %s", Year}, - {math.MaxInt64, "a long while %s", 1}, -} - -// RelTime formats a time into a relative string. -// -// It takes two times and two labels. In addition to the generic time -// delta string (e.g. 5 minutes), the labels are used applied so that -// the label corresponding to the smaller time is applied. -// -// RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier" -func RelTime(a, b time.Time, albl, blbl string) string { - return CustomRelTime(a, b, albl, blbl, defaultMagnitudes) -} - -// CustomRelTime formats a time into a relative string. -// -// It takes two times two labels and a table of relative time formats. -// In addition to the generic time delta string (e.g. 5 minutes), the -// labels are used applied so that the label corresponding to the -// smaller time is applied. -func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnitude) string { - lbl := albl - diff := b.Sub(a) - - if a.After(b) { - lbl = blbl - diff = a.Sub(b) - } - - n := sort.Search(len(magnitudes), func(i int) bool { - return magnitudes[i].D > diff - }) - - if n >= len(magnitudes) { - n = len(magnitudes) - 1 - } - mag := magnitudes[n] - args := []interface{}{} - escaped := false - for _, ch := range mag.Format { - if escaped { - switch ch { - case 's': - args = append(args, lbl) - case 'd': - args = append(args, diff/mag.DivBy) - } - escaped = false - } else { - escaped = ch == '%' - } - } - return fmt.Sprintf(mag.Format, args...) -} diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/.travis.yml b/taskman-server/vendor/github.com/gin-contrib/sse/.travis.yml deleted file mode 100644 index d0e8fcf9..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: go -sudo: false -go: - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - master - -git: - depth: 10 - -matrix: - fast_finish: true - include: - - go: 1.11.x - env: GO111MODULE=on - - go: 1.12.x - env: GO111MODULE=on - -script: - - go test -v -covermode=count -coverprofile=coverage.out - -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/LICENSE b/taskman-server/vendor/github.com/gin-contrib/sse/LICENSE deleted file mode 100644 index 1ff7f370..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Manuel Martínez-Almeida - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/README.md b/taskman-server/vendor/github.com/gin-contrib/sse/README.md deleted file mode 100644 index c9c49cf9..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# Server-Sent Events - -[![GoDoc](https://godoc.org/github.com/gin-contrib/sse?status.svg)](https://godoc.org/github.com/gin-contrib/sse) -[![Build Status](https://travis-ci.org/gin-contrib/sse.svg)](https://travis-ci.org/gin-contrib/sse) -[![codecov](https://codecov.io/gh/gin-contrib/sse/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-contrib/sse) -[![Go Report Card](https://goreportcard.com/badge/github.com/gin-contrib/sse)](https://goreportcard.com/report/github.com/gin-contrib/sse) - -Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is [standardized as part of HTML5[1] by the W3C](http://www.w3.org/TR/2009/WD-eventsource-20091029/). - -- [Read this great SSE introduction by the HTML5Rocks guys](http://www.html5rocks.com/en/tutorials/eventsource/basics/) -- [Browser support](http://caniuse.com/#feat=eventsource) - -## Sample code - -```go -import "github.com/gin-contrib/sse" - -func httpHandler(w http.ResponseWriter, req *http.Request) { - // data can be a primitive like a string, an integer or a float - sse.Encode(w, sse.Event{ - Event: "message", - Data: "some data\nmore data", - }) - - // also a complex type, like a map, a struct or a slice - sse.Encode(w, sse.Event{ - Id: "124", - Event: "message", - Data: map[string]interface{}{ - "user": "manu", - "date": time.Now().Unix(), - "content": "hi!", - }, - }) -} -``` -``` -event: message -data: some data\\nmore data - -id: 124 -event: message -data: {"content":"hi!","date":1431540810,"user":"manu"} - -``` - -## Content-Type - -```go -fmt.Println(sse.ContentType) -``` -``` -text/event-stream -``` - -## Decoding support - -There is a client-side implementation of SSE coming soon. diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/go.mod b/taskman-server/vendor/github.com/gin-contrib/sse/go.mod deleted file mode 100644 index b9c03f47..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module github.com/gin-contrib/sse - -go 1.12 - -require github.com/stretchr/testify v1.3.0 diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/go.sum b/taskman-server/vendor/github.com/gin-contrib/sse/go.sum deleted file mode 100644 index 4347755a..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/go.sum +++ /dev/null @@ -1,7 +0,0 @@ -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/sse-decoder.go b/taskman-server/vendor/github.com/gin-contrib/sse/sse-decoder.go deleted file mode 100644 index fd49b9c3..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/sse-decoder.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package sse - -import ( - "bytes" - "io" - "io/ioutil" -) - -type decoder struct { - events []Event -} - -func Decode(r io.Reader) ([]Event, error) { - var dec decoder - return dec.decode(r) -} - -func (d *decoder) dispatchEvent(event Event, data string) { - dataLength := len(data) - if dataLength > 0 { - //If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer. - data = data[:dataLength-1] - dataLength-- - } - if dataLength == 0 && event.Event == "" { - return - } - if event.Event == "" { - event.Event = "message" - } - event.Data = data - d.events = append(d.events, event) -} - -func (d *decoder) decode(r io.Reader) ([]Event, error) { - buf, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - var currentEvent Event - var dataBuffer *bytes.Buffer = new(bytes.Buffer) - // TODO (and unit tests) - // Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, - // a single U+000A LINE FEED (LF) character, - // or a single U+000D CARRIAGE RETURN (CR) character. - lines := bytes.Split(buf, []byte{'\n'}) - for _, line := range lines { - if len(line) == 0 { - // If the line is empty (a blank line). Dispatch the event. - d.dispatchEvent(currentEvent, dataBuffer.String()) - - // reset current event and data buffer - currentEvent = Event{} - dataBuffer.Reset() - continue - } - if line[0] == byte(':') { - // If the line starts with a U+003A COLON character (:), ignore the line. - continue - } - - var field, value []byte - colonIndex := bytes.IndexRune(line, ':') - if colonIndex != -1 { - // If the line contains a U+003A COLON character character (:) - // Collect the characters on the line before the first U+003A COLON character (:), - // and let field be that string. - field = line[:colonIndex] - // Collect the characters on the line after the first U+003A COLON character (:), - // and let value be that string. - value = line[colonIndex+1:] - // If value starts with a single U+0020 SPACE character, remove it from value. - if len(value) > 0 && value[0] == ' ' { - value = value[1:] - } - } else { - // Otherwise, the string is not empty but does not contain a U+003A COLON character character (:) - // Use the whole line as the field name, and the empty string as the field value. - field = line - value = []byte{} - } - // The steps to process the field given a field name and a field value depend on the field name, - // as given in the following list. Field names must be compared literally, - // with no case folding performed. - switch string(field) { - case "event": - // Set the event name buffer to field value. - currentEvent.Event = string(value) - case "id": - // Set the event stream's last event ID to the field value. - currentEvent.Id = string(value) - case "retry": - // If the field value consists of only characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), - // then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer. - // Otherwise, ignore the field. - currentEvent.Id = string(value) - case "data": - // Append the field value to the data buffer, - dataBuffer.Write(value) - // then append a single U+000A LINE FEED (LF) character to the data buffer. - dataBuffer.WriteString("\n") - default: - //Otherwise. The field is ignored. - continue - } - } - // Once the end of the file is reached, the user agent must dispatch the event one final time. - d.dispatchEvent(currentEvent, dataBuffer.String()) - - return d.events, nil -} diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/sse-encoder.go b/taskman-server/vendor/github.com/gin-contrib/sse/sse-encoder.go deleted file mode 100644 index f9c80875..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/sse-encoder.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package sse - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "reflect" - "strconv" - "strings" -) - -// Server-Sent Events -// W3C Working Draft 29 October 2009 -// http://www.w3.org/TR/2009/WD-eventsource-20091029/ - -const ContentType = "text/event-stream" - -var contentType = []string{ContentType} -var noCache = []string{"no-cache"} - -var fieldReplacer = strings.NewReplacer( - "\n", "\\n", - "\r", "\\r") - -var dataReplacer = strings.NewReplacer( - "\n", "\ndata:", - "\r", "\\r") - -type Event struct { - Event string - Id string - Retry uint - Data interface{} -} - -func Encode(writer io.Writer, event Event) error { - w := checkWriter(writer) - writeId(w, event.Id) - writeEvent(w, event.Event) - writeRetry(w, event.Retry) - return writeData(w, event.Data) -} - -func writeId(w stringWriter, id string) { - if len(id) > 0 { - w.WriteString("id:") - fieldReplacer.WriteString(w, id) - w.WriteString("\n") - } -} - -func writeEvent(w stringWriter, event string) { - if len(event) > 0 { - w.WriteString("event:") - fieldReplacer.WriteString(w, event) - w.WriteString("\n") - } -} - -func writeRetry(w stringWriter, retry uint) { - if retry > 0 { - w.WriteString("retry:") - w.WriteString(strconv.FormatUint(uint64(retry), 10)) - w.WriteString("\n") - } -} - -func writeData(w stringWriter, data interface{}) error { - w.WriteString("data:") - switch kindOfData(data) { - case reflect.Struct, reflect.Slice, reflect.Map: - err := json.NewEncoder(w).Encode(data) - if err != nil { - return err - } - w.WriteString("\n") - default: - dataReplacer.WriteString(w, fmt.Sprint(data)) - w.WriteString("\n\n") - } - return nil -} - -func (r Event) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - return Encode(w, r) -} - -func (r Event) WriteContentType(w http.ResponseWriter) { - header := w.Header() - header["Content-Type"] = contentType - - if _, exist := header["Cache-Control"]; !exist { - header["Cache-Control"] = noCache - } -} - -func kindOfData(data interface{}) reflect.Kind { - value := reflect.ValueOf(data) - valueType := value.Kind() - if valueType == reflect.Ptr { - valueType = value.Elem().Kind() - } - return valueType -} diff --git a/taskman-server/vendor/github.com/gin-contrib/sse/writer.go b/taskman-server/vendor/github.com/gin-contrib/sse/writer.go deleted file mode 100644 index 6f9806c5..00000000 --- a/taskman-server/vendor/github.com/gin-contrib/sse/writer.go +++ /dev/null @@ -1,24 +0,0 @@ -package sse - -import "io" - -type stringWriter interface { - io.Writer - WriteString(string) (int, error) -} - -type stringWrapper struct { - io.Writer -} - -func (w stringWrapper) WriteString(str string) (int, error) { - return w.Writer.Write([]byte(str)) -} - -func checkWriter(writer io.Writer) stringWriter { - if w, ok := writer.(stringWriter); ok { - return w - } else { - return stringWrapper{writer} - } -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/.gitignore b/taskman-server/vendor/github.com/gin-gonic/gin/.gitignore deleted file mode 100644 index bdd50c95..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -vendor/* -!vendor/vendor.json -coverage.out -count.out -test -profile.out -tmp.out diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/.travis.yml b/taskman-server/vendor/github.com/gin-gonic/gin/.travis.yml deleted file mode 100644 index 8ebae712..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/.travis.yml +++ /dev/null @@ -1,50 +0,0 @@ -language: go - -matrix: - fast_finish: true - include: - - go: 1.12.x - env: GO111MODULE=on - - go: 1.13.x - - go: 1.13.x - env: - - TESTTAGS=nomsgpack - - go: 1.14.x - - go: 1.14.x - env: - - TESTTAGS=nomsgpack - - go: 1.15.x - - go: 1.15.x - env: - - TESTTAGS=nomsgpack - - go: master - -git: - depth: 10 - -before_install: - - if [[ "${GO111MODULE}" = "on" ]]; then mkdir "${HOME}/go"; export GOPATH="${HOME}/go"; fi - -install: - - if [[ "${GO111MODULE}" = "on" ]]; then go mod download; fi - - if [[ "${GO111MODULE}" = "on" ]]; then export PATH="${GOPATH}/bin:${GOROOT}/bin:${PATH}"; fi - - if [[ "${GO111MODULE}" = "on" ]]; then make tools; fi - -go_import_path: github.com/gin-gonic/gin - -script: - - make vet - - make fmt-check - - make misspell-check - - make test - -after_success: - - bash <(curl -s https://codecov.io/bash) - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/7f95bf605c4d356372f4 - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: false # default: false diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/AUTHORS.md b/taskman-server/vendor/github.com/gin-gonic/gin/AUTHORS.md deleted file mode 100644 index c634e6be..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/AUTHORS.md +++ /dev/null @@ -1,233 +0,0 @@ -List of all the awesome people working to make Gin the best Web Framework in Go. - -## gin 1.x series authors - -**Gin Core Team:** Bo-Yi Wu (@appleboy), 田欧 (@thinkerou), Javier Provecho (@javierprovecho) - -## gin 0.x series authors - -**Maintainers:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) - -People and companies, who have contributed, in alphabetical order. - -**@858806258 (杰哥)** -- Fix typo in example - - -**@achedeuzot (Klemen Sever)** -- Fix newline debug printing - - -**@adammck (Adam Mckaig)** -- Add MIT license - - -**@AlexanderChen1989 (Alexander)** -- Typos in README - - -**@alexanderdidenko (Aleksandr Didenko)** -- Add support multipart/form-data - - -**@alexandernyquist (Alexander Nyquist)** -- Using template.Must to fix multiple return issue -- ★ Added support for OPTIONS verb -- ★ Setting response headers before calling WriteHeader -- Improved documentation for model binding -- ★ Added Content.Redirect() -- ★ Added tons of Unit tests - - -**@austinheap (Austin Heap)** -- Added travis CI integration - - -**@andredublin (Andre Dublin)** -- Fix typo in comment - - -**@bredov (Ludwig Valda Vasquez)** -- Fix html templating in debug mode - - -**@bluele (Jun Kimura)** -- Fixes code examples in README - - -**@chad-russell** -- ★ Support for serializing gin.H into XML - - -**@dickeyxxx (Jeff Dickey)** -- Typos in README -- Add example about serving static files - - -**@donileo (Adonis)** -- Add NoMethod handler - - -**@dutchcoders (DutchCoders)** -- ★ Fix security bug that allows client to spoof ip -- Fix typo. r.HTMLTemplates -> SetHTMLTemplate - - -**@el3ctro- (Joshua Loper)** -- Fix typo in example - - -**@ethankan (Ethan Kan)** -- Unsigned integers in binding - - -**(Evgeny Persienko)** -- Validate sub structures - - -**@frankbille (Frank Bille)** -- Add support for HTTP Realm Auth - - -**@fmd (Fareed Dudhia)** -- Fix typo. SetHTTPTemplate -> SetHTMLTemplate - - -**@ironiridis (Christopher Harrington)** -- Remove old reference - - -**@jammie-stackhouse (Jamie Stackhouse)** -- Add more shortcuts for router methods - - -**@jasonrhansen** -- Fix spelling and grammar errors in documentation - - -**@JasonSoft (Jason Lee)** -- Fix typo in comment - - -**@joiggama (Ignacio Galindo)** -- Add utf-8 charset header on renders - - -**@julienschmidt (Julien Schmidt)** -- gofmt the code examples - - -**@kelcecil (Kel Cecil)** -- Fix readme typo - - -**@kyledinh (Kyle Dinh)** -- Adds RunTLS() - - -**@LinusU (Linus Unnebäck)** -- Small fixes in README - - -**@loongmxbt (Saint Asky)** -- Fix typo in example - - -**@lucas-clemente (Lucas Clemente)** -- ★ work around path.Join removing trailing slashes from routes - - -**@mattn (Yasuhiro Matsumoto)** -- Improve color logger - - -**@mdigger (Dmitry Sedykh)** -- Fixes Form binding when content-type is x-www-form-urlencoded -- No repeat call c.Writer.Status() in gin.Logger -- Fixes Content-Type for json render - - -**@mirzac (Mirza Ceric)** -- Fix debug printing - - -**@mopemope (Yutaka Matsubara)** -- ★ Adds Godep support (Dependencies Manager) -- Fix variadic parameter in the flexible render API -- Fix Corrupted plain render -- Add Pluggable View Renderer Example - - -**@msemenistyi (Mykyta Semenistyi)** -- update Readme.md. Add code to String method - - -**@msoedov (Sasha Myasoedov)** -- ★ Adds tons of unit tests. - - -**@ngerakines (Nick Gerakines)** -- ★ Improves API, c.GET() doesn't panic -- Adds MustGet() method - - -**@r8k (Rajiv Kilaparti)** -- Fix Port usage in README. - - -**@rayrod2030 (Ray Rodriguez)** -- Fix typo in example - - -**@rns** -- Fix typo in example - - -**@RobAWilkinson (Robert Wilkinson)** -- Add example of forms and params - - -**@rogierlommers (Rogier Lommers)** -- Add updated static serve example - -**@rw-access (Ross Wolf)** -- Added support to mix exact and param routes - -**@se77en (Damon Zhao)** -- Improve color logging - - -**@silasb (Silas Baronda)** -- Fixing quotes in README - - -**@SkuliOskarsson (Skuli Oskarsson)** -- Fixes some texts in README II - - -**@slimmy (Jimmy Pettersson)** -- Added messages for required bindings - - -**@smira (Andrey Smirnov)** -- Add support for ignored/unexported fields in binding - - -**@superalsrk (SRK.Lyu)** -- Update httprouter godeps - - -**@tebeka (Miki Tebeka)** -- Use net/http constants instead of numeric values - - -**@techjanitor** -- Update context.go reserved IPs - - -**@yosssi (Keiji Yoshida)** -- Fix link in README - - -**@yuyabee** -- Fixed README diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/BENCHMARKS.md b/taskman-server/vendor/github.com/gin-gonic/gin/BENCHMARKS.md deleted file mode 100644 index c11ee99a..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/BENCHMARKS.md +++ /dev/null @@ -1,666 +0,0 @@ - -# Benchmark System - -**VM HOST:** Travis -**Machine:** Ubuntu 16.04.6 LTS x64 -**Date:** May 04th, 2020 -**Version:** Gin v1.6.3 -**Go Version:** 1.14.2 linux/amd64 -**Source:** [Go HTTP Router Benchmark](https://github.com/gin-gonic/go-http-routing-benchmark) -**Result:** [See the gist](https://gist.github.com/appleboy/b5f2ecfaf50824ae9c64dcfb9165ae5e) or [Travis result](https://travis-ci.org/github/gin-gonic/go-http-routing-benchmark/jobs/682947061) - -## Static Routes: 157 - -```sh -Gin: 34936 Bytes - -HttpServeMux: 14512 Bytes -Ace: 30680 Bytes -Aero: 34536 Bytes -Bear: 30456 Bytes -Beego: 98456 Bytes -Bone: 40224 Bytes -Chi: 83608 Bytes -Denco: 10216 Bytes -Echo: 80328 Bytes -GocraftWeb: 55288 Bytes -Goji: 29744 Bytes -Gojiv2: 105840 Bytes -GoJsonRest: 137496 Bytes -GoRestful: 816936 Bytes -GorillaMux: 585632 Bytes -GowwwRouter: 24968 Bytes -HttpRouter: 21712 Bytes -HttpTreeMux: 73448 Bytes -Kocha: 115472 Bytes -LARS: 30640 Bytes -Macaron: 38592 Bytes -Martini: 310864 Bytes -Pat: 19696 Bytes -Possum: 89920 Bytes -R2router: 23712 Bytes -Rivet: 24608 Bytes -Tango: 28264 Bytes -TigerTonic: 78768 Bytes -Traffic: 538976 Bytes -Vulcan: 369960 Bytes -``` - -## GithubAPI Routes: 203 - -```sh -Gin: 58512 Bytes - -Ace: 48688 Bytes -Aero: 318568 Bytes -Bear: 84248 Bytes -Beego: 150936 Bytes -Bone: 100976 Bytes -Chi: 95112 Bytes -Denco: 36736 Bytes -Echo: 100296 Bytes -GocraftWeb: 95432 Bytes -Goji: 49680 Bytes -Gojiv2: 104704 Bytes -GoJsonRest: 141976 Bytes -GoRestful: 1241656 Bytes -GorillaMux: 1322784 Bytes -GowwwRouter: 80008 Bytes -HttpRouter: 37144 Bytes -HttpTreeMux: 78800 Bytes -Kocha: 785120 Bytes -LARS: 48600 Bytes -Macaron: 92784 Bytes -Martini: 485264 Bytes -Pat: 21200 Bytes -Possum: 85312 Bytes -R2router: 47104 Bytes -Rivet: 42840 Bytes -Tango: 54840 Bytes -TigerTonic: 95264 Bytes -Traffic: 921744 Bytes -Vulcan: 425992 Bytes -``` - -## GPlusAPI Routes: 13 - -```sh -Gin: 4384 Bytes - -Ace: 3712 Bytes -Aero: 26056 Bytes -Bear: 7112 Bytes -Beego: 10272 Bytes -Bone: 6688 Bytes -Chi: 8024 Bytes -Denco: 3264 Bytes -Echo: 9688 Bytes -GocraftWeb: 7496 Bytes -Goji: 3152 Bytes -Gojiv2: 7376 Bytes -GoJsonRest: 11400 Bytes -GoRestful: 74328 Bytes -GorillaMux: 66208 Bytes -GowwwRouter: 5744 Bytes -HttpRouter: 2808 Bytes -HttpTreeMux: 7440 Bytes -Kocha: 128880 Bytes -LARS: 3656 Bytes -Macaron: 8656 Bytes -Martini: 23920 Bytes -Pat: 1856 Bytes -Possum: 7248 Bytes -R2router: 3928 Bytes -Rivet: 3064 Bytes -Tango: 5168 Bytes -TigerTonic: 9408 Bytes -Traffic: 46400 Bytes -Vulcan: 25544 Bytes -``` - -## ParseAPI Routes: 26 - -```sh -Gin: 7776 Bytes - -Ace: 6704 Bytes -Aero: 28488 Bytes -Bear: 12320 Bytes -Beego: 19280 Bytes -Bone: 11440 Bytes -Chi: 9744 Bytes -Denco: 4192 Bytes -Echo: 11664 Bytes -GocraftWeb: 12800 Bytes -Goji: 5680 Bytes -Gojiv2: 14464 Bytes -GoJsonRest: 14072 Bytes -GoRestful: 116264 Bytes -GorillaMux: 105880 Bytes -GowwwRouter: 9344 Bytes -HttpRouter: 5072 Bytes -HttpTreeMux: 7848 Bytes -Kocha: 181712 Bytes -LARS: 6632 Bytes -Macaron: 13648 Bytes -Martini: 45888 Bytes -Pat: 2560 Bytes -Possum: 9200 Bytes -R2router: 7056 Bytes -Rivet: 5680 Bytes -Tango: 8920 Bytes -TigerTonic: 9840 Bytes -Traffic: 79096 Bytes -Vulcan: 44504 Bytes -``` - -## Static Routes - -```sh -BenchmarkGin_StaticAll 62169 19319 ns/op 0 B/op 0 allocs/op - -BenchmarkAce_StaticAll 65428 18313 ns/op 0 B/op 0 allocs/op -BenchmarkAero_StaticAll 121132 9632 ns/op 0 B/op 0 allocs/op -BenchmarkHttpServeMux_StaticAll 52626 22758 ns/op 0 B/op 0 allocs/op -BenchmarkBeego_StaticAll 9962 179058 ns/op 55264 B/op 471 allocs/op -BenchmarkBear_StaticAll 14894 80966 ns/op 20272 B/op 469 allocs/op -BenchmarkBone_StaticAll 18718 64065 ns/op 0 B/op 0 allocs/op -BenchmarkChi_StaticAll 10000 149827 ns/op 67824 B/op 471 allocs/op -BenchmarkDenco_StaticAll 211393 5680 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_StaticAll 49341 24343 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_StaticAll 10000 126209 ns/op 46312 B/op 785 allocs/op -BenchmarkGoji_StaticAll 27956 43174 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_StaticAll 3430 370718 ns/op 205984 B/op 1570 allocs/op -BenchmarkGoJsonRest_StaticAll 9134 188888 ns/op 51653 B/op 1727 allocs/op -BenchmarkGoRestful_StaticAll 706 1703330 ns/op 613280 B/op 2053 allocs/op -BenchmarkGorillaMux_StaticAll 1268 924083 ns/op 153233 B/op 1413 allocs/op -BenchmarkGowwwRouter_StaticAll 63374 18935 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_StaticAll 109938 10902 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_StaticAll 109166 10861 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_StaticAll 92258 12992 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_StaticAll 65200 18387 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_StaticAll 5671 291501 ns/op 115553 B/op 1256 allocs/op -BenchmarkMartini_StaticAll 807 1460498 ns/op 125444 B/op 1717 allocs/op -BenchmarkPat_StaticAll 513 2342396 ns/op 602832 B/op 12559 allocs/op -BenchmarkPossum_StaticAll 10000 128270 ns/op 65312 B/op 471 allocs/op -BenchmarkR2router_StaticAll 16726 71760 ns/op 22608 B/op 628 allocs/op -BenchmarkRivet_StaticAll 41722 28723 ns/op 0 B/op 0 allocs/op -BenchmarkTango_StaticAll 7606 205082 ns/op 39209 B/op 1256 allocs/op -BenchmarkTigerTonic_StaticAll 26247 45806 ns/op 7376 B/op 157 allocs/op -BenchmarkTraffic_StaticAll 550 2284518 ns/op 754864 B/op 14601 allocs/op -BenchmarkVulcan_StaticAll 10000 131343 ns/op 15386 B/op 471 allocs/op -``` - -## Micro Benchmarks - -```sh -BenchmarkGin_Param 18785022 63.9 ns/op 0 B/op 0 allocs/op - -BenchmarkAce_Param 14689765 81.5 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Param 23094770 51.2 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Param 1417045 845 ns/op 456 B/op 5 allocs/op -BenchmarkBeego_Param 1000000 1080 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Param 1000000 1463 ns/op 816 B/op 6 allocs/op -BenchmarkChi_Param 1378756 885 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Param 8557899 143 ns/op 32 B/op 1 allocs/op -BenchmarkEcho_Param 16433347 75.5 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Param 1000000 1218 ns/op 648 B/op 8 allocs/op -BenchmarkGoji_Param 1921248 617 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_Param 561848 2156 ns/op 1328 B/op 11 allocs/op -BenchmarkGoJsonRest_Param 1000000 1358 ns/op 649 B/op 13 allocs/op -BenchmarkGoRestful_Param 224857 5307 ns/op 4192 B/op 14 allocs/op -BenchmarkGorillaMux_Param 498313 2459 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_Param 1864354 654 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Param 26269074 47.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Param 2109829 557 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_Param 5050216 243 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_Param 19811712 59.9 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Param 662746 2329 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_Param 279902 4260 ns/op 1072 B/op 10 allocs/op -BenchmarkPat_Param 1000000 1382 ns/op 536 B/op 11 allocs/op -BenchmarkPossum_Param 1000000 1014 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Param 1712559 707 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_Param 6648086 182 ns/op 48 B/op 1 allocs/op -BenchmarkTango_Param 1221504 994 ns/op 248 B/op 8 allocs/op -BenchmarkTigerTonic_Param 891661 2261 ns/op 776 B/op 16 allocs/op -BenchmarkTraffic_Param 350059 3598 ns/op 1856 B/op 21 allocs/op -BenchmarkVulcan_Param 2517823 472 ns/op 98 B/op 3 allocs/op -BenchmarkAce_Param5 9214365 130 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Param5 15369013 77.9 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Param5 1000000 1113 ns/op 501 B/op 5 allocs/op -BenchmarkBeego_Param5 1000000 1269 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Param5 986820 1873 ns/op 864 B/op 6 allocs/op -BenchmarkChi_Param5 1000000 1156 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Param5 3036331 400 ns/op 160 B/op 1 allocs/op -BenchmarkEcho_Param5 6447133 186 ns/op 0 B/op 0 allocs/op -BenchmarkGin_Param5 10786068 110 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Param5 844820 1944 ns/op 920 B/op 11 allocs/op -BenchmarkGoji_Param5 1474965 827 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_Param5 442820 2516 ns/op 1392 B/op 11 allocs/op -BenchmarkGoJsonRest_Param5 507555 2711 ns/op 1097 B/op 16 allocs/op -BenchmarkGoRestful_Param5 216481 6093 ns/op 4288 B/op 14 allocs/op -BenchmarkGorillaMux_Param5 314402 3628 ns/op 1344 B/op 10 allocs/op -BenchmarkGowwwRouter_Param5 1624660 733 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Param5 13167324 92.0 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Param5 1000000 1295 ns/op 576 B/op 6 allocs/op -BenchmarkKocha_Param5 1000000 1138 ns/op 440 B/op 10 allocs/op -BenchmarkLARS_Param5 11580613 105 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Param5 473596 2755 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_Param5 230756 5111 ns/op 1232 B/op 11 allocs/op -BenchmarkPat_Param5 469190 3370 ns/op 888 B/op 29 allocs/op -BenchmarkPossum_Param5 1000000 1002 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Param5 1422129 844 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_Param5 2263789 539 ns/op 240 B/op 1 allocs/op -BenchmarkTango_Param5 1000000 1256 ns/op 360 B/op 8 allocs/op -BenchmarkTigerTonic_Param5 175500 7492 ns/op 2279 B/op 39 allocs/op -BenchmarkTraffic_Param5 233631 5816 ns/op 2208 B/op 27 allocs/op -BenchmarkVulcan_Param5 1923416 629 ns/op 98 B/op 3 allocs/op -BenchmarkAce_Param20 4321266 281 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Param20 31501641 35.2 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Param20 335204 3489 ns/op 1665 B/op 5 allocs/op -BenchmarkBeego_Param20 503674 2860 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Param20 298922 4741 ns/op 2031 B/op 6 allocs/op -BenchmarkChi_Param20 878181 1957 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Param20 1000000 1360 ns/op 640 B/op 1 allocs/op -BenchmarkEcho_Param20 2104946 580 ns/op 0 B/op 0 allocs/op -BenchmarkGin_Param20 4167204 290 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Param20 173064 7514 ns/op 3796 B/op 15 allocs/op -BenchmarkGoji_Param20 458778 2651 ns/op 1247 B/op 2 allocs/op -BenchmarkGojiv2_Param20 364862 3178 ns/op 1632 B/op 11 allocs/op -BenchmarkGoJsonRest_Param20 125514 9760 ns/op 4485 B/op 20 allocs/op -BenchmarkGoRestful_Param20 101217 11964 ns/op 6715 B/op 18 allocs/op -BenchmarkGorillaMux_Param20 147654 8132 ns/op 3452 B/op 12 allocs/op -BenchmarkGowwwRouter_Param20 1000000 1225 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Param20 4920895 247 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Param20 173202 6605 ns/op 3196 B/op 10 allocs/op -BenchmarkKocha_Param20 345988 3620 ns/op 1808 B/op 27 allocs/op -BenchmarkLARS_Param20 4592326 262 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Param20 166492 7286 ns/op 2924 B/op 12 allocs/op -BenchmarkMartini_Param20 122162 10653 ns/op 3595 B/op 13 allocs/op -BenchmarkPat_Param20 78630 15239 ns/op 4424 B/op 93 allocs/op -BenchmarkPossum_Param20 1000000 1008 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Param20 294981 4587 ns/op 2284 B/op 7 allocs/op -BenchmarkRivet_Param20 691798 2090 ns/op 1024 B/op 1 allocs/op -BenchmarkTango_Param20 842440 2505 ns/op 856 B/op 8 allocs/op -BenchmarkTigerTonic_Param20 38614 31509 ns/op 9870 B/op 119 allocs/op -BenchmarkTraffic_Param20 57633 21107 ns/op 7853 B/op 47 allocs/op -BenchmarkVulcan_Param20 1000000 1178 ns/op 98 B/op 3 allocs/op -BenchmarkAce_ParamWrite 7330743 180 ns/op 8 B/op 1 allocs/op -BenchmarkAero_ParamWrite 13833598 86.7 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParamWrite 1363321 867 ns/op 456 B/op 5 allocs/op -BenchmarkBeego_ParamWrite 1000000 1104 ns/op 360 B/op 4 allocs/op -BenchmarkBone_ParamWrite 1000000 1475 ns/op 816 B/op 6 allocs/op -BenchmarkChi_ParamWrite 1320590 892 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_ParamWrite 7093605 172 ns/op 32 B/op 1 allocs/op -BenchmarkEcho_ParamWrite 8434424 161 ns/op 8 B/op 1 allocs/op -BenchmarkGin_ParamWrite 10377034 118 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParamWrite 1000000 1266 ns/op 656 B/op 9 allocs/op -BenchmarkGoji_ParamWrite 1874168 654 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_ParamWrite 459032 2352 ns/op 1360 B/op 13 allocs/op -BenchmarkGoJsonRest_ParamWrite 499434 2145 ns/op 1128 B/op 18 allocs/op -BenchmarkGoRestful_ParamWrite 241087 5470 ns/op 4200 B/op 15 allocs/op -BenchmarkGorillaMux_ParamWrite 425686 2522 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_ParamWrite 922172 1778 ns/op 976 B/op 8 allocs/op -BenchmarkHttpRouter_ParamWrite 15392049 77.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParamWrite 1973385 597 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_ParamWrite 4262500 281 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_ParamWrite 10764410 113 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParamWrite 486769 2726 ns/op 1176 B/op 14 allocs/op -BenchmarkMartini_ParamWrite 264804 4842 ns/op 1176 B/op 14 allocs/op -BenchmarkPat_ParamWrite 735116 2047 ns/op 960 B/op 15 allocs/op -BenchmarkPossum_ParamWrite 1000000 1004 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_ParamWrite 1592136 768 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_ParamWrite 3582051 339 ns/op 112 B/op 2 allocs/op -BenchmarkTango_ParamWrite 2237337 534 ns/op 136 B/op 4 allocs/op -BenchmarkTigerTonic_ParamWrite 439608 3136 ns/op 1216 B/op 21 allocs/op -BenchmarkTraffic_ParamWrite 306979 4328 ns/op 2280 B/op 25 allocs/op -BenchmarkVulcan_ParamWrite 2529973 472 ns/op 98 B/op 3 allocs/op -``` - -## GitHub - -```sh -BenchmarkGin_GithubStatic 15629472 76.7 ns/op 0 B/op 0 allocs/op - -BenchmarkAce_GithubStatic 15542612 75.9 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GithubStatic 24777151 48.5 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GithubStatic 2788894 435 ns/op 120 B/op 3 allocs/op -BenchmarkBeego_GithubStatic 1000000 1064 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GithubStatic 93507 12838 ns/op 2880 B/op 60 allocs/op -BenchmarkChi_GithubStatic 1387743 860 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GithubStatic 39384996 30.4 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_GithubStatic 12076382 99.1 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GithubStatic 1596495 756 ns/op 296 B/op 5 allocs/op -BenchmarkGoji_GithubStatic 6364876 189 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_GithubStatic 550202 2098 ns/op 1312 B/op 10 allocs/op -BenchmarkGoRestful_GithubStatic 102183 12552 ns/op 4256 B/op 13 allocs/op -BenchmarkGoJsonRest_GithubStatic 1000000 1029 ns/op 329 B/op 11 allocs/op -BenchmarkGorillaMux_GithubStatic 255552 5190 ns/op 976 B/op 9 allocs/op -BenchmarkGowwwRouter_GithubStatic 15531916 77.1 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_GithubStatic 27920724 43.1 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GithubStatic 21448953 55.8 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_GithubStatic 21405310 56.0 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_GithubStatic 13625156 89.0 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GithubStatic 1000000 1747 ns/op 736 B/op 8 allocs/op -BenchmarkMartini_GithubStatic 187186 7326 ns/op 768 B/op 9 allocs/op -BenchmarkPat_GithubStatic 109143 11563 ns/op 3648 B/op 76 allocs/op -BenchmarkPossum_GithubStatic 1575898 770 ns/op 416 B/op 3 allocs/op -BenchmarkR2router_GithubStatic 3046231 404 ns/op 144 B/op 4 allocs/op -BenchmarkRivet_GithubStatic 11484826 105 ns/op 0 B/op 0 allocs/op -BenchmarkTango_GithubStatic 1000000 1153 ns/op 248 B/op 8 allocs/op -BenchmarkTigerTonic_GithubStatic 4929780 249 ns/op 48 B/op 1 allocs/op -BenchmarkTraffic_GithubStatic 106351 11819 ns/op 4664 B/op 90 allocs/op -BenchmarkVulcan_GithubStatic 1613271 722 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GithubParam 8386032 143 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GithubParam 11816200 102 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GithubParam 1000000 1012 ns/op 496 B/op 5 allocs/op -BenchmarkBeego_GithubParam 1000000 1157 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GithubParam 184653 6912 ns/op 1888 B/op 19 allocs/op -BenchmarkChi_GithubParam 1000000 1102 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GithubParam 3484798 352 ns/op 128 B/op 1 allocs/op -BenchmarkEcho_GithubParam 6337380 189 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GithubParam 9132032 131 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GithubParam 1000000 1446 ns/op 712 B/op 9 allocs/op -BenchmarkGoji_GithubParam 1248640 977 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_GithubParam 383233 2784 ns/op 1408 B/op 13 allocs/op -BenchmarkGoJsonRest_GithubParam 1000000 1991 ns/op 713 B/op 14 allocs/op -BenchmarkGoRestful_GithubParam 76414 16015 ns/op 4352 B/op 16 allocs/op -BenchmarkGorillaMux_GithubParam 150026 7663 ns/op 1296 B/op 10 allocs/op -BenchmarkGowwwRouter_GithubParam 1592044 751 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_GithubParam 10420628 115 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GithubParam 1403755 835 ns/op 384 B/op 4 allocs/op -BenchmarkKocha_GithubParam 2286170 533 ns/op 128 B/op 5 allocs/op -BenchmarkLARS_GithubParam 9540374 129 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GithubParam 533154 2742 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_GithubParam 119397 9638 ns/op 1152 B/op 11 allocs/op -BenchmarkPat_GithubParam 150675 8858 ns/op 2408 B/op 48 allocs/op -BenchmarkPossum_GithubParam 1000000 1001 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_GithubParam 1602886 761 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_GithubParam 2986579 409 ns/op 96 B/op 1 allocs/op -BenchmarkTango_GithubParam 1000000 1356 ns/op 344 B/op 8 allocs/op -BenchmarkTigerTonic_GithubParam 388899 3429 ns/op 1176 B/op 22 allocs/op -BenchmarkTraffic_GithubParam 123160 9734 ns/op 2816 B/op 40 allocs/op -BenchmarkVulcan_GithubParam 1000000 1138 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GithubAll 40543 29670 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GithubAll 57632 20648 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GithubAll 9234 216179 ns/op 86448 B/op 943 allocs/op -BenchmarkBeego_GithubAll 7407 243496 ns/op 71456 B/op 609 allocs/op -BenchmarkBone_GithubAll 420 2922835 ns/op 720160 B/op 8620 allocs/op -BenchmarkChi_GithubAll 7620 238331 ns/op 87696 B/op 609 allocs/op -BenchmarkDenco_GithubAll 18355 64494 ns/op 20224 B/op 167 allocs/op -BenchmarkEcho_GithubAll 31251 38479 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GithubAll 43550 27364 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GithubAll 4117 300062 ns/op 131656 B/op 1686 allocs/op -BenchmarkGoji_GithubAll 3274 416158 ns/op 56112 B/op 334 allocs/op -BenchmarkGojiv2_GithubAll 1402 870518 ns/op 352720 B/op 4321 allocs/op -BenchmarkGoJsonRest_GithubAll 2976 401507 ns/op 134371 B/op 2737 allocs/op -BenchmarkGoRestful_GithubAll 410 2913158 ns/op 910144 B/op 2938 allocs/op -BenchmarkGorillaMux_GithubAll 346 3384987 ns/op 251650 B/op 1994 allocs/op -BenchmarkGowwwRouter_GithubAll 10000 143025 ns/op 72144 B/op 501 allocs/op -BenchmarkHttpRouter_GithubAll 55938 21360 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GithubAll 10000 153944 ns/op 65856 B/op 671 allocs/op -BenchmarkKocha_GithubAll 10000 106315 ns/op 23304 B/op 843 allocs/op -BenchmarkLARS_GithubAll 47779 25084 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GithubAll 3266 371907 ns/op 149409 B/op 1624 allocs/op -BenchmarkMartini_GithubAll 331 3444706 ns/op 226551 B/op 2325 allocs/op -BenchmarkPat_GithubAll 273 4381818 ns/op 1483152 B/op 26963 allocs/op -BenchmarkPossum_GithubAll 10000 164367 ns/op 84448 B/op 609 allocs/op -BenchmarkR2router_GithubAll 10000 160220 ns/op 77328 B/op 979 allocs/op -BenchmarkRivet_GithubAll 14625 82453 ns/op 16272 B/op 167 allocs/op -BenchmarkTango_GithubAll 6255 279611 ns/op 63826 B/op 1618 allocs/op -BenchmarkTigerTonic_GithubAll 2008 687874 ns/op 193856 B/op 4474 allocs/op -BenchmarkTraffic_GithubAll 355 3478508 ns/op 820744 B/op 14114 allocs/op -BenchmarkVulcan_GithubAll 6885 193333 ns/op 19894 B/op 609 allocs/op -``` - -## Google+ - -```sh -BenchmarkGin_GPlusStatic 19247326 62.2 ns/op 0 B/op 0 allocs/op - -BenchmarkAce_GPlusStatic 20235060 59.2 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlusStatic 31978935 37.6 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlusStatic 3516523 341 ns/op 104 B/op 3 allocs/op -BenchmarkBeego_GPlusStatic 1212036 991 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GPlusStatic 6736242 183 ns/op 32 B/op 1 allocs/op -BenchmarkChi_GPlusStatic 1490640 814 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GPlusStatic 55006856 21.8 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_GPlusStatic 17688258 67.9 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlusStatic 1829181 666 ns/op 280 B/op 5 allocs/op -BenchmarkGoji_GPlusStatic 9147451 130 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_GPlusStatic 594015 2063 ns/op 1312 B/op 10 allocs/op -BenchmarkGoJsonRest_GPlusStatic 1264906 950 ns/op 329 B/op 11 allocs/op -BenchmarkGoRestful_GPlusStatic 231558 5341 ns/op 3872 B/op 13 allocs/op -BenchmarkGorillaMux_GPlusStatic 908418 1809 ns/op 976 B/op 9 allocs/op -BenchmarkGowwwRouter_GPlusStatic 40684604 29.5 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_GPlusStatic 46742804 25.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlusStatic 32567161 36.9 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_GPlusStatic 33800060 35.3 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_GPlusStatic 20431858 60.0 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlusStatic 1000000 1745 ns/op 736 B/op 8 allocs/op -BenchmarkMartini_GPlusStatic 442248 3619 ns/op 768 B/op 9 allocs/op -BenchmarkPat_GPlusStatic 4328004 292 ns/op 96 B/op 2 allocs/op -BenchmarkPossum_GPlusStatic 1570753 763 ns/op 416 B/op 3 allocs/op -BenchmarkR2router_GPlusStatic 3339474 355 ns/op 144 B/op 4 allocs/op -BenchmarkRivet_GPlusStatic 18570961 64.7 ns/op 0 B/op 0 allocs/op -BenchmarkTango_GPlusStatic 1388702 860 ns/op 200 B/op 8 allocs/op -BenchmarkTigerTonic_GPlusStatic 7803543 159 ns/op 32 B/op 1 allocs/op -BenchmarkTraffic_GPlusStatic 878605 2171 ns/op 1112 B/op 16 allocs/op -BenchmarkVulcan_GPlusStatic 2742446 437 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GPlusParam 11626975 105 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlusParam 16914322 71.6 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlusParam 1405173 832 ns/op 480 B/op 5 allocs/op -BenchmarkBeego_GPlusParam 1000000 1075 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GPlusParam 1000000 1557 ns/op 816 B/op 6 allocs/op -BenchmarkChi_GPlusParam 1347926 894 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GPlusParam 5513000 212 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_GPlusParam 11884383 101 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GPlusParam 12898952 93.1 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlusParam 1000000 1194 ns/op 648 B/op 8 allocs/op -BenchmarkGoji_GPlusParam 1857229 645 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_GPlusParam 520939 2322 ns/op 1328 B/op 11 allocs/op -BenchmarkGoJsonRest_GPlusParam 1000000 1536 ns/op 649 B/op 13 allocs/op -BenchmarkGoRestful_GPlusParam 205449 5800 ns/op 4192 B/op 14 allocs/op -BenchmarkGorillaMux_GPlusParam 395310 3188 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_GPlusParam 1851798 667 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_GPlusParam 18420789 65.2 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlusParam 1878463 629 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_GPlusParam 4495610 273 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_GPlusParam 14615976 83.2 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlusParam 584145 2549 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_GPlusParam 250501 4583 ns/op 1072 B/op 10 allocs/op -BenchmarkPat_GPlusParam 1000000 1645 ns/op 576 B/op 11 allocs/op -BenchmarkPossum_GPlusParam 1000000 1008 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_GPlusParam 1708191 688 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_GPlusParam 5795014 211 ns/op 48 B/op 1 allocs/op -BenchmarkTango_GPlusParam 1000000 1091 ns/op 264 B/op 8 allocs/op -BenchmarkTigerTonic_GPlusParam 760221 2489 ns/op 856 B/op 16 allocs/op -BenchmarkTraffic_GPlusParam 309774 4039 ns/op 1872 B/op 21 allocs/op -BenchmarkVulcan_GPlusParam 1935730 623 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GPlus2Params 9158314 134 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlus2Params 11300517 107 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlus2Params 1239238 961 ns/op 496 B/op 5 allocs/op -BenchmarkBeego_GPlus2Params 1000000 1202 ns/op 352 B/op 3 allocs/op -BenchmarkBone_GPlus2Params 335576 3725 ns/op 1168 B/op 10 allocs/op -BenchmarkChi_GPlus2Params 1000000 1014 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_GPlus2Params 4394598 280 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_GPlus2Params 7851861 154 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GPlus2Params 9958588 120 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlus2Params 1000000 1433 ns/op 712 B/op 9 allocs/op -BenchmarkGoji_GPlus2Params 1325134 909 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_GPlus2Params 405955 2870 ns/op 1408 B/op 14 allocs/op -BenchmarkGoJsonRest_GPlus2Params 977038 1987 ns/op 713 B/op 14 allocs/op -BenchmarkGoRestful_GPlus2Params 205018 6142 ns/op 4384 B/op 16 allocs/op -BenchmarkGorillaMux_GPlus2Params 205641 6015 ns/op 1296 B/op 10 allocs/op -BenchmarkGowwwRouter_GPlus2Params 1748542 684 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_GPlus2Params 14047102 87.7 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlus2Params 1418673 828 ns/op 384 B/op 4 allocs/op -BenchmarkKocha_GPlus2Params 2334562 520 ns/op 128 B/op 5 allocs/op -BenchmarkLARS_GPlus2Params 11954094 101 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlus2Params 491552 2890 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_GPlus2Params 120532 9545 ns/op 1200 B/op 13 allocs/op -BenchmarkPat_GPlus2Params 194739 6766 ns/op 2168 B/op 33 allocs/op -BenchmarkPossum_GPlus2Params 1201224 1009 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_GPlus2Params 1575535 756 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_GPlus2Params 3698930 325 ns/op 96 B/op 1 allocs/op -BenchmarkTango_GPlus2Params 1000000 1212 ns/op 344 B/op 8 allocs/op -BenchmarkTigerTonic_GPlus2Params 349350 3660 ns/op 1200 B/op 22 allocs/op -BenchmarkTraffic_GPlus2Params 169714 7862 ns/op 2248 B/op 28 allocs/op -BenchmarkVulcan_GPlus2Params 1222288 974 ns/op 98 B/op 3 allocs/op -BenchmarkAce_GPlusAll 845606 1398 ns/op 0 B/op 0 allocs/op -BenchmarkAero_GPlusAll 1000000 1009 ns/op 0 B/op 0 allocs/op -BenchmarkBear_GPlusAll 103830 11386 ns/op 5488 B/op 61 allocs/op -BenchmarkBeego_GPlusAll 82653 14784 ns/op 4576 B/op 39 allocs/op -BenchmarkBone_GPlusAll 36601 33123 ns/op 11744 B/op 109 allocs/op -BenchmarkChi_GPlusAll 95264 12831 ns/op 5616 B/op 39 allocs/op -BenchmarkDenco_GPlusAll 567681 2950 ns/op 672 B/op 11 allocs/op -BenchmarkEcho_GPlusAll 720366 1665 ns/op 0 B/op 0 allocs/op -BenchmarkGin_GPlusAll 1000000 1185 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_GPlusAll 71575 16365 ns/op 8040 B/op 103 allocs/op -BenchmarkGoji_GPlusAll 136352 9191 ns/op 3696 B/op 22 allocs/op -BenchmarkGojiv2_GPlusAll 38006 31802 ns/op 17616 B/op 154 allocs/op -BenchmarkGoJsonRest_GPlusAll 57238 21561 ns/op 8117 B/op 170 allocs/op -BenchmarkGoRestful_GPlusAll 15147 79276 ns/op 55520 B/op 192 allocs/op -BenchmarkGorillaMux_GPlusAll 24446 48410 ns/op 16112 B/op 128 allocs/op -BenchmarkGowwwRouter_GPlusAll 150112 7770 ns/op 4752 B/op 33 allocs/op -BenchmarkHttpRouter_GPlusAll 1367820 878 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_GPlusAll 166628 8004 ns/op 4032 B/op 38 allocs/op -BenchmarkKocha_GPlusAll 265694 4570 ns/op 976 B/op 43 allocs/op -BenchmarkLARS_GPlusAll 1000000 1068 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_GPlusAll 54564 23305 ns/op 9568 B/op 104 allocs/op -BenchmarkMartini_GPlusAll 16274 73845 ns/op 14016 B/op 145 allocs/op -BenchmarkPat_GPlusAll 27181 44478 ns/op 15264 B/op 271 allocs/op -BenchmarkPossum_GPlusAll 122587 10277 ns/op 5408 B/op 39 allocs/op -BenchmarkR2router_GPlusAll 130137 9297 ns/op 5040 B/op 63 allocs/op -BenchmarkRivet_GPlusAll 532438 3323 ns/op 768 B/op 11 allocs/op -BenchmarkTango_GPlusAll 86054 14531 ns/op 3656 B/op 104 allocs/op -BenchmarkTigerTonic_GPlusAll 33936 35356 ns/op 11600 B/op 242 allocs/op -BenchmarkTraffic_GPlusAll 17833 68181 ns/op 26248 B/op 341 allocs/op -BenchmarkVulcan_GPlusAll 120109 9861 ns/op 1274 B/op 39 allocs/op -``` - -## Parse.com - -```sh -BenchmarkGin_ParseStatic 18877833 63.5 ns/op 0 B/op 0 allocs/op - -BenchmarkAce_ParseStatic 19663731 60.8 ns/op 0 B/op 0 allocs/op -BenchmarkAero_ParseStatic 28967341 41.5 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParseStatic 3006984 402 ns/op 120 B/op 3 allocs/op -BenchmarkBeego_ParseStatic 1000000 1031 ns/op 352 B/op 3 allocs/op -BenchmarkBone_ParseStatic 1782482 675 ns/op 144 B/op 3 allocs/op -BenchmarkChi_ParseStatic 1453261 819 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_ParseStatic 45023595 26.5 ns/op 0 B/op 0 allocs/op -BenchmarkEcho_ParseStatic 17330470 69.3 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParseStatic 1644006 731 ns/op 296 B/op 5 allocs/op -BenchmarkGoji_ParseStatic 7026930 170 ns/op 0 B/op 0 allocs/op -BenchmarkGojiv2_ParseStatic 517618 2037 ns/op 1312 B/op 10 allocs/op -BenchmarkGoJsonRest_ParseStatic 1227080 975 ns/op 329 B/op 11 allocs/op -BenchmarkGoRestful_ParseStatic 192458 6659 ns/op 4256 B/op 13 allocs/op -BenchmarkGorillaMux_ParseStatic 744062 2109 ns/op 976 B/op 9 allocs/op -BenchmarkGowwwRouter_ParseStatic 37781062 31.8 ns/op 0 B/op 0 allocs/op -BenchmarkHttpRouter_ParseStatic 45311223 26.5 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParseStatic 21383475 56.1 ns/op 0 B/op 0 allocs/op -BenchmarkKocha_ParseStatic 29953290 40.1 ns/op 0 B/op 0 allocs/op -BenchmarkLARS_ParseStatic 20036196 62.7 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParseStatic 1000000 1740 ns/op 736 B/op 8 allocs/op -BenchmarkMartini_ParseStatic 404156 3801 ns/op 768 B/op 9 allocs/op -BenchmarkPat_ParseStatic 1547180 772 ns/op 240 B/op 5 allocs/op -BenchmarkPossum_ParseStatic 1608991 757 ns/op 416 B/op 3 allocs/op -BenchmarkR2router_ParseStatic 3177936 385 ns/op 144 B/op 4 allocs/op -BenchmarkRivet_ParseStatic 17783205 67.4 ns/op 0 B/op 0 allocs/op -BenchmarkTango_ParseStatic 1210777 990 ns/op 248 B/op 8 allocs/op -BenchmarkTigerTonic_ParseStatic 5316440 231 ns/op 48 B/op 1 allocs/op -BenchmarkTraffic_ParseStatic 496050 2539 ns/op 1256 B/op 19 allocs/op -BenchmarkVulcan_ParseStatic 2462798 488 ns/op 98 B/op 3 allocs/op -BenchmarkAce_ParseParam 13393669 89.6 ns/op 0 B/op 0 allocs/op -BenchmarkAero_ParseParam 19836619 60.4 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParseParam 1405954 864 ns/op 467 B/op 5 allocs/op -BenchmarkBeego_ParseParam 1000000 1065 ns/op 352 B/op 3 allocs/op -BenchmarkBone_ParseParam 1000000 1698 ns/op 896 B/op 7 allocs/op -BenchmarkChi_ParseParam 1356037 873 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_ParseParam 6241392 204 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_ParseParam 14088100 85.1 ns/op 0 B/op 0 allocs/op -BenchmarkGin_ParseParam 17426064 68.9 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParseParam 1000000 1254 ns/op 664 B/op 8 allocs/op -BenchmarkGoji_ParseParam 1682574 713 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_ParseParam 502224 2333 ns/op 1360 B/op 12 allocs/op -BenchmarkGoJsonRest_ParseParam 1000000 1401 ns/op 649 B/op 13 allocs/op -BenchmarkGoRestful_ParseParam 182623 7097 ns/op 4576 B/op 14 allocs/op -BenchmarkGorillaMux_ParseParam 482332 2477 ns/op 1280 B/op 10 allocs/op -BenchmarkGowwwRouter_ParseParam 1834873 657 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_ParseParam 23593393 51.0 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParseParam 2100160 574 ns/op 352 B/op 3 allocs/op -BenchmarkKocha_ParseParam 4837220 252 ns/op 56 B/op 3 allocs/op -BenchmarkLARS_ParseParam 18411192 66.2 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParseParam 571870 2398 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_ParseParam 286262 4268 ns/op 1072 B/op 10 allocs/op -BenchmarkPat_ParseParam 692906 2157 ns/op 992 B/op 15 allocs/op -BenchmarkPossum_ParseParam 1000000 1011 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_ParseParam 1722735 697 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_ParseParam 6058054 203 ns/op 48 B/op 1 allocs/op -BenchmarkTango_ParseParam 1000000 1061 ns/op 280 B/op 8 allocs/op -BenchmarkTigerTonic_ParseParam 890275 2277 ns/op 784 B/op 15 allocs/op -BenchmarkTraffic_ParseParam 351322 3543 ns/op 1896 B/op 21 allocs/op -BenchmarkVulcan_ParseParam 2076544 572 ns/op 98 B/op 3 allocs/op -BenchmarkAce_Parse2Params 11718074 101 ns/op 0 B/op 0 allocs/op -BenchmarkAero_Parse2Params 16264988 73.4 ns/op 0 B/op 0 allocs/op -BenchmarkBear_Parse2Params 1238322 973 ns/op 496 B/op 5 allocs/op -BenchmarkBeego_Parse2Params 1000000 1120 ns/op 352 B/op 3 allocs/op -BenchmarkBone_Parse2Params 1000000 1632 ns/op 848 B/op 6 allocs/op -BenchmarkChi_Parse2Params 1239477 955 ns/op 432 B/op 3 allocs/op -BenchmarkDenco_Parse2Params 4944133 245 ns/op 64 B/op 1 allocs/op -BenchmarkEcho_Parse2Params 10518286 114 ns/op 0 B/op 0 allocs/op -BenchmarkGin_Parse2Params 14505195 82.7 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_Parse2Params 1000000 1437 ns/op 712 B/op 9 allocs/op -BenchmarkGoji_Parse2Params 1689883 707 ns/op 336 B/op 2 allocs/op -BenchmarkGojiv2_Parse2Params 502334 2308 ns/op 1344 B/op 11 allocs/op -BenchmarkGoJsonRest_Parse2Params 1000000 1771 ns/op 713 B/op 14 allocs/op -BenchmarkGoRestful_Parse2Params 159092 7583 ns/op 4928 B/op 14 allocs/op -BenchmarkGorillaMux_Parse2Params 417548 2980 ns/op 1296 B/op 10 allocs/op -BenchmarkGowwwRouter_Parse2Params 1751737 686 ns/op 432 B/op 3 allocs/op -BenchmarkHttpRouter_Parse2Params 18089204 66.3 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_Parse2Params 1556986 777 ns/op 384 B/op 4 allocs/op -BenchmarkKocha_Parse2Params 2493082 485 ns/op 128 B/op 5 allocs/op -BenchmarkLARS_Parse2Params 15350108 78.5 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_Parse2Params 530974 2605 ns/op 1072 B/op 10 allocs/op -BenchmarkMartini_Parse2Params 247069 4673 ns/op 1152 B/op 11 allocs/op -BenchmarkPat_Parse2Params 816295 2126 ns/op 752 B/op 16 allocs/op -BenchmarkPossum_Parse2Params 1000000 1002 ns/op 496 B/op 5 allocs/op -BenchmarkR2router_Parse2Params 1569771 733 ns/op 432 B/op 5 allocs/op -BenchmarkRivet_Parse2Params 4080546 295 ns/op 96 B/op 1 allocs/op -BenchmarkTango_Parse2Params 1000000 1121 ns/op 312 B/op 8 allocs/op -BenchmarkTigerTonic_Parse2Params 399556 3470 ns/op 1168 B/op 22 allocs/op -BenchmarkTraffic_Parse2Params 314194 4159 ns/op 1944 B/op 22 allocs/op -BenchmarkVulcan_Parse2Params 1827559 664 ns/op 98 B/op 3 allocs/op -BenchmarkAce_ParseAll 478395 2503 ns/op 0 B/op 0 allocs/op -BenchmarkAero_ParseAll 715392 1658 ns/op 0 B/op 0 allocs/op -BenchmarkBear_ParseAll 59191 20124 ns/op 8928 B/op 110 allocs/op -BenchmarkBeego_ParseAll 45507 27266 ns/op 9152 B/op 78 allocs/op -BenchmarkBone_ParseAll 29328 41459 ns/op 16208 B/op 147 allocs/op -BenchmarkChi_ParseAll 48531 25053 ns/op 11232 B/op 78 allocs/op -BenchmarkDenco_ParseAll 325532 4284 ns/op 928 B/op 16 allocs/op -BenchmarkEcho_ParseAll 433771 2759 ns/op 0 B/op 0 allocs/op -BenchmarkGin_ParseAll 576316 2082 ns/op 0 B/op 0 allocs/op -BenchmarkGocraftWeb_ParseAll 41500 29692 ns/op 13728 B/op 181 allocs/op -BenchmarkGoji_ParseAll 80833 15563 ns/op 5376 B/op 32 allocs/op -BenchmarkGojiv2_ParseAll 19836 60335 ns/op 34448 B/op 277 allocs/op -BenchmarkGoJsonRest_ParseAll 32210 38027 ns/op 13866 B/op 321 allocs/op -BenchmarkGoRestful_ParseAll 6644 190842 ns/op 117600 B/op 354 allocs/op -BenchmarkGorillaMux_ParseAll 12634 95894 ns/op 30288 B/op 250 allocs/op -BenchmarkGowwwRouter_ParseAll 98152 12159 ns/op 6912 B/op 48 allocs/op -BenchmarkHttpRouter_ParseAll 933208 1273 ns/op 0 B/op 0 allocs/op -BenchmarkHttpTreeMux_ParseAll 107191 11554 ns/op 5728 B/op 51 allocs/op -BenchmarkKocha_ParseAll 184862 6225 ns/op 1112 B/op 54 allocs/op -BenchmarkLARS_ParseAll 644546 1858 ns/op 0 B/op 0 allocs/op -BenchmarkMacaron_ParseAll 26145 46484 ns/op 19136 B/op 208 allocs/op -BenchmarkMartini_ParseAll 10000 121838 ns/op 25072 B/op 253 allocs/op -BenchmarkPat_ParseAll 25417 47196 ns/op 15216 B/op 308 allocs/op -BenchmarkPossum_ParseAll 58550 20735 ns/op 10816 B/op 78 allocs/op -BenchmarkR2router_ParseAll 72732 16584 ns/op 8352 B/op 120 allocs/op -BenchmarkRivet_ParseAll 281365 4968 ns/op 912 B/op 16 allocs/op -BenchmarkTango_ParseAll 42831 28668 ns/op 7168 B/op 208 allocs/op -BenchmarkTigerTonic_ParseAll 23774 49972 ns/op 16048 B/op 332 allocs/op -BenchmarkTraffic_ParseAll 10000 104679 ns/op 45520 B/op 605 allocs/op -BenchmarkVulcan_ParseAll 64810 18108 ns/op 2548 B/op 78 allocs/op -``` diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/CHANGELOG.md b/taskman-server/vendor/github.com/gin-gonic/gin/CHANGELOG.md deleted file mode 100644 index 308af74c..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/CHANGELOG.md +++ /dev/null @@ -1,424 +0,0 @@ -# Gin ChangeLog - -## Gin v1.7.3 - -### BUGFIXES - -* fix level 1 router match [#2767](https://github.com/gin-gonic/gin/issues/2767), [#2796](https://github.com/gin-gonic/gin/issues/2796) - -## Gin v1.7.2 - -### BUGFIXES - -* Fix conflict between param and exact path [#2706](https://github.com/gin-gonic/gin/issues/2706). Close issue [#2682](https://github.com/gin-gonic/gin/issues/2682) [#2696](https://github.com/gin-gonic/gin/issues/2696). - -## Gin v1.7.1 - -### BUGFIXES - -* fix: data race with trustedCIDRs from [#2674](https://github.com/gin-gonic/gin/issues/2674)([#2675](https://github.com/gin-gonic/gin/pull/2675)) - -## Gin v1.7.0 - -### BUGFIXES - -* fix compile error from [#2572](https://github.com/gin-gonic/gin/pull/2572) ([#2600](https://github.com/gin-gonic/gin/pull/2600)) -* fix: print headers without Authorization header on broken pipe ([#2528](https://github.com/gin-gonic/gin/pull/2528)) -* fix(tree): reassign fullpath when register new node ([#2366](https://github.com/gin-gonic/gin/pull/2366)) - -### ENHANCEMENTS - -* Support params and exact routes without creating conflicts ([#2663](https://github.com/gin-gonic/gin/pull/2663)) -* chore: improve render string performance ([#2365](https://github.com/gin-gonic/gin/pull/2365)) -* Sync route tree to httprouter latest code ([#2368](https://github.com/gin-gonic/gin/pull/2368)) -* chore: rename getQueryCache/getFormCache to initQueryCache/initFormCa ([#2375](https://github.com/gin-gonic/gin/pull/2375)) -* chore(performance): improve countParams ([#2378](https://github.com/gin-gonic/gin/pull/2378)) -* Remove some functions that have the same effect as the bytes package ([#2387](https://github.com/gin-gonic/gin/pull/2387)) -* update:SetMode function ([#2321](https://github.com/gin-gonic/gin/pull/2321)) -* remove a unused type SecureJSONPrefix ([#2391](https://github.com/gin-gonic/gin/pull/2391)) -* Add a redirect sample for POST method ([#2389](https://github.com/gin-gonic/gin/pull/2389)) -* Add CustomRecovery builtin middleware ([#2322](https://github.com/gin-gonic/gin/pull/2322)) -* binding: avoid 2038 problem on 32-bit architectures ([#2450](https://github.com/gin-gonic/gin/pull/2450)) -* Prevent panic in Context.GetQuery() when there is no Request ([#2412](https://github.com/gin-gonic/gin/pull/2412)) -* Add GetUint and GetUint64 method on gin.context ([#2487](https://github.com/gin-gonic/gin/pull/2487)) -* update content-disposition header to MIME-style ([#2512](https://github.com/gin-gonic/gin/pull/2512)) -* reduce allocs and improve the render `WriteString` ([#2508](https://github.com/gin-gonic/gin/pull/2508)) -* implement ".Unwrap() error" on Error type ([#2525](https://github.com/gin-gonic/gin/pull/2525)) ([#2526](https://github.com/gin-gonic/gin/pull/2526)) -* Allow bind with a map[string]string ([#2484](https://github.com/gin-gonic/gin/pull/2484)) -* chore: update tree ([#2371](https://github.com/gin-gonic/gin/pull/2371)) -* Support binding for slice/array obj [Rewrite] ([#2302](https://github.com/gin-gonic/gin/pull/2302)) -* basic auth: fix timing oracle ([#2609](https://github.com/gin-gonic/gin/pull/2609)) -* Add mixed param and non-param paths (port of httprouter[#329](https://github.com/gin-gonic/gin/pull/329)) ([#2663](https://github.com/gin-gonic/gin/pull/2663)) -* feat(engine): add trustedproxies and remoteIP ([#2632](https://github.com/gin-gonic/gin/pull/2632)) - -## Gin v1.6.3 - -### ENHANCEMENTS - - * Improve performance: Change `*sync.RWMutex` to `sync.RWMutex` in context. [#2351](https://github.com/gin-gonic/gin/pull/2351) - -## Gin v1.6.2 - -### BUGFIXES - * fix missing initial sync.RWMutex [#2305](https://github.com/gin-gonic/gin/pull/2305) -### ENHANCEMENTS - * Add set samesite in cookie. [#2306](https://github.com/gin-gonic/gin/pull/2306) - -## Gin v1.6.1 - -### BUGFIXES - * Revert "fix accept incoming network connections" [#2294](https://github.com/gin-gonic/gin/pull/2294) - -## Gin v1.6.0 - -### BREAKING - * chore(performance): Improve performance for adding RemoveExtraSlash flag [#2159](https://github.com/gin-gonic/gin/pull/2159) - * drop support govendor [#2148](https://github.com/gin-gonic/gin/pull/2148) - * Added support for SameSite cookie flag [#1615](https://github.com/gin-gonic/gin/pull/1615) -### FEATURES - * add yaml negotiation [#2220](https://github.com/gin-gonic/gin/pull/2220) - * FileFromFS [#2112](https://github.com/gin-gonic/gin/pull/2112) -### BUGFIXES - * Unix Socket Handling [#2280](https://github.com/gin-gonic/gin/pull/2280) - * Use json marshall in context json to fix breaking new line issue. Fixes #2209 [#2228](https://github.com/gin-gonic/gin/pull/2228) - * fix accept incoming network connections [#2216](https://github.com/gin-gonic/gin/pull/2216) - * Fixed a bug in the calculation of the maximum number of parameters [#2166](https://github.com/gin-gonic/gin/pull/2166) - * [FIX] allow empty headers on DataFromReader [#2121](https://github.com/gin-gonic/gin/pull/2121) - * Add mutex for protect Context.Keys map [#1391](https://github.com/gin-gonic/gin/pull/1391) -### ENHANCEMENTS - * Add mitigation for log injection [#2277](https://github.com/gin-gonic/gin/pull/2277) - * tree: range over nodes values [#2229](https://github.com/gin-gonic/gin/pull/2229) - * tree: remove duplicate assignment [#2222](https://github.com/gin-gonic/gin/pull/2222) - * chore: upgrade go-isatty and json-iterator/go [#2215](https://github.com/gin-gonic/gin/pull/2215) - * path: sync code with httprouter [#2212](https://github.com/gin-gonic/gin/pull/2212) - * Use zero-copy approach to convert types between string and byte slice [#2206](https://github.com/gin-gonic/gin/pull/2206) - * Reuse bytes when cleaning the URL paths [#2179](https://github.com/gin-gonic/gin/pull/2179) - * tree: remove one else statement [#2177](https://github.com/gin-gonic/gin/pull/2177) - * tree: sync httprouter update (#2173) (#2172) [#2171](https://github.com/gin-gonic/gin/pull/2171) - * tree: sync part httprouter codes and reduce if/else [#2163](https://github.com/gin-gonic/gin/pull/2163) - * use http method constant [#2155](https://github.com/gin-gonic/gin/pull/2155) - * upgrade go-validator to v10 [#2149](https://github.com/gin-gonic/gin/pull/2149) - * Refactor redirect request in gin.go [#1970](https://github.com/gin-gonic/gin/pull/1970) - * Add build tag nomsgpack [#1852](https://github.com/gin-gonic/gin/pull/1852) -### DOCS - * docs(path): improve comments [#2223](https://github.com/gin-gonic/gin/pull/2223) - * Renew README to fit the modification of SetCookie method [#2217](https://github.com/gin-gonic/gin/pull/2217) - * Fix spelling [#2202](https://github.com/gin-gonic/gin/pull/2202) - * Remove broken link from README. [#2198](https://github.com/gin-gonic/gin/pull/2198) - * Update docs on Context.Done(), Context.Deadline() and Context.Err() [#2196](https://github.com/gin-gonic/gin/pull/2196) - * Update validator to v10 [#2190](https://github.com/gin-gonic/gin/pull/2190) - * upgrade go-validator to v10 for README [#2189](https://github.com/gin-gonic/gin/pull/2189) - * Update to currently output [#2188](https://github.com/gin-gonic/gin/pull/2188) - * Fix "Custom Validators" example [#2186](https://github.com/gin-gonic/gin/pull/2186) - * Add project to README [#2165](https://github.com/gin-gonic/gin/pull/2165) - * docs(benchmarks): for gin v1.5 [#2153](https://github.com/gin-gonic/gin/pull/2153) - * Changed wording for clarity in README.md [#2122](https://github.com/gin-gonic/gin/pull/2122) -### MISC - * ci support go1.14 [#2262](https://github.com/gin-gonic/gin/pull/2262) - * chore: upgrade depend version [#2231](https://github.com/gin-gonic/gin/pull/2231) - * Drop support go1.10 [#2147](https://github.com/gin-gonic/gin/pull/2147) - * fix comment in `mode.go` [#2129](https://github.com/gin-gonic/gin/pull/2129) - -## Gin v1.5.0 - -- [FIX] Use DefaultWriter and DefaultErrorWriter for debug messages [#1891](https://github.com/gin-gonic/gin/pull/1891) -- [NEW] Now you can parse the inline lowercase start structure [#1893](https://github.com/gin-gonic/gin/pull/1893) -- [FIX] Some code improvements [#1909](https://github.com/gin-gonic/gin/pull/1909) -- [FIX] Use encode replace json marshal increase json encoder speed [#1546](https://github.com/gin-gonic/gin/pull/1546) -- [NEW] Hold matched route full path in the Context [#1826](https://github.com/gin-gonic/gin/pull/1826) -- [FIX] Fix context.Params race condition on Copy() [#1841](https://github.com/gin-gonic/gin/pull/1841) -- [NEW] Add context param query cache [#1450](https://github.com/gin-gonic/gin/pull/1450) -- [FIX] Improve GetQueryMap performance [#1918](https://github.com/gin-gonic/gin/pull/1918) -- [FIX] Improve get post data [#1920](https://github.com/gin-gonic/gin/pull/1920) -- [FIX] Use context instead of x/net/context [#1922](https://github.com/gin-gonic/gin/pull/1922) -- [FIX] Attempt to fix PostForm cache bug [#1931](https://github.com/gin-gonic/gin/pull/1931) -- [NEW] Add support of multipart multi files [#1949](https://github.com/gin-gonic/gin/pull/1949) -- [NEW] Support bind http header param [#1957](https://github.com/gin-gonic/gin/pull/1957) -- [FIX] Drop support for go1.8 and go1.9 [#1933](https://github.com/gin-gonic/gin/pull/1933) -- [FIX] Bugfix for the FullPath feature [#1919](https://github.com/gin-gonic/gin/pull/1919) -- [FIX] Gin1.5 bytes.Buffer to strings.Builder [#1939](https://github.com/gin-gonic/gin/pull/1939) -- [FIX] Upgrade github.com/ugorji/go/codec [#1969](https://github.com/gin-gonic/gin/pull/1969) -- [NEW] Support bind unix time [#1980](https://github.com/gin-gonic/gin/pull/1980) -- [FIX] Simplify code [#2004](https://github.com/gin-gonic/gin/pull/2004) -- [NEW] Support negative Content-Length in DataFromReader [#1981](https://github.com/gin-gonic/gin/pull/1981) -- [FIX] Identify terminal on a RISC-V architecture for auto-colored logs [#2019](https://github.com/gin-gonic/gin/pull/2019) -- [BREAKING] `Context.JSONP()` now expects a semicolon (`;`) at the end [#2007](https://github.com/gin-gonic/gin/pull/2007) -- [BREAKING] Upgrade default `binding.Validator` to v9 (see [its changelog](https://github.com/go-playground/validator/releases/tag/v9.0.0)) [#1015](https://github.com/gin-gonic/gin/pull/1015) -- [NEW] Add `DisallowUnknownFields()` in `Context.BindJSON()` [#2028](https://github.com/gin-gonic/gin/pull/2028) -- [NEW] Use specific `net.Listener` with `Engine.RunListener()` [#2023](https://github.com/gin-gonic/gin/pull/2023) -- [FIX] Fix some typo [#2079](https://github.com/gin-gonic/gin/pull/2079) [#2080](https://github.com/gin-gonic/gin/pull/2080) -- [FIX] Relocate binding body tests [#2086](https://github.com/gin-gonic/gin/pull/2086) -- [FIX] Use Writer in Context.Status [#1606](https://github.com/gin-gonic/gin/pull/1606) -- [FIX] `Engine.RunUnix()` now returns the error if it can't change the file mode [#2093](https://github.com/gin-gonic/gin/pull/2093) -- [FIX] `RouterGroup.StaticFS()` leaked files. Now it closes them. [#2118](https://github.com/gin-gonic/gin/pull/2118) -- [FIX] `Context.Request.FormFile` leaked file. Now it closes it. [#2114](https://github.com/gin-gonic/gin/pull/2114) -- [FIX] Ignore walking on `form:"-"` mapping [#1943](https://github.com/gin-gonic/gin/pull/1943) - -### Gin v1.4.0 - -- [NEW] Support for [Go Modules](https://github.com/golang/go/wiki/Modules) [#1569](https://github.com/gin-gonic/gin/pull/1569) -- [NEW] Refactor of form mapping multipart request [#1829](https://github.com/gin-gonic/gin/pull/1829) -- [FIX] Truncate Latency precision in long running request [#1830](https://github.com/gin-gonic/gin/pull/1830) -- [FIX] IsTerm flag should not be affected by DisableConsoleColor method. [#1802](https://github.com/gin-gonic/gin/pull/1802) -- [NEW] Supporting file binding [#1264](https://github.com/gin-gonic/gin/pull/1264) -- [NEW] Add support for mapping arrays [#1797](https://github.com/gin-gonic/gin/pull/1797) -- [FIX] Readme updates [#1793](https://github.com/gin-gonic/gin/pull/1793) [#1788](https://github.com/gin-gonic/gin/pull/1788) [1789](https://github.com/gin-gonic/gin/pull/1789) -- [FIX] StaticFS: Fixed Logging two log lines on 404. [#1805](https://github.com/gin-gonic/gin/pull/1805), [#1804](https://github.com/gin-gonic/gin/pull/1804) -- [NEW] Make context.Keys available as LogFormatterParams [#1779](https://github.com/gin-gonic/gin/pull/1779) -- [NEW] Use internal/json for Marshal/Unmarshal [#1791](https://github.com/gin-gonic/gin/pull/1791) -- [NEW] Support mapping time.Duration [#1794](https://github.com/gin-gonic/gin/pull/1794) -- [NEW] Refactor form mappings [#1749](https://github.com/gin-gonic/gin/pull/1749) -- [NEW] Added flag to context.Stream indicates if client disconnected in middle of stream [#1252](https://github.com/gin-gonic/gin/pull/1252) -- [FIX] Moved [examples](https://github.com/gin-gonic/examples) to stand alone Repo [#1775](https://github.com/gin-gonic/gin/pull/1775) -- [NEW] Extend context.File to allow for the content-disposition attachments via a new method context.Attachment [#1260](https://github.com/gin-gonic/gin/pull/1260) -- [FIX] Support HTTP content negotiation wildcards [#1112](https://github.com/gin-gonic/gin/pull/1112) -- [NEW] Add prefix from X-Forwarded-Prefix in redirectTrailingSlash [#1238](https://github.com/gin-gonic/gin/pull/1238) -- [FIX] context.Copy() race condition [#1020](https://github.com/gin-gonic/gin/pull/1020) -- [NEW] Add context.HandlerNames() [#1729](https://github.com/gin-gonic/gin/pull/1729) -- [FIX] Change color methods to public in the defaultLogger. [#1771](https://github.com/gin-gonic/gin/pull/1771) -- [FIX] Update writeHeaders method to use http.Header.Set [#1722](https://github.com/gin-gonic/gin/pull/1722) -- [NEW] Add response size to LogFormatterParams [#1752](https://github.com/gin-gonic/gin/pull/1752) -- [NEW] Allow ignoring field on form mapping [#1733](https://github.com/gin-gonic/gin/pull/1733) -- [NEW] Add a function to force color in console output. [#1724](https://github.com/gin-gonic/gin/pull/1724) -- [FIX] Context.Next() - recheck len of handlers on every iteration. [#1745](https://github.com/gin-gonic/gin/pull/1745) -- [FIX] Fix all errcheck warnings [#1739](https://github.com/gin-gonic/gin/pull/1739) [#1653](https://github.com/gin-gonic/gin/pull/1653) -- [NEW] context: inherits context cancellation and deadline from http.Request context for Go>=1.7 [#1690](https://github.com/gin-gonic/gin/pull/1690) -- [NEW] Binding for URL Params [#1694](https://github.com/gin-gonic/gin/pull/1694) -- [NEW] Add LoggerWithFormatter method [#1677](https://github.com/gin-gonic/gin/pull/1677) -- [FIX] CI testing updates [#1671](https://github.com/gin-gonic/gin/pull/1671) [#1670](https://github.com/gin-gonic/gin/pull/1670) [#1682](https://github.com/gin-gonic/gin/pull/1682) [#1669](https://github.com/gin-gonic/gin/pull/1669) -- [FIX] StaticFS(): Send 404 when path does not exist [#1663](https://github.com/gin-gonic/gin/pull/1663) -- [FIX] Handle nil body for JSON binding [#1638](https://github.com/gin-gonic/gin/pull/1638) -- [FIX] Support bind uri param [#1612](https://github.com/gin-gonic/gin/pull/1612) -- [FIX] recovery: fix issue with syscall import on google app engine [#1640](https://github.com/gin-gonic/gin/pull/1640) -- [FIX] Make sure the debug log contains line breaks [#1650](https://github.com/gin-gonic/gin/pull/1650) -- [FIX] Panic stack trace being printed during recovery of broken pipe [#1089](https://github.com/gin-gonic/gin/pull/1089) [#1259](https://github.com/gin-gonic/gin/pull/1259) -- [NEW] RunFd method to run http.Server through a file descriptor [#1609](https://github.com/gin-gonic/gin/pull/1609) -- [NEW] Yaml binding support [#1618](https://github.com/gin-gonic/gin/pull/1618) -- [FIX] Pass MaxMultipartMemory when FormFile is called [#1600](https://github.com/gin-gonic/gin/pull/1600) -- [FIX] LoadHTML* tests [#1559](https://github.com/gin-gonic/gin/pull/1559) -- [FIX] Removed use of sync.pool from HandleContext [#1565](https://github.com/gin-gonic/gin/pull/1565) -- [FIX] Format output log to os.Stderr [#1571](https://github.com/gin-gonic/gin/pull/1571) -- [FIX] Make logger use a yellow background and a darkgray text for legibility [#1570](https://github.com/gin-gonic/gin/pull/1570) -- [FIX] Remove sensitive request information from panic log. [#1370](https://github.com/gin-gonic/gin/pull/1370) -- [FIX] log.Println() does not print timestamp [#829](https://github.com/gin-gonic/gin/pull/829) [#1560](https://github.com/gin-gonic/gin/pull/1560) -- [NEW] Add PureJSON renderer [#694](https://github.com/gin-gonic/gin/pull/694) -- [FIX] Add missing copyright and update if/else [#1497](https://github.com/gin-gonic/gin/pull/1497) -- [FIX] Update msgpack usage [#1498](https://github.com/gin-gonic/gin/pull/1498) -- [FIX] Use protobuf on render [#1496](https://github.com/gin-gonic/gin/pull/1496) -- [FIX] Add support for Protobuf format response [#1479](https://github.com/gin-gonic/gin/pull/1479) -- [NEW] Set default time format in form binding [#1487](https://github.com/gin-gonic/gin/pull/1487) -- [FIX] Add BindXML and ShouldBindXML [#1485](https://github.com/gin-gonic/gin/pull/1485) -- [NEW] Upgrade dependency libraries [#1491](https://github.com/gin-gonic/gin/pull/1491) - - -## Gin v1.3.0 - -- [NEW] Add [`func (*Context) QueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.QueryMap), [`func (*Context) GetQueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetQueryMap), [`func (*Context) PostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.PostFormMap) and [`func (*Context) GetPostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetPostFormMap) to support `type map[string]string` as query string or form parameters, see [#1383](https://github.com/gin-gonic/gin/pull/1383) -- [NEW] Add [`func (*Context) AsciiJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.AsciiJSON), see [#1358](https://github.com/gin-gonic/gin/pull/1358) -- [NEW] Add `Pusher()` in [`type ResponseWriter`](https://godoc.org/github.com/gin-gonic/gin#ResponseWriter) for supporting http2 push, see [#1273](https://github.com/gin-gonic/gin/pull/1273) -- [NEW] Add [`func (*Context) DataFromReader`](https://godoc.org/github.com/gin-gonic/gin#Context.DataFromReader) for serving dynamic data, see [#1304](https://github.com/gin-gonic/gin/pull/1304) -- [NEW] Add [`func (*Context) ShouldBindBodyWith`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindBodyWith) allowing to call binding multiple times, see [#1341](https://github.com/gin-gonic/gin/pull/1341) -- [NEW] Support pointers in form binding, see [#1336](https://github.com/gin-gonic/gin/pull/1336) -- [NEW] Add [`func (*Context) JSONP`](https://godoc.org/github.com/gin-gonic/gin#Context.JSONP), see [#1333](https://github.com/gin-gonic/gin/pull/1333) -- [NEW] Support default value in form binding, see [#1138](https://github.com/gin-gonic/gin/pull/1138) -- [NEW] Expose validator engine in [`type StructValidator`](https://godoc.org/github.com/gin-gonic/gin/binding#StructValidator), see [#1277](https://github.com/gin-gonic/gin/pull/1277) -- [NEW] Add [`func (*Context) ShouldBind`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBind), [`func (*Context) ShouldBindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindQuery) and [`func (*Context) ShouldBindJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindJSON), see [#1047](https://github.com/gin-gonic/gin/pull/1047) -- [NEW] Add support for `time.Time` location in form binding, see [#1117](https://github.com/gin-gonic/gin/pull/1117) -- [NEW] Add [`func (*Context) BindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.BindQuery), see [#1029](https://github.com/gin-gonic/gin/pull/1029) -- [NEW] Make [jsonite](https://github.com/json-iterator/go) optional with build tags, see [#1026](https://github.com/gin-gonic/gin/pull/1026) -- [NEW] Show query string in logger, see [#999](https://github.com/gin-gonic/gin/pull/999) -- [NEW] Add [`func (*Context) SecureJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.SecureJSON), see [#987](https://github.com/gin-gonic/gin/pull/987) and [#993](https://github.com/gin-gonic/gin/pull/993) -- [DEPRECATE] `func (*Context) GetCookie` for [`func (*Context) Cookie`](https://godoc.org/github.com/gin-gonic/gin#Context.Cookie) -- [FIX] Don't display color tags if [`func DisableConsoleColor`](https://godoc.org/github.com/gin-gonic/gin#DisableConsoleColor) called, see [#1072](https://github.com/gin-gonic/gin/pull/1072) -- [FIX] Gin Mode `""` when calling [`func Mode`](https://godoc.org/github.com/gin-gonic/gin#Mode) now returns `const DebugMode`, see [#1250](https://github.com/gin-gonic/gin/pull/1250) -- [FIX] `Flush()` now doesn't overwrite `responseWriter` status code, see [#1460](https://github.com/gin-gonic/gin/pull/1460) - -## Gin 1.2.0 - -- [NEW] Switch from godeps to govendor -- [NEW] Add support for Let's Encrypt via gin-gonic/autotls -- [NEW] Improve README examples and add extra at examples folder -- [NEW] Improved support with App Engine -- [NEW] Add custom template delimiters, see #860 -- [NEW] Add Template Func Maps, see #962 -- [NEW] Add \*context.Handler(), see #928 -- [NEW] Add \*context.GetRawData() -- [NEW] Add \*context.GetHeader() (request) -- [NEW] Add \*context.AbortWithStatusJSON() (JSON content type) -- [NEW] Add \*context.Keys type cast helpers -- [NEW] Add \*context.ShouldBindWith() -- [NEW] Add \*context.MustBindWith() -- [NEW] Add \*engine.SetFuncMap() -- [DEPRECATE] On next release: \*context.BindWith(), see #855 -- [FIX] Refactor render -- [FIX] Reworked tests -- [FIX] logger now supports cygwin -- [FIX] Use X-Forwarded-For before X-Real-Ip -- [FIX] time.Time binding (#904) - -## Gin 1.1.4 - -- [NEW] Support google appengine for IsTerminal func - -## Gin 1.1.3 - -- [FIX] Reverted Logger: skip ANSI color commands - -## Gin 1.1 - -- [NEW] Implement QueryArray and PostArray methods -- [NEW] Refactor GetQuery and GetPostForm -- [NEW] Add contribution guide -- [FIX] Corrected typos in README -- [FIX] Removed additional Iota -- [FIX] Changed imports to gopkg instead of github in README (#733) -- [FIX] Logger: skip ANSI color commands if output is not a tty - -## Gin 1.0rc2 (...) - -- [PERFORMANCE] Fast path for writing Content-Type. -- [PERFORMANCE] Much faster 404 routing -- [PERFORMANCE] Allocation optimizations -- [PERFORMANCE] Faster root tree lookup -- [PERFORMANCE] Zero overhead, String() and JSON() rendering. -- [PERFORMANCE] Faster ClientIP parsing -- [PERFORMANCE] Much faster SSE implementation -- [NEW] Benchmarks suite -- [NEW] Bind validation can be disabled and replaced with custom validators. -- [NEW] More flexible HTML render -- [NEW] Multipart and PostForm bindings -- [NEW] Adds method to return all the registered routes -- [NEW] Context.HandlerName() returns the main handler's name -- [NEW] Adds Error.IsType() helper -- [FIX] Binding multipart form -- [FIX] Integration tests -- [FIX] Crash when binding non struct object in Context. -- [FIX] RunTLS() implementation -- [FIX] Logger() unit tests -- [FIX] Adds SetHTMLTemplate() warning -- [FIX] Context.IsAborted() -- [FIX] More unit tests -- [FIX] JSON, XML, HTML renders accept custom content-types -- [FIX] gin.AbortIndex is unexported -- [FIX] Better approach to avoid directory listing in StaticFS() -- [FIX] Context.ClientIP() always returns the IP with trimmed spaces. -- [FIX] Better warning when running in debug mode. -- [FIX] Google App Engine integration. debugPrint does not use os.Stdout -- [FIX] Fixes integer overflow in error type -- [FIX] Error implements the json.Marshaller interface -- [FIX] MIT license in every file - - -## Gin 1.0rc1 (May 22, 2015) - -- [PERFORMANCE] Zero allocation router -- [PERFORMANCE] Faster JSON, XML and text rendering -- [PERFORMANCE] Custom hand optimized HttpRouter for Gin -- [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations -- [NEW] Built-in support for golang.org/x/net/context -- [NEW] Any(path, handler). Create a route that matches any path -- [NEW] Refactored rendering pipeline (faster and static typed) -- [NEW] Refactored errors API -- [NEW] IndentedJSON() prints pretty JSON -- [NEW] Added gin.DefaultWriter -- [NEW] UNIX socket support -- [NEW] RouterGroup.BasePath is exposed -- [NEW] JSON validation using go-validate-yourself (very powerful options) -- [NEW] Completed suite of unit tests -- [NEW] HTTP streaming with c.Stream() -- [NEW] StaticFile() creates a router for serving just one file. -- [NEW] StaticFS() has an option to disable directory listing. -- [NEW] StaticFS() for serving static files through virtual filesystems -- [NEW] Server-Sent Events native support -- [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler -- [NEW] Added LoggerWithWriter() middleware -- [NEW] Added RecoveryWithWriter() middleware -- [NEW] Added DefaultPostFormValue() -- [NEW] Added DefaultFormValue() -- [NEW] Added DefaultParamValue() -- [FIX] BasicAuth() when using custom realm -- [FIX] Bug when serving static files in nested routing group -- [FIX] Redirect using built-in http.Redirect() -- [FIX] Logger when printing the requested path -- [FIX] Documentation typos -- [FIX] Context.Engine renamed to Context.engine -- [FIX] Better debugging messages -- [FIX] ErrorLogger -- [FIX] Debug HTTP render -- [FIX] Refactored binding and render modules -- [FIX] Refactored Context initialization -- [FIX] Refactored BasicAuth() -- [FIX] NoMethod/NoRoute handlers -- [FIX] Hijacking http -- [FIX] Better support for Google App Engine (using log instead of fmt) - - -## Gin 0.6 (Mar 9, 2015) - -- [NEW] Support multipart/form-data -- [NEW] NoMethod handler -- [NEW] Validate sub structures -- [NEW] Support for HTTP Realm Auth -- [FIX] Unsigned integers in binding -- [FIX] Improve color logger - - -## Gin 0.5 (Feb 7, 2015) - -- [NEW] Content Negotiation -- [FIX] Solved security bug that allow a client to spoof ip -- [FIX] Fix unexported/ignored fields in binding - - -## Gin 0.4 (Aug 21, 2014) - -- [NEW] Development mode -- [NEW] Unit tests -- [NEW] Add Content.Redirect() -- [FIX] Deferring WriteHeader() -- [FIX] Improved documentation for model binding - - -## Gin 0.3 (Jul 18, 2014) - -- [PERFORMANCE] Normal log and error log are printed in the same call. -- [PERFORMANCE] Improve performance of NoRouter() -- [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults. -- [NEW] Flexible rendering API -- [NEW] Add Context.File() -- [NEW] Add shortcut RunTLS() for http.ListenAndServeTLS -- [FIX] Rename NotFound404() to NoRoute() -- [FIX] Errors in context are purged -- [FIX] Adds HEAD method in Static file serving -- [FIX] Refactors Static() file serving -- [FIX] Using keyed initialization to fix app-engine integration -- [FIX] Can't unmarshal JSON array, #63 -- [FIX] Renaming Context.Req to Context.Request -- [FIX] Check application/x-www-form-urlencoded when parsing form - - -## Gin 0.2b (Jul 08, 2014) -- [PERFORMANCE] Using sync.Pool to allocatio/gc overhead -- [NEW] Travis CI integration -- [NEW] Completely new logger -- [NEW] New API for serving static files. gin.Static() -- [NEW] gin.H() can be serialized into XML -- [NEW] Typed errors. Errors can be typed. Internet/external/custom. -- [NEW] Support for Godeps -- [NEW] Travis/Godocs badges in README -- [NEW] New Bind() and BindWith() methods for parsing request body. -- [NEW] Add Content.Copy() -- [NEW] Add context.LastError() -- [NEW] Add shortcut for OPTIONS HTTP method -- [FIX] Tons of README fixes -- [FIX] Header is written before body -- [FIX] BasicAuth() and changes API a little bit -- [FIX] Recovery() middleware only prints panics -- [FIX] Context.Get() does not panic anymore. Use MustGet() instead. -- [FIX] Multiple http.WriteHeader() in NotFound handlers -- [FIX] Engine.Run() panics if http server can't be set up -- [FIX] Crash when route path doesn't start with '/' -- [FIX] Do not update header when status code is negative -- [FIX] Setting response headers before calling WriteHeader in context.String() -- [FIX] Add MIT license -- [FIX] Changes behaviour of ErrorLogger() and Logger() diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/CODE_OF_CONDUCT.md b/taskman-server/vendor/github.com/gin-gonic/gin/CODE_OF_CONDUCT.md deleted file mode 100644 index 4ea14f39..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at teamgingonic@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/CONTRIBUTING.md b/taskman-server/vendor/github.com/gin-gonic/gin/CONTRIBUTING.md deleted file mode 100644 index 97daa808..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/CONTRIBUTING.md +++ /dev/null @@ -1,13 +0,0 @@ -## Contributing - -- With issues: - - Use the search tool before opening a new issue. - - Please provide source code and commit sha if you found a bug. - - Review existing issues and provide feedback or react to them. - -- With pull requests: - - Open your pull request against `master` - - Your pull request should have no more than two commits, if not you should squash them. - - It should pass all tests in the available continuous integration systems such as TravisCI. - - You should add/modify tests to cover your proposed code changes. - - If your pull request contains a new feature, please document it on the README. diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/LICENSE b/taskman-server/vendor/github.com/gin-gonic/gin/LICENSE deleted file mode 100644 index 1ff7f370..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Manuel Martínez-Almeida - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/Makefile b/taskman-server/vendor/github.com/gin-gonic/gin/Makefile deleted file mode 100644 index 1a991939..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/Makefile +++ /dev/null @@ -1,71 +0,0 @@ -GO ?= go -GOFMT ?= gofmt "-s" -PACKAGES ?= $(shell $(GO) list ./...) -VETPACKAGES ?= $(shell $(GO) list ./... | grep -v /examples/) -GOFILES := $(shell find . -name "*.go") -TESTFOLDER := $(shell $(GO) list ./... | grep -E 'gin$$|binding$$|render$$' | grep -v examples) -TESTTAGS ?= "" - -.PHONY: test -test: - echo "mode: count" > coverage.out - for d in $(TESTFOLDER); do \ - $(GO) test -tags $(TESTTAGS) -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \ - cat tmp.out; \ - if grep -q "^--- FAIL" tmp.out; then \ - rm tmp.out; \ - exit 1; \ - elif grep -q "build failed" tmp.out; then \ - rm tmp.out; \ - exit 1; \ - elif grep -q "setup failed" tmp.out; then \ - rm tmp.out; \ - exit 1; \ - fi; \ - if [ -f profile.out ]; then \ - cat profile.out | grep -v "mode:" >> coverage.out; \ - rm profile.out; \ - fi; \ - done - -.PHONY: fmt -fmt: - $(GOFMT) -w $(GOFILES) - -.PHONY: fmt-check -fmt-check: - @diff=$$($(GOFMT) -d $(GOFILES)); \ - if [ -n "$$diff" ]; then \ - echo "Please run 'make fmt' and commit the result:"; \ - echo "$${diff}"; \ - exit 1; \ - fi; - -vet: - $(GO) vet $(VETPACKAGES) - -.PHONY: lint -lint: - @hash golint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ - $(GO) get -u golang.org/x/lint/golint; \ - fi - for PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done; - -.PHONY: misspell-check -misspell-check: - @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ - $(GO) get -u github.com/client9/misspell/cmd/misspell; \ - fi - misspell -error $(GOFILES) - -.PHONY: misspell -misspell: - @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ - $(GO) get -u github.com/client9/misspell/cmd/misspell; \ - fi - misspell -w $(GOFILES) - -.PHONY: tools -tools: - go install golang.org/x/lint/golint; \ - go install github.com/client9/misspell/cmd/misspell; diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/README.md b/taskman-server/vendor/github.com/gin-gonic/gin/README.md deleted file mode 100644 index d4772d76..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/README.md +++ /dev/null @@ -1,2217 +0,0 @@ -# Gin Web Framework - - - -[![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin) -[![codecov](https://codecov.io/gh/gin-gonic/gin/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-gonic/gin) -[![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin) -[![GoDoc](https://pkg.go.dev/badge/github.com/gin-gonic/gin?status.svg)](https://pkg.go.dev/github.com/gin-gonic/gin?tab=doc) -[![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Sourcegraph](https://sourcegraph.com/github.com/gin-gonic/gin/-/badge.svg)](https://sourcegraph.com/github.com/gin-gonic/gin?badge) -[![Open Source Helpers](https://www.codetriage.com/gin-gonic/gin/badges/users.svg)](https://www.codetriage.com/gin-gonic/gin) -[![Release](https://img.shields.io/github/release/gin-gonic/gin.svg?style=flat-square)](https://github.com/gin-gonic/gin/releases) -[![TODOs](https://badgen.net/https/api.tickgit.com/badgen/github.com/gin-gonic/gin)](https://www.tickgit.com/browse?repo=github.com/gin-gonic/gin) - -Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin. - - -## Contents - -- [Gin Web Framework](#gin-web-framework) - - [Contents](#contents) - - [Installation](#installation) - - [Quick start](#quick-start) - - [Benchmarks](#benchmarks) - - [Gin v1. stable](#gin-v1-stable) - - [Build with jsoniter](#build-with-jsoniter) - - [API Examples](#api-examples) - - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options) - - [Parameters in path](#parameters-in-path) - - [Querystring parameters](#querystring-parameters) - - [Multipart/Urlencoded Form](#multiparturlencoded-form) - - [Another example: query + post form](#another-example-query--post-form) - - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters) - - [Upload files](#upload-files) - - [Single file](#single-file) - - [Multiple files](#multiple-files) - - [Grouping routes](#grouping-routes) - - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default) - - [Using middleware](#using-middleware) - - [How to write log file](#how-to-write-log-file) - - [Custom Log Format](#custom-log-format) - - [Controlling Log output coloring](#controlling-log-output-coloring) - - [Model binding and validation](#model-binding-and-validation) - - [Custom Validators](#custom-validators) - - [Only Bind Query String](#only-bind-query-string) - - [Bind Query String or Post Data](#bind-query-string-or-post-data) - - [Bind Uri](#bind-uri) - - [Bind Header](#bind-header) - - [Bind HTML checkboxes](#bind-html-checkboxes) - - [Multipart/Urlencoded binding](#multiparturlencoded-binding) - - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering) - - [SecureJSON](#securejson) - - [JSONP](#jsonp) - - [AsciiJSON](#asciijson) - - [PureJSON](#purejson) - - [Serving static files](#serving-static-files) - - [Serving data from file](#serving-data-from-file) - - [Serving data from reader](#serving-data-from-reader) - - [HTML rendering](#html-rendering) - - [Custom Template renderer](#custom-template-renderer) - - [Custom Delimiters](#custom-delimiters) - - [Custom Template Funcs](#custom-template-funcs) - - [Multitemplate](#multitemplate) - - [Redirects](#redirects) - - [Custom Middleware](#custom-middleware) - - [Using BasicAuth() middleware](#using-basicauth-middleware) - - [Goroutines inside a middleware](#goroutines-inside-a-middleware) - - [Custom HTTP configuration](#custom-http-configuration) - - [Support Let's Encrypt](#support-lets-encrypt) - - [Run multiple service using Gin](#run-multiple-service-using-gin) - - [Graceful shutdown or restart](#graceful-shutdown-or-restart) - - [Third-party packages](#third-party-packages) - - [Manually](#manually) - - [Build a single binary with templates](#build-a-single-binary-with-templates) - - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct) - - [Try to bind body into different structs](#try-to-bind-body-into-different-structs) - - [http2 server push](#http2-server-push) - - [Define format for the log of routes](#define-format-for-the-log-of-routes) - - [Set and get a cookie](#set-and-get-a-cookie) - - [Testing](#testing) - - [Users](#users) - -## Installation - -To install Gin package, you need to install Go and set your Go workspace first. - -1. The first need [Go](https://golang.org/) installed (**version 1.12+ is required**), then you can use the below Go command to install Gin. - -```sh -$ go get -u github.com/gin-gonic/gin -``` - -2. Import it in your code: - -```go -import "github.com/gin-gonic/gin" -``` - -3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`. - -```go -import "net/http" -``` - -## Quick start - -```sh -# assume the following codes in example.go file -$ cat example.go -``` - -```go -package main - -import "github.com/gin-gonic/gin" - -func main() { - r := gin.Default() - r.GET("/ping", func(c *gin.Context) { - c.JSON(200, gin.H{ - "message": "pong", - }) - }) - r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") -} -``` - -``` -# run example.go and visit 0.0.0.0:8080/ping (for windows "localhost:8080/ping") on browser -$ go run example.go -``` - -## Benchmarks - -Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) - -[See all benchmarks](/BENCHMARKS.md) - -| Benchmark name | (1) | (2) | (3) | (4) | -| ------------------------------ | ---------:| ---------------:| ------------:| ---------------:| -| BenchmarkGin_GithubAll | **43550** | **27364 ns/op** | **0 B/op** | **0 allocs/op** | -| BenchmarkAce_GithubAll | 40543 | 29670 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAero_GithubAll | 57632 | 20648 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBear_GithubAll | 9234 | 216179 ns/op | 86448 B/op | 943 allocs/op | -| BenchmarkBeego_GithubAll | 7407 | 243496 ns/op | 71456 B/op | 609 allocs/op | -| BenchmarkBone_GithubAll | 420 | 2922835 ns/op | 720160 B/op | 8620 allocs/op | -| BenchmarkChi_GithubAll | 7620 | 238331 ns/op | 87696 B/op | 609 allocs/op | -| BenchmarkDenco_GithubAll | 18355 | 64494 ns/op | 20224 B/op | 167 allocs/op | -| BenchmarkEcho_GithubAll | 31251 | 38479 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkGocraftWeb_GithubAll | 4117 | 300062 ns/op | 131656 B/op | 1686 allocs/op | -| BenchmarkGoji_GithubAll | 3274 | 416158 ns/op | 56112 B/op | 334 allocs/op | -| BenchmarkGojiv2_GithubAll | 1402 | 870518 ns/op | 352720 B/op | 4321 allocs/op | -| BenchmarkGoJsonRest_GithubAll | 2976 | 401507 ns/op | 134371 B/op | 2737 allocs/op | -| BenchmarkGoRestful_GithubAll | 410 | 2913158 ns/op | 910144 B/op | 2938 allocs/op | -| BenchmarkGorillaMux_GithubAll | 346 | 3384987 ns/op | 251650 B/op | 1994 allocs/op | -| BenchmarkGowwwRouter_GithubAll | 10000 | 143025 ns/op | 72144 B/op | 501 allocs/op | -| BenchmarkHttpRouter_GithubAll | 55938 | 21360 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHttpTreeMux_GithubAll | 10000 | 153944 ns/op | 65856 B/op | 671 allocs/op | -| BenchmarkKocha_GithubAll | 10000 | 106315 ns/op | 23304 B/op | 843 allocs/op | -| BenchmarkLARS_GithubAll | 47779 | 25084 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMacaron_GithubAll | 3266 | 371907 ns/op | 149409 B/op | 1624 allocs/op | -| BenchmarkMartini_GithubAll | 331 | 3444706 ns/op | 226551 B/op | 2325 allocs/op | -| BenchmarkPat_GithubAll | 273 | 4381818 ns/op | 1483152 B/op | 26963 allocs/op | -| BenchmarkPossum_GithubAll | 10000 | 164367 ns/op | 84448 B/op | 609 allocs/op | -| BenchmarkR2router_GithubAll | 10000 | 160220 ns/op | 77328 B/op | 979 allocs/op | -| BenchmarkRivet_GithubAll | 14625 | 82453 ns/op | 16272 B/op | 167 allocs/op | -| BenchmarkTango_GithubAll | 6255 | 279611 ns/op | 63826 B/op | 1618 allocs/op | -| BenchmarkTigerTonic_GithubAll | 2008 | 687874 ns/op | 193856 B/op | 4474 allocs/op | -| BenchmarkTraffic_GithubAll | 355 | 3478508 ns/op | 820744 B/op | 14114 allocs/op | -| BenchmarkVulcan_GithubAll | 6885 | 193333 ns/op | 19894 B/op | 609 allocs/op | - -- (1): Total Repetitions achieved in constant time, higher means more confident result -- (2): Single Repetition Duration (ns/op), lower is better -- (3): Heap Memory (B/op), lower is better -- (4): Average Allocations per Repetition (allocs/op), lower is better - -## Gin v1. stable - -- [x] Zero allocation router. -- [x] Still the fastest http router and framework. From routing to writing. -- [x] Complete suite of unit tests. -- [x] Battle tested. -- [x] API frozen, new releases will not break your code. - -## Build with [jsoniter](https://github.com/json-iterator/go) - -Gin uses `encoding/json` as default json package but you can change to [jsoniter](https://github.com/json-iterator/go) by build from other tags. - -```sh -$ go build -tags=jsoniter . -``` - -## API Examples - -You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples). - -### Using GET, POST, PUT, PATCH, DELETE and OPTIONS - -```go -func main() { - // Creates a gin router with default middleware: - // logger and recovery (crash-free) middleware - router := gin.Default() - - router.GET("/someGet", getting) - router.POST("/somePost", posting) - router.PUT("/somePut", putting) - router.DELETE("/someDelete", deleting) - router.PATCH("/somePatch", patching) - router.HEAD("/someHead", head) - router.OPTIONS("/someOptions", options) - - // By default it serves on :8080 unless a - // PORT environment variable was defined. - router.Run() - // router.Run(":3000") for a hard coded port -} -``` - -### Parameters in path - -```go -func main() { - router := gin.Default() - - // This handler will match /user/john but will not match /user/ or /user - router.GET("/user/:name", func(c *gin.Context) { - name := c.Param("name") - c.String(http.StatusOK, "Hello %s", name) - }) - - // However, this one will match /user/john/ and also /user/john/send - // If no other routers match /user/john, it will redirect to /user/john/ - router.GET("/user/:name/*action", func(c *gin.Context) { - name := c.Param("name") - action := c.Param("action") - message := name + " is " + action - c.String(http.StatusOK, message) - }) - - // For each matched request Context will hold the route definition - router.POST("/user/:name/*action", func(c *gin.Context) { - c.FullPath() == "/user/:name/*action" // true - }) - - // This handler will add a new router for /user/groups. - // Exact routes are resolved before param routes, regardless of the order they were defined. - // Routes starting with /user/groups are never interpreted as /user/:name/... routes - router.GET("/user/groups", func(c *gin.Context) { - c.String(http.StatusOK, "The available groups are [...]", name) - }) - - router.Run(":8080") -} -``` - -### Querystring parameters - -```go -func main() { - router := gin.Default() - - // Query string parameters are parsed using the existing underlying request object. - // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe - router.GET("/welcome", func(c *gin.Context) { - firstname := c.DefaultQuery("firstname", "Guest") - lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname") - - c.String(http.StatusOK, "Hello %s %s", firstname, lastname) - }) - router.Run(":8080") -} -``` - -### Multipart/Urlencoded Form - -```go -func main() { - router := gin.Default() - - router.POST("/form_post", func(c *gin.Context) { - message := c.PostForm("message") - nick := c.DefaultPostForm("nick", "anonymous") - - c.JSON(200, gin.H{ - "status": "posted", - "message": message, - "nick": nick, - }) - }) - router.Run(":8080") -} -``` - -### Another example: query + post form - -``` -POST /post?id=1234&page=1 HTTP/1.1 -Content-Type: application/x-www-form-urlencoded - -name=manu&message=this_is_great -``` - -```go -func main() { - router := gin.Default() - - router.POST("/post", func(c *gin.Context) { - - id := c.Query("id") - page := c.DefaultQuery("page", "0") - name := c.PostForm("name") - message := c.PostForm("message") - - fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message) - }) - router.Run(":8080") -} -``` - -``` -id: 1234; page: 1; name: manu; message: this_is_great -``` - -### Map as querystring or postform parameters - -``` -POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1 -Content-Type: application/x-www-form-urlencoded - -names[first]=thinkerou&names[second]=tianou -``` - -```go -func main() { - router := gin.Default() - - router.POST("/post", func(c *gin.Context) { - - ids := c.QueryMap("ids") - names := c.PostFormMap("names") - - fmt.Printf("ids: %v; names: %v", ids, names) - }) - router.Run(":8080") -} -``` - -``` -ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou] -``` - -### Upload files - -#### Single file - -References issue [#774](https://github.com/gin-gonic/gin/issues/774) and detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/single). - -`file.Filename` **SHOULD NOT** be trusted. See [`Content-Disposition` on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives) and [#1693](https://github.com/gin-gonic/gin/issues/1693) - -> The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. - -```go -func main() { - router := gin.Default() - // Set a lower memory limit for multipart forms (default is 32 MiB) - router.MaxMultipartMemory = 8 << 20 // 8 MiB - router.POST("/upload", func(c *gin.Context) { - // single file - file, _ := c.FormFile("file") - log.Println(file.Filename) - - // Upload the file to specific dst. - c.SaveUploadedFile(file, dst) - - c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) - }) - router.Run(":8080") -} -``` - -How to `curl`: - -```bash -curl -X POST http://localhost:8080/upload \ - -F "file=@/Users/appleboy/test.zip" \ - -H "Content-Type: multipart/form-data" -``` - -#### Multiple files - -See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple). - -```go -func main() { - router := gin.Default() - // Set a lower memory limit for multipart forms (default is 32 MiB) - router.MaxMultipartMemory = 8 << 20 // 8 MiB - router.POST("/upload", func(c *gin.Context) { - // Multipart form - form, _ := c.MultipartForm() - files := form.File["upload[]"] - - for _, file := range files { - log.Println(file.Filename) - - // Upload the file to specific dst. - c.SaveUploadedFile(file, dst) - } - c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) - }) - router.Run(":8080") -} -``` - -How to `curl`: - -```bash -curl -X POST http://localhost:8080/upload \ - -F "upload[]=@/Users/appleboy/test1.zip" \ - -F "upload[]=@/Users/appleboy/test2.zip" \ - -H "Content-Type: multipart/form-data" -``` - -### Grouping routes - -```go -func main() { - router := gin.Default() - - // Simple group: v1 - v1 := router.Group("/v1") - { - v1.POST("/login", loginEndpoint) - v1.POST("/submit", submitEndpoint) - v1.POST("/read", readEndpoint) - } - - // Simple group: v2 - v2 := router.Group("/v2") - { - v2.POST("/login", loginEndpoint) - v2.POST("/submit", submitEndpoint) - v2.POST("/read", readEndpoint) - } - - router.Run(":8080") -} -``` - -### Blank Gin without middleware by default - -Use - -```go -r := gin.New() -``` - -instead of - -```go -// Default With the Logger and Recovery middleware already attached -r := gin.Default() -``` - - -### Using middleware -```go -func main() { - // Creates a router without any middleware by default - r := gin.New() - - // Global middleware - // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. - // By default gin.DefaultWriter = os.Stdout - r.Use(gin.Logger()) - - // Recovery middleware recovers from any panics and writes a 500 if there was one. - r.Use(gin.Recovery()) - - // Per route middleware, you can add as many as you desire. - r.GET("/benchmark", MyBenchLogger(), benchEndpoint) - - // Authorization group - // authorized := r.Group("/", AuthRequired()) - // exactly the same as: - authorized := r.Group("/") - // per group middleware! in this case we use the custom created - // AuthRequired() middleware just in the "authorized" group. - authorized.Use(AuthRequired()) - { - authorized.POST("/login", loginEndpoint) - authorized.POST("/submit", submitEndpoint) - authorized.POST("/read", readEndpoint) - - // nested group - testing := authorized.Group("testing") - testing.GET("/analytics", analyticsEndpoint) - } - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -### Custom Recovery behavior -```go -func main() { - // Creates a router without any middleware by default - r := gin.New() - - // Global middleware - // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. - // By default gin.DefaultWriter = os.Stdout - r.Use(gin.Logger()) - - // Recovery middleware recovers from any panics and writes a 500 if there was one. - r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) { - if err, ok := recovered.(string); ok { - c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) - } - c.AbortWithStatus(http.StatusInternalServerError) - })) - - r.GET("/panic", func(c *gin.Context) { - // panic with a string -- the custom middleware could save this to a database or report it to the user - panic("foo") - }) - - r.GET("/", func(c *gin.Context) { - c.String(http.StatusOK, "ohai") - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -### How to write log file -```go -func main() { - // Disable Console Color, you don't need console color when writing the logs to file. - gin.DisableConsoleColor() - - // Logging to a file. - f, _ := os.Create("gin.log") - gin.DefaultWriter = io.MultiWriter(f) - - // Use the following code if you need to write the logs to file and console at the same time. - // gin.DefaultWriter = io.MultiWriter(f, os.Stdout) - - router := gin.Default() - router.GET("/ping", func(c *gin.Context) { - c.String(200, "pong") - }) - -    router.Run(":8080") -} -``` - -### Custom Log Format -```go -func main() { - router := gin.New() - - // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter - // By default gin.DefaultWriter = os.Stdout - router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { - - // your custom format - return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n", - param.ClientIP, - param.TimeStamp.Format(time.RFC1123), - param.Method, - param.Path, - param.Request.Proto, - param.StatusCode, - param.Latency, - param.Request.UserAgent(), - param.ErrorMessage, - ) - })) - router.Use(gin.Recovery()) - - router.GET("/ping", func(c *gin.Context) { - c.String(200, "pong") - }) - - router.Run(":8080") -} -``` - -**Sample Output** -``` -::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" " -``` - -### Controlling Log output coloring - -By default, logs output on console should be colorized depending on the detected TTY. - -Never colorize logs: - -```go -func main() { - // Disable log's color - gin.DisableConsoleColor() - - // Creates a gin router with default middleware: - // logger and recovery (crash-free) middleware - router := gin.Default() - - router.GET("/ping", func(c *gin.Context) { - c.String(200, "pong") - }) - - router.Run(":8080") -} -``` - -Always colorize logs: - -```go -func main() { - // Force log's color - gin.ForceConsoleColor() - - // Creates a gin router with default middleware: - // logger and recovery (crash-free) middleware - router := gin.Default() - - router.GET("/ping", func(c *gin.Context) { - c.String(200, "pong") - }) - - router.Run(":8080") -} -``` - -### Model binding and validation - -To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML and standard form values (foo=bar&boo=baz). - -Gin uses [**go-playground/validator/v10**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](https://godoc.org/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags). - -Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`. - -Also, Gin provides two sets of methods for binding: -- **Type** - Must bind - - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader` - - **Behavior** - These methods use `MustBindWith` under the hood. If there is a binding error, the request is aborted with `c.AbortWithError(400, err).SetType(ErrorTypeBind)`. This sets the response status code to 400 and the `Content-Type` header is set to `text/plain; charset=utf-8`. Note that if you try to set the response code after this, it will result in a warning `[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422`. If you wish to have greater control over the behavior, consider using the `ShouldBind` equivalent method. -- **Type** - Should bind - - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader` - - **Behavior** - These methods use `ShouldBindWith` under the hood. If there is a binding error, the error is returned and it is the developer's responsibility to handle the request and error appropriately. - -When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use `MustBindWith` or `ShouldBindWith`. - -You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, an error will be returned. - -```go -// Binding from JSON -type Login struct { - User string `form:"user" json:"user" xml:"user" binding:"required"` - Password string `form:"password" json:"password" xml:"password" binding:"required"` -} - -func main() { - router := gin.Default() - - // Example for binding JSON ({"user": "manu", "password": "123"}) - router.POST("/loginJSON", func(c *gin.Context) { - var json Login - if err := c.ShouldBindJSON(&json); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - - if json.User != "manu" || json.Password != "123" { - c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) - return - } - - c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) - }) - - // Example for binding XML ( - // - // - // user - // 123 - // ) - router.POST("/loginXML", func(c *gin.Context) { - var xml Login - if err := c.ShouldBindXML(&xml); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - - if xml.User != "manu" || xml.Password != "123" { - c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) - return - } - - c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) - }) - - // Example for binding a HTML form (user=manu&password=123) - router.POST("/loginForm", func(c *gin.Context) { - var form Login - // This will infer what binder to use depending on the content-type header. - if err := c.ShouldBind(&form); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - - if form.User != "manu" || form.Password != "123" { - c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) - return - } - - c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) - }) - - // Listen and serve on 0.0.0.0:8080 - router.Run(":8080") -} -``` - -**Sample request** -```shell -$ curl -v -X POST \ - http://localhost:8080/loginJSON \ - -H 'content-type: application/json' \ - -d '{ "user": "manu" }' -> POST /loginJSON HTTP/1.1 -> Host: localhost:8080 -> User-Agent: curl/7.51.0 -> Accept: */* -> content-type: application/json -> Content-Length: 18 -> -* upload completely sent off: 18 out of 18 bytes -< HTTP/1.1 400 Bad Request -< Content-Type: application/json; charset=utf-8 -< Date: Fri, 04 Aug 2017 03:51:31 GMT -< Content-Length: 100 -< -{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"} -``` - -**Skip validate** - -When running the above example using the above the `curl` command, it returns error. Because the example use `binding:"required"` for `Password`. If use `binding:"-"` for `Password`, then it will not return error when running the above example again. - -### Custom Validators - -It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go). - -```go -package main - -import ( - "net/http" - "time" - - "github.com/gin-gonic/gin" - "github.com/gin-gonic/gin/binding" - "github.com/go-playground/validator/v10" -) - -// Booking contains binded and validated data. -type Booking struct { - CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` - CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` -} - -var bookableDate validator.Func = func(fl validator.FieldLevel) bool { - date, ok := fl.Field().Interface().(time.Time) - if ok { - today := time.Now() - if today.After(date) { - return false - } - } - return true -} - -func main() { - route := gin.Default() - - if v, ok := binding.Validator.Engine().(*validator.Validate); ok { - v.RegisterValidation("bookabledate", bookableDate) - } - - route.GET("/bookable", getBookable) - route.Run(":8085") -} - -func getBookable(c *gin.Context) { - var b Booking - if err := c.ShouldBindWith(&b, binding.Query); err == nil { - c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) - } else { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - } -} -``` - -```console -$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17" -{"message":"Booking dates are valid!"} - -$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09" -{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"} - -$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10" -{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}% -``` - -[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way. -See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more. - -### Only Bind Query String - -`ShouldBindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017). - -```go -package main - -import ( - "log" - - "github.com/gin-gonic/gin" -) - -type Person struct { - Name string `form:"name"` - Address string `form:"address"` -} - -func main() { - route := gin.Default() - route.Any("/testing", startPage) - route.Run(":8085") -} - -func startPage(c *gin.Context) { - var person Person - if c.ShouldBindQuery(&person) == nil { - log.Println("====== Only Bind By Query String ======") - log.Println(person.Name) - log.Println(person.Address) - } - c.String(200, "Success") -} - -``` - -### Bind Query String or Post Data - -See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292). - -```go -package main - -import ( - "log" - "time" - - "github.com/gin-gonic/gin" -) - -type Person struct { - Name string `form:"name"` - Address string `form:"address"` - Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` - CreateTime time.Time `form:"createTime" time_format:"unixNano"` - UnixTime time.Time `form:"unixTime" time_format:"unix"` -} - -func main() { - route := gin.Default() - route.GET("/testing", startPage) - route.Run(":8085") -} - -func startPage(c *gin.Context) { - var person Person - // If `GET`, only `Form` binding engine (`query`) used. - // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`). - // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48 - if c.ShouldBind(&person) == nil { - log.Println(person.Name) - log.Println(person.Address) - log.Println(person.Birthday) - log.Println(person.CreateTime) - log.Println(person.UnixTime) - } - - c.String(200, "Success") -} -``` - -Test it with: -```sh -$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" -``` - -### Bind Uri - -See the [detail information](https://github.com/gin-gonic/gin/issues/846). - -```go -package main - -import "github.com/gin-gonic/gin" - -type Person struct { - ID string `uri:"id" binding:"required,uuid"` - Name string `uri:"name" binding:"required"` -} - -func main() { - route := gin.Default() - route.GET("/:name/:id", func(c *gin.Context) { - var person Person - if err := c.ShouldBindUri(&person); err != nil { - c.JSON(400, gin.H{"msg": err}) - return - } - c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID}) - }) - route.Run(":8088") -} -``` - -Test it with: -```sh -$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 -$ curl -v localhost:8088/thinkerou/not-uuid -``` - -### Bind Header - -```go -package main - -import ( - "fmt" - "github.com/gin-gonic/gin" -) - -type testHeader struct { - Rate int `header:"Rate"` - Domain string `header:"Domain"` -} - -func main() { - r := gin.Default() - r.GET("/", func(c *gin.Context) { - h := testHeader{} - - if err := c.ShouldBindHeader(&h); err != nil { - c.JSON(200, err) - } - - fmt.Printf("%#v\n", h) - c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain}) - }) - - r.Run() - -// client -// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/ -// output -// {"Domain":"music","Rate":300} -} -``` - -### Bind HTML checkboxes - -See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092) - -main.go - -```go -... - -type myForm struct { - Colors []string `form:"colors[]"` -} - -... - -func formHandler(c *gin.Context) { - var fakeForm myForm - c.ShouldBind(&fakeForm) - c.JSON(200, gin.H{"color": fakeForm.Colors}) -} - -... - -``` - -form.html - -```html -
-

Check some colors

- - - - - - - -
-``` - -result: - -``` -{"color":["red","green","blue"]} -``` - -### Multipart/Urlencoded binding - -```go -type ProfileForm struct { - Name string `form:"name" binding:"required"` - Avatar *multipart.FileHeader `form:"avatar" binding:"required"` - - // or for multiple files - // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"` -} - -func main() { - router := gin.Default() - router.POST("/profile", func(c *gin.Context) { - // you can bind multipart form with explicit binding declaration: - // c.ShouldBindWith(&form, binding.Form) - // or you can simply use autobinding with ShouldBind method: - var form ProfileForm - // in this case proper binding will be automatically selected - if err := c.ShouldBind(&form); err != nil { - c.String(http.StatusBadRequest, "bad request") - return - } - - err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename) - if err != nil { - c.String(http.StatusInternalServerError, "unknown error") - return - } - - // db.Save(&form) - - c.String(http.StatusOK, "ok") - }) - router.Run(":8080") -} -``` - -Test it with: -```sh -$ curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile -``` - -### XML, JSON, YAML and ProtoBuf rendering - -```go -func main() { - r := gin.Default() - - // gin.H is a shortcut for map[string]interface{} - r.GET("/someJSON", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) - }) - - r.GET("/moreJSON", func(c *gin.Context) { - // You also can use a struct - var msg struct { - Name string `json:"user"` - Message string - Number int - } - msg.Name = "Lena" - msg.Message = "hey" - msg.Number = 123 - // Note that msg.Name becomes "user" in the JSON - // Will output : {"user": "Lena", "Message": "hey", "Number": 123} - c.JSON(http.StatusOK, msg) - }) - - r.GET("/someXML", func(c *gin.Context) { - c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) - }) - - r.GET("/someYAML", func(c *gin.Context) { - c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) - }) - - r.GET("/someProtoBuf", func(c *gin.Context) { - reps := []int64{int64(1), int64(2)} - label := "test" - // The specific definition of protobuf is written in the testdata/protoexample file. - data := &protoexample.Test{ - Label: &label, - Reps: reps, - } - // Note that data becomes binary data in the response - // Will output protoexample.Test protobuf serialized data - c.ProtoBuf(http.StatusOK, data) - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -#### SecureJSON - -Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values. - -```go -func main() { - r := gin.Default() - - // You can also use your own secure json prefix - // r.SecureJsonPrefix(")]}',\n") - - r.GET("/someJSON", func(c *gin.Context) { - names := []string{"lena", "austin", "foo"} - - // Will output : while(1);["lena","austin","foo"] - c.SecureJSON(http.StatusOK, names) - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` -#### JSONP - -Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists. - -```go -func main() { - r := gin.Default() - - r.GET("/JSONP", func(c *gin.Context) { - data := gin.H{ - "foo": "bar", - } - - //callback is x - // Will output : x({\"foo\":\"bar\"}) - c.JSONP(http.StatusOK, data) - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") - - // client - // curl http://127.0.0.1:8080/JSONP?callback=x -} -``` - -#### AsciiJSON - -Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters. - -```go -func main() { - r := gin.Default() - - r.GET("/someJSON", func(c *gin.Context) { - data := gin.H{ - "lang": "GO语言", - "tag": "
", - } - - // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"} - c.AsciiJSON(http.StatusOK, data) - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -#### PureJSON - -Normally, JSON replaces special HTML characters with their unicode entities, e.g. `<` becomes `\u003c`. If you want to encode such characters literally, you can use PureJSON instead. -This feature is unavailable in Go 1.6 and lower. - -```go -func main() { - r := gin.Default() - - // Serves unicode entities - r.GET("/json", func(c *gin.Context) { - c.JSON(200, gin.H{ - "html": "Hello, world!", - }) - }) - - // Serves literal characters - r.GET("/purejson", func(c *gin.Context) { - c.PureJSON(200, gin.H{ - "html": "Hello, world!", - }) - }) - - // listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -### Serving static files - -```go -func main() { - router := gin.Default() - router.Static("/assets", "./assets") - router.StaticFS("/more_static", http.Dir("my_file_system")) - router.StaticFile("/favicon.ico", "./resources/favicon.ico") - - // Listen and serve on 0.0.0.0:8080 - router.Run(":8080") -} -``` - -### Serving data from file - -```go -func main() { - router := gin.Default() - - router.GET("/local/file", func(c *gin.Context) { - c.File("local/file.go") - }) - - var fs http.FileSystem = // ... - router.GET("/fs/file", func(c *gin.Context) { - c.FileFromFS("fs/file.go", fs) - }) -} - -``` - -### Serving data from reader - -```go -func main() { - router := gin.Default() - router.GET("/someDataFromReader", func(c *gin.Context) { - response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png") - if err != nil || response.StatusCode != http.StatusOK { - c.Status(http.StatusServiceUnavailable) - return - } - - reader := response.Body - defer reader.Close() - contentLength := response.ContentLength - contentType := response.Header.Get("Content-Type") - - extraHeaders := map[string]string{ - "Content-Disposition": `attachment; filename="gopher.png"`, - } - - c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) - }) - router.Run(":8080") -} -``` - -### HTML rendering - -Using LoadHTMLGlob() or LoadHTMLFiles() - -```go -func main() { - router := gin.Default() - router.LoadHTMLGlob("templates/*") - //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") - router.GET("/index", func(c *gin.Context) { - c.HTML(http.StatusOK, "index.tmpl", gin.H{ - "title": "Main website", - }) - }) - router.Run(":8080") -} -``` - -templates/index.tmpl - -```html - -

- {{ .title }} -

- -``` - -Using templates with same name in different directories - -```go -func main() { - router := gin.Default() - router.LoadHTMLGlob("templates/**/*") - router.GET("/posts/index", func(c *gin.Context) { - c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ - "title": "Posts", - }) - }) - router.GET("/users/index", func(c *gin.Context) { - c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ - "title": "Users", - }) - }) - router.Run(":8080") -} -``` - -templates/posts/index.tmpl - -```html -{{ define "posts/index.tmpl" }} -

- {{ .title }} -

-

Using posts/index.tmpl

- -{{ end }} -``` - -templates/users/index.tmpl - -```html -{{ define "users/index.tmpl" }} -

- {{ .title }} -

-

Using users/index.tmpl

- -{{ end }} -``` - -#### Custom Template renderer - -You can also use your own html template render - -```go -import "html/template" - -func main() { - router := gin.Default() - html := template.Must(template.ParseFiles("file1", "file2")) - router.SetHTMLTemplate(html) - router.Run(":8080") -} -``` - -#### Custom Delimiters - -You may use custom delims - -```go - r := gin.Default() - r.Delims("{[{", "}]}") - r.LoadHTMLGlob("/path/to/templates") -``` - -#### Custom Template Funcs - -See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template). - -main.go - -```go -import ( - "fmt" - "html/template" - "net/http" - "time" - - "github.com/gin-gonic/gin" -) - -func formatAsDate(t time.Time) string { - year, month, day := t.Date() - return fmt.Sprintf("%d%02d/%02d", year, month, day) -} - -func main() { - router := gin.Default() - router.Delims("{[{", "}]}") - router.SetFuncMap(template.FuncMap{ - "formatAsDate": formatAsDate, - }) - router.LoadHTMLFiles("./testdata/template/raw.tmpl") - - router.GET("/raw", func(c *gin.Context) { - c.HTML(http.StatusOK, "raw.tmpl", gin.H{ - "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), - }) - }) - - router.Run(":8080") -} - -``` - -raw.tmpl - -```html -Date: {[{.now | formatAsDate}]} -``` - -Result: -``` -Date: 2017/07/01 -``` - -### Multitemplate - -Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`. - -### Redirects - -Issuing a HTTP redirect is easy. Both internal and external locations are supported. - -```go -r.GET("/test", func(c *gin.Context) { - c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") -}) -``` - -Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444) -```go -r.POST("/test", func(c *gin.Context) { - c.Redirect(http.StatusFound, "/foo") -}) -``` - -Issuing a Router redirect, use `HandleContext` like below. - -``` go -r.GET("/test", func(c *gin.Context) { - c.Request.URL.Path = "/test2" - r.HandleContext(c) -}) -r.GET("/test2", func(c *gin.Context) { - c.JSON(200, gin.H{"hello": "world"}) -}) -``` - - -### Custom Middleware - -```go -func Logger() gin.HandlerFunc { - return func(c *gin.Context) { - t := time.Now() - - // Set example variable - c.Set("example", "12345") - - // before request - - c.Next() - - // after request - latency := time.Since(t) - log.Print(latency) - - // access the status we are sending - status := c.Writer.Status() - log.Println(status) - } -} - -func main() { - r := gin.New() - r.Use(Logger()) - - r.GET("/test", func(c *gin.Context) { - example := c.MustGet("example").(string) - - // it would print: "12345" - log.Println(example) - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -### Using BasicAuth() middleware - -```go -// simulate some private data -var secrets = gin.H{ - "foo": gin.H{"email": "foo@bar.com", "phone": "123433"}, - "austin": gin.H{"email": "austin@example.com", "phone": "666"}, - "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"}, -} - -func main() { - r := gin.Default() - - // Group using gin.BasicAuth() middleware - // gin.Accounts is a shortcut for map[string]string - authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{ - "foo": "bar", - "austin": "1234", - "lena": "hello2", - "manu": "4321", - })) - - // /admin/secrets endpoint - // hit "localhost:8080/admin/secrets - authorized.GET("/secrets", func(c *gin.Context) { - // get user, it was set by the BasicAuth middleware - user := c.MustGet(gin.AuthUserKey).(string) - if secret, ok := secrets[user]; ok { - c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret}) - } else { - c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("}) - } - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -### Goroutines inside a middleware - -When starting new Goroutines inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy. - -```go -func main() { - r := gin.Default() - - r.GET("/long_async", func(c *gin.Context) { - // create copy to be used inside the goroutine - cCp := c.Copy() - go func() { - // simulate a long task with time.Sleep(). 5 seconds - time.Sleep(5 * time.Second) - - // note that you are using the copied context "cCp", IMPORTANT - log.Println("Done! in path " + cCp.Request.URL.Path) - }() - }) - - r.GET("/long_sync", func(c *gin.Context) { - // simulate a long task with time.Sleep(). 5 seconds - time.Sleep(5 * time.Second) - - // since we are NOT using a goroutine, we do not have to copy the context - log.Println("Done! in path " + c.Request.URL.Path) - }) - - // Listen and serve on 0.0.0.0:8080 - r.Run(":8080") -} -``` - -### Custom HTTP configuration - -Use `http.ListenAndServe()` directly, like this: - -```go -func main() { - router := gin.Default() - http.ListenAndServe(":8080", router) -} -``` -or - -```go -func main() { - router := gin.Default() - - s := &http.Server{ - Addr: ":8080", - Handler: router, - ReadTimeout: 10 * time.Second, - WriteTimeout: 10 * time.Second, - MaxHeaderBytes: 1 << 20, - } - s.ListenAndServe() -} -``` - -### Support Let's Encrypt - -example for 1-line LetsEncrypt HTTPS servers. - -```go -package main - -import ( - "log" - - "github.com/gin-gonic/autotls" - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - - // Ping handler - r.GET("/ping", func(c *gin.Context) { - c.String(200, "pong") - }) - - log.Fatal(autotls.Run(r, "example1.com", "example2.com")) -} -``` - -example for custom autocert manager. - -```go -package main - -import ( - "log" - - "github.com/gin-gonic/autotls" - "github.com/gin-gonic/gin" - "golang.org/x/crypto/acme/autocert" -) - -func main() { - r := gin.Default() - - // Ping handler - r.GET("/ping", func(c *gin.Context) { - c.String(200, "pong") - }) - - m := autocert.Manager{ - Prompt: autocert.AcceptTOS, - HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"), - Cache: autocert.DirCache("/var/www/.cache"), - } - - log.Fatal(autotls.RunWithManager(r, &m)) -} -``` - -### Run multiple service using Gin - -See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example: - -```go -package main - -import ( - "log" - "net/http" - "time" - - "github.com/gin-gonic/gin" - "golang.org/x/sync/errgroup" -) - -var ( - g errgroup.Group -) - -func router01() http.Handler { - e := gin.New() - e.Use(gin.Recovery()) - e.GET("/", func(c *gin.Context) { - c.JSON( - http.StatusOK, - gin.H{ - "code": http.StatusOK, - "error": "Welcome server 01", - }, - ) - }) - - return e -} - -func router02() http.Handler { - e := gin.New() - e.Use(gin.Recovery()) - e.GET("/", func(c *gin.Context) { - c.JSON( - http.StatusOK, - gin.H{ - "code": http.StatusOK, - "error": "Welcome server 02", - }, - ) - }) - - return e -} - -func main() { - server01 := &http.Server{ - Addr: ":8080", - Handler: router01(), - ReadTimeout: 5 * time.Second, - WriteTimeout: 10 * time.Second, - } - - server02 := &http.Server{ - Addr: ":8081", - Handler: router02(), - ReadTimeout: 5 * time.Second, - WriteTimeout: 10 * time.Second, - } - - g.Go(func() error { - err := server01.ListenAndServe() - if err != nil && err != http.ErrServerClosed { - log.Fatal(err) - } - return err - }) - - g.Go(func() error { - err := server02.ListenAndServe() - if err != nil && err != http.ErrServerClosed { - log.Fatal(err) - } - return err - }) - - if err := g.Wait(); err != nil { - log.Fatal(err) - } -} -``` - -### Graceful shutdown or restart - -There are a few approaches you can use to perform a graceful shutdown or restart. You can make use of third-party packages specifically built for that, or you can manually do the same with the functions and methods from the built-in packages. - -#### Third-party packages - -We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer to issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details. - -```go -router := gin.Default() -router.GET("/", handler) -// [...] -endless.ListenAndServe(":4242", router) -``` - -Alternatives: - -* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. -* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server. -* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers. - -#### Manually - -In case you are using Go 1.8 or a later version, you may not need to use those libraries. Consider using `http.Server`'s built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. The example below describes its usage, and we've got more examples using gin [here](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown). - -```go -// +build go1.8 - -package main - -import ( - "context" - "log" - "net/http" - "os" - "os/signal" - "syscall" - "time" - - "github.com/gin-gonic/gin" -) - -func main() { - router := gin.Default() - router.GET("/", func(c *gin.Context) { - time.Sleep(5 * time.Second) - c.String(http.StatusOK, "Welcome Gin Server") - }) - - srv := &http.Server{ - Addr: ":8080", - Handler: router, - } - - // Initializing the server in a goroutine so that - // it won't block the graceful shutdown handling below - go func() { - if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) { - log.Printf("listen: %s\n", err) - } - }() - - // Wait for interrupt signal to gracefully shutdown the server with - // a timeout of 5 seconds. - quit := make(chan os.Signal) - // kill (no param) default send syscall.SIGTERM - // kill -2 is syscall.SIGINT - // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it - signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) - <-quit - log.Println("Shutting down server...") - - // The context is used to inform the server it has 5 seconds to finish - // the request it is currently handling - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - if err := srv.Shutdown(ctx); err != nil { - log.Fatal("Server forced to shutdown:", err) - } - - log.Println("Server exiting") -} -``` - -### Build a single binary with templates - -You can build a server into a single binary containing templates by using [go-assets][]. - -[go-assets]: https://github.com/jessevdk/go-assets - -```go -func main() { - r := gin.New() - - t, err := loadTemplate() - if err != nil { - panic(err) - } - r.SetHTMLTemplate(t) - - r.GET("/", func(c *gin.Context) { - c.HTML(http.StatusOK, "/html/index.tmpl",nil) - }) - r.Run(":8080") -} - -// loadTemplate loads templates embedded by go-assets-builder -func loadTemplate() (*template.Template, error) { - t := template.New("") - for name, file := range Assets.Files { - defer file.Close() - if file.IsDir() || !strings.HasSuffix(name, ".tmpl") { - continue - } - h, err := ioutil.ReadAll(file) - if err != nil { - return nil, err - } - t, err = t.New(name).Parse(string(h)) - if err != nil { - return nil, err - } - } - return t, nil -} -``` - -See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary` directory. - -### Bind form-data request with custom struct - -The follow example using custom struct: - -```go -type StructA struct { - FieldA string `form:"field_a"` -} - -type StructB struct { - NestedStruct StructA - FieldB string `form:"field_b"` -} - -type StructC struct { - NestedStructPointer *StructA - FieldC string `form:"field_c"` -} - -type StructD struct { - NestedAnonyStruct struct { - FieldX string `form:"field_x"` - } - FieldD string `form:"field_d"` -} - -func GetDataB(c *gin.Context) { - var b StructB - c.Bind(&b) - c.JSON(200, gin.H{ - "a": b.NestedStruct, - "b": b.FieldB, - }) -} - -func GetDataC(c *gin.Context) { - var b StructC - c.Bind(&b) - c.JSON(200, gin.H{ - "a": b.NestedStructPointer, - "c": b.FieldC, - }) -} - -func GetDataD(c *gin.Context) { - var b StructD - c.Bind(&b) - c.JSON(200, gin.H{ - "x": b.NestedAnonyStruct, - "d": b.FieldD, - }) -} - -func main() { - r := gin.Default() - r.GET("/getb", GetDataB) - r.GET("/getc", GetDataC) - r.GET("/getd", GetDataD) - - r.Run() -} -``` - -Using the command `curl` command result: - -``` -$ curl "http://localhost:8080/getb?field_a=hello&field_b=world" -{"a":{"FieldA":"hello"},"b":"world"} -$ curl "http://localhost:8080/getc?field_a=hello&field_c=world" -{"a":{"FieldA":"hello"},"c":"world"} -$ curl "http://localhost:8080/getd?field_x=hello&field_d=world" -{"d":"world","x":{"FieldX":"hello"}} -``` - -### Try to bind body into different structs - -The normal methods for binding request body consumes `c.Request.Body` and they -cannot be called multiple times. - -```go -type formA struct { - Foo string `json:"foo" xml:"foo" binding:"required"` -} - -type formB struct { - Bar string `json:"bar" xml:"bar" binding:"required"` -} - -func SomeHandler(c *gin.Context) { - objA := formA{} - objB := formB{} - // This c.ShouldBind consumes c.Request.Body and it cannot be reused. - if errA := c.ShouldBind(&objA); errA == nil { - c.String(http.StatusOK, `the body should be formA`) - // Always an error is occurred by this because c.Request.Body is EOF now. - } else if errB := c.ShouldBind(&objB); errB == nil { - c.String(http.StatusOK, `the body should be formB`) - } else { - ... - } -} -``` - -For this, you can use `c.ShouldBindBodyWith`. - -```go -func SomeHandler(c *gin.Context) { - objA := formA{} - objB := formB{} - // This reads c.Request.Body and stores the result into the context. - if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil { - c.String(http.StatusOK, `the body should be formA`) - // At this time, it reuses body stored in the context. - } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { - c.String(http.StatusOK, `the body should be formB JSON`) - // And it can accepts other formats - } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil { - c.String(http.StatusOK, `the body should be formB XML`) - } else { - ... - } -} -``` - -* `c.ShouldBindBodyWith` stores body into the context before binding. This has -a slight impact to performance, so you should not use this method if you are -enough to call binding at once. -* This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`, -`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`, -can be called by `c.ShouldBind()` multiple times without any damage to -performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)). - -### http2 server push - -http.Pusher is supported only **go1.8+**. See the [golang blog](https://blog.golang.org/h2push) for detail information. - -```go -package main - -import ( - "html/template" - "log" - - "github.com/gin-gonic/gin" -) - -var html = template.Must(template.New("https").Parse(` - - - Https Test - - - -

Welcome, Ginner!

- - -`)) - -func main() { - r := gin.Default() - r.Static("/assets", "./assets") - r.SetHTMLTemplate(html) - - r.GET("/", func(c *gin.Context) { - if pusher := c.Writer.Pusher(); pusher != nil { - // use pusher.Push() to do server push - if err := pusher.Push("/assets/app.js", nil); err != nil { - log.Printf("Failed to push: %v", err) - } - } - c.HTML(200, "https", gin.H{ - "status": "success", - }) - }) - - // Listen and Server in https://127.0.0.1:8080 - r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key") -} -``` - -### Define format for the log of routes - -The default log of routes is: -``` -[GIN-debug] POST /foo --> main.main.func1 (3 handlers) -[GIN-debug] GET /bar --> main.main.func2 (3 handlers) -[GIN-debug] GET /status --> main.main.func3 (3 handlers) -``` - -If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`. -In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs. -```go -import ( - "log" - "net/http" - - "github.com/gin-gonic/gin" -) - -func main() { - r := gin.Default() - gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { - log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) - } - - r.POST("/foo", func(c *gin.Context) { - c.JSON(http.StatusOK, "foo") - }) - - r.GET("/bar", func(c *gin.Context) { - c.JSON(http.StatusOK, "bar") - }) - - r.GET("/status", func(c *gin.Context) { - c.JSON(http.StatusOK, "ok") - }) - - // Listen and Server in http://0.0.0.0:8080 - r.Run() -} -``` - -### Set and get a cookie - -```go -import ( - "fmt" - - "github.com/gin-gonic/gin" -) - -func main() { - - router := gin.Default() - - router.GET("/cookie", func(c *gin.Context) { - - cookie, err := c.Cookie("gin_cookie") - - if err != nil { - cookie = "NotSet" - c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) - } - - fmt.Printf("Cookie value: %s \n", cookie) - }) - - router.Run() -} -``` - -## Don't trust all proxies - -Gin lets you specify which headers to hold the real client IP (if any), -as well as specifying which proxies (or direct clients) you trust to -specify one of these headers. - -The `TrustedProxies` slice on your `gin.Engine` specifes network addresses or -network CIDRs from where clients which their request headers related to client -IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or -IPv6 CIDRs. - -```go -import ( - "fmt" - - "github.com/gin-gonic/gin" -) - -func main() { - - router := gin.Default() - router.TrustedProxies = []string{"192.168.1.2"} - - router.GET("/", func(c *gin.Context) { - // If the client is 192.168.1.2, use the X-Forwarded-For - // header to deduce the original client IP from the trust- - // worthy parts of that header. - // Otherwise, simply return the direct client IP - fmt.Printf("ClientIP: %s\n", c.ClientIP()) - }) - router.Run() -} -``` - -## Testing - -The `net/http/httptest` package is preferable way for HTTP testing. - -```go -package main - -func setupRouter() *gin.Engine { - r := gin.Default() - r.GET("/ping", func(c *gin.Context) { - c.String(200, "pong") - }) - return r -} - -func main() { - r := setupRouter() - r.Run(":8080") -} -``` - -Test for code example above: - -```go -package main - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestPingRoute(t *testing.T) { - router := setupRouter() - - w := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/ping", nil) - router.ServeHTTP(w, req) - - assert.Equal(t, 200, w.Code) - assert.Equal(t, "pong", w.Body.String()) -} -``` - -## Users - -Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework. - -* [gorush](https://github.com/appleboy/gorush): A push notification server written in Go. -* [fnproject](https://github.com/fnproject/fn): The container native, cloud agnostic serverless platform. -* [photoprism](https://github.com/photoprism/photoprism): Personal photo management powered by Go and Google TensorFlow. -* [krakend](https://github.com/devopsfaith/krakend): Ultra performant API Gateway with middlewares. -* [picfit](https://github.com/thoas/picfit): An image resizing server written in Go. -* [brigade](https://github.com/brigadecore/brigade): Event-based Scripting for Kubernetes. -* [dkron](https://github.com/distribworks/dkron): Distributed, fault tolerant job scheduling system. diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/auth.go b/taskman-server/vendor/github.com/gin-gonic/gin/auth.go deleted file mode 100644 index 4d8a6ce4..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/auth.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "crypto/subtle" - "encoding/base64" - "net/http" - "strconv" - - "github.com/gin-gonic/gin/internal/bytesconv" -) - -// AuthUserKey is the cookie name for user credential in basic auth. -const AuthUserKey = "user" - -// Accounts defines a key/value for user/pass list of authorized logins. -type Accounts map[string]string - -type authPair struct { - value string - user string -} - -type authPairs []authPair - -func (a authPairs) searchCredential(authValue string) (string, bool) { - if authValue == "" { - return "", false - } - for _, pair := range a { - if subtle.ConstantTimeCompare([]byte(pair.value), []byte(authValue)) == 1 { - return pair.user, true - } - } - return "", false -} - -// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where -// the key is the user name and the value is the password, as well as the name of the Realm. -// If the realm is empty, "Authorization Required" will be used by default. -// (see http://tools.ietf.org/html/rfc2617#section-1.2) -func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { - if realm == "" { - realm = "Authorization Required" - } - realm = "Basic realm=" + strconv.Quote(realm) - pairs := processAccounts(accounts) - return func(c *Context) { - // Search user in the slice of allowed credentials - user, found := pairs.searchCredential(c.requestHeader("Authorization")) - if !found { - // Credentials doesn't match, we return 401 and abort handlers chain. - c.Header("WWW-Authenticate", realm) - c.AbortWithStatus(http.StatusUnauthorized) - return - } - - // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using - // c.MustGet(gin.AuthUserKey). - c.Set(AuthUserKey, user) - } -} - -// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where -// the key is the user name and the value is the password. -func BasicAuth(accounts Accounts) HandlerFunc { - return BasicAuthForRealm(accounts, "") -} - -func processAccounts(accounts Accounts) authPairs { - length := len(accounts) - assert1(length > 0, "Empty list of authorized credentials") - pairs := make(authPairs, 0, length) - for user, password := range accounts { - assert1(user != "", "User can not be empty") - value := authorizationHeader(user, password) - pairs = append(pairs, authPair{ - value: value, - user: user, - }) - } - return pairs -} - -func authorizationHeader(user, password string) string { - base := user + ":" + password - return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base)) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding.go deleted file mode 100644 index 5caeb581..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -//go:build !nomsgpack -// +build !nomsgpack - -package binding - -import "net/http" - -// Content-Type MIME of the most common data formats. -const ( - MIMEJSON = "application/json" - MIMEHTML = "text/html" - MIMEXML = "application/xml" - MIMEXML2 = "text/xml" - MIMEPlain = "text/plain" - MIMEPOSTForm = "application/x-www-form-urlencoded" - MIMEMultipartPOSTForm = "multipart/form-data" - MIMEPROTOBUF = "application/x-protobuf" - MIMEMSGPACK = "application/x-msgpack" - MIMEMSGPACK2 = "application/msgpack" - MIMEYAML = "application/x-yaml" -) - -// Binding describes the interface which needs to be implemented for binding the -// data present in the request such as JSON request body, query parameters or -// the form POST. -type Binding interface { - Name() string - Bind(*http.Request, interface{}) error -} - -// BindingBody adds BindBody method to Binding. BindBody is similar with Bind, -// but it reads the body from supplied bytes instead of req.Body. -type BindingBody interface { - Binding - BindBody([]byte, interface{}) error -} - -// BindingUri adds BindUri method to Binding. BindUri is similar with Bind, -// but it read the Params. -type BindingUri interface { - Name() string - BindUri(map[string][]string, interface{}) error -} - -// StructValidator is the minimal interface which needs to be implemented in -// order for it to be used as the validator engine for ensuring the correctness -// of the request. Gin provides a default implementation for this using -// https://github.com/go-playground/validator/tree/v8.18.2. -type StructValidator interface { - // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. - // If the received type is a slice|array, the validation should be performed travel on every element. - // If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned. - // If the received type is a struct or pointer to a struct, the validation should be performed. - // If the struct is not valid or the validation itself fails, a descriptive error should be returned. - // Otherwise nil must be returned. - ValidateStruct(interface{}) error - - // Engine returns the underlying validator engine which powers the - // StructValidator implementation. - Engine() interface{} -} - -// Validator is the default validator which implements the StructValidator -// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2 -// under the hood. -var Validator StructValidator = &defaultValidator{} - -// These implement the Binding interface and can be used to bind the data -// present in the request to struct instances. -var ( - JSON = jsonBinding{} - XML = xmlBinding{} - Form = formBinding{} - Query = queryBinding{} - FormPost = formPostBinding{} - FormMultipart = formMultipartBinding{} - ProtoBuf = protobufBinding{} - MsgPack = msgpackBinding{} - YAML = yamlBinding{} - Uri = uriBinding{} - Header = headerBinding{} -) - -// Default returns the appropriate Binding instance based on the HTTP method -// and the content type. -func Default(method, contentType string) Binding { - if method == http.MethodGet { - return Form - } - - switch contentType { - case MIMEJSON: - return JSON - case MIMEXML, MIMEXML2: - return XML - case MIMEPROTOBUF: - return ProtoBuf - case MIMEMSGPACK, MIMEMSGPACK2: - return MsgPack - case MIMEYAML: - return YAML - case MIMEMultipartPOSTForm: - return FormMultipart - default: // case MIMEPOSTForm: - return Form - } -} - -func validate(obj interface{}) error { - if Validator == nil { - return nil - } - return Validator.ValidateStruct(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go deleted file mode 100644 index 9afa3dcf..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2020 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -//go:build nomsgpack -// +build nomsgpack - -package binding - -import "net/http" - -// Content-Type MIME of the most common data formats. -const ( - MIMEJSON = "application/json" - MIMEHTML = "text/html" - MIMEXML = "application/xml" - MIMEXML2 = "text/xml" - MIMEPlain = "text/plain" - MIMEPOSTForm = "application/x-www-form-urlencoded" - MIMEMultipartPOSTForm = "multipart/form-data" - MIMEPROTOBUF = "application/x-protobuf" - MIMEYAML = "application/x-yaml" -) - -// Binding describes the interface which needs to be implemented for binding the -// data present in the request such as JSON request body, query parameters or -// the form POST. -type Binding interface { - Name() string - Bind(*http.Request, interface{}) error -} - -// BindingBody adds BindBody method to Binding. BindBody is similar with Bind, -// but it reads the body from supplied bytes instead of req.Body. -type BindingBody interface { - Binding - BindBody([]byte, interface{}) error -} - -// BindingUri adds BindUri method to Binding. BindUri is similar with Bind, -// but it read the Params. -type BindingUri interface { - Name() string - BindUri(map[string][]string, interface{}) error -} - -// StructValidator is the minimal interface which needs to be implemented in -// order for it to be used as the validator engine for ensuring the correctness -// of the request. Gin provides a default implementation for this using -// https://github.com/go-playground/validator/tree/v8.18.2. -type StructValidator interface { - // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. - // If the received type is not a struct, any validation should be skipped and nil must be returned. - // If the received type is a struct or pointer to a struct, the validation should be performed. - // If the struct is not valid or the validation itself fails, a descriptive error should be returned. - // Otherwise nil must be returned. - ValidateStruct(interface{}) error - - // Engine returns the underlying validator engine which powers the - // StructValidator implementation. - Engine() interface{} -} - -// Validator is the default validator which implements the StructValidator -// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2 -// under the hood. -var Validator StructValidator = &defaultValidator{} - -// These implement the Binding interface and can be used to bind the data -// present in the request to struct instances. -var ( - JSON = jsonBinding{} - XML = xmlBinding{} - Form = formBinding{} - Query = queryBinding{} - FormPost = formPostBinding{} - FormMultipart = formMultipartBinding{} - ProtoBuf = protobufBinding{} - YAML = yamlBinding{} - Uri = uriBinding{} - Header = headerBinding{} -) - -// Default returns the appropriate Binding instance based on the HTTP method -// and the content type. -func Default(method, contentType string) Binding { - if method == "GET" { - return Form - } - - switch contentType { - case MIMEJSON: - return JSON - case MIMEXML, MIMEXML2: - return XML - case MIMEPROTOBUF: - return ProtoBuf - case MIMEYAML: - return YAML - case MIMEMultipartPOSTForm: - return FormMultipart - default: // case MIMEPOSTForm: - return Form - } -} - -func validate(obj interface{}) error { - if Validator == nil { - return nil - } - return Validator.ValidateStruct(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/default_validator.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/default_validator.go deleted file mode 100644 index c57a120f..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/default_validator.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "fmt" - "reflect" - "strings" - "sync" - - "github.com/go-playground/validator/v10" -) - -type defaultValidator struct { - once sync.Once - validate *validator.Validate -} - -type sliceValidateError []error - -func (err sliceValidateError) Error() string { - var errMsgs []string - for i, e := range err { - if e == nil { - continue - } - errMsgs = append(errMsgs, fmt.Sprintf("[%d]: %s", i, e.Error())) - } - return strings.Join(errMsgs, "\n") -} - -var _ StructValidator = &defaultValidator{} - -// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type. -func (v *defaultValidator) ValidateStruct(obj interface{}) error { - if obj == nil { - return nil - } - - value := reflect.ValueOf(obj) - switch value.Kind() { - case reflect.Ptr: - return v.ValidateStruct(value.Elem().Interface()) - case reflect.Struct: - return v.validateStruct(obj) - case reflect.Slice, reflect.Array: - count := value.Len() - validateRet := make(sliceValidateError, 0) - for i := 0; i < count; i++ { - if err := v.ValidateStruct(value.Index(i).Interface()); err != nil { - validateRet = append(validateRet, err) - } - } - if len(validateRet) == 0 { - return nil - } - return validateRet - default: - return nil - } -} - -// validateStruct receives struct type -func (v *defaultValidator) validateStruct(obj interface{}) error { - v.lazyinit() - return v.validate.Struct(obj) -} - -// Engine returns the underlying validator engine which powers the default -// Validator instance. This is useful if you want to register custom validations -// or struct level validations. See validator GoDoc for more info - -// https://godoc.org/gopkg.in/go-playground/validator.v8 -func (v *defaultValidator) Engine() interface{} { - v.lazyinit() - return v.validate -} - -func (v *defaultValidator) lazyinit() { - v.once.Do(func() { - v.validate = validator.New() - v.validate.SetTagName("binding") - }) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/form.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/form.go deleted file mode 100644 index b93c34cf..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/form.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "net/http" -) - -const defaultMemory = 32 << 20 - -type formBinding struct{} -type formPostBinding struct{} -type formMultipartBinding struct{} - -func (formBinding) Name() string { - return "form" -} - -func (formBinding) Bind(req *http.Request, obj interface{}) error { - if err := req.ParseForm(); err != nil { - return err - } - if err := req.ParseMultipartForm(defaultMemory); err != nil { - if err != http.ErrNotMultipart { - return err - } - } - if err := mapForm(obj, req.Form); err != nil { - return err - } - return validate(obj) -} - -func (formPostBinding) Name() string { - return "form-urlencoded" -} - -func (formPostBinding) Bind(req *http.Request, obj interface{}) error { - if err := req.ParseForm(); err != nil { - return err - } - if err := mapForm(obj, req.PostForm); err != nil { - return err - } - return validate(obj) -} - -func (formMultipartBinding) Name() string { - return "multipart/form-data" -} - -func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error { - if err := req.ParseMultipartForm(defaultMemory); err != nil { - return err - } - if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { - return err - } - - return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/form_mapping.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/form_mapping.go deleted file mode 100644 index 2f4e45b4..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/form_mapping.go +++ /dev/null @@ -1,392 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "time" - - "github.com/gin-gonic/gin/internal/bytesconv" - "github.com/gin-gonic/gin/internal/json" -) - -var errUnknownType = errors.New("unknown type") - -func mapUri(ptr interface{}, m map[string][]string) error { - return mapFormByTag(ptr, m, "uri") -} - -func mapForm(ptr interface{}, form map[string][]string) error { - return mapFormByTag(ptr, form, "form") -} - -var emptyField = reflect.StructField{} - -func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error { - // Check if ptr is a map - ptrVal := reflect.ValueOf(ptr) - var pointed interface{} - if ptrVal.Kind() == reflect.Ptr { - ptrVal = ptrVal.Elem() - pointed = ptrVal.Interface() - } - if ptrVal.Kind() == reflect.Map && - ptrVal.Type().Key().Kind() == reflect.String { - if pointed != nil { - ptr = pointed - } - return setFormMap(ptr, form) - } - - return mappingByPtr(ptr, formSource(form), tag) -} - -// setter tries to set value on a walking by fields of a struct -type setter interface { - TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSetted bool, err error) -} - -type formSource map[string][]string - -var _ setter = formSource(nil) - -// TrySet tries to set a value by request's form source (like map[string][]string) -func (form formSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) { - return setByForm(value, field, form, tagValue, opt) -} - -func mappingByPtr(ptr interface{}, setter setter, tag string) error { - _, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag) - return err -} - -func mapping(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) { - if field.Tag.Get(tag) == "-" { // just ignoring this field - return false, nil - } - - var vKind = value.Kind() - - if vKind == reflect.Ptr { - var isNew bool - vPtr := value - if value.IsNil() { - isNew = true - vPtr = reflect.New(value.Type().Elem()) - } - isSetted, err := mapping(vPtr.Elem(), field, setter, tag) - if err != nil { - return false, err - } - if isNew && isSetted { - value.Set(vPtr) - } - return isSetted, nil - } - - if vKind != reflect.Struct || !field.Anonymous { - ok, err := tryToSetValue(value, field, setter, tag) - if err != nil { - return false, err - } - if ok { - return true, nil - } - } - - if vKind == reflect.Struct { - tValue := value.Type() - - var isSetted bool - for i := 0; i < value.NumField(); i++ { - sf := tValue.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { // unexported - continue - } - ok, err := mapping(value.Field(i), tValue.Field(i), setter, tag) - if err != nil { - return false, err - } - isSetted = isSetted || ok - } - return isSetted, nil - } - return false, nil -} - -type setOptions struct { - isDefaultExists bool - defaultValue string -} - -func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) { - var tagValue string - var setOpt setOptions - - tagValue = field.Tag.Get(tag) - tagValue, opts := head(tagValue, ",") - - if tagValue == "" { // default value is FieldName - tagValue = field.Name - } - if tagValue == "" { // when field is "emptyField" variable - return false, nil - } - - var opt string - for len(opts) > 0 { - opt, opts = head(opts, ",") - - if k, v := head(opt, "="); k == "default" { - setOpt.isDefaultExists = true - setOpt.defaultValue = v - } - } - - return setter.TrySet(value, field, tagValue, setOpt) -} - -func setByForm(value reflect.Value, field reflect.StructField, form map[string][]string, tagValue string, opt setOptions) (isSetted bool, err error) { - vs, ok := form[tagValue] - if !ok && !opt.isDefaultExists { - return false, nil - } - - switch value.Kind() { - case reflect.Slice: - if !ok { - vs = []string{opt.defaultValue} - } - return true, setSlice(vs, value, field) - case reflect.Array: - if !ok { - vs = []string{opt.defaultValue} - } - if len(vs) != value.Len() { - return false, fmt.Errorf("%q is not valid value for %s", vs, value.Type().String()) - } - return true, setArray(vs, value, field) - default: - var val string - if !ok { - val = opt.defaultValue - } - - if len(vs) > 0 { - val = vs[0] - } - return true, setWithProperType(val, value, field) - } -} - -func setWithProperType(val string, value reflect.Value, field reflect.StructField) error { - switch value.Kind() { - case reflect.Int: - return setIntField(val, 0, value) - case reflect.Int8: - return setIntField(val, 8, value) - case reflect.Int16: - return setIntField(val, 16, value) - case reflect.Int32: - return setIntField(val, 32, value) - case reflect.Int64: - switch value.Interface().(type) { - case time.Duration: - return setTimeDuration(val, value, field) - } - return setIntField(val, 64, value) - case reflect.Uint: - return setUintField(val, 0, value) - case reflect.Uint8: - return setUintField(val, 8, value) - case reflect.Uint16: - return setUintField(val, 16, value) - case reflect.Uint32: - return setUintField(val, 32, value) - case reflect.Uint64: - return setUintField(val, 64, value) - case reflect.Bool: - return setBoolField(val, value) - case reflect.Float32: - return setFloatField(val, 32, value) - case reflect.Float64: - return setFloatField(val, 64, value) - case reflect.String: - value.SetString(val) - case reflect.Struct: - switch value.Interface().(type) { - case time.Time: - return setTimeField(val, field, value) - } - return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface()) - case reflect.Map: - return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface()) - default: - return errUnknownType - } - return nil -} - -func setIntField(val string, bitSize int, field reflect.Value) error { - if val == "" { - val = "0" - } - intVal, err := strconv.ParseInt(val, 10, bitSize) - if err == nil { - field.SetInt(intVal) - } - return err -} - -func setUintField(val string, bitSize int, field reflect.Value) error { - if val == "" { - val = "0" - } - uintVal, err := strconv.ParseUint(val, 10, bitSize) - if err == nil { - field.SetUint(uintVal) - } - return err -} - -func setBoolField(val string, field reflect.Value) error { - if val == "" { - val = "false" - } - boolVal, err := strconv.ParseBool(val) - if err == nil { - field.SetBool(boolVal) - } - return err -} - -func setFloatField(val string, bitSize int, field reflect.Value) error { - if val == "" { - val = "0.0" - } - floatVal, err := strconv.ParseFloat(val, bitSize) - if err == nil { - field.SetFloat(floatVal) - } - return err -} - -func setTimeField(val string, structField reflect.StructField, value reflect.Value) error { - timeFormat := structField.Tag.Get("time_format") - if timeFormat == "" { - timeFormat = time.RFC3339 - } - - switch tf := strings.ToLower(timeFormat); tf { - case "unix", "unixnano": - tv, err := strconv.ParseInt(val, 10, 64) - if err != nil { - return err - } - - d := time.Duration(1) - if tf == "unixnano" { - d = time.Second - } - - t := time.Unix(tv/int64(d), tv%int64(d)) - value.Set(reflect.ValueOf(t)) - return nil - - } - - if val == "" { - value.Set(reflect.ValueOf(time.Time{})) - return nil - } - - l := time.Local - if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC { - l = time.UTC - } - - if locTag := structField.Tag.Get("time_location"); locTag != "" { - loc, err := time.LoadLocation(locTag) - if err != nil { - return err - } - l = loc - } - - t, err := time.ParseInLocation(timeFormat, val, l) - if err != nil { - return err - } - - value.Set(reflect.ValueOf(t)) - return nil -} - -func setArray(vals []string, value reflect.Value, field reflect.StructField) error { - for i, s := range vals { - err := setWithProperType(s, value.Index(i), field) - if err != nil { - return err - } - } - return nil -} - -func setSlice(vals []string, value reflect.Value, field reflect.StructField) error { - slice := reflect.MakeSlice(value.Type(), len(vals), len(vals)) - err := setArray(vals, slice, field) - if err != nil { - return err - } - value.Set(slice) - return nil -} - -func setTimeDuration(val string, value reflect.Value, field reflect.StructField) error { - d, err := time.ParseDuration(val) - if err != nil { - return err - } - value.Set(reflect.ValueOf(d)) - return nil -} - -func head(str, sep string) (head string, tail string) { - idx := strings.Index(str, sep) - if idx < 0 { - return str, "" - } - return str[:idx], str[idx+len(sep):] -} - -func setFormMap(ptr interface{}, form map[string][]string) error { - el := reflect.TypeOf(ptr).Elem() - - if el.Kind() == reflect.Slice { - ptrMap, ok := ptr.(map[string][]string) - if !ok { - return errors.New("cannot convert to map slices of strings") - } - for k, v := range form { - ptrMap[k] = v - } - - return nil - } - - ptrMap, ok := ptr.(map[string]string) - if !ok { - return errors.New("cannot convert to map of strings") - } - for k, v := range form { - ptrMap[k] = v[len(v)-1] // pick last - } - - return nil -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/header.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/header.go deleted file mode 100644 index 179ce4ea..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/header.go +++ /dev/null @@ -1,34 +0,0 @@ -package binding - -import ( - "net/http" - "net/textproto" - "reflect" -) - -type headerBinding struct{} - -func (headerBinding) Name() string { - return "header" -} - -func (headerBinding) Bind(req *http.Request, obj interface{}) error { - - if err := mapHeader(obj, req.Header); err != nil { - return err - } - - return validate(obj) -} - -func mapHeader(ptr interface{}, h map[string][]string) error { - return mappingByPtr(ptr, headerSource(h), "header") -} - -type headerSource map[string][]string - -var _ setter = headerSource(nil) - -func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) { - return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/json.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/json.go deleted file mode 100644 index d62e0705..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/json.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "bytes" - "fmt" - "io" - "net/http" - - "github.com/gin-gonic/gin/internal/json" -) - -// EnableDecoderUseNumber is used to call the UseNumber method on the JSON -// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an -// interface{} as a Number instead of as a float64. -var EnableDecoderUseNumber = false - -// EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method -// on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to -// return an error when the destination is a struct and the input contains object -// keys which do not match any non-ignored, exported fields in the destination. -var EnableDecoderDisallowUnknownFields = false - -type jsonBinding struct{} - -func (jsonBinding) Name() string { - return "json" -} - -func (jsonBinding) Bind(req *http.Request, obj interface{}) error { - if req == nil || req.Body == nil { - return fmt.Errorf("invalid request") - } - return decodeJSON(req.Body, obj) -} - -func (jsonBinding) BindBody(body []byte, obj interface{}) error { - return decodeJSON(bytes.NewReader(body), obj) -} - -func decodeJSON(r io.Reader, obj interface{}) error { - decoder := json.NewDecoder(r) - if EnableDecoderUseNumber { - decoder.UseNumber() - } - if EnableDecoderDisallowUnknownFields { - decoder.DisallowUnknownFields() - } - if err := decoder.Decode(obj); err != nil { - return err - } - return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/msgpack.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/msgpack.go deleted file mode 100644 index 2a442996..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/msgpack.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -//go:build !nomsgpack -// +build !nomsgpack - -package binding - -import ( - "bytes" - "io" - "net/http" - - "github.com/ugorji/go/codec" -) - -type msgpackBinding struct{} - -func (msgpackBinding) Name() string { - return "msgpack" -} - -func (msgpackBinding) Bind(req *http.Request, obj interface{}) error { - return decodeMsgPack(req.Body, obj) -} - -func (msgpackBinding) BindBody(body []byte, obj interface{}) error { - return decodeMsgPack(bytes.NewReader(body), obj) -} - -func decodeMsgPack(r io.Reader, obj interface{}) error { - cdc := new(codec.MsgpackHandle) - if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil { - return err - } - return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go deleted file mode 100644 index f85a1aa6..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2019 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "errors" - "mime/multipart" - "net/http" - "reflect" -) - -type multipartRequest http.Request - -var _ setter = (*multipartRequest)(nil) - -// TrySet tries to set a value by the multipart request with the binding a form file -func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSetted bool, err error) { - if files := r.MultipartForm.File[key]; len(files) != 0 { - return setByMultipartFormFile(value, field, files) - } - - return setByForm(value, field, r.MultipartForm.Value, key, opt) -} - -func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSetted bool, err error) { - switch value.Kind() { - case reflect.Ptr: - switch value.Interface().(type) { - case *multipart.FileHeader: - value.Set(reflect.ValueOf(files[0])) - return true, nil - } - case reflect.Struct: - switch value.Interface().(type) { - case multipart.FileHeader: - value.Set(reflect.ValueOf(*files[0])) - return true, nil - } - case reflect.Slice: - slice := reflect.MakeSlice(value.Type(), len(files), len(files)) - isSetted, err = setArrayOfMultipartFormFiles(slice, field, files) - if err != nil || !isSetted { - return isSetted, err - } - value.Set(slice) - return true, nil - case reflect.Array: - return setArrayOfMultipartFormFiles(value, field, files) - } - return false, errors.New("unsupported field type for multipart.FileHeader") -} - -func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSetted bool, err error) { - if value.Len() != len(files) { - return false, errors.New("unsupported len of array for []*multipart.FileHeader") - } - for i := range files { - setted, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1]) - if err != nil || !setted { - return setted, err - } - } - return true, nil -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/protobuf.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/protobuf.go deleted file mode 100644 index f9ece928..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/protobuf.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "io/ioutil" - "net/http" - - "github.com/golang/protobuf/proto" -) - -type protobufBinding struct{} - -func (protobufBinding) Name() string { - return "protobuf" -} - -func (b protobufBinding) Bind(req *http.Request, obj interface{}) error { - buf, err := ioutil.ReadAll(req.Body) - if err != nil { - return err - } - return b.BindBody(buf, obj) -} - -func (protobufBinding) BindBody(body []byte, obj interface{}) error { - if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil { - return err - } - // Here it's same to return validate(obj), but util now we can't add - // `binding:""` to the struct which automatically generate by gen-proto - return nil - // return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/query.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/query.go deleted file mode 100644 index 219743f2..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/query.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import "net/http" - -type queryBinding struct{} - -func (queryBinding) Name() string { - return "query" -} - -func (queryBinding) Bind(req *http.Request, obj interface{}) error { - values := req.URL.Query() - if err := mapForm(obj, values); err != nil { - return err - } - return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/uri.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/uri.go deleted file mode 100644 index f91ec381..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/uri.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -type uriBinding struct{} - -func (uriBinding) Name() string { - return "uri" -} - -func (uriBinding) BindUri(m map[string][]string, obj interface{}) error { - if err := mapUri(obj, m); err != nil { - return err - } - return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/xml.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/xml.go deleted file mode 100644 index 4e901149..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/xml.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "bytes" - "encoding/xml" - "io" - "net/http" -) - -type xmlBinding struct{} - -func (xmlBinding) Name() string { - return "xml" -} - -func (xmlBinding) Bind(req *http.Request, obj interface{}) error { - return decodeXML(req.Body, obj) -} - -func (xmlBinding) BindBody(body []byte, obj interface{}) error { - return decodeXML(bytes.NewReader(body), obj) -} -func decodeXML(r io.Reader, obj interface{}) error { - decoder := xml.NewDecoder(r) - if err := decoder.Decode(obj); err != nil { - return err - } - return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/yaml.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/yaml.go deleted file mode 100644 index a2d36d6a..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/binding/yaml.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2018 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package binding - -import ( - "bytes" - "io" - "net/http" - - "gopkg.in/yaml.v2" -) - -type yamlBinding struct{} - -func (yamlBinding) Name() string { - return "yaml" -} - -func (yamlBinding) Bind(req *http.Request, obj interface{}) error { - return decodeYAML(req.Body, obj) -} - -func (yamlBinding) BindBody(body []byte, obj interface{}) error { - return decodeYAML(bytes.NewReader(body), obj) -} - -func decodeYAML(r io.Reader, obj interface{}) error { - decoder := yaml.NewDecoder(r) - if err := decoder.Decode(obj); err != nil { - return err - } - return validate(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/codecov.yml b/taskman-server/vendor/github.com/gin-gonic/gin/codecov.yml deleted file mode 100644 index c9c9a522..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/codecov.yml +++ /dev/null @@ -1,5 +0,0 @@ -coverage: - notify: - gitter: - default: - url: https://webhooks.gitter.im/e/d90dcdeeab2f1e357165 diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/context.go b/taskman-server/vendor/github.com/gin-gonic/gin/context.go deleted file mode 100644 index dc03c358..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/context.go +++ /dev/null @@ -1,1178 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "math" - "mime/multipart" - "net" - "net/http" - "net/url" - "os" - "strings" - "sync" - "time" - - "github.com/gin-contrib/sse" - "github.com/gin-gonic/gin/binding" - "github.com/gin-gonic/gin/render" -) - -// Content-Type MIME of the most common data formats. -const ( - MIMEJSON = binding.MIMEJSON - MIMEHTML = binding.MIMEHTML - MIMEXML = binding.MIMEXML - MIMEXML2 = binding.MIMEXML2 - MIMEPlain = binding.MIMEPlain - MIMEPOSTForm = binding.MIMEPOSTForm - MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm - MIMEYAML = binding.MIMEYAML -) - -// BodyBytesKey indicates a default body bytes key. -const BodyBytesKey = "_gin-gonic/gin/bodybyteskey" - -const abortIndex int8 = math.MaxInt8 / 2 - -// Context is the most important part of gin. It allows us to pass variables between middleware, -// manage the flow, validate the JSON of a request and render a JSON response for example. -type Context struct { - writermem responseWriter - Request *http.Request - Writer ResponseWriter - - Params Params - handlers HandlersChain - index int8 - fullPath string - - engine *Engine - params *Params - - // This mutex protect Keys map - mu sync.RWMutex - - // Keys is a key/value pair exclusively for the context of each request. - Keys map[string]interface{} - - // Errors is a list of errors attached to all the handlers/middlewares who used this context. - Errors errorMsgs - - // Accepted defines a list of manually accepted formats for content negotiation. - Accepted []string - - // queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query() - queryCache url.Values - - // formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH, - // or PUT body parameters. - formCache url.Values - - // SameSite allows a server to define a cookie attribute making it impossible for - // the browser to send this cookie along with cross-site requests. - sameSite http.SameSite -} - -/************************************/ -/********** CONTEXT CREATION ********/ -/************************************/ - -func (c *Context) reset() { - c.Writer = &c.writermem - c.Params = c.Params[0:0] - c.handlers = nil - c.index = -1 - - c.fullPath = "" - c.Keys = nil - c.Errors = c.Errors[0:0] - c.Accepted = nil - c.queryCache = nil - c.formCache = nil - *c.params = (*c.params)[0:0] -} - -// Copy returns a copy of the current context that can be safely used outside the request's scope. -// This has to be used when the context has to be passed to a goroutine. -func (c *Context) Copy() *Context { - cp := Context{ - writermem: c.writermem, - Request: c.Request, - Params: c.Params, - engine: c.engine, - } - cp.writermem.ResponseWriter = nil - cp.Writer = &cp.writermem - cp.index = abortIndex - cp.handlers = nil - cp.Keys = map[string]interface{}{} - for k, v := range c.Keys { - cp.Keys[k] = v - } - paramCopy := make([]Param, len(cp.Params)) - copy(paramCopy, cp.Params) - cp.Params = paramCopy - return &cp -} - -// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", -// this function will return "main.handleGetUsers". -func (c *Context) HandlerName() string { - return nameOfFunction(c.handlers.Last()) -} - -// HandlerNames returns a list of all registered handlers for this context in descending order, -// following the semantics of HandlerName() -func (c *Context) HandlerNames() []string { - hn := make([]string, 0, len(c.handlers)) - for _, val := range c.handlers { - hn = append(hn, nameOfFunction(val)) - } - return hn -} - -// Handler returns the main handler. -func (c *Context) Handler() HandlerFunc { - return c.handlers.Last() -} - -// FullPath returns a matched route full path. For not found routes -// returns an empty string. -// router.GET("/user/:id", func(c *gin.Context) { -// c.FullPath() == "/user/:id" // true -// }) -func (c *Context) FullPath() string { - return c.fullPath -} - -/************************************/ -/*********** FLOW CONTROL ***********/ -/************************************/ - -// Next should be used only inside middleware. -// It executes the pending handlers in the chain inside the calling handler. -// See example in GitHub. -func (c *Context) Next() { - c.index++ - for c.index < int8(len(c.handlers)) { - c.handlers[c.index](c) - c.index++ - } -} - -// IsAborted returns true if the current context was aborted. -func (c *Context) IsAborted() bool { - return c.index >= abortIndex -} - -// Abort prevents pending handlers from being called. Note that this will not stop the current handler. -// Let's say you have an authorization middleware that validates that the current request is authorized. -// If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers -// for this request are not called. -func (c *Context) Abort() { - c.index = abortIndex -} - -// AbortWithStatus calls `Abort()` and writes the headers with the specified status code. -// For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401). -func (c *Context) AbortWithStatus(code int) { - c.Status(code) - c.Writer.WriteHeaderNow() - c.Abort() -} - -// AbortWithStatusJSON calls `Abort()` and then `JSON` internally. -// This method stops the chain, writes the status code and return a JSON body. -// It also sets the Content-Type as "application/json". -func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) { - c.Abort() - c.JSON(code, jsonObj) -} - -// AbortWithError calls `AbortWithStatus()` and `Error()` internally. -// This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. -// See Context.Error() for more details. -func (c *Context) AbortWithError(code int, err error) *Error { - c.AbortWithStatus(code) - return c.Error(err) -} - -/************************************/ -/********* ERROR MANAGEMENT *********/ -/************************************/ - -// Error attaches an error to the current context. The error is pushed to a list of errors. -// It's a good idea to call Error for each error that occurred during the resolution of a request. -// A middleware can be used to collect all the errors and push them to a database together, -// print a log, or append it in the HTTP response. -// Error will panic if err is nil. -func (c *Context) Error(err error) *Error { - if err == nil { - panic("err is nil") - } - - parsedError, ok := err.(*Error) - if !ok { - parsedError = &Error{ - Err: err, - Type: ErrorTypePrivate, - } - } - - c.Errors = append(c.Errors, parsedError) - return parsedError -} - -/************************************/ -/******** METADATA MANAGEMENT********/ -/************************************/ - -// Set is used to store a new key/value pair exclusively for this context. -// It also lazy initializes c.Keys if it was not used previously. -func (c *Context) Set(key string, value interface{}) { - c.mu.Lock() - if c.Keys == nil { - c.Keys = make(map[string]interface{}) - } - - c.Keys[key] = value - c.mu.Unlock() -} - -// Get returns the value for the given key, ie: (value, true). -// If the value does not exists it returns (nil, false) -func (c *Context) Get(key string) (value interface{}, exists bool) { - c.mu.RLock() - value, exists = c.Keys[key] - c.mu.RUnlock() - return -} - -// MustGet returns the value for the given key if it exists, otherwise it panics. -func (c *Context) MustGet(key string) interface{} { - if value, exists := c.Get(key); exists { - return value - } - panic("Key \"" + key + "\" does not exist") -} - -// GetString returns the value associated with the key as a string. -func (c *Context) GetString(key string) (s string) { - if val, ok := c.Get(key); ok && val != nil { - s, _ = val.(string) - } - return -} - -// GetBool returns the value associated with the key as a boolean. -func (c *Context) GetBool(key string) (b bool) { - if val, ok := c.Get(key); ok && val != nil { - b, _ = val.(bool) - } - return -} - -// GetInt returns the value associated with the key as an integer. -func (c *Context) GetInt(key string) (i int) { - if val, ok := c.Get(key); ok && val != nil { - i, _ = val.(int) - } - return -} - -// GetInt64 returns the value associated with the key as an integer. -func (c *Context) GetInt64(key string) (i64 int64) { - if val, ok := c.Get(key); ok && val != nil { - i64, _ = val.(int64) - } - return -} - -// GetUint returns the value associated with the key as an unsigned integer. -func (c *Context) GetUint(key string) (ui uint) { - if val, ok := c.Get(key); ok && val != nil { - ui, _ = val.(uint) - } - return -} - -// GetUint64 returns the value associated with the key as an unsigned integer. -func (c *Context) GetUint64(key string) (ui64 uint64) { - if val, ok := c.Get(key); ok && val != nil { - ui64, _ = val.(uint64) - } - return -} - -// GetFloat64 returns the value associated with the key as a float64. -func (c *Context) GetFloat64(key string) (f64 float64) { - if val, ok := c.Get(key); ok && val != nil { - f64, _ = val.(float64) - } - return -} - -// GetTime returns the value associated with the key as time. -func (c *Context) GetTime(key string) (t time.Time) { - if val, ok := c.Get(key); ok && val != nil { - t, _ = val.(time.Time) - } - return -} - -// GetDuration returns the value associated with the key as a duration. -func (c *Context) GetDuration(key string) (d time.Duration) { - if val, ok := c.Get(key); ok && val != nil { - d, _ = val.(time.Duration) - } - return -} - -// GetStringSlice returns the value associated with the key as a slice of strings. -func (c *Context) GetStringSlice(key string) (ss []string) { - if val, ok := c.Get(key); ok && val != nil { - ss, _ = val.([]string) - } - return -} - -// GetStringMap returns the value associated with the key as a map of interfaces. -func (c *Context) GetStringMap(key string) (sm map[string]interface{}) { - if val, ok := c.Get(key); ok && val != nil { - sm, _ = val.(map[string]interface{}) - } - return -} - -// GetStringMapString returns the value associated with the key as a map of strings. -func (c *Context) GetStringMapString(key string) (sms map[string]string) { - if val, ok := c.Get(key); ok && val != nil { - sms, _ = val.(map[string]string) - } - return -} - -// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. -func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) { - if val, ok := c.Get(key); ok && val != nil { - smss, _ = val.(map[string][]string) - } - return -} - -/************************************/ -/************ INPUT DATA ************/ -/************************************/ - -// Param returns the value of the URL param. -// It is a shortcut for c.Params.ByName(key) -// router.GET("/user/:id", func(c *gin.Context) { -// // a GET request to /user/john -// id := c.Param("id") // id == "john" -// }) -func (c *Context) Param(key string) string { - return c.Params.ByName(key) -} - -// Query returns the keyed url query value if it exists, -// otherwise it returns an empty string `("")`. -// It is shortcut for `c.Request.URL.Query().Get(key)` -// GET /path?id=1234&name=Manu&value= -// c.Query("id") == "1234" -// c.Query("name") == "Manu" -// c.Query("value") == "" -// c.Query("wtf") == "" -func (c *Context) Query(key string) string { - value, _ := c.GetQuery(key) - return value -} - -// DefaultQuery returns the keyed url query value if it exists, -// otherwise it returns the specified defaultValue string. -// See: Query() and GetQuery() for further information. -// GET /?name=Manu&lastname= -// c.DefaultQuery("name", "unknown") == "Manu" -// c.DefaultQuery("id", "none") == "none" -// c.DefaultQuery("lastname", "none") == "" -func (c *Context) DefaultQuery(key, defaultValue string) string { - if value, ok := c.GetQuery(key); ok { - return value - } - return defaultValue -} - -// GetQuery is like Query(), it returns the keyed url query value -// if it exists `(value, true)` (even when the value is an empty string), -// otherwise it returns `("", false)`. -// It is shortcut for `c.Request.URL.Query().Get(key)` -// GET /?name=Manu&lastname= -// ("Manu", true) == c.GetQuery("name") -// ("", false) == c.GetQuery("id") -// ("", true) == c.GetQuery("lastname") -func (c *Context) GetQuery(key string) (string, bool) { - if values, ok := c.GetQueryArray(key); ok { - return values[0], ok - } - return "", false -} - -// QueryArray returns a slice of strings for a given query key. -// The length of the slice depends on the number of params with the given key. -func (c *Context) QueryArray(key string) []string { - values, _ := c.GetQueryArray(key) - return values -} - -func (c *Context) initQueryCache() { - if c.queryCache == nil { - if c.Request != nil { - c.queryCache = c.Request.URL.Query() - } else { - c.queryCache = url.Values{} - } - } -} - -// GetQueryArray returns a slice of strings for a given query key, plus -// a boolean value whether at least one value exists for the given key. -func (c *Context) GetQueryArray(key string) ([]string, bool) { - c.initQueryCache() - if values, ok := c.queryCache[key]; ok && len(values) > 0 { - return values, true - } - return []string{}, false -} - -// QueryMap returns a map for a given query key. -func (c *Context) QueryMap(key string) map[string]string { - dicts, _ := c.GetQueryMap(key) - return dicts -} - -// GetQueryMap returns a map for a given query key, plus a boolean value -// whether at least one value exists for the given key. -func (c *Context) GetQueryMap(key string) (map[string]string, bool) { - c.initQueryCache() - return c.get(c.queryCache, key) -} - -// PostForm returns the specified key from a POST urlencoded form or multipart form -// when it exists, otherwise it returns an empty string `("")`. -func (c *Context) PostForm(key string) string { - value, _ := c.GetPostForm(key) - return value -} - -// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form -// when it exists, otherwise it returns the specified defaultValue string. -// See: PostForm() and GetPostForm() for further information. -func (c *Context) DefaultPostForm(key, defaultValue string) string { - if value, ok := c.GetPostForm(key); ok { - return value - } - return defaultValue -} - -// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded -// form or multipart form when it exists `(value, true)` (even when the value is an empty string), -// otherwise it returns ("", false). -// For example, during a PATCH request to update the user's email: -// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" -// email= --> ("", true) := GetPostForm("email") // set email to "" -// --> ("", false) := GetPostForm("email") // do nothing with email -func (c *Context) GetPostForm(key string) (string, bool) { - if values, ok := c.GetPostFormArray(key); ok { - return values[0], ok - } - return "", false -} - -// PostFormArray returns a slice of strings for a given form key. -// The length of the slice depends on the number of params with the given key. -func (c *Context) PostFormArray(key string) []string { - values, _ := c.GetPostFormArray(key) - return values -} - -func (c *Context) initFormCache() { - if c.formCache == nil { - c.formCache = make(url.Values) - req := c.Request - if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { - if err != http.ErrNotMultipart { - debugPrint("error on parse multipart form array: %v", err) - } - } - c.formCache = req.PostForm - } -} - -// GetPostFormArray returns a slice of strings for a given form key, plus -// a boolean value whether at least one value exists for the given key. -func (c *Context) GetPostFormArray(key string) ([]string, bool) { - c.initFormCache() - if values := c.formCache[key]; len(values) > 0 { - return values, true - } - return []string{}, false -} - -// PostFormMap returns a map for a given form key. -func (c *Context) PostFormMap(key string) map[string]string { - dicts, _ := c.GetPostFormMap(key) - return dicts -} - -// GetPostFormMap returns a map for a given form key, plus a boolean value -// whether at least one value exists for the given key. -func (c *Context) GetPostFormMap(key string) (map[string]string, bool) { - c.initFormCache() - return c.get(c.formCache, key) -} - -// get is an internal method and returns a map which satisfy conditions. -func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) { - dicts := make(map[string]string) - exist := false - for k, v := range m { - if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key { - if j := strings.IndexByte(k[i+1:], ']'); j >= 1 { - exist = true - dicts[k[i+1:][:j]] = v[0] - } - } - } - return dicts, exist -} - -// FormFile returns the first file for the provided form key. -func (c *Context) FormFile(name string) (*multipart.FileHeader, error) { - if c.Request.MultipartForm == nil { - if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { - return nil, err - } - } - f, fh, err := c.Request.FormFile(name) - if err != nil { - return nil, err - } - f.Close() - return fh, err -} - -// MultipartForm is the parsed multipart form, including file uploads. -func (c *Context) MultipartForm() (*multipart.Form, error) { - err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory) - return c.Request.MultipartForm, err -} - -// SaveUploadedFile uploads the form file to specific dst. -func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error { - src, err := file.Open() - if err != nil { - return err - } - defer src.Close() - - out, err := os.Create(dst) - if err != nil { - return err - } - defer out.Close() - - _, err = io.Copy(out, src) - return err -} - -// Bind checks the Content-Type to select a binding engine automatically, -// Depending the "Content-Type" header different bindings are used: -// "application/json" --> JSON binding -// "application/xml" --> XML binding -// otherwise --> returns an error. -// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. -// It decodes the json payload into the struct specified as a pointer. -// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid. -func (c *Context) Bind(obj interface{}) error { - b := binding.Default(c.Request.Method, c.ContentType()) - return c.MustBindWith(obj, b) -} - -// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON). -func (c *Context) BindJSON(obj interface{}) error { - return c.MustBindWith(obj, binding.JSON) -} - -// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML). -func (c *Context) BindXML(obj interface{}) error { - return c.MustBindWith(obj, binding.XML) -} - -// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query). -func (c *Context) BindQuery(obj interface{}) error { - return c.MustBindWith(obj, binding.Query) -} - -// BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML). -func (c *Context) BindYAML(obj interface{}) error { - return c.MustBindWith(obj, binding.YAML) -} - -// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header). -func (c *Context) BindHeader(obj interface{}) error { - return c.MustBindWith(obj, binding.Header) -} - -// BindUri binds the passed struct pointer using binding.Uri. -// It will abort the request with HTTP 400 if any error occurs. -func (c *Context) BindUri(obj interface{}) error { - if err := c.ShouldBindUri(obj); err != nil { - c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck - return err - } - return nil -} - -// MustBindWith binds the passed struct pointer using the specified binding engine. -// It will abort the request with HTTP 400 if any error occurs. -// See the binding package. -func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error { - if err := c.ShouldBindWith(obj, b); err != nil { - c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck - return err - } - return nil -} - -// ShouldBind checks the Content-Type to select a binding engine automatically, -// Depending the "Content-Type" header different bindings are used: -// "application/json" --> JSON binding -// "application/xml" --> XML binding -// otherwise --> returns an error -// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. -// It decodes the json payload into the struct specified as a pointer. -// Like c.Bind() but this method does not set the response status code to 400 and abort if the json is not valid. -func (c *Context) ShouldBind(obj interface{}) error { - b := binding.Default(c.Request.Method, c.ContentType()) - return c.ShouldBindWith(obj, b) -} - -// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON). -func (c *Context) ShouldBindJSON(obj interface{}) error { - return c.ShouldBindWith(obj, binding.JSON) -} - -// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML). -func (c *Context) ShouldBindXML(obj interface{}) error { - return c.ShouldBindWith(obj, binding.XML) -} - -// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query). -func (c *Context) ShouldBindQuery(obj interface{}) error { - return c.ShouldBindWith(obj, binding.Query) -} - -// ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML). -func (c *Context) ShouldBindYAML(obj interface{}) error { - return c.ShouldBindWith(obj, binding.YAML) -} - -// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header). -func (c *Context) ShouldBindHeader(obj interface{}) error { - return c.ShouldBindWith(obj, binding.Header) -} - -// ShouldBindUri binds the passed struct pointer using the specified binding engine. -func (c *Context) ShouldBindUri(obj interface{}) error { - m := make(map[string][]string) - for _, v := range c.Params { - m[v.Key] = []string{v.Value} - } - return binding.Uri.BindUri(m, obj) -} - -// ShouldBindWith binds the passed struct pointer using the specified binding engine. -// See the binding package. -func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error { - return b.Bind(c.Request, obj) -} - -// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request -// body into the context, and reuse when it is called again. -// -// NOTE: This method reads the body before binding. So you should use -// ShouldBindWith for better performance if you need to call only once. -func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) { - var body []byte - if cb, ok := c.Get(BodyBytesKey); ok { - if cbb, ok := cb.([]byte); ok { - body = cbb - } - } - if body == nil { - body, err = ioutil.ReadAll(c.Request.Body) - if err != nil { - return err - } - c.Set(BodyBytesKey, body) - } - return bb.BindBody(body, obj) -} - -// ClientIP implements a best effort algorithm to return the real client IP. -// It called c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. -// If it's it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]). -// If the headers are nots syntactically valid OR the remote IP does not correspong to a trusted proxy, -// the remote IP (coming form Request.RemoteAddr) is returned. -func (c *Context) ClientIP() string { - if c.engine.AppEngine { - if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" { - return addr - } - } - - remoteIP, trusted := c.RemoteIP() - if remoteIP == nil { - return "" - } - - if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil { - for _, headerName := range c.engine.RemoteIPHeaders { - ip, valid := validateHeader(c.requestHeader(headerName)) - if valid { - return ip - } - } - } - return remoteIP.String() -} - -// RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). -// It also checks if the remoteIP is a trusted proxy or not. -// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks -// defined in Engine.TrustedProxies -func (c *Context) RemoteIP() (net.IP, bool) { - ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)) - if err != nil { - return nil, false - } - remoteIP := net.ParseIP(ip) - if remoteIP == nil { - return nil, false - } - - if c.engine.trustedCIDRs != nil { - for _, cidr := range c.engine.trustedCIDRs { - if cidr.Contains(remoteIP) { - return remoteIP, true - } - } - } - - return remoteIP, false -} - -func validateHeader(header string) (clientIP string, valid bool) { - if header == "" { - return "", false - } - items := strings.Split(header, ",") - for i, ipStr := range items { - ipStr = strings.TrimSpace(ipStr) - ip := net.ParseIP(ipStr) - if ip == nil { - return "", false - } - - // We need to return the first IP in the list, but, - // we should not early return since we need to validate that - // the rest of the header is syntactically valid - if i == 0 { - clientIP = ipStr - valid = true - } - } - return -} - -// ContentType returns the Content-Type header of the request. -func (c *Context) ContentType() string { - return filterFlags(c.requestHeader("Content-Type")) -} - -// IsWebsocket returns true if the request headers indicate that a websocket -// handshake is being initiated by the client. -func (c *Context) IsWebsocket() bool { - if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") && - strings.EqualFold(c.requestHeader("Upgrade"), "websocket") { - return true - } - return false -} - -func (c *Context) requestHeader(key string) string { - return c.Request.Header.Get(key) -} - -/************************************/ -/******** RESPONSE RENDERING ********/ -/************************************/ - -// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function. -func bodyAllowedForStatus(status int) bool { - switch { - case status >= 100 && status <= 199: - return false - case status == http.StatusNoContent: - return false - case status == http.StatusNotModified: - return false - } - return true -} - -// Status sets the HTTP response code. -func (c *Context) Status(code int) { - c.Writer.WriteHeader(code) -} - -// Header is a intelligent shortcut for c.Writer.Header().Set(key, value). -// It writes a header in the response. -// If value == "", this method removes the header `c.Writer.Header().Del(key)` -func (c *Context) Header(key, value string) { - if value == "" { - c.Writer.Header().Del(key) - return - } - c.Writer.Header().Set(key, value) -} - -// GetHeader returns value from request headers. -func (c *Context) GetHeader(key string) string { - return c.requestHeader(key) -} - -// GetRawData return stream data. -func (c *Context) GetRawData() ([]byte, error) { - return ioutil.ReadAll(c.Request.Body) -} - -// SetSameSite with cookie -func (c *Context) SetSameSite(samesite http.SameSite) { - c.sameSite = samesite -} - -// SetCookie adds a Set-Cookie header to the ResponseWriter's headers. -// The provided cookie must have a valid Name. Invalid cookies may be -// silently dropped. -func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) { - if path == "" { - path = "/" - } - http.SetCookie(c.Writer, &http.Cookie{ - Name: name, - Value: url.QueryEscape(value), - MaxAge: maxAge, - Path: path, - Domain: domain, - SameSite: c.sameSite, - Secure: secure, - HttpOnly: httpOnly, - }) -} - -// Cookie returns the named cookie provided in the request or -// ErrNoCookie if not found. And return the named cookie is unescaped. -// If multiple cookies match the given name, only one cookie will -// be returned. -func (c *Context) Cookie(name string) (string, error) { - cookie, err := c.Request.Cookie(name) - if err != nil { - return "", err - } - val, _ := url.QueryUnescape(cookie.Value) - return val, nil -} - -// Render writes the response headers and calls render.Render to render data. -func (c *Context) Render(code int, r render.Render) { - c.Status(code) - - if !bodyAllowedForStatus(code) { - r.WriteContentType(c.Writer) - c.Writer.WriteHeaderNow() - return - } - - if err := r.Render(c.Writer); err != nil { - panic(err) - } -} - -// HTML renders the HTTP template specified by its file name. -// It also updates the HTTP code and sets the Content-Type as "text/html". -// See http://golang.org/doc/articles/wiki/ -func (c *Context) HTML(code int, name string, obj interface{}) { - instance := c.engine.HTMLRender.Instance(name, obj) - c.Render(code, instance) -} - -// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. -// It also sets the Content-Type as "application/json". -// WARNING: we recommend to use this only for development purposes since printing pretty JSON is -// more CPU and bandwidth consuming. Use Context.JSON() instead. -func (c *Context) IndentedJSON(code int, obj interface{}) { - c.Render(code, render.IndentedJSON{Data: obj}) -} - -// SecureJSON serializes the given struct as Secure JSON into the response body. -// Default prepends "while(1)," to response body if the given struct is array values. -// It also sets the Content-Type as "application/json". -func (c *Context) SecureJSON(code int, obj interface{}) { - c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj}) -} - -// JSONP serializes the given struct as JSON into the response body. -// It adds padding to response body to request data from a server residing in a different domain than the client. -// It also sets the Content-Type as "application/javascript". -func (c *Context) JSONP(code int, obj interface{}) { - callback := c.DefaultQuery("callback", "") - if callback == "" { - c.Render(code, render.JSON{Data: obj}) - return - } - c.Render(code, render.JsonpJSON{Callback: callback, Data: obj}) -} - -// JSON serializes the given struct as JSON into the response body. -// It also sets the Content-Type as "application/json". -func (c *Context) JSON(code int, obj interface{}) { - c.Render(code, render.JSON{Data: obj}) -} - -// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string. -// It also sets the Content-Type as "application/json". -func (c *Context) AsciiJSON(code int, obj interface{}) { - c.Render(code, render.AsciiJSON{Data: obj}) -} - -// PureJSON serializes the given struct as JSON into the response body. -// PureJSON, unlike JSON, does not replace special html characters with their unicode entities. -func (c *Context) PureJSON(code int, obj interface{}) { - c.Render(code, render.PureJSON{Data: obj}) -} - -// XML serializes the given struct as XML into the response body. -// It also sets the Content-Type as "application/xml". -func (c *Context) XML(code int, obj interface{}) { - c.Render(code, render.XML{Data: obj}) -} - -// YAML serializes the given struct as YAML into the response body. -func (c *Context) YAML(code int, obj interface{}) { - c.Render(code, render.YAML{Data: obj}) -} - -// ProtoBuf serializes the given struct as ProtoBuf into the response body. -func (c *Context) ProtoBuf(code int, obj interface{}) { - c.Render(code, render.ProtoBuf{Data: obj}) -} - -// String writes the given string into the response body. -func (c *Context) String(code int, format string, values ...interface{}) { - c.Render(code, render.String{Format: format, Data: values}) -} - -// Redirect returns a HTTP redirect to the specific location. -func (c *Context) Redirect(code int, location string) { - c.Render(-1, render.Redirect{ - Code: code, - Location: location, - Request: c.Request, - }) -} - -// Data writes some data into the body stream and updates the HTTP code. -func (c *Context) Data(code int, contentType string, data []byte) { - c.Render(code, render.Data{ - ContentType: contentType, - Data: data, - }) -} - -// DataFromReader writes the specified reader into the body stream and updates the HTTP code. -func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) { - c.Render(code, render.Reader{ - Headers: extraHeaders, - ContentType: contentType, - ContentLength: contentLength, - Reader: reader, - }) -} - -// File writes the specified file into the body stream in an efficient way. -func (c *Context) File(filepath string) { - http.ServeFile(c.Writer, c.Request, filepath) -} - -// FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way. -func (c *Context) FileFromFS(filepath string, fs http.FileSystem) { - defer func(old string) { - c.Request.URL.Path = old - }(c.Request.URL.Path) - - c.Request.URL.Path = filepath - - http.FileServer(fs).ServeHTTP(c.Writer, c.Request) -} - -// FileAttachment writes the specified file into the body stream in an efficient way -// On the client side, the file will typically be downloaded with the given filename -func (c *Context) FileAttachment(filepath, filename string) { - c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename)) - http.ServeFile(c.Writer, c.Request, filepath) -} - -// SSEvent writes a Server-Sent Event into the body stream. -func (c *Context) SSEvent(name string, message interface{}) { - c.Render(-1, sse.Event{ - Event: name, - Data: message, - }) -} - -// Stream sends a streaming response and returns a boolean -// indicates "Is client disconnected in middle of stream" -func (c *Context) Stream(step func(w io.Writer) bool) bool { - w := c.Writer - clientGone := w.CloseNotify() - for { - select { - case <-clientGone: - return true - default: - keepOpen := step(w) - w.Flush() - if !keepOpen { - return false - } - } - } -} - -/************************************/ -/******** CONTENT NEGOTIATION *******/ -/************************************/ - -// Negotiate contains all negotiations data. -type Negotiate struct { - Offered []string - HTMLName string - HTMLData interface{} - JSONData interface{} - XMLData interface{} - YAMLData interface{} - Data interface{} -} - -// Negotiate calls different Render according acceptable Accept format. -func (c *Context) Negotiate(code int, config Negotiate) { - switch c.NegotiateFormat(config.Offered...) { - case binding.MIMEJSON: - data := chooseData(config.JSONData, config.Data) - c.JSON(code, data) - - case binding.MIMEHTML: - data := chooseData(config.HTMLData, config.Data) - c.HTML(code, config.HTMLName, data) - - case binding.MIMEXML: - data := chooseData(config.XMLData, config.Data) - c.XML(code, data) - - case binding.MIMEYAML: - data := chooseData(config.YAMLData, config.Data) - c.YAML(code, data) - - default: - c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck - } -} - -// NegotiateFormat returns an acceptable Accept format. -func (c *Context) NegotiateFormat(offered ...string) string { - assert1(len(offered) > 0, "you must provide at least one offer") - - if c.Accepted == nil { - c.Accepted = parseAccept(c.requestHeader("Accept")) - } - if len(c.Accepted) == 0 { - return offered[0] - } - for _, accepted := range c.Accepted { - for _, offer := range offered { - // According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers, - // therefore we can just iterate over the string without casting it into []rune - i := 0 - for ; i < len(accepted); i++ { - if accepted[i] == '*' || offer[i] == '*' { - return offer - } - if accepted[i] != offer[i] { - break - } - } - if i == len(accepted) { - return offer - } - } - } - return "" -} - -// SetAccepted sets Accept header data. -func (c *Context) SetAccepted(formats ...string) { - c.Accepted = formats -} - -/************************************/ -/***** GOLANG.ORG/X/NET/CONTEXT *****/ -/************************************/ - -// Deadline always returns that there is no deadline (ok==false), -// maybe you want to use Request.Context().Deadline() instead. -func (c *Context) Deadline() (deadline time.Time, ok bool) { - return -} - -// Done always returns nil (chan which will wait forever), -// if you want to abort your work when the connection was closed -// you should use Request.Context().Done() instead. -func (c *Context) Done() <-chan struct{} { - return nil -} - -// Err always returns nil, maybe you want to use Request.Context().Err() instead. -func (c *Context) Err() error { - return nil -} - -// Value returns the value associated with this context for key, or nil -// if no value is associated with key. Successive calls to Value with -// the same key returns the same result. -func (c *Context) Value(key interface{}) interface{} { - if key == 0 { - return c.Request - } - if keyAsString, ok := key.(string); ok { - val, _ := c.Get(keyAsString) - return val - } - return nil -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/context_appengine.go b/taskman-server/vendor/github.com/gin-gonic/gin/context_appengine.go deleted file mode 100644 index d5658434..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/context_appengine.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -//go:build appengine -// +build appengine - -package gin - -func init() { - defaultAppEngine = true -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/debug.go b/taskman-server/vendor/github.com/gin-gonic/gin/debug.go deleted file mode 100644 index 4c7cd0c3..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/debug.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "fmt" - "html/template" - "runtime" - "strconv" - "strings" -) - -const ginSupportMinGoVer = 12 - -// IsDebugging returns true if the framework is running in debug mode. -// Use SetMode(gin.ReleaseMode) to disable debug mode. -func IsDebugging() bool { - return ginMode == debugCode -} - -// DebugPrintRouteFunc indicates debug log output format. -var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int) - -func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { - if IsDebugging() { - nuHandlers := len(handlers) - handlerName := nameOfFunction(handlers.Last()) - if DebugPrintRouteFunc == nil { - debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) - } else { - DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) - } - } -} - -func debugPrintLoadTemplate(tmpl *template.Template) { - if IsDebugging() { - var buf strings.Builder - for _, tmpl := range tmpl.Templates() { - buf.WriteString("\t- ") - buf.WriteString(tmpl.Name()) - buf.WriteString("\n") - } - debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) - } -} - -func debugPrint(format string, values ...interface{}) { - if IsDebugging() { - if !strings.HasSuffix(format, "\n") { - format += "\n" - } - fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) - } -} - -func getMinVer(v string) (uint64, error) { - first := strings.IndexByte(v, '.') - last := strings.LastIndexByte(v, '.') - if first == last { - return strconv.ParseUint(v[first+1:], 10, 64) - } - return strconv.ParseUint(v[first+1:last], 10, 64) -} - -func debugPrintWARNINGDefault() { - if v, e := getMinVer(runtime.Version()); e == nil && v <= ginSupportMinGoVer { - debugPrint(`[WARNING] Now Gin requires Go 1.12+. - -`) - } - debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. - -`) -} - -func debugPrintWARNINGNew() { - debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - - using env: export GIN_MODE=release - - using code: gin.SetMode(gin.ReleaseMode) - -`) -} - -func debugPrintWARNINGSetHTMLTemplate() { - debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called -at initialization. ie. before any route is registered or the router is listening in a socket: - - router := gin.Default() - router.SetHTMLTemplate(template) // << good place - -`) -} - -func debugPrintError(err error) { - if err != nil { - if IsDebugging() { - fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) - } - } -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/deprecated.go b/taskman-server/vendor/github.com/gin-gonic/gin/deprecated.go deleted file mode 100644 index ab447429..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/deprecated.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "log" - - "github.com/gin-gonic/gin/binding" -) - -// BindWith binds the passed struct pointer using the specified binding engine. -// See the binding package. -func (c *Context) BindWith(obj interface{}, b binding.Binding) error { - log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to - be deprecated, please check issue #662 and either use MustBindWith() if you - want HTTP 400 to be automatically returned if any error occur, or use - ShouldBindWith() if you need to manage the error.`) - return c.MustBindWith(obj, b) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/doc.go b/taskman-server/vendor/github.com/gin-gonic/gin/doc.go deleted file mode 100644 index 1bd03864..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -/* -Package gin implements a HTTP web framework called gin. - -See https://gin-gonic.com/ for more information about gin. -*/ -package gin // import "github.com/gin-gonic/gin" diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/errors.go b/taskman-server/vendor/github.com/gin-gonic/gin/errors.go deleted file mode 100644 index 0f276c13..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/errors.go +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "fmt" - "reflect" - "strings" - - "github.com/gin-gonic/gin/internal/json" -) - -// ErrorType is an unsigned 64-bit error code as defined in the gin spec. -type ErrorType uint64 - -const ( - // ErrorTypeBind is used when Context.Bind() fails. - ErrorTypeBind ErrorType = 1 << 63 - // ErrorTypeRender is used when Context.Render() fails. - ErrorTypeRender ErrorType = 1 << 62 - // ErrorTypePrivate indicates a private error. - ErrorTypePrivate ErrorType = 1 << 0 - // ErrorTypePublic indicates a public error. - ErrorTypePublic ErrorType = 1 << 1 - // ErrorTypeAny indicates any other error. - ErrorTypeAny ErrorType = 1<<64 - 1 - // ErrorTypeNu indicates any other error. - ErrorTypeNu = 2 -) - -// Error represents a error's specification. -type Error struct { - Err error - Type ErrorType - Meta interface{} -} - -type errorMsgs []*Error - -var _ error = &Error{} - -// SetType sets the error's type. -func (msg *Error) SetType(flags ErrorType) *Error { - msg.Type = flags - return msg -} - -// SetMeta sets the error's meta data. -func (msg *Error) SetMeta(data interface{}) *Error { - msg.Meta = data - return msg -} - -// JSON creates a properly formatted JSON -func (msg *Error) JSON() interface{} { - jsonData := H{} - if msg.Meta != nil { - value := reflect.ValueOf(msg.Meta) - switch value.Kind() { - case reflect.Struct: - return msg.Meta - case reflect.Map: - for _, key := range value.MapKeys() { - jsonData[key.String()] = value.MapIndex(key).Interface() - } - default: - jsonData["meta"] = msg.Meta - } - } - if _, ok := jsonData["error"]; !ok { - jsonData["error"] = msg.Error() - } - return jsonData -} - -// MarshalJSON implements the json.Marshaller interface. -func (msg *Error) MarshalJSON() ([]byte, error) { - return json.Marshal(msg.JSON()) -} - -// Error implements the error interface. -func (msg Error) Error() string { - return msg.Err.Error() -} - -// IsType judges one error. -func (msg *Error) IsType(flags ErrorType) bool { - return (msg.Type & flags) > 0 -} - -// Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap() -func (msg *Error) Unwrap() error { - return msg.Err -} - -// ByType returns a readonly copy filtered the byte. -// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic. -func (a errorMsgs) ByType(typ ErrorType) errorMsgs { - if len(a) == 0 { - return nil - } - if typ == ErrorTypeAny { - return a - } - var result errorMsgs - for _, msg := range a { - if msg.IsType(typ) { - result = append(result, msg) - } - } - return result -} - -// Last returns the last error in the slice. It returns nil if the array is empty. -// Shortcut for errors[len(errors)-1]. -func (a errorMsgs) Last() *Error { - if length := len(a); length > 0 { - return a[length-1] - } - return nil -} - -// Errors returns an array will all the error messages. -// Example: -// c.Error(errors.New("first")) -// c.Error(errors.New("second")) -// c.Error(errors.New("third")) -// c.Errors.Errors() // == []string{"first", "second", "third"} -func (a errorMsgs) Errors() []string { - if len(a) == 0 { - return nil - } - errorStrings := make([]string, len(a)) - for i, err := range a { - errorStrings[i] = err.Error() - } - return errorStrings -} - -func (a errorMsgs) JSON() interface{} { - switch length := len(a); length { - case 0: - return nil - case 1: - return a.Last().JSON() - default: - jsonData := make([]interface{}, length) - for i, err := range a { - jsonData[i] = err.JSON() - } - return jsonData - } -} - -// MarshalJSON implements the json.Marshaller interface. -func (a errorMsgs) MarshalJSON() ([]byte, error) { - return json.Marshal(a.JSON()) -} - -func (a errorMsgs) String() string { - if len(a) == 0 { - return "" - } - var buffer strings.Builder - for i, msg := range a { - fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err) - if msg.Meta != nil { - fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) - } - } - return buffer.String() -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/fs.go b/taskman-server/vendor/github.com/gin-gonic/gin/fs.go deleted file mode 100644 index 007d9b75..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/fs.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "net/http" - "os" -) - -type onlyFilesFS struct { - fs http.FileSystem -} - -type neuteredReaddirFile struct { - http.File -} - -// Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally -// in router.Static(). -// if listDirectory == true, then it works the same as http.Dir() otherwise it returns -// a filesystem that prevents http.FileServer() to list the directory files. -func Dir(root string, listDirectory bool) http.FileSystem { - fs := http.Dir(root) - if listDirectory { - return fs - } - return &onlyFilesFS{fs} -} - -// Open conforms to http.Filesystem. -func (fs onlyFilesFS) Open(name string) (http.File, error) { - f, err := fs.fs.Open(name) - if err != nil { - return nil, err - } - return neuteredReaddirFile{f}, nil -} - -// Readdir overrides the http.File default implementation. -func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) { - // this disables directory listing - return nil, nil -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/gin.go b/taskman-server/vendor/github.com/gin-gonic/gin/gin.go deleted file mode 100644 index 03a0e127..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/gin.go +++ /dev/null @@ -1,577 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "fmt" - "html/template" - "net" - "net/http" - "os" - "path" - "strings" - "sync" - - "github.com/gin-gonic/gin/internal/bytesconv" - "github.com/gin-gonic/gin/render" -) - -const defaultMultipartMemory = 32 << 20 // 32 MB - -var ( - default404Body = []byte("404 page not found") - default405Body = []byte("405 method not allowed") -) - -var defaultAppEngine bool - -// HandlerFunc defines the handler used by gin middleware as return value. -type HandlerFunc func(*Context) - -// HandlersChain defines a HandlerFunc array. -type HandlersChain []HandlerFunc - -// Last returns the last handler in the chain. ie. the last handler is the main one. -func (c HandlersChain) Last() HandlerFunc { - if length := len(c); length > 0 { - return c[length-1] - } - return nil -} - -// RouteInfo represents a request route's specification which contains method and path and its handler. -type RouteInfo struct { - Method string - Path string - Handler string - HandlerFunc HandlerFunc -} - -// RoutesInfo defines a RouteInfo array. -type RoutesInfo []RouteInfo - -// Engine is the framework's instance, it contains the muxer, middleware and configuration settings. -// Create an instance of Engine, by using New() or Default() -type Engine struct { - RouterGroup - - // Enables automatic redirection if the current route can't be matched but a - // handler for the path with (without) the trailing slash exists. - // For example if /foo/ is requested but a route only exists for /foo, the - // client is redirected to /foo with http status code 301 for GET requests - // and 307 for all other request methods. - RedirectTrailingSlash bool - - // If enabled, the router tries to fix the current request path, if no - // handle is registered for it. - // First superfluous path elements like ../ or // are removed. - // Afterwards the router does a case-insensitive lookup of the cleaned path. - // If a handle can be found for this route, the router makes a redirection - // to the corrected path with status code 301 for GET requests and 307 for - // all other request methods. - // For example /FOO and /..//Foo could be redirected to /foo. - // RedirectTrailingSlash is independent of this option. - RedirectFixedPath bool - - // If enabled, the router checks if another method is allowed for the - // current route, if the current request can not be routed. - // If this is the case, the request is answered with 'Method Not Allowed' - // and HTTP status code 405. - // If no other Method is allowed, the request is delegated to the NotFound - // handler. - HandleMethodNotAllowed bool - - // If enabled, client IP will be parsed from the request's headers that - // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was - // fetched, it falls back to the IP obtained from - // `(*gin.Context).Request.RemoteAddr`. - ForwardedByClientIP bool - - // List of headers used to obtain the client IP when - // `(*gin.Engine).ForwardedByClientIP` is `true` and - // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the - // network origins of `(*gin.Engine).TrustedProxies`. - RemoteIPHeaders []string - - // List of network origins (IPv4 addresses, IPv4 CIDRs, IPv6 addresses or - // IPv6 CIDRs) from which to trust request's headers that contain - // alternative client IP when `(*gin.Engine).ForwardedByClientIP` is - // `true`. - TrustedProxies []string - - // #726 #755 If enabled, it will trust some headers starting with - // 'X-AppEngine...' for better integration with that PaaS. - AppEngine bool - - // If enabled, the url.RawPath will be used to find parameters. - UseRawPath bool - - // If true, the path value will be unescaped. - // If UseRawPath is false (by default), the UnescapePathValues effectively is true, - // as url.Path gonna be used, which is already unescaped. - UnescapePathValues bool - - // Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm - // method call. - MaxMultipartMemory int64 - - // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. - // See the PR #1817 and issue #1644 - RemoveExtraSlash bool - - delims render.Delims - secureJSONPrefix string - HTMLRender render.HTMLRender - FuncMap template.FuncMap - allNoRoute HandlersChain - allNoMethod HandlersChain - noRoute HandlersChain - noMethod HandlersChain - pool sync.Pool - trees methodTrees - maxParams uint16 - trustedCIDRs []*net.IPNet -} - -var _ IRouter = &Engine{} - -// New returns a new blank Engine instance without any middleware attached. -// By default the configuration is: -// - RedirectTrailingSlash: true -// - RedirectFixedPath: false -// - HandleMethodNotAllowed: false -// - ForwardedByClientIP: true -// - UseRawPath: false -// - UnescapePathValues: true -func New() *Engine { - debugPrintWARNINGNew() - engine := &Engine{ - RouterGroup: RouterGroup{ - Handlers: nil, - basePath: "/", - root: true, - }, - FuncMap: template.FuncMap{}, - RedirectTrailingSlash: true, - RedirectFixedPath: false, - HandleMethodNotAllowed: false, - ForwardedByClientIP: true, - RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, - TrustedProxies: []string{"0.0.0.0/0"}, - AppEngine: defaultAppEngine, - UseRawPath: false, - RemoveExtraSlash: false, - UnescapePathValues: true, - MaxMultipartMemory: defaultMultipartMemory, - trees: make(methodTrees, 0, 9), - delims: render.Delims{Left: "{{", Right: "}}"}, - secureJSONPrefix: "while(1);", - } - engine.RouterGroup.engine = engine - engine.pool.New = func() interface{} { - return engine.allocateContext() - } - return engine -} - -// Default returns an Engine instance with the Logger and Recovery middleware already attached. -func Default() *Engine { - debugPrintWARNINGDefault() - engine := New() - engine.Use(Logger(), Recovery()) - return engine -} - -func (engine *Engine) allocateContext() *Context { - v := make(Params, 0, engine.maxParams) - return &Context{engine: engine, params: &v} -} - -// Delims sets template left and right delims and returns a Engine instance. -func (engine *Engine) Delims(left, right string) *Engine { - engine.delims = render.Delims{Left: left, Right: right} - return engine -} - -// SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. -func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { - engine.secureJSONPrefix = prefix - return engine -} - -// LoadHTMLGlob loads HTML files identified by glob pattern -// and associates the result with HTML renderer. -func (engine *Engine) LoadHTMLGlob(pattern string) { - left := engine.delims.Left - right := engine.delims.Right - templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) - - if IsDebugging() { - debugPrintLoadTemplate(templ) - engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} - return - } - - engine.SetHTMLTemplate(templ) -} - -// LoadHTMLFiles loads a slice of HTML files -// and associates the result with HTML renderer. -func (engine *Engine) LoadHTMLFiles(files ...string) { - if IsDebugging() { - engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} - return - } - - templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) - engine.SetHTMLTemplate(templ) -} - -// SetHTMLTemplate associate a template with HTML renderer. -func (engine *Engine) SetHTMLTemplate(templ *template.Template) { - if len(engine.trees) > 0 { - debugPrintWARNINGSetHTMLTemplate() - } - - engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} -} - -// SetFuncMap sets the FuncMap used for template.FuncMap. -func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { - engine.FuncMap = funcMap -} - -// NoRoute adds handlers for NoRoute. It return a 404 code by default. -func (engine *Engine) NoRoute(handlers ...HandlerFunc) { - engine.noRoute = handlers - engine.rebuild404Handlers() -} - -// NoMethod sets the handlers called when... TODO. -func (engine *Engine) NoMethod(handlers ...HandlerFunc) { - engine.noMethod = handlers - engine.rebuild405Handlers() -} - -// Use attaches a global middleware to the router. ie. the middleware attached though Use() will be -// included in the handlers chain for every single request. Even 404, 405, static files... -// For example, this is the right place for a logger or error management middleware. -func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { - engine.RouterGroup.Use(middleware...) - engine.rebuild404Handlers() - engine.rebuild405Handlers() - return engine -} - -func (engine *Engine) rebuild404Handlers() { - engine.allNoRoute = engine.combineHandlers(engine.noRoute) -} - -func (engine *Engine) rebuild405Handlers() { - engine.allNoMethod = engine.combineHandlers(engine.noMethod) -} - -func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { - assert1(path[0] == '/', "path must begin with '/'") - assert1(method != "", "HTTP method can not be empty") - assert1(len(handlers) > 0, "there must be at least one handler") - - debugPrintRoute(method, path, handlers) - - root := engine.trees.get(method) - if root == nil { - root = new(node) - root.fullPath = "/" - engine.trees = append(engine.trees, methodTree{method: method, root: root}) - } - root.addRoute(path, handlers) - - // Update maxParams - if paramsCount := countParams(path); paramsCount > engine.maxParams { - engine.maxParams = paramsCount - } -} - -// Routes returns a slice of registered routes, including some useful information, such as: -// the http method, path and the handler name. -func (engine *Engine) Routes() (routes RoutesInfo) { - for _, tree := range engine.trees { - routes = iterate("", tree.method, routes, tree.root) - } - return routes -} - -func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { - path += root.path - if len(root.handlers) > 0 { - handlerFunc := root.handlers.Last() - routes = append(routes, RouteInfo{ - Method: method, - Path: path, - Handler: nameOfFunction(handlerFunc), - HandlerFunc: handlerFunc, - }) - } - for _, child := range root.children { - routes = iterate(path, method, routes, child) - } - return routes -} - -// Run attaches the router to a http.Server and starts listening and serving HTTP requests. -// It is a shortcut for http.ListenAndServe(addr, router) -// Note: this method will block the calling goroutine indefinitely unless an error happens. -func (engine *Engine) Run(addr ...string) (err error) { - defer func() { debugPrintError(err) }() - - trustedCIDRs, err := engine.prepareTrustedCIDRs() - if err != nil { - return err - } - engine.trustedCIDRs = trustedCIDRs - address := resolveAddress(addr) - debugPrint("Listening and serving HTTP on %s\n", address) - err = http.ListenAndServe(address, engine) - return -} - -func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { - if engine.TrustedProxies == nil { - return nil, nil - } - - cidr := make([]*net.IPNet, 0, len(engine.TrustedProxies)) - for _, trustedProxy := range engine.TrustedProxies { - if !strings.Contains(trustedProxy, "/") { - ip := parseIP(trustedProxy) - if ip == nil { - return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} - } - - switch len(ip) { - case net.IPv4len: - trustedProxy += "/32" - case net.IPv6len: - trustedProxy += "/128" - } - } - _, cidrNet, err := net.ParseCIDR(trustedProxy) - if err != nil { - return cidr, err - } - cidr = append(cidr, cidrNet) - } - return cidr, nil -} - -// parseIP parse a string representation of an IP and returns a net.IP with the -// minimum byte representation or nil if input is invalid. -func parseIP(ip string) net.IP { - parsedIP := net.ParseIP(ip) - - if ipv4 := parsedIP.To4(); ipv4 != nil { - // return ip in a 4-byte representation - return ipv4 - } - - // return ip in a 16-byte representation or nil - return parsedIP -} - -// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. -// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) -// Note: this method will block the calling goroutine indefinitely unless an error happens. -func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { - debugPrint("Listening and serving HTTPS on %s\n", addr) - defer func() { debugPrintError(err) }() - - err = http.ListenAndServeTLS(addr, certFile, keyFile, engine) - return -} - -// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests -// through the specified unix socket (ie. a file). -// Note: this method will block the calling goroutine indefinitely unless an error happens. -func (engine *Engine) RunUnix(file string) (err error) { - debugPrint("Listening and serving HTTP on unix:/%s", file) - defer func() { debugPrintError(err) }() - - listener, err := net.Listen("unix", file) - if err != nil { - return - } - defer listener.Close() - defer os.Remove(file) - - err = http.Serve(listener, engine) - return -} - -// RunFd attaches the router to a http.Server and starts listening and serving HTTP requests -// through the specified file descriptor. -// Note: this method will block the calling goroutine indefinitely unless an error happens. -func (engine *Engine) RunFd(fd int) (err error) { - debugPrint("Listening and serving HTTP on fd@%d", fd) - defer func() { debugPrintError(err) }() - - f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) - listener, err := net.FileListener(f) - if err != nil { - return - } - defer listener.Close() - err = engine.RunListener(listener) - return -} - -// RunListener attaches the router to a http.Server and starts listening and serving HTTP requests -// through the specified net.Listener -func (engine *Engine) RunListener(listener net.Listener) (err error) { - debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) - defer func() { debugPrintError(err) }() - err = http.Serve(listener, engine) - return -} - -// ServeHTTP conforms to the http.Handler interface. -func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { - c := engine.pool.Get().(*Context) - c.writermem.reset(w) - c.Request = req - c.reset() - - engine.handleHTTPRequest(c) - - engine.pool.Put(c) -} - -// HandleContext re-enter a context that has been rewritten. -// This can be done by setting c.Request.URL.Path to your new target. -// Disclaimer: You can loop yourself to death with this, use wisely. -func (engine *Engine) HandleContext(c *Context) { - oldIndexValue := c.index - c.reset() - engine.handleHTTPRequest(c) - - c.index = oldIndexValue -} - -func (engine *Engine) handleHTTPRequest(c *Context) { - httpMethod := c.Request.Method - rPath := c.Request.URL.Path - unescape := false - if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { - rPath = c.Request.URL.RawPath - unescape = engine.UnescapePathValues - } - - if engine.RemoveExtraSlash { - rPath = cleanPath(rPath) - } - - // Find root of the tree for the given HTTP method - t := engine.trees - for i, tl := 0, len(t); i < tl; i++ { - if t[i].method != httpMethod { - continue - } - root := t[i].root - // Find route in tree - value := root.getValue(rPath, c.params, unescape) - if value.params != nil { - c.Params = *value.params - } - if value.handlers != nil { - c.handlers = value.handlers - c.fullPath = value.fullPath - c.Next() - c.writermem.WriteHeaderNow() - return - } - if httpMethod != "CONNECT" && rPath != "/" { - if value.tsr && engine.RedirectTrailingSlash { - redirectTrailingSlash(c) - return - } - if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { - return - } - } - break - } - - if engine.HandleMethodNotAllowed { - for _, tree := range engine.trees { - if tree.method == httpMethod { - continue - } - if value := tree.root.getValue(rPath, nil, unescape); value.handlers != nil { - c.handlers = engine.allNoMethod - serveError(c, http.StatusMethodNotAllowed, default405Body) - return - } - } - } - c.handlers = engine.allNoRoute - serveError(c, http.StatusNotFound, default404Body) -} - -var mimePlain = []string{MIMEPlain} - -func serveError(c *Context, code int, defaultMessage []byte) { - c.writermem.status = code - c.Next() - if c.writermem.Written() { - return - } - if c.writermem.Status() == code { - c.writermem.Header()["Content-Type"] = mimePlain - _, err := c.Writer.Write(defaultMessage) - if err != nil { - debugPrint("cannot write message to writer during serve error: %v", err) - } - return - } - c.writermem.WriteHeaderNow() -} - -func redirectTrailingSlash(c *Context) { - req := c.Request - p := req.URL.Path - if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { - p = prefix + "/" + req.URL.Path - } - req.URL.Path = p + "/" - if length := len(p); length > 1 && p[length-1] == '/' { - req.URL.Path = p[:length-1] - } - redirectRequest(c) -} - -func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { - req := c.Request - rPath := req.URL.Path - - if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { - req.URL.Path = bytesconv.BytesToString(fixedPath) - redirectRequest(c) - return true - } - return false -} - -func redirectRequest(c *Context) { - req := c.Request - rPath := req.URL.Path - rURL := req.URL.String() - - code := http.StatusMovedPermanently // Permanent redirect, request with GET method - if req.Method != http.MethodGet { - code = http.StatusTemporaryRedirect - } - debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) - http.Redirect(c.Writer, req, rURL, code) - c.writermem.WriteHeaderNow() -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/go.mod b/taskman-server/vendor/github.com/gin-gonic/gin/go.mod deleted file mode 100644 index 884ff851..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/go.mod +++ /dev/null @@ -1,14 +0,0 @@ -module github.com/gin-gonic/gin - -go 1.13 - -require ( - github.com/gin-contrib/sse v0.1.0 - github.com/go-playground/validator/v10 v10.4.1 - github.com/golang/protobuf v1.3.3 - github.com/json-iterator/go v1.1.9 - github.com/mattn/go-isatty v0.0.12 - github.com/stretchr/testify v1.4.0 - github.com/ugorji/go/codec v1.1.7 - gopkg.in/yaml.v2 v2.2.8 -) diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/go.sum b/taskman-server/vendor/github.com/gin-gonic/gin/go.sum deleted file mode 100644 index a64b3319..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/go.sum +++ /dev/null @@ -1,52 +0,0 @@ -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv.go b/taskman-server/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv.go deleted file mode 100644 index 86e4c4d4..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2020 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package bytesconv - -import ( - "unsafe" -) - -// StringToBytes converts string to byte slice without a memory allocation. -func StringToBytes(s string) []byte { - return *(*[]byte)(unsafe.Pointer( - &struct { - string - Cap int - }{s, len(s)}, - )) -} - -// BytesToString converts byte slice to string without a memory allocation. -func BytesToString(b []byte) string { - return *(*string)(unsafe.Pointer(&b)) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/json.go b/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/json.go deleted file mode 100644 index 172aeb24..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/json.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017 Bo-Yi Wu. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -//go:build !jsoniter -// +build !jsoniter - -package json - -import "encoding/json" - -var ( - // Marshal is exported by gin/json package. - Marshal = json.Marshal - // Unmarshal is exported by gin/json package. - Unmarshal = json.Unmarshal - // MarshalIndent is exported by gin/json package. - MarshalIndent = json.MarshalIndent - // NewDecoder is exported by gin/json package. - NewDecoder = json.NewDecoder - // NewEncoder is exported by gin/json package. - NewEncoder = json.NewEncoder -) diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go b/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go deleted file mode 100644 index 232f8dca..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017 Bo-Yi Wu. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -//go:build jsoniter -// +build jsoniter - -package json - -import jsoniter "github.com/json-iterator/go" - -var ( - json = jsoniter.ConfigCompatibleWithStandardLibrary - // Marshal is exported by gin/json package. - Marshal = json.Marshal - // Unmarshal is exported by gin/json package. - Unmarshal = json.Unmarshal - // MarshalIndent is exported by gin/json package. - MarshalIndent = json.MarshalIndent - // NewDecoder is exported by gin/json package. - NewDecoder = json.NewDecoder - // NewEncoder is exported by gin/json package. - NewEncoder = json.NewEncoder -) diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/logger.go b/taskman-server/vendor/github.com/gin-gonic/gin/logger.go deleted file mode 100644 index d361b74d..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/logger.go +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "fmt" - "io" - "net/http" - "os" - "time" - - "github.com/mattn/go-isatty" -) - -type consoleColorModeValue int - -const ( - autoColor consoleColorModeValue = iota - disableColor - forceColor -) - -const ( - green = "\033[97;42m" - white = "\033[90;47m" - yellow = "\033[90;43m" - red = "\033[97;41m" - blue = "\033[97;44m" - magenta = "\033[97;45m" - cyan = "\033[97;46m" - reset = "\033[0m" -) - -var consoleColorMode = autoColor - -// LoggerConfig defines the config for Logger middleware. -type LoggerConfig struct { - // Optional. Default value is gin.defaultLogFormatter - Formatter LogFormatter - - // Output is a writer where logs are written. - // Optional. Default value is gin.DefaultWriter. - Output io.Writer - - // SkipPaths is a url path array which logs are not written. - // Optional. - SkipPaths []string -} - -// LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter -type LogFormatter func(params LogFormatterParams) string - -// LogFormatterParams is the structure any formatter will be handed when time to log comes -type LogFormatterParams struct { - Request *http.Request - - // TimeStamp shows the time after the server returns a response. - TimeStamp time.Time - // StatusCode is HTTP response code. - StatusCode int - // Latency is how much time the server cost to process a certain request. - Latency time.Duration - // ClientIP equals Context's ClientIP method. - ClientIP string - // Method is the HTTP method given to the request. - Method string - // Path is a path the client requests. - Path string - // ErrorMessage is set if error has occurred in processing the request. - ErrorMessage string - // isTerm shows whether does gin's output descriptor refers to a terminal. - isTerm bool - // BodySize is the size of the Response Body - BodySize int - // Keys are the keys set on the request's context. - Keys map[string]interface{} -} - -// StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal. -func (p *LogFormatterParams) StatusCodeColor() string { - code := p.StatusCode - - switch { - case code >= http.StatusOK && code < http.StatusMultipleChoices: - return green - case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: - return white - case code >= http.StatusBadRequest && code < http.StatusInternalServerError: - return yellow - default: - return red - } -} - -// MethodColor is the ANSI color for appropriately logging http method to a terminal. -func (p *LogFormatterParams) MethodColor() string { - method := p.Method - - switch method { - case http.MethodGet: - return blue - case http.MethodPost: - return cyan - case http.MethodPut: - return yellow - case http.MethodDelete: - return red - case http.MethodPatch: - return green - case http.MethodHead: - return magenta - case http.MethodOptions: - return white - default: - return reset - } -} - -// ResetColor resets all escape attributes. -func (p *LogFormatterParams) ResetColor() string { - return reset -} - -// IsOutputColor indicates whether can colors be outputted to the log. -func (p *LogFormatterParams) IsOutputColor() bool { - return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm) -} - -// defaultLogFormatter is the default log format function Logger middleware uses. -var defaultLogFormatter = func(param LogFormatterParams) string { - var statusColor, methodColor, resetColor string - if param.IsOutputColor() { - statusColor = param.StatusCodeColor() - methodColor = param.MethodColor() - resetColor = param.ResetColor() - } - - if param.Latency > time.Minute { - // Truncate in a golang < 1.8 safe way - param.Latency = param.Latency - param.Latency%time.Second - } - return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s", - param.TimeStamp.Format("2006/01/02 - 15:04:05"), - statusColor, param.StatusCode, resetColor, - param.Latency, - param.ClientIP, - methodColor, param.Method, resetColor, - param.Path, - param.ErrorMessage, - ) -} - -// DisableConsoleColor disables color output in the console. -func DisableConsoleColor() { - consoleColorMode = disableColor -} - -// ForceConsoleColor force color output in the console. -func ForceConsoleColor() { - consoleColorMode = forceColor -} - -// ErrorLogger returns a handlerfunc for any error type. -func ErrorLogger() HandlerFunc { - return ErrorLoggerT(ErrorTypeAny) -} - -// ErrorLoggerT returns a handlerfunc for a given error type. -func ErrorLoggerT(typ ErrorType) HandlerFunc { - return func(c *Context) { - c.Next() - errors := c.Errors.ByType(typ) - if len(errors) > 0 { - c.JSON(-1, errors) - } - } -} - -// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. -// By default gin.DefaultWriter = os.Stdout. -func Logger() HandlerFunc { - return LoggerWithConfig(LoggerConfig{}) -} - -// LoggerWithFormatter instance a Logger middleware with the specified log format function. -func LoggerWithFormatter(f LogFormatter) HandlerFunc { - return LoggerWithConfig(LoggerConfig{ - Formatter: f, - }) -} - -// LoggerWithWriter instance a Logger middleware with the specified writer buffer. -// Example: os.Stdout, a file opened in write mode, a socket... -func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { - return LoggerWithConfig(LoggerConfig{ - Output: out, - SkipPaths: notlogged, - }) -} - -// LoggerWithConfig instance a Logger middleware with config. -func LoggerWithConfig(conf LoggerConfig) HandlerFunc { - formatter := conf.Formatter - if formatter == nil { - formatter = defaultLogFormatter - } - - out := conf.Output - if out == nil { - out = DefaultWriter - } - - notlogged := conf.SkipPaths - - isTerm := true - - if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" || - (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) { - isTerm = false - } - - var skip map[string]struct{} - - if length := len(notlogged); length > 0 { - skip = make(map[string]struct{}, length) - - for _, path := range notlogged { - skip[path] = struct{}{} - } - } - - return func(c *Context) { - // Start timer - start := time.Now() - path := c.Request.URL.Path - raw := c.Request.URL.RawQuery - - // Process request - c.Next() - - // Log only when path is not being skipped - if _, ok := skip[path]; !ok { - param := LogFormatterParams{ - Request: c.Request, - isTerm: isTerm, - Keys: c.Keys, - } - - // Stop timer - param.TimeStamp = time.Now() - param.Latency = param.TimeStamp.Sub(start) - - param.ClientIP = c.ClientIP() - param.Method = c.Request.Method - param.StatusCode = c.Writer.Status() - param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String() - - param.BodySize = c.Writer.Size() - - if raw != "" { - path = path + "?" + raw - } - - param.Path = path - - fmt.Fprint(out, formatter(param)) - } - } -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/mode.go b/taskman-server/vendor/github.com/gin-gonic/gin/mode.go deleted file mode 100644 index c8813aff..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/mode.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "io" - "os" - - "github.com/gin-gonic/gin/binding" -) - -// EnvGinMode indicates environment name for gin mode. -const EnvGinMode = "GIN_MODE" - -const ( - // DebugMode indicates gin mode is debug. - DebugMode = "debug" - // ReleaseMode indicates gin mode is release. - ReleaseMode = "release" - // TestMode indicates gin mode is test. - TestMode = "test" -) - -const ( - debugCode = iota - releaseCode - testCode -) - -// DefaultWriter is the default io.Writer used by Gin for debug output and -// middleware output like Logger() or Recovery(). -// Note that both Logger and Recovery provides custom ways to configure their -// output io.Writer. -// To support coloring in Windows use: -// import "github.com/mattn/go-colorable" -// gin.DefaultWriter = colorable.NewColorableStdout() -var DefaultWriter io.Writer = os.Stdout - -// DefaultErrorWriter is the default io.Writer used by Gin to debug errors -var DefaultErrorWriter io.Writer = os.Stderr - -var ginMode = debugCode -var modeName = DebugMode - -func init() { - mode := os.Getenv(EnvGinMode) - SetMode(mode) -} - -// SetMode sets gin mode according to input string. -func SetMode(value string) { - if value == "" { - value = DebugMode - } - - switch value { - case DebugMode: - ginMode = debugCode - case ReleaseMode: - ginMode = releaseCode - case TestMode: - ginMode = testCode - default: - panic("gin mode unknown: " + value + " (available mode: debug release test)") - } - - modeName = value -} - -// DisableBindValidation closes the default validator. -func DisableBindValidation() { - binding.Validator = nil -} - -// EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to -// call the UseNumber method on the JSON Decoder instance. -func EnableJsonDecoderUseNumber() { - binding.EnableDecoderUseNumber = true -} - -// EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to -// call the DisallowUnknownFields method on the JSON Decoder instance. -func EnableJsonDecoderDisallowUnknownFields() { - binding.EnableDecoderDisallowUnknownFields = true -} - -// Mode returns currently gin mode. -func Mode() string { - return modeName -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/path.go b/taskman-server/vendor/github.com/gin-gonic/gin/path.go deleted file mode 100644 index d42d6b9d..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/path.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2013 Julien Schmidt. All rights reserved. -// Based on the path package, Copyright 2009 The Go Authors. -// Use of this source code is governed by a BSD-style license that can be found -// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE. - -package gin - -// cleanPath is the URL version of path.Clean, it returns a canonical URL path -// for p, eliminating . and .. elements. -// -// The following rules are applied iteratively until no further processing can -// be done: -// 1. Replace multiple slashes with a single slash. -// 2. Eliminate each . path name element (the current directory). -// 3. Eliminate each inner .. path name element (the parent directory) -// along with the non-.. element that precedes it. -// 4. Eliminate .. elements that begin a rooted path: -// that is, replace "/.." by "/" at the beginning of a path. -// -// If the result of this process is an empty string, "/" is returned. -func cleanPath(p string) string { - const stackBufSize = 128 - // Turn empty string into "/" - if p == "" { - return "/" - } - - // Reasonably sized buffer on stack to avoid allocations in the common case. - // If a larger buffer is required, it gets allocated dynamically. - buf := make([]byte, 0, stackBufSize) - - n := len(p) - - // Invariants: - // reading from path; r is index of next byte to process. - // writing to buf; w is index of next byte to write. - - // path must start with '/' - r := 1 - w := 1 - - if p[0] != '/' { - r = 0 - - if n+1 > stackBufSize { - buf = make([]byte, n+1) - } else { - buf = buf[:n+1] - } - buf[0] = '/' - } - - trailing := n > 1 && p[n-1] == '/' - - // A bit more clunky without a 'lazybuf' like the path package, but the loop - // gets completely inlined (bufApp calls). - // loop has no expensive function calls (except 1x make) // So in contrast to the path package this loop has no expensive function - // calls (except make, if needed). - - for r < n { - switch { - case p[r] == '/': - // empty path element, trailing slash is added after the end - r++ - - case p[r] == '.' && r+1 == n: - trailing = true - r++ - - case p[r] == '.' && p[r+1] == '/': - // . element - r += 2 - - case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): - // .. element: remove to last / - r += 3 - - if w > 1 { - // can backtrack - w-- - - if len(buf) == 0 { - for w > 1 && p[w] != '/' { - w-- - } - } else { - for w > 1 && buf[w] != '/' { - w-- - } - } - } - - default: - // Real path element. - // Add slash if needed - if w > 1 { - bufApp(&buf, p, w, '/') - w++ - } - - // Copy element - for r < n && p[r] != '/' { - bufApp(&buf, p, w, p[r]) - w++ - r++ - } - } - } - - // Re-append trailing slash - if trailing && w > 1 { - bufApp(&buf, p, w, '/') - w++ - } - - // If the original string was not modified (or only shortened at the end), - // return the respective substring of the original string. - // Otherwise return a new string from the buffer. - if len(buf) == 0 { - return p[:w] - } - return string(buf[:w]) -} - -// Internal helper to lazily create a buffer if necessary. -// Calls to this function get inlined. -func bufApp(buf *[]byte, s string, w int, c byte) { - b := *buf - if len(b) == 0 { - // No modification of the original string so far. - // If the next character is the same as in the original string, we do - // not yet have to allocate a buffer. - if s[w] == c { - return - } - - // Otherwise use either the stack buffer, if it is large enough, or - // allocate a new buffer on the heap, and copy all previous characters. - length := len(s) - if length > cap(b) { - *buf = make([]byte, length) - } else { - *buf = (*buf)[:length] - } - b = *buf - - copy(b, s[:w]) - } - b[w] = c -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/recovery.go b/taskman-server/vendor/github.com/gin-gonic/gin/recovery.go deleted file mode 100644 index 563f5aaa..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/recovery.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/http/httputil" - "os" - "runtime" - "strings" - "time" -) - -var ( - dunno = []byte("???") - centerDot = []byte("·") - dot = []byte(".") - slash = []byte("/") -) - -// RecoveryFunc defines the function passable to CustomRecovery. -type RecoveryFunc func(c *Context, err interface{}) - -// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. -func Recovery() HandlerFunc { - return RecoveryWithWriter(DefaultErrorWriter) -} - -//CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it. -func CustomRecovery(handle RecoveryFunc) HandlerFunc { - return RecoveryWithWriter(DefaultErrorWriter, handle) -} - -// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one. -func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc { - if len(recovery) > 0 { - return CustomRecoveryWithWriter(out, recovery[0]) - } - return CustomRecoveryWithWriter(out, defaultHandleRecovery) -} - -// CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it. -func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc { - var logger *log.Logger - if out != nil { - logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags) - } - return func(c *Context) { - defer func() { - if err := recover(); err != nil { - // Check for a broken connection, as it is not really a - // condition that warrants a panic stack trace. - var brokenPipe bool - if ne, ok := err.(*net.OpError); ok { - if se, ok := ne.Err.(*os.SyscallError); ok { - if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { - brokenPipe = true - } - } - } - if logger != nil { - stack := stack(3) - httpRequest, _ := httputil.DumpRequest(c.Request, false) - headers := strings.Split(string(httpRequest), "\r\n") - for idx, header := range headers { - current := strings.Split(header, ":") - if current[0] == "Authorization" { - headers[idx] = current[0] + ": *" - } - } - headersToStr := strings.Join(headers, "\r\n") - if brokenPipe { - logger.Printf("%s\n%s%s", err, headersToStr, reset) - } else if IsDebugging() { - logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s", - timeFormat(time.Now()), headersToStr, err, stack, reset) - } else { - logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s", - timeFormat(time.Now()), err, stack, reset) - } - } - if brokenPipe { - // If the connection is dead, we can't write a status to it. - c.Error(err.(error)) // nolint: errcheck - c.Abort() - } else { - handle(c, err) - } - } - }() - c.Next() - } -} - -func defaultHandleRecovery(c *Context, err interface{}) { - c.AbortWithStatus(http.StatusInternalServerError) -} - -// stack returns a nicely formatted stack frame, skipping skip frames. -func stack(skip int) []byte { - buf := new(bytes.Buffer) // the returned data - // As we loop, we open files and read them. These variables record the currently - // loaded file. - var lines [][]byte - var lastFile string - for i := skip; ; i++ { // Skip the expected number of frames - pc, file, line, ok := runtime.Caller(i) - if !ok { - break - } - // Print this much at least. If we can't find the source, it won't show. - fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) - if file != lastFile { - data, err := ioutil.ReadFile(file) - if err != nil { - continue - } - lines = bytes.Split(data, []byte{'\n'}) - lastFile = file - } - fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) - } - return buf.Bytes() -} - -// source returns a space-trimmed slice of the n'th line. -func source(lines [][]byte, n int) []byte { - n-- // in stack trace, lines are 1-indexed but our array is 0-indexed - if n < 0 || n >= len(lines) { - return dunno - } - return bytes.TrimSpace(lines[n]) -} - -// function returns, if possible, the name of the function containing the PC. -func function(pc uintptr) []byte { - fn := runtime.FuncForPC(pc) - if fn == nil { - return dunno - } - name := []byte(fn.Name()) - // The name includes the path name to the package, which is unnecessary - // since the file name is already included. Plus, it has center dots. - // That is, we see - // runtime/debug.*T·ptrmethod - // and want - // *T.ptrmethod - // Also the package path might contains dot (e.g. code.google.com/...), - // so first eliminate the path prefix - if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 { - name = name[lastSlash+1:] - } - if period := bytes.Index(name, dot); period >= 0 { - name = name[period+1:] - } - name = bytes.Replace(name, centerDot, dot, -1) - return name -} - -func timeFormat(t time.Time) string { - timeString := t.Format("2006/01/02 - 15:04:05") - return timeString -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/data.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/data.go deleted file mode 100644 index 6ba657ba..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/data.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import "net/http" - -// Data contains ContentType and bytes data. -type Data struct { - ContentType string - Data []byte -} - -// Render (Data) writes data with custom ContentType. -func (r Data) Render(w http.ResponseWriter) (err error) { - r.WriteContentType(w) - _, err = w.Write(r.Data) - return -} - -// WriteContentType (Data) writes custom ContentType. -func (r Data) WriteContentType(w http.ResponseWriter) { - writeContentType(w, []string{r.ContentType}) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/html.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/html.go deleted file mode 100644 index 6696ece9..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/html.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "html/template" - "net/http" -) - -// Delims represents a set of Left and Right delimiters for HTML template rendering. -type Delims struct { - // Left delimiter, defaults to {{. - Left string - // Right delimiter, defaults to }}. - Right string -} - -// HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. -type HTMLRender interface { - // Instance returns an HTML instance. - Instance(string, interface{}) Render -} - -// HTMLProduction contains template reference and its delims. -type HTMLProduction struct { - Template *template.Template - Delims Delims -} - -// HTMLDebug contains template delims and pattern and function with file list. -type HTMLDebug struct { - Files []string - Glob string - Delims Delims - FuncMap template.FuncMap -} - -// HTML contains template reference and its name with given interface object. -type HTML struct { - Template *template.Template - Name string - Data interface{} -} - -var htmlContentType = []string{"text/html; charset=utf-8"} - -// Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. -func (r HTMLProduction) Instance(name string, data interface{}) Render { - return HTML{ - Template: r.Template, - Name: name, - Data: data, - } -} - -// Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. -func (r HTMLDebug) Instance(name string, data interface{}) Render { - return HTML{ - Template: r.loadTemplate(), - Name: name, - Data: data, - } -} -func (r HTMLDebug) loadTemplate() *template.Template { - if r.FuncMap == nil { - r.FuncMap = template.FuncMap{} - } - if len(r.Files) > 0 { - return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) - } - if r.Glob != "" { - return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) - } - panic("the HTML debug render was created without files or glob pattern") -} - -// Render (HTML) executes template and writes its result with custom ContentType for response. -func (r HTML) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - - if r.Name == "" { - return r.Template.Execute(w, r.Data) - } - return r.Template.ExecuteTemplate(w, r.Name, r.Data) -} - -// WriteContentType (HTML) writes HTML ContentType. -func (r HTML) WriteContentType(w http.ResponseWriter) { - writeContentType(w, htmlContentType) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/json.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/json.go deleted file mode 100644 index 41863093..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/json.go +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "bytes" - "fmt" - "html/template" - "net/http" - - "github.com/gin-gonic/gin/internal/bytesconv" - "github.com/gin-gonic/gin/internal/json" -) - -// JSON contains the given interface object. -type JSON struct { - Data interface{} -} - -// IndentedJSON contains the given interface object. -type IndentedJSON struct { - Data interface{} -} - -// SecureJSON contains the given interface object and its prefix. -type SecureJSON struct { - Prefix string - Data interface{} -} - -// JsonpJSON contains the given interface object its callback. -type JsonpJSON struct { - Callback string - Data interface{} -} - -// AsciiJSON contains the given interface object. -type AsciiJSON struct { - Data interface{} -} - -// PureJSON contains the given interface object. -type PureJSON struct { - Data interface{} -} - -var jsonContentType = []string{"application/json; charset=utf-8"} -var jsonpContentType = []string{"application/javascript; charset=utf-8"} -var jsonAsciiContentType = []string{"application/json"} - -// Render (JSON) writes data with custom ContentType. -func (r JSON) Render(w http.ResponseWriter) (err error) { - if err = WriteJSON(w, r.Data); err != nil { - panic(err) - } - return -} - -// WriteContentType (JSON) writes JSON ContentType. -func (r JSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonContentType) -} - -// WriteJSON marshals the given interface object and writes it with custom ContentType. -func WriteJSON(w http.ResponseWriter, obj interface{}) error { - writeContentType(w, jsonContentType) - jsonBytes, err := json.Marshal(obj) - if err != nil { - return err - } - _, err = w.Write(jsonBytes) - return err -} - -// Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType. -func (r IndentedJSON) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - jsonBytes, err := json.MarshalIndent(r.Data, "", " ") - if err != nil { - return err - } - _, err = w.Write(jsonBytes) - return err -} - -// WriteContentType (IndentedJSON) writes JSON ContentType. -func (r IndentedJSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonContentType) -} - -// Render (SecureJSON) marshals the given interface object and writes it with custom ContentType. -func (r SecureJSON) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - jsonBytes, err := json.Marshal(r.Data) - if err != nil { - return err - } - // if the jsonBytes is array values - if bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes("[")) && bytes.HasSuffix(jsonBytes, - bytesconv.StringToBytes("]")) { - _, err = w.Write(bytesconv.StringToBytes(r.Prefix)) - if err != nil { - return err - } - } - _, err = w.Write(jsonBytes) - return err -} - -// WriteContentType (SecureJSON) writes JSON ContentType. -func (r SecureJSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonContentType) -} - -// Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType. -func (r JsonpJSON) Render(w http.ResponseWriter) (err error) { - r.WriteContentType(w) - ret, err := json.Marshal(r.Data) - if err != nil { - return err - } - - if r.Callback == "" { - _, err = w.Write(ret) - return err - } - - callback := template.JSEscapeString(r.Callback) - _, err = w.Write(bytesconv.StringToBytes(callback)) - if err != nil { - return err - } - _, err = w.Write(bytesconv.StringToBytes("(")) - if err != nil { - return err - } - _, err = w.Write(ret) - if err != nil { - return err - } - _, err = w.Write(bytesconv.StringToBytes(");")) - if err != nil { - return err - } - - return nil -} - -// WriteContentType (JsonpJSON) writes Javascript ContentType. -func (r JsonpJSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonpContentType) -} - -// Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType. -func (r AsciiJSON) Render(w http.ResponseWriter) (err error) { - r.WriteContentType(w) - ret, err := json.Marshal(r.Data) - if err != nil { - return err - } - - var buffer bytes.Buffer - for _, r := range bytesconv.BytesToString(ret) { - cvt := string(r) - if r >= 128 { - cvt = fmt.Sprintf("\\u%04x", int64(r)) - } - buffer.WriteString(cvt) - } - - _, err = w.Write(buffer.Bytes()) - return err -} - -// WriteContentType (AsciiJSON) writes JSON ContentType. -func (r AsciiJSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonAsciiContentType) -} - -// Render (PureJSON) writes custom ContentType and encodes the given interface object. -func (r PureJSON) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - encoder := json.NewEncoder(w) - encoder.SetEscapeHTML(false) - return encoder.Encode(r.Data) -} - -// WriteContentType (PureJSON) writes custom ContentType. -func (r PureJSON) WriteContentType(w http.ResponseWriter) { - writeContentType(w, jsonContentType) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/msgpack.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/msgpack.go deleted file mode 100644 index 6ef5b6e5..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/msgpack.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -//go:build !nomsgpack -// +build !nomsgpack - -package render - -import ( - "net/http" - - "github.com/ugorji/go/codec" -) - -var ( - _ Render = MsgPack{} -) - -// MsgPack contains the given interface object. -type MsgPack struct { - Data interface{} -} - -var msgpackContentType = []string{"application/msgpack; charset=utf-8"} - -// WriteContentType (MsgPack) writes MsgPack ContentType. -func (r MsgPack) WriteContentType(w http.ResponseWriter) { - writeContentType(w, msgpackContentType) -} - -// Render (MsgPack) encodes the given interface object and writes data with custom ContentType. -func (r MsgPack) Render(w http.ResponseWriter) error { - return WriteMsgPack(w, r.Data) -} - -// WriteMsgPack writes MsgPack ContentType and encodes the given interface object. -func WriteMsgPack(w http.ResponseWriter, obj interface{}) error { - writeContentType(w, msgpackContentType) - var mh codec.MsgpackHandle - return codec.NewEncoder(w, &mh).Encode(obj) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/protobuf.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/protobuf.go deleted file mode 100644 index 15aca995..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/protobuf.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2018 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "net/http" - - "github.com/golang/protobuf/proto" -) - -// ProtoBuf contains the given interface object. -type ProtoBuf struct { - Data interface{} -} - -var protobufContentType = []string{"application/x-protobuf"} - -// Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType. -func (r ProtoBuf) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - - bytes, err := proto.Marshal(r.Data.(proto.Message)) - if err != nil { - return err - } - - _, err = w.Write(bytes) - return err -} - -// WriteContentType (ProtoBuf) writes ProtoBuf ContentType. -func (r ProtoBuf) WriteContentType(w http.ResponseWriter) { - writeContentType(w, protobufContentType) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/reader.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/reader.go deleted file mode 100644 index d5282e49..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/reader.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2018 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "io" - "net/http" - "strconv" -) - -// Reader contains the IO reader and its length, and custom ContentType and other headers. -type Reader struct { - ContentType string - ContentLength int64 - Reader io.Reader - Headers map[string]string -} - -// Render (Reader) writes data with custom ContentType and headers. -func (r Reader) Render(w http.ResponseWriter) (err error) { - r.WriteContentType(w) - if r.ContentLength >= 0 { - if r.Headers == nil { - r.Headers = map[string]string{} - } - r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10) - } - r.writeHeaders(w, r.Headers) - _, err = io.Copy(w, r.Reader) - return -} - -// WriteContentType (Reader) writes custom ContentType. -func (r Reader) WriteContentType(w http.ResponseWriter) { - writeContentType(w, []string{r.ContentType}) -} - -// writeHeaders writes custom Header. -func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) { - header := w.Header() - for k, v := range headers { - if header.Get(k) == "" { - header.Set(k, v) - } - } -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/redirect.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/redirect.go deleted file mode 100644 index c006691c..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/redirect.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "fmt" - "net/http" -) - -// Redirect contains the http request reference and redirects status code and location. -type Redirect struct { - Code int - Request *http.Request - Location string -} - -// Render (Redirect) redirects the http request to new location and writes redirect response. -func (r Redirect) Render(w http.ResponseWriter) error { - if (r.Code < http.StatusMultipleChoices || r.Code > http.StatusPermanentRedirect) && r.Code != http.StatusCreated { - panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code)) - } - http.Redirect(w, r.Request, r.Location, r.Code) - return nil -} - -// WriteContentType (Redirect) don't write any ContentType. -func (r Redirect) WriteContentType(http.ResponseWriter) {} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/render.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/render.go deleted file mode 100644 index bcd568bf..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/render.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import "net/http" - -// Render interface is to be implemented by JSON, XML, HTML, YAML and so on. -type Render interface { - // Render writes data with custom ContentType. - Render(http.ResponseWriter) error - // WriteContentType writes custom ContentType. - WriteContentType(w http.ResponseWriter) -} - -var ( - _ Render = JSON{} - _ Render = IndentedJSON{} - _ Render = SecureJSON{} - _ Render = JsonpJSON{} - _ Render = XML{} - _ Render = String{} - _ Render = Redirect{} - _ Render = Data{} - _ Render = HTML{} - _ HTMLRender = HTMLDebug{} - _ HTMLRender = HTMLProduction{} - _ Render = YAML{} - _ Render = Reader{} - _ Render = AsciiJSON{} - _ Render = ProtoBuf{} -) - -func writeContentType(w http.ResponseWriter, value []string) { - header := w.Header() - if val := header["Content-Type"]; len(val) == 0 { - header["Content-Type"] = value - } -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/text.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/text.go deleted file mode 100644 index 461b720a..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/text.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "fmt" - "net/http" - - "github.com/gin-gonic/gin/internal/bytesconv" -) - -// String contains the given interface object slice and its format. -type String struct { - Format string - Data []interface{} -} - -var plainContentType = []string{"text/plain; charset=utf-8"} - -// Render (String) writes data with custom ContentType. -func (r String) Render(w http.ResponseWriter) error { - return WriteString(w, r.Format, r.Data) -} - -// WriteContentType (String) writes Plain ContentType. -func (r String) WriteContentType(w http.ResponseWriter) { - writeContentType(w, plainContentType) -} - -// WriteString writes data according to its format and write custom ContentType. -func WriteString(w http.ResponseWriter, format string, data []interface{}) (err error) { - writeContentType(w, plainContentType) - if len(data) > 0 { - _, err = fmt.Fprintf(w, format, data...) - return - } - _, err = w.Write(bytesconv.StringToBytes(format)) - return -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/xml.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/xml.go deleted file mode 100644 index cc5390a2..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/xml.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "encoding/xml" - "net/http" -) - -// XML contains the given interface object. -type XML struct { - Data interface{} -} - -var xmlContentType = []string{"application/xml; charset=utf-8"} - -// Render (XML) encodes the given interface object and writes data with custom ContentType. -func (r XML) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - return xml.NewEncoder(w).Encode(r.Data) -} - -// WriteContentType (XML) writes XML ContentType for response. -func (r XML) WriteContentType(w http.ResponseWriter) { - writeContentType(w, xmlContentType) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/yaml.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/yaml.go deleted file mode 100644 index 0df78360..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/render/yaml.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package render - -import ( - "net/http" - - "gopkg.in/yaml.v2" -) - -// YAML contains the given interface object. -type YAML struct { - Data interface{} -} - -var yamlContentType = []string{"application/x-yaml; charset=utf-8"} - -// Render (YAML) marshals the given interface object and writes data with custom ContentType. -func (r YAML) Render(w http.ResponseWriter) error { - r.WriteContentType(w) - - bytes, err := yaml.Marshal(r.Data) - if err != nil { - return err - } - - _, err = w.Write(bytes) - return err -} - -// WriteContentType (YAML) writes YAML ContentType for response. -func (r YAML) WriteContentType(w http.ResponseWriter) { - writeContentType(w, yamlContentType) -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/response_writer.go b/taskman-server/vendor/github.com/gin-gonic/gin/response_writer.go deleted file mode 100644 index 26826689..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/response_writer.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "bufio" - "io" - "net" - "net/http" -) - -const ( - noWritten = -1 - defaultStatus = http.StatusOK -) - -// ResponseWriter ... -type ResponseWriter interface { - http.ResponseWriter - http.Hijacker - http.Flusher - http.CloseNotifier - - // Returns the HTTP response status code of the current request. - Status() int - - // Returns the number of bytes already written into the response http body. - // See Written() - Size() int - - // Writes the string into the response body. - WriteString(string) (int, error) - - // Returns true if the response body was already written. - Written() bool - - // Forces to write the http header (status code + headers). - WriteHeaderNow() - - // get the http.Pusher for server push - Pusher() http.Pusher -} - -type responseWriter struct { - http.ResponseWriter - size int - status int -} - -var _ ResponseWriter = &responseWriter{} - -func (w *responseWriter) reset(writer http.ResponseWriter) { - w.ResponseWriter = writer - w.size = noWritten - w.status = defaultStatus -} - -func (w *responseWriter) WriteHeader(code int) { - if code > 0 && w.status != code { - if w.Written() { - debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) - } - w.status = code - } -} - -func (w *responseWriter) WriteHeaderNow() { - if !w.Written() { - w.size = 0 - w.ResponseWriter.WriteHeader(w.status) - } -} - -func (w *responseWriter) Write(data []byte) (n int, err error) { - w.WriteHeaderNow() - n, err = w.ResponseWriter.Write(data) - w.size += n - return -} - -func (w *responseWriter) WriteString(s string) (n int, err error) { - w.WriteHeaderNow() - n, err = io.WriteString(w.ResponseWriter, s) - w.size += n - return -} - -func (w *responseWriter) Status() int { - return w.status -} - -func (w *responseWriter) Size() int { - return w.size -} - -func (w *responseWriter) Written() bool { - return w.size != noWritten -} - -// Hijack implements the http.Hijacker interface. -func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if w.size < 0 { - w.size = 0 - } - return w.ResponseWriter.(http.Hijacker).Hijack() -} - -// CloseNotify implements the http.CloseNotify interface. -func (w *responseWriter) CloseNotify() <-chan bool { - return w.ResponseWriter.(http.CloseNotifier).CloseNotify() -} - -// Flush implements the http.Flush interface. -func (w *responseWriter) Flush() { - w.WriteHeaderNow() - w.ResponseWriter.(http.Flusher).Flush() -} - -func (w *responseWriter) Pusher() (pusher http.Pusher) { - if pusher, ok := w.ResponseWriter.(http.Pusher); ok { - return pusher - } - return nil -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/routergroup.go b/taskman-server/vendor/github.com/gin-gonic/gin/routergroup.go deleted file mode 100644 index 15d9930d..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/routergroup.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "net/http" - "path" - "regexp" - "strings" -) - -// IRouter defines all router handle interface includes single and group router. -type IRouter interface { - IRoutes - Group(string, ...HandlerFunc) *RouterGroup -} - -// IRoutes defines all router handle interface. -type IRoutes interface { - Use(...HandlerFunc) IRoutes - - Handle(string, string, ...HandlerFunc) IRoutes - Any(string, ...HandlerFunc) IRoutes - GET(string, ...HandlerFunc) IRoutes - POST(string, ...HandlerFunc) IRoutes - DELETE(string, ...HandlerFunc) IRoutes - PATCH(string, ...HandlerFunc) IRoutes - PUT(string, ...HandlerFunc) IRoutes - OPTIONS(string, ...HandlerFunc) IRoutes - HEAD(string, ...HandlerFunc) IRoutes - - StaticFile(string, string) IRoutes - Static(string, string) IRoutes - StaticFS(string, http.FileSystem) IRoutes -} - -// RouterGroup is used internally to configure router, a RouterGroup is associated with -// a prefix and an array of handlers (middleware). -type RouterGroup struct { - Handlers HandlersChain - basePath string - engine *Engine - root bool -} - -var _ IRouter = &RouterGroup{} - -// Use adds middleware to the group, see example code in GitHub. -func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { - group.Handlers = append(group.Handlers, middleware...) - return group.returnObj() -} - -// Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. -// For example, all the routes that use a common middleware for authorization could be grouped. -func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { - return &RouterGroup{ - Handlers: group.combineHandlers(handlers), - basePath: group.calculateAbsolutePath(relativePath), - engine: group.engine, - } -} - -// BasePath returns the base path of router group. -// For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api". -func (group *RouterGroup) BasePath() string { - return group.basePath -} - -func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { - absolutePath := group.calculateAbsolutePath(relativePath) - handlers = group.combineHandlers(handlers) - group.engine.addRoute(httpMethod, absolutePath, handlers) - return group.returnObj() -} - -// Handle registers a new request handle and middleware with the given path and method. -// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. -// See the example code in GitHub. -// -// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut -// functions can be used. -// -// This function is intended for bulk loading and to allow the usage of less -// frequently used, non-standardized or custom methods (e.g. for internal -// communication with a proxy). -func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { - if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil { - panic("http method " + httpMethod + " is not valid") - } - return group.handle(httpMethod, relativePath, handlers) -} - -// POST is a shortcut for router.Handle("POST", path, handle). -func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle(http.MethodPost, relativePath, handlers) -} - -// GET is a shortcut for router.Handle("GET", path, handle). -func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle(http.MethodGet, relativePath, handlers) -} - -// DELETE is a shortcut for router.Handle("DELETE", path, handle). -func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle(http.MethodDelete, relativePath, handlers) -} - -// PATCH is a shortcut for router.Handle("PATCH", path, handle). -func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle(http.MethodPatch, relativePath, handlers) -} - -// PUT is a shortcut for router.Handle("PUT", path, handle). -func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle(http.MethodPut, relativePath, handlers) -} - -// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle). -func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle(http.MethodOptions, relativePath, handlers) -} - -// HEAD is a shortcut for router.Handle("HEAD", path, handle). -func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle(http.MethodHead, relativePath, handlers) -} - -// Any registers a route that matches all the HTTP methods. -// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. -func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { - group.handle(http.MethodGet, relativePath, handlers) - group.handle(http.MethodPost, relativePath, handlers) - group.handle(http.MethodPut, relativePath, handlers) - group.handle(http.MethodPatch, relativePath, handlers) - group.handle(http.MethodHead, relativePath, handlers) - group.handle(http.MethodOptions, relativePath, handlers) - group.handle(http.MethodDelete, relativePath, handlers) - group.handle(http.MethodConnect, relativePath, handlers) - group.handle(http.MethodTrace, relativePath, handlers) - return group.returnObj() -} - -// StaticFile registers a single route in order to serve a single file of the local filesystem. -// router.StaticFile("favicon.ico", "./resources/favicon.ico") -func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { - if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { - panic("URL parameters can not be used when serving a static file") - } - handler := func(c *Context) { - c.File(filepath) - } - group.GET(relativePath, handler) - group.HEAD(relativePath, handler) - return group.returnObj() -} - -// Static serves files from the given file system root. -// Internally a http.FileServer is used, therefore http.NotFound is used instead -// of the Router's NotFound handler. -// To use the operating system's file system implementation, -// use : -// router.Static("/static", "/var/www") -func (group *RouterGroup) Static(relativePath, root string) IRoutes { - return group.StaticFS(relativePath, Dir(root, false)) -} - -// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. -// Gin by default user: gin.Dir() -func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { - if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { - panic("URL parameters can not be used when serving a static folder") - } - handler := group.createStaticHandler(relativePath, fs) - urlPattern := path.Join(relativePath, "/*filepath") - - // Register GET and HEAD handlers - group.GET(urlPattern, handler) - group.HEAD(urlPattern, handler) - return group.returnObj() -} - -func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { - absolutePath := group.calculateAbsolutePath(relativePath) - fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) - - return func(c *Context) { - if _, noListing := fs.(*onlyFilesFS); noListing { - c.Writer.WriteHeader(http.StatusNotFound) - } - - file := c.Param("filepath") - // Check if file exists and/or if we have permission to access it - f, err := fs.Open(file) - if err != nil { - c.Writer.WriteHeader(http.StatusNotFound) - c.handlers = group.engine.noRoute - // Reset index - c.index = -1 - return - } - f.Close() - - fileServer.ServeHTTP(c.Writer, c.Request) - } -} - -func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { - finalSize := len(group.Handlers) + len(handlers) - if finalSize >= int(abortIndex) { - panic("too many handlers") - } - mergedHandlers := make(HandlersChain, finalSize) - copy(mergedHandlers, group.Handlers) - copy(mergedHandlers[len(group.Handlers):], handlers) - return mergedHandlers -} - -func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { - return joinPaths(group.basePath, relativePath) -} - -func (group *RouterGroup) returnObj() IRoutes { - if group.root { - return group.engine - } - return group -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/test_helpers.go b/taskman-server/vendor/github.com/gin-gonic/gin/test_helpers.go deleted file mode 100644 index 3a7a5ddf..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/test_helpers.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import "net/http" - -// CreateTestContext returns a fresh engine and context for testing purposes -func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { - r = New() - c = r.allocateContext() - c.reset() - c.writermem.reset(w) - return -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/tree.go b/taskman-server/vendor/github.com/gin-gonic/gin/tree.go deleted file mode 100644 index 5eb09348..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/tree.go +++ /dev/null @@ -1,831 +0,0 @@ -// Copyright 2013 Julien Schmidt. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be found -// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE - -package gin - -import ( - "bytes" - "net/url" - "strings" - "unicode" - "unicode/utf8" - - "github.com/gin-gonic/gin/internal/bytesconv" -) - -var ( - strColon = []byte(":") - strStar = []byte("*") -) - -// Param is a single URL parameter, consisting of a key and a value. -type Param struct { - Key string - Value string -} - -// Params is a Param-slice, as returned by the router. -// The slice is ordered, the first URL parameter is also the first slice value. -// It is therefore safe to read values by the index. -type Params []Param - -// Get returns the value of the first Param which key matches the given name. -// If no matching Param is found, an empty string is returned. -func (ps Params) Get(name string) (string, bool) { - for _, entry := range ps { - if entry.Key == name { - return entry.Value, true - } - } - return "", false -} - -// ByName returns the value of the first Param which key matches the given name. -// If no matching Param is found, an empty string is returned. -func (ps Params) ByName(name string) (va string) { - va, _ = ps.Get(name) - return -} - -type methodTree struct { - method string - root *node -} - -type methodTrees []methodTree - -func (trees methodTrees) get(method string) *node { - for _, tree := range trees { - if tree.method == method { - return tree.root - } - } - return nil -} - -func min(a, b int) int { - if a <= b { - return a - } - return b -} - -func longestCommonPrefix(a, b string) int { - i := 0 - max := min(len(a), len(b)) - for i < max && a[i] == b[i] { - i++ - } - return i -} - -// addChild will add a child node, keeping wildcards at the end -func (n *node) addChild(child *node) { - if n.wildChild && len(n.children) > 0 { - wildcardChild := n.children[len(n.children)-1] - n.children = append(n.children[:len(n.children)-1], child, wildcardChild) - } else { - n.children = append(n.children, child) - } -} - -func countParams(path string) uint16 { - var n uint16 - s := bytesconv.StringToBytes(path) - n += uint16(bytes.Count(s, strColon)) - n += uint16(bytes.Count(s, strStar)) - return n -} - -type nodeType uint8 - -const ( - static nodeType = iota // default - root - param - catchAll -) - -type node struct { - path string - indices string - wildChild bool - nType nodeType - priority uint32 - children []*node // child nodes, at most 1 :param style node at the end of the array - handlers HandlersChain - fullPath string -} - -// Increments priority of the given child and reorders if necessary -func (n *node) incrementChildPrio(pos int) int { - cs := n.children - cs[pos].priority++ - prio := cs[pos].priority - - // Adjust position (move to front) - newPos := pos - for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- { - // Swap node positions - cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1] - } - - // Build new index char string - if newPos != pos { - n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty - n.indices[pos:pos+1] + // The index char we move - n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos' - } - - return newPos -} - -// addRoute adds a node with the given handle to the path. -// Not concurrency-safe! -func (n *node) addRoute(path string, handlers HandlersChain) { - fullPath := path - n.priority++ - - // Empty tree - if len(n.path) == 0 && len(n.children) == 0 { - n.insertChild(path, fullPath, handlers) - n.nType = root - return - } - - parentFullPathIndex := 0 - -walk: - for { - // Find the longest common prefix. - // This also implies that the common prefix contains no ':' or '*' - // since the existing key can't contain those chars. - i := longestCommonPrefix(path, n.path) - - // Split edge - if i < len(n.path) { - child := node{ - path: n.path[i:], - wildChild: n.wildChild, - indices: n.indices, - children: n.children, - handlers: n.handlers, - priority: n.priority - 1, - fullPath: n.fullPath, - } - - n.children = []*node{&child} - // []byte for proper unicode char conversion, see #65 - n.indices = bytesconv.BytesToString([]byte{n.path[i]}) - n.path = path[:i] - n.handlers = nil - n.wildChild = false - n.fullPath = fullPath[:parentFullPathIndex+i] - } - - // Make new node a child of this node - if i < len(path) { - path = path[i:] - c := path[0] - - // '/' after param - if n.nType == param && c == '/' && len(n.children) == 1 { - parentFullPathIndex += len(n.path) - n = n.children[0] - n.priority++ - continue walk - } - - // Check if a child with the next path byte exists - for i, max := 0, len(n.indices); i < max; i++ { - if c == n.indices[i] { - parentFullPathIndex += len(n.path) - i = n.incrementChildPrio(i) - n = n.children[i] - continue walk - } - } - - // Otherwise insert it - if c != ':' && c != '*' && n.nType != catchAll { - // []byte for proper unicode char conversion, see #65 - n.indices += bytesconv.BytesToString([]byte{c}) - child := &node{ - fullPath: fullPath, - } - n.addChild(child) - n.incrementChildPrio(len(n.indices) - 1) - n = child - } else if n.wildChild { - // inserting a wildcard node, need to check if it conflicts with the existing wildcard - n = n.children[len(n.children)-1] - n.priority++ - - // Check if the wildcard matches - if len(path) >= len(n.path) && n.path == path[:len(n.path)] && - // Adding a child to a catchAll is not possible - n.nType != catchAll && - // Check for longer wildcard, e.g. :name and :names - (len(n.path) >= len(path) || path[len(n.path)] == '/') { - continue walk - } - - // Wildcard conflict - pathSeg := path - if n.nType != catchAll { - pathSeg = strings.SplitN(pathSeg, "/", 2)[0] - } - prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path - panic("'" + pathSeg + - "' in new path '" + fullPath + - "' conflicts with existing wildcard '" + n.path + - "' in existing prefix '" + prefix + - "'") - } - - n.insertChild(path, fullPath, handlers) - return - } - - // Otherwise add handle to current node - if n.handlers != nil { - panic("handlers are already registered for path '" + fullPath + "'") - } - n.handlers = handlers - n.fullPath = fullPath - return - } -} - -// Search for a wildcard segment and check the name for invalid characters. -// Returns -1 as index, if no wildcard was found. -func findWildcard(path string) (wildcard string, i int, valid bool) { - // Find start - for start, c := range []byte(path) { - // A wildcard starts with ':' (param) or '*' (catch-all) - if c != ':' && c != '*' { - continue - } - - // Find end and check for invalid characters - valid = true - for end, c := range []byte(path[start+1:]) { - switch c { - case '/': - return path[start : start+1+end], start, valid - case ':', '*': - valid = false - } - } - return path[start:], start, valid - } - return "", -1, false -} - -func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) { - for { - // Find prefix until first wildcard - wildcard, i, valid := findWildcard(path) - if i < 0 { // No wildcard found - break - } - - // The wildcard name must not contain ':' and '*' - if !valid { - panic("only one wildcard per path segment is allowed, has: '" + - wildcard + "' in path '" + fullPath + "'") - } - - // check if the wildcard has a name - if len(wildcard) < 2 { - panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") - } - - if wildcard[0] == ':' { // param - if i > 0 { - // Insert prefix before the current wildcard - n.path = path[:i] - path = path[i:] - } - - child := &node{ - nType: param, - path: wildcard, - fullPath: fullPath, - } - n.addChild(child) - n.wildChild = true - n = child - n.priority++ - - // if the path doesn't end with the wildcard, then there - // will be another non-wildcard subpath starting with '/' - if len(wildcard) < len(path) { - path = path[len(wildcard):] - - child := &node{ - priority: 1, - fullPath: fullPath, - } - n.addChild(child) - n = child - continue - } - - // Otherwise we're done. Insert the handle in the new leaf - n.handlers = handlers - return - } - - // catchAll - if i+len(wildcard) != len(path) { - panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") - } - - if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { - panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'") - } - - // currently fixed width 1 for '/' - i-- - if path[i] != '/' { - panic("no / before catch-all in path '" + fullPath + "'") - } - - n.path = path[:i] - - // First node: catchAll node with empty path - child := &node{ - wildChild: true, - nType: catchAll, - fullPath: fullPath, - } - - n.addChild(child) - n.indices = string('/') - n = child - n.priority++ - - // second node: node holding the variable - child = &node{ - path: path[i:], - nType: catchAll, - handlers: handlers, - priority: 1, - fullPath: fullPath, - } - n.children = []*node{child} - - return - } - - // If no wildcard was found, simply insert the path and handle - n.path = path - n.handlers = handlers - n.fullPath = fullPath -} - -// nodeValue holds return values of (*Node).getValue method -type nodeValue struct { - handlers HandlersChain - params *Params - tsr bool - fullPath string -} - -// Returns the handle registered with the given path (key). The values of -// wildcards are saved to a map. -// If no handle can be found, a TSR (trailing slash redirect) recommendation is -// made if a handle exists with an extra (without the) trailing slash for the -// given path. -func (n *node) getValue(path string, params *Params, unescape bool) (value nodeValue) { - var ( - skippedPath string - latestNode = n // Caching the latest node - ) - -walk: // Outer loop for walking the tree - for { - prefix := n.path - if len(path) > len(prefix) { - if path[:len(prefix)] == prefix { - path = path[len(prefix):] - - // Try all the non-wildcard children first by matching the indices - idxc := path[0] - for i, c := range []byte(n.indices) { - if c == idxc { - // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild - if n.wildChild { - skippedPath = prefix + path - latestNode = &node{ - path: n.path, - wildChild: n.wildChild, - nType: n.nType, - priority: n.priority, - children: n.children, - handlers: n.handlers, - fullPath: n.fullPath, - } - } - - n = n.children[i] - continue walk - } - } - // If the path at the end of the loop is not equal to '/' and the current node has no child nodes - // the current node needs to be equal to the latest matching node - matched := path != "/" && !n.wildChild - if matched { - n = latestNode - } - - // If there is no wildcard pattern, recommend a redirection - if !n.wildChild { - // Nothing found. - // We can recommend to redirect to the same URL without a - // trailing slash if a leaf exists for that path. - value.tsr = path == "/" && n.handlers != nil - return - } - - // Handle wildcard child, which is always at the end of the array - n = n.children[len(n.children)-1] - - switch n.nType { - case param: - // fix truncate the parameter - // tree_test.go line: 204 - if matched { - path = prefix + path - // The saved path is used after the prefix route is intercepted by matching - if n.indices == "/" { - path = skippedPath[1:] - } - } - - // Find param end (either '/' or path end) - end := 0 - for end < len(path) && path[end] != '/' { - end++ - } - - // Save param value - if params != nil { - if value.params == nil { - value.params = params - } - // Expand slice within preallocated capacity - i := len(*value.params) - *value.params = (*value.params)[:i+1] - val := path[:end] - if unescape { - if v, err := url.QueryUnescape(val); err == nil { - val = v - } - } - (*value.params)[i] = Param{ - Key: n.path[1:], - Value: val, - } - } - - // we need to go deeper! - if end < len(path) { - if len(n.children) > 0 { - path = path[end:] - n = n.children[0] - continue walk - } - - // ... but we can't - value.tsr = (len(path) == end+1) - return - } - - if value.handlers = n.handlers; value.handlers != nil { - value.fullPath = n.fullPath - return - } - if len(n.children) == 1 { - // No handle found. Check if a handle for this path + a - // trailing slash exists for TSR recommendation - n = n.children[0] - value.tsr = (n.path == "/" && n.handlers != nil) - } - return - - case catchAll: - // Save param value - if params != nil { - if value.params == nil { - value.params = params - } - // Expand slice within preallocated capacity - i := len(*value.params) - *value.params = (*value.params)[:i+1] - val := path - if unescape { - if v, err := url.QueryUnescape(path); err == nil { - val = v - } - } - (*value.params)[i] = Param{ - Key: n.path[2:], - Value: val, - } - } - - value.handlers = n.handlers - value.fullPath = n.fullPath - return - - default: - panic("invalid node type") - } - } - } - - if path == prefix { - // If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node - // the current node needs to be equal to the latest matching node - if latestNode.wildChild && n.handlers == nil && path != "/" { - n = latestNode.children[len(latestNode.children)-1] - } - // We should have reached the node containing the handle. - // Check if this node has a handle registered. - if value.handlers = n.handlers; value.handlers != nil { - value.fullPath = n.fullPath - return - } - - // If there is no handle for this route, but this route has a - // wildcard child, there must be a handle for this path with an - // additional trailing slash - if path == "/" && n.wildChild && n.nType != root { - value.tsr = true - return - } - - // No handle found. Check if a handle for this path + a - // trailing slash exists for trailing slash recommendation - for i, c := range []byte(n.indices) { - if c == '/' { - n = n.children[i] - value.tsr = (len(n.path) == 1 && n.handlers != nil) || - (n.nType == catchAll && n.children[0].handlers != nil) - return - } - } - - return - } - - if path != "/" && len(skippedPath) > 0 && strings.HasSuffix(skippedPath, path) { - path = skippedPath - // Reduce the number of cycles - n, latestNode = latestNode, n - // skippedPath cannot execute - // example: - // * /:cc/cc - // call /a/cc expectations:match/200 Actual:match/200 - // call /a/dd expectations:unmatch/404 Actual: panic - // call /addr/dd/aa expectations:unmatch/404 Actual: panic - // skippedPath: It can only be executed if the secondary route is not found - skippedPath = "" - continue walk - } - - // Nothing found. We can recommend to redirect to the same URL with an - // extra trailing slash if a leaf exists for that path - value.tsr = path == "/" || - (len(prefix) == len(path)+1 && n.handlers != nil) - return - } -} - -// Makes a case-insensitive lookup of the given path and tries to find a handler. -// It can optionally also fix trailing slashes. -// It returns the case-corrected path and a bool indicating whether the lookup -// was successful. -func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) { - const stackBufSize = 128 - - // Use a static sized buffer on the stack in the common case. - // If the path is too long, allocate a buffer on the heap instead. - buf := make([]byte, 0, stackBufSize) - if length := len(path) + 1; length > stackBufSize { - buf = make([]byte, 0, length) - } - - ciPath := n.findCaseInsensitivePathRec( - path, - buf, // Preallocate enough memory for new path - [4]byte{}, // Empty rune buffer - fixTrailingSlash, - ) - - return ciPath, ciPath != nil -} - -// Shift bytes in array by n bytes left -func shiftNRuneBytes(rb [4]byte, n int) [4]byte { - switch n { - case 0: - return rb - case 1: - return [4]byte{rb[1], rb[2], rb[3], 0} - case 2: - return [4]byte{rb[2], rb[3]} - case 3: - return [4]byte{rb[3]} - default: - return [4]byte{} - } -} - -// Recursive case-insensitive lookup function used by n.findCaseInsensitivePath -func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte { - npLen := len(n.path) - -walk: // Outer loop for walking the tree - for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) { - // Add common prefix to result - oldPath := path - path = path[npLen:] - ciPath = append(ciPath, n.path...) - - if len(path) == 0 { - // We should have reached the node containing the handle. - // Check if this node has a handle registered. - if n.handlers != nil { - return ciPath - } - - // No handle found. - // Try to fix the path by adding a trailing slash - if fixTrailingSlash { - for i, c := range []byte(n.indices) { - if c == '/' { - n = n.children[i] - if (len(n.path) == 1 && n.handlers != nil) || - (n.nType == catchAll && n.children[0].handlers != nil) { - return append(ciPath, '/') - } - return nil - } - } - } - return nil - } - - // If this node does not have a wildcard (param or catchAll) child, - // we can just look up the next child node and continue to walk down - // the tree - if !n.wildChild { - // Skip rune bytes already processed - rb = shiftNRuneBytes(rb, npLen) - - if rb[0] != 0 { - // Old rune not finished - idxc := rb[0] - for i, c := range []byte(n.indices) { - if c == idxc { - // continue with child node - n = n.children[i] - npLen = len(n.path) - continue walk - } - } - } else { - // Process a new rune - var rv rune - - // Find rune start. - // Runes are up to 4 byte long, - // -4 would definitely be another rune. - var off int - for max := min(npLen, 3); off < max; off++ { - if i := npLen - off; utf8.RuneStart(oldPath[i]) { - // read rune from cached path - rv, _ = utf8.DecodeRuneInString(oldPath[i:]) - break - } - } - - // Calculate lowercase bytes of current rune - lo := unicode.ToLower(rv) - utf8.EncodeRune(rb[:], lo) - - // Skip already processed bytes - rb = shiftNRuneBytes(rb, off) - - idxc := rb[0] - for i, c := range []byte(n.indices) { - // Lowercase matches - if c == idxc { - // must use a recursive approach since both the - // uppercase byte and the lowercase byte might exist - // as an index - if out := n.children[i].findCaseInsensitivePathRec( - path, ciPath, rb, fixTrailingSlash, - ); out != nil { - return out - } - break - } - } - - // If we found no match, the same for the uppercase rune, - // if it differs - if up := unicode.ToUpper(rv); up != lo { - utf8.EncodeRune(rb[:], up) - rb = shiftNRuneBytes(rb, off) - - idxc := rb[0] - for i, c := range []byte(n.indices) { - // Uppercase matches - if c == idxc { - // Continue with child node - n = n.children[i] - npLen = len(n.path) - continue walk - } - } - } - } - - // Nothing found. We can recommend to redirect to the same URL - // without a trailing slash if a leaf exists for that path - if fixTrailingSlash && path == "/" && n.handlers != nil { - return ciPath - } - return nil - } - - n = n.children[0] - switch n.nType { - case param: - // Find param end (either '/' or path end) - end := 0 - for end < len(path) && path[end] != '/' { - end++ - } - - // Add param value to case insensitive path - ciPath = append(ciPath, path[:end]...) - - // We need to go deeper! - if end < len(path) { - if len(n.children) > 0 { - // Continue with child node - n = n.children[0] - npLen = len(n.path) - path = path[end:] - continue - } - - // ... but we can't - if fixTrailingSlash && len(path) == end+1 { - return ciPath - } - return nil - } - - if n.handlers != nil { - return ciPath - } - - if fixTrailingSlash && len(n.children) == 1 { - // No handle found. Check if a handle for this path + a - // trailing slash exists - n = n.children[0] - if n.path == "/" && n.handlers != nil { - return append(ciPath, '/') - } - } - - return nil - - case catchAll: - return append(ciPath, path...) - - default: - panic("invalid node type") - } - } - - // Nothing found. - // Try to fix the path by adding / removing a trailing slash - if fixTrailingSlash { - if path == "/" { - return ciPath - } - if len(path)+1 == npLen && n.path[len(path)] == '/' && - strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil { - return append(ciPath, n.path...) - } - } - return nil -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/utils.go b/taskman-server/vendor/github.com/gin-gonic/gin/utils.go deleted file mode 100644 index c32f0eeb..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/utils.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2014 Manu Martinez-Almeida. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -import ( - "encoding/xml" - "net/http" - "os" - "path" - "reflect" - "runtime" - "strings" -) - -// BindKey indicates a default bind key. -const BindKey = "_gin-gonic/gin/bindkey" - -// Bind is a helper function for given interface object and returns a Gin middleware. -func Bind(val interface{}) HandlerFunc { - value := reflect.ValueOf(val) - if value.Kind() == reflect.Ptr { - panic(`Bind struct can not be a pointer. Example: - Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{}) -`) - } - typ := value.Type() - - return func(c *Context) { - obj := reflect.New(typ).Interface() - if c.Bind(obj) == nil { - c.Set(BindKey, obj) - } - } -} - -// WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware. -func WrapF(f http.HandlerFunc) HandlerFunc { - return func(c *Context) { - f(c.Writer, c.Request) - } -} - -// WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. -func WrapH(h http.Handler) HandlerFunc { - return func(c *Context) { - h.ServeHTTP(c.Writer, c.Request) - } -} - -// H is a shortcut for map[string]interface{} -type H map[string]interface{} - -// MarshalXML allows type H to be used with xml.Marshal. -func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { - start.Name = xml.Name{ - Space: "", - Local: "map", - } - if err := e.EncodeToken(start); err != nil { - return err - } - for key, value := range h { - elem := xml.StartElement{ - Name: xml.Name{Space: "", Local: key}, - Attr: []xml.Attr{}, - } - if err := e.EncodeElement(value, elem); err != nil { - return err - } - } - - return e.EncodeToken(xml.EndElement{Name: start.Name}) -} - -func assert1(guard bool, text string) { - if !guard { - panic(text) - } -} - -func filterFlags(content string) string { - for i, char := range content { - if char == ' ' || char == ';' { - return content[:i] - } - } - return content -} - -func chooseData(custom, wildcard interface{}) interface{} { - if custom != nil { - return custom - } - if wildcard != nil { - return wildcard - } - panic("negotiation config is invalid") -} - -func parseAccept(acceptHeader string) []string { - parts := strings.Split(acceptHeader, ",") - out := make([]string, 0, len(parts)) - for _, part := range parts { - if i := strings.IndexByte(part, ';'); i > 0 { - part = part[:i] - } - if part = strings.TrimSpace(part); part != "" { - out = append(out, part) - } - } - return out -} - -func lastChar(str string) uint8 { - if str == "" { - panic("The length of the string can't be 0") - } - return str[len(str)-1] -} - -func nameOfFunction(f interface{}) string { - return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() -} - -func joinPaths(absolutePath, relativePath string) string { - if relativePath == "" { - return absolutePath - } - - finalPath := path.Join(absolutePath, relativePath) - if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' { - return finalPath + "/" - } - return finalPath -} - -func resolveAddress(addr []string) string { - switch len(addr) { - case 0: - if port := os.Getenv("PORT"); port != "" { - debugPrint("Environment variable PORT=\"%s\"", port) - return ":" + port - } - debugPrint("Environment variable PORT is undefined. Using port :8080 by default") - return ":8080" - case 1: - return addr[0] - default: - panic("too many parameters") - } -} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/version.go b/taskman-server/vendor/github.com/gin-gonic/gin/version.go deleted file mode 100644 index 535bfc82..00000000 --- a/taskman-server/vendor/github.com/gin-gonic/gin/version.go +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2018 Gin Core Team. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package gin - -// Version is the current gin framework's version. -const Version = "v1.7.3" diff --git a/taskman-server/vendor/github.com/go-playground/locales/.gitignore b/taskman-server/vendor/github.com/go-playground/locales/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/taskman-server/vendor/github.com/go-playground/locales/.travis.yml b/taskman-server/vendor/github.com/go-playground/locales/.travis.yml deleted file mode 100644 index d50237a6..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: go -go: - - 1.13.1 - - tip -matrix: - allow_failures: - - go: tip - -notifications: - email: - recipients: dean.karn@gmail.com - on_success: change - on_failure: always - -before_install: - - go install github.com/mattn/goveralls - -# Only clone the most recent commit. -git: - depth: 1 - -script: - - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... - -after_success: | - goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/locales/LICENSE b/taskman-server/vendor/github.com/go-playground/locales/LICENSE deleted file mode 100644 index 75854ac4..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Go Playground - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/locales/README.md b/taskman-server/vendor/github.com/go-playground/locales/README.md deleted file mode 100644 index ba1b0680..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/README.md +++ /dev/null @@ -1,172 +0,0 @@ -## locales -![Project status](https://img.shields.io/badge/version-0.13.0-green.svg) -[![Build Status](https://travis-ci.org/go-playground/locales.svg?branch=master)](https://travis-ci.org/go-playground/locales) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/locales)](https://goreportcard.com/report/github.com/go-playground/locales) -[![GoDoc](https://godoc.org/github.com/go-playground/locales?status.svg)](https://godoc.org/github.com/go-playground/locales) -![License](https://img.shields.io/dub/l/vibe-d.svg) -[![Gitter](https://badges.gitter.im/go-playground/locales.svg)](https://gitter.im/go-playground/locales?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -Locales is a set of locales generated from the [Unicode CLDR Project](http://cldr.unicode.org/) which can be used independently or within -an i18n package; these were built for use with, but not exclusive to, [Universal Translator](https://github.com/go-playground/universal-translator). - -Features --------- -- [x] Rules generated from the latest [CLDR](http://cldr.unicode.org/index/downloads) data, v31.0.1 -- [x] Contains Cardinal, Ordinal and Range Plural Rules -- [x] Contains Month, Weekday and Timezone translations built in -- [x] Contains Date & Time formatting functions -- [x] Contains Number, Currency, Accounting and Percent formatting functions -- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) - -Full Tests --------------------- -I could sure use your help adding tests for every locale, it is a huge undertaking and I just don't have the free time to do it all at the moment; -any help would be **greatly appreciated!!!!** please see [issue](https://github.com/go-playground/locales/issues/1) for details. - -Installation ------------ - -Use go get - -```shell -go get github.com/go-playground/locales -``` - -NOTES --------- -You'll notice most return types are []byte, this is because most of the time the results will be concatenated with a larger body -of text and can avoid some allocations if already appending to a byte array, otherwise just cast as string. - -Usage -------- -```go -package main - -import ( - "fmt" - "time" - - "github.com/go-playground/locales/currency" - "github.com/go-playground/locales/en_CA" -) - -func main() { - - loc, _ := time.LoadLocation("America/Toronto") - datetime := time.Date(2016, 02, 03, 9, 0, 1, 0, loc) - - l := en_CA.New() - - // Dates - fmt.Println(l.FmtDateFull(datetime)) - fmt.Println(l.FmtDateLong(datetime)) - fmt.Println(l.FmtDateMedium(datetime)) - fmt.Println(l.FmtDateShort(datetime)) - - // Times - fmt.Println(l.FmtTimeFull(datetime)) - fmt.Println(l.FmtTimeLong(datetime)) - fmt.Println(l.FmtTimeMedium(datetime)) - fmt.Println(l.FmtTimeShort(datetime)) - - // Months Wide - fmt.Println(l.MonthWide(time.January)) - fmt.Println(l.MonthWide(time.February)) - fmt.Println(l.MonthWide(time.March)) - // ... - - // Months Abbreviated - fmt.Println(l.MonthAbbreviated(time.January)) - fmt.Println(l.MonthAbbreviated(time.February)) - fmt.Println(l.MonthAbbreviated(time.March)) - // ... - - // Months Narrow - fmt.Println(l.MonthNarrow(time.January)) - fmt.Println(l.MonthNarrow(time.February)) - fmt.Println(l.MonthNarrow(time.March)) - // ... - - // Weekdays Wide - fmt.Println(l.WeekdayWide(time.Sunday)) - fmt.Println(l.WeekdayWide(time.Monday)) - fmt.Println(l.WeekdayWide(time.Tuesday)) - // ... - - // Weekdays Abbreviated - fmt.Println(l.WeekdayAbbreviated(time.Sunday)) - fmt.Println(l.WeekdayAbbreviated(time.Monday)) - fmt.Println(l.WeekdayAbbreviated(time.Tuesday)) - // ... - - // Weekdays Short - fmt.Println(l.WeekdayShort(time.Sunday)) - fmt.Println(l.WeekdayShort(time.Monday)) - fmt.Println(l.WeekdayShort(time.Tuesday)) - // ... - - // Weekdays Narrow - fmt.Println(l.WeekdayNarrow(time.Sunday)) - fmt.Println(l.WeekdayNarrow(time.Monday)) - fmt.Println(l.WeekdayNarrow(time.Tuesday)) - // ... - - var f64 float64 - - f64 = -10356.4523 - - // Number - fmt.Println(l.FmtNumber(f64, 2)) - - // Currency - fmt.Println(l.FmtCurrency(f64, 2, currency.CAD)) - fmt.Println(l.FmtCurrency(f64, 2, currency.USD)) - - // Accounting - fmt.Println(l.FmtAccounting(f64, 2, currency.CAD)) - fmt.Println(l.FmtAccounting(f64, 2, currency.USD)) - - f64 = 78.12 - - // Percent - fmt.Println(l.FmtPercent(f64, 0)) - - // Plural Rules for locale, so you know what rules you must cover - fmt.Println(l.PluralsCardinal()) - fmt.Println(l.PluralsOrdinal()) - - // Cardinal Plural Rules - fmt.Println(l.CardinalPluralRule(1, 0)) - fmt.Println(l.CardinalPluralRule(1.0, 0)) - fmt.Println(l.CardinalPluralRule(1.0, 1)) - fmt.Println(l.CardinalPluralRule(3, 0)) - - // Ordinal Plural Rules - fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st - fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd - fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd - fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th - - // Range Plural Rules - fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 - fmt.Println(l.RangePluralRule(1, 0, 2, 0)) // 1-2 - fmt.Println(l.RangePluralRule(5, 0, 8, 0)) // 5-8 -} -``` - -NOTES: -------- -These rules were generated from the [Unicode CLDR Project](http://cldr.unicode.org/), if you encounter any issues -I strongly encourage contributing to the CLDR project to get the locale information corrected and the next time -these locales are regenerated the fix will come with. - -I do however realize that time constraints are often important and so there are two options: - -1. Create your own locale, copy, paste and modify, and ensure it complies with the `Translator` interface. -2. Add an exception in the locale generation code directly and once regenerated, fix will be in place. - -Please to not make fixes inside the locale files, they WILL get overwritten when the locales are regenerated. - -License ------- -Distributed under MIT License, please see license file in code for more details. diff --git a/taskman-server/vendor/github.com/go-playground/locales/currency/currency.go b/taskman-server/vendor/github.com/go-playground/locales/currency/currency.go deleted file mode 100644 index cdaba596..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/currency/currency.go +++ /dev/null @@ -1,308 +0,0 @@ -package currency - -// Type is the currency type associated with the locales currency enum -type Type int - -// locale currencies -const ( - ADP Type = iota - AED - AFA - AFN - ALK - ALL - AMD - ANG - AOA - AOK - AON - AOR - ARA - ARL - ARM - ARP - ARS - ATS - AUD - AWG - AZM - AZN - BAD - BAM - BAN - BBD - BDT - BEC - BEF - BEL - BGL - BGM - BGN - BGO - BHD - BIF - BMD - BND - BOB - BOL - BOP - BOV - BRB - BRC - BRE - BRL - BRN - BRR - BRZ - BSD - BTN - BUK - BWP - BYB - BYN - BYR - BZD - CAD - CDF - CHE - CHF - CHW - CLE - CLF - CLP - CNH - CNX - CNY - COP - COU - CRC - CSD - CSK - CUC - CUP - CVE - CYP - CZK - DDM - DEM - DJF - DKK - DOP - DZD - ECS - ECV - EEK - EGP - ERN - ESA - ESB - ESP - ETB - EUR - FIM - FJD - FKP - FRF - GBP - GEK - GEL - GHC - GHS - GIP - GMD - GNF - GNS - GQE - GRD - GTQ - GWE - GWP - GYD - HKD - HNL - HRD - HRK - HTG - HUF - IDR - IEP - ILP - ILR - ILS - INR - IQD - IRR - ISJ - ISK - ITL - JMD - JOD - JPY - KES - KGS - KHR - KMF - KPW - KRH - KRO - KRW - KWD - KYD - KZT - LAK - LBP - LKR - LRD - LSL - LTL - LTT - LUC - LUF - LUL - LVL - LVR - LYD - MAD - MAF - MCF - MDC - MDL - MGA - MGF - MKD - MKN - MLF - MMK - MNT - MOP - MRO - MTL - MTP - MUR - MVP - MVR - MWK - MXN - MXP - MXV - MYR - MZE - MZM - MZN - NAD - NGN - NIC - NIO - NLG - NOK - NPR - NZD - OMR - PAB - PEI - PEN - PES - PGK - PHP - PKR - PLN - PLZ - PTE - PYG - QAR - RHD - ROL - RON - RSD - RUB - RUR - RWF - SAR - SBD - SCR - SDD - SDG - SDP - SEK - SGD - SHP - SIT - SKK - SLL - SOS - SRD - SRG - SSP - STD - STN - SUR - SVC - SYP - SZL - THB - TJR - TJS - TMM - TMT - TND - TOP - TPE - TRL - TRY - TTD - TWD - TZS - UAH - UAK - UGS - UGX - USD - USN - USS - UYI - UYP - UYU - UZS - VEB - VEF - VND - VNN - VUV - WST - XAF - XAG - XAU - XBA - XBB - XBC - XBD - XCD - XDR - XEU - XFO - XFU - XOF - XPD - XPF - XPT - XRE - XSU - XTS - XUA - XXX - YDD - YER - YUD - YUM - YUN - YUR - ZAL - ZAR - ZMK - ZMW - ZRN - ZRZ - ZWD - ZWL - ZWR -) diff --git a/taskman-server/vendor/github.com/go-playground/locales/go.mod b/taskman-server/vendor/github.com/go-playground/locales/go.mod deleted file mode 100644 index 34ab6f23..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module github.com/go-playground/locales - -go 1.13 - -require golang.org/x/text v0.3.2 diff --git a/taskman-server/vendor/github.com/go-playground/locales/go.sum b/taskman-server/vendor/github.com/go-playground/locales/go.sum deleted file mode 100644 index 63c9200f..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/go.sum +++ /dev/null @@ -1,3 +0,0 @@ -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/taskman-server/vendor/github.com/go-playground/locales/logo.png b/taskman-server/vendor/github.com/go-playground/locales/logo.png deleted file mode 100644 index 3038276e6873076ecd542099e95b25037b1c0c34..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 37360 zcmV(-K-|BHP)ysx*JK zMpBX=dbK}5gAy}y3R{{beYQe$t~_(EI9HY=983!yQ4BbH2t9fee6m7kr7b^x7%_4X zJ9`gfp(=T?K~s?>F>nbtbqz;?9&D*HLWLAVf)p1<2qIzzh`mlUaSo2aQfQ+xioj4u zi57RSK09+4J$n}=VG1>K6C+;`IdT#dKnQiRIYfOMa;!RRrZpi|42HT(K7kH5Z51D0 z2RV8bBU%zznI$e~3~;G9N{kpKWf73XRDQWdPL3KgZV)nR5J7tvJAVu-VG5JQScJDo zR+bL!Ta3IbT6ncoYNbC?j4!6pWoxTBl*n#=wPJ6nPG_V?T&y%kcr-zED1W(DRHZFT zhB7~qA6u3+V3JBCZ4gs{L}jKoF=`!luS|!&X@DUWZdUYba2WIU7L}XOvil!bU7wAXuO|PIN?OtwU_FF?ptGuGegAxjs8(G9yYG zg|%{%%2R#1JvUt~pwDwIP%5I+ft0_2vEYw`$yQ3QA)Db+A{7b_0054wNkl}YE}wrc9DS+rDCwcq-kLn z6*rr9Gievg)&9W#+|En4X(tdH=fj-$InQ~{3w3k;I<^V903k*-k%?L`+gy zD<80`%CcVCt7&b)>-AWo}M*k4L#h*SN=*WN=wOPGQCc(S19x{GH}}yZ*TGF ziK2LMaUoYPF2r$dT&q?u0Q}(MpEI#8)^7>wy*j~dU6yeGL|G)4Z!`D?6v$J?4GNiF zGNUM+N-|jqFSt^;^pX20u^KaC*wKL1)CJS$%Vk@iEmQRU!98y?czh5h263h#&UI8G~>;F&}3tQ$@xhmG@h5396##KW2c6&nD-->t* zzH&?cgu?c})WwUscng4f{a@;`oGHloVP3&K8 zYWaY-m3_Qz=Z77^NgMadOSSCt@E=Ps4GgQlTkY0kAe~EC|Lpg z0C`J&DPN2UyU7&Gu-tM7^CfvM>!_q$|F7zV-={;NRk*zX^&Xy|sN>Mfv~agPsrszZ zST{=H##(12j$1JtBfT5p%`HZ(R~kw8ecKQFg5WJ*x&2m`V}}Y*yZ+#L(7tQhrOc;? zl-q4QvB#(*`_Y3X_Vss0x8Fk3#a~Y$nt>$Qn2*D~V85{yB8iQ{r9&gU|I zev9S7uL8Gt)I|dF=Y>|QegWzPvP@{V3Nn!IR4VydvXh@BKI2xUMBh(6aBL~@%r!AuWVG?f=&mJDxzGOktCLsq`D9Be0N@V+ zw0ap7DLEZtMdX4AhRfVstkov-f;^PxlkxbXr%Y<&X1CewisGbJ`y`1>y^eD%RgLHX zYcVG7w{0ENyVVm($?-3NBx$ln5*EKMtyUbD4wv+JlvSVUD^3~+YL43}RqjpaZ>3ze_N$kOC+VOY{hW+5B@jP%seQ7^>9XbyLO_reD=`#sdf2i+$u9o?M zdc~#Q*=#JUW~0w|6Dzl8Ec<(uJGK{c1uP-ECFnFoEcE?p>b=X@zgJgrNs7N?y_(l62vH_2aOTu; zH1Wkuhrd?fG^jc{yVoI7S9+u_MCut_7!Id3v9PUUb&ldf@7>y_JFay%O|e@o7B~1R zR>f}jzhMAekSBme7+=8B<$4CP2M`qy9;PHYV6Jyi@gzzQxufnYeT4}(ia$$dqsPwU z5sO*J_umWFSAy&Qz_!oZ_MFx;KV|fIOpaJ^|IlRj`#mo`7L%L${sFWDr)GmSX15!x z-ju0rqgjo2_ERjgP*qK!X^q!LX;y>Hu?d|?f1KrU_f9eo=CJlH^$aSqrQQSef(+VI zC|ev?=iM66d@OdmUC?cIyVcDG)WLl$UUUh>iAb>R_igW2u?(N61L7?ic^SATn9E7n zNxqRMszu^JF zAl2kMNq7&8r$ZVW%4{j9Mn@?q+c73i$N&u<3-i9;kLlEE%cl5$T`V6CkTnyOJ+mDaOaDWQ*^ecn!U$EDGLmsW}B zARh3Q)rAo6JL!FggZ3F6jy>B;&&!jW5FMg-Pfri`&2I0*$r<%!@Z{{~#$u(6L5tIC z^ct$p<0cjz2bs`3+o&=gg zN0I9tG<<%Iswa`AOAJdUZZ^xs-z{*A5120pqimm1%e$$8lj2Rz-5n3_^+!xU`FD3; z?p{7vc6^8QYfHemZ=l>~d!hFs`#E}j$4Ogk{OLe2Q=08L;!#{n!QPLNUsaV8bX6T_ zoZeWG8?W;fL^?9qw}QvFOlz1NW~S4EBF|xQlOZ}B-97Er#?yIiJSVn3uGPB5yDgsX za>d8T9K^q@j<*wkQ>~J@2auzPFOmx}x0!EFdB9!yU9WwxvgjR&?#kfg)Re^ zU-wz6Z!-%j`#HxBkmxujd;G3VYpX;y0Xtz}E(t{V$~uW0lOc^)=|GS@GK+e7MHx=# z!*RE|?AE3ejI;Sv?ZxLMm2b0E0P-M#%6ch}d~Pk7{t#OF7gYEvW_6V_EC`1%sm z;p`;DqvO$3nU9KswqGY#rE*CRhZCi6Vg+4BzY4?O1Z^=|F|5~1w-IQ|ecyr0B;3%> z6NBS&$4u{pLhhSaJ04eT@6<#cQlX#RA=lns%xy$Iav8;|8b2CeW=l2{s^~`vfxD{}nt5yRf<*f`crJol5KDpU+ooq#9&8 zolytKS$vp#7S*yGSBhp|TzSfi1;>|pT8b=!z8&|j&*(e&+8TUqFrCtl8|%?a$FBL@ z{y>@BXE$djM^uFJTU_rioz{q{e5Fbf#|)xZ>^Gwk$Huc-c9m^sKiA@Euns4o_3#?h z5i=0rkge;=Umc~s?o7dWGHh16c;nOB7RtO!P^{%PB)h}wuHU|SgU1_E^|#l+Q}qdS zH#zt}!9}+!7OMbK0D7Km3rMzut~&X`M`exqrYM-~VVJwhgjJnk7U?*AzI_a9V$zJD zYHhE&WAk}!5pOwiZ;S039$dytin18|FPwW+$P$X}!sSCocO(=%2_8{qAMNLT)*Y5M ztEsG{FE zcd6Zz*ty+c+4me7W7MhL5el9=Tt?^XuMb_;vSwBV%E_{HLRF>yV3AH_j|HcTm^;>a zvC_jO>{*oxChK<3CbtTePO|dXP!_ATF7#edCex`hO``srW-Zsv6_-_5+@v|i8We%Y zyMIuG>bHs?7YPXYC-gp6qnLxi$pt8CqEy8~wN7FkrU^!Uudp5tkYr|StbYSr7gfDV zsM%*}B(Tv6Atx0*<3}nIIDfx$@1=y-X3vRdKeE41dk)V6r>|lW>)}zv|MC*Fy`WVDgB%|{yeSf>k=9~(Lk%M*Vv}w0f(3C@}$xW z=X;gp5Q-lcaybmN2}XLiG@bn1#U(Pt?#M*{@CI`K@ZrY~KmPdP15Q4?y(75}eD891 zC_7n)=49M0h?tLJO|BA$D3Dz}f!wJx7^$#1Y~R+{IWt^h(BQN*7k{Rg64=2xqpssD zn`W{H_xI(6YZSCPV+TC8tNs^9A%it&I(jN+PxAE94F2TRn(Smgm^H4&{6j33fOh zZjjt+-FdS%$#sj9&A8U=j_334usFvB82#hjhsQtOJig5p-xephIDsOb#>Knora0d; z5&SmI<#x`^b0pP@Q&HaT3K3^9*D>9aop88;9J?Or>4dJ6EzBUTMqjBY_GmR4Fe6FO z3~ldwf$o=IUERAW(~Wh{VsiKmmaF?;oDlu_3w%;_Zb7fRgLaG6Y~wF^?Tgs-~d>j&DCZN@>`>j_xTR{}t_f9U)W2S+R648V8hb{3Dmp813n?7e z6LF4tmd&OUt5Qilew8{x$Uy@An?-AlX{&(3EiElA<#AhfOL=T557!owu4yP~DebPa ztx)PswzAR!84X=8C4fe0x=1Ru)JJIjfz$+3Ov@v(L?jKOMvF@vC=8ABl}ra>#Kgob zYE1lL)E|Bqy)c%ACEK~@obP-O%4%vKqpYuMEaDb% z>Xe*wLNU)%FK*z7Jri6>qYAqoQ~6u3ywE}DD8MH{89OM0G^)dF;hsksFBVOkXtT0L zA)0_y?A`NfeW$BFX`cjk;gmBhQ?bvFCP#gkc*f;o0ClWv2_(_=U@$V0blZKCc3>Z- zBH*?Mrjtn*NIp28+w$lrc+K<-%I$&t#c9`?SWEITs|_o5YRdX)Clyr@1azy>;plKs zILBxE2xv?d84A5>{!r^s^r5BjTb85%_(J2Zgm{-@VQR0h$oiG zruagSqDUa91*Hjf5jbT!=~D(dN$Ax^u%=i_N2ScHLF4s8w)Nt}WP($HD+eob4+B3P z2EH?PEIFp0@qxWyt=$peI9dq>gRu@o0?Cm`BpwOQCWH9i=%n2qna56ySnw)tT9SZx z7W;3W%9&~C7}KMVF^|Hnz%@C&C$MdCP+=BOb8{&*LJl6^&o&ZZ4|lRKcdWUR5qED&dJGwX)i)6B?n$ zOosG;3l-6!Kd&dR7|)UkH5H9Iqee`1;=ypJmBx9KQkSgDkU6M&@Vi>>Nx#3cdf>G)y~J z&y#G)I3rK8{v8dNM(U#AD~htsQ86ORxE5|0tFhji;NKFrW=+J=$c#L1JJ;M3Mo_yeqOj zI*IXjLAHKtzljb9u;77UFc6Gj1l&oB<)$6oo{t240gG#7-W|uHxO+xnbWFQPvFn(8 z06vU5$U{urHQalQn-%>gb9(cFpCbKaOy_`aLnc}uni3iZLGy;BwGx#%B&?Pz`TT~< zFIEW7G%Cug1j7}YPEPZslA;&+91*slk5kMm7b`V6lCvX`*`#a40zeNW<2d^Ek(+jmJ02821OEzy2yukV2AJ!GIcxE4Ry$&BNVa08W#W3>t(6_>z^&514EIOeh48)L8Is~0v&gIH(NED?41y597-PtVe ztf&wb7hftBovGq@#uW{fb@gJ6a7rT=iAw}xLt+TXNf>nJ_2#p+1oW!jxIpLhY~ImD z)3g=0m8H?JDzsiy-{OUD>}momhezG8Bi!@ho?h3ew`JS6?XyoO?MX`{Ih#D(y!*>9 z+lTvccHUpd#|p+Dy$89$(8o`yZD0gi7RQifvXf1ZYH!*`dtl5$w6P=Kgt*4kqBS`k zZ87L|XlFX4PEgbw;V@nSjrSXf1d#yj8;QQY>e`_$saY=MD$1%SN@bU1&CUD<4__hV z);A6)J(s#KahiuakvBoOl!z)MwHkBvl!nWJ!}XfO2yB<)O8EN?dLu~@C>lNY(lkk7 z%>nDC$81b5fCsm>ZD!Jk+96JX>F(s=w?{|5h$UdRj7(eX(}C@~J3Bka`S;#<@4-$0 zs&(!CIG#W-fb9;T-S`X!lEL|TOC(^QwOb;}TLyyISCYV#&QNUdD#Y z8cn6pZ6c?m`rBi=tFajL1t5>Cl`71}b}+o5E}^8lt4sD`?W>%+@rl6-nShT&4y3zu z8==dP>3Wy1BO2Ja{(tAGGVi5@LkIAJwZ<;7?X>ZyThF6J~`Y z)dCX%APghL<^pjCuKBRackk|hcl*w*Z@=B1Y#ROVdfolx?VXeNj^BImX<_HkJrc05 zj6_zF$ys;A9uG$1zIf2h-uU^X9kUJ%=Y~_m(xIEDwiTcqN6i|B)e9EEdXumwL8`1& zMpfH^;0e_3JWWwVDArE2OAW1aF%rh2G&ZEFl#M;DktuGJb$6dB@|-KL@Kn@^M9re{ zhQ2{g5qM3txY(o6C^cf4CS(u*89P+chm7aXN)cmGdP*JDJM<|%kEnDhfBfDX$0tW? zAoA>p2jW0=7V%I26rcSc=fUTpc+l`3#xgzGV?*%LG};1-3g@H=8*c-DhDDXIB6tJT zr5tkcWhiB#^XZIIm1NVpA^G9I5_BDio#spM7E7oU-V+LUlO z4fsyEh|j4W6I6>PM6!tv%1n_lIQmi&c7>6|9Ca9}s2ai{ipE?0aO7Z*GreB;q7}Kubavrj@AubsZ=XzW9AwkkEC&9KH}c1afW4b6*s)YD zhzARg)~`io0r_Y>i}1b~@L*74Bok~L#RinfAsDTdZgXPfuCWdqal^+`jaeh0fc2EuRfs}21N(Wucufk-eWo4VJO@TRbITCj|;iwPI3 z1%1Yu%S>+Uj_#b?-A|{dJj<)ku0H$4Zl-X1=iueT&4a0Qb}4_nxpU{>zRwbAdjF<< z#WKHQ58~KI;_j8Wdln22EEd`Ybk;qCgE(Vx2Uwi%VY4XQ&o){M|Jww}ga41D8AfPS z?I8TRJ~BpuZRphiB&omMIA}Ds8;H;i5Lu+{;Ka8 zjzHW{*EtRfFB|KtmGEwu`yh75Nb^Gp74AB28zK&*j9pPZ%7bJ@@?b*5*6VF)Q!{j1 zrjWUp$=qZ1!h0^)^ufu4^won0X|z54$mY8{yE~t}a_9bsZ|~g7ZebR_Iyzcgiv%od zcaKu8;0m!87n4#^Z#FKMQfWtRskx*I$t7X%HQl4ee4k?0&e z=jqeVA`sR->zDR%cc6xa!o83J4WaIv= z{lK4_CvT$6wfO%!W{v%f2UphcLfC<~!^gFQ9AVd4mlB>&3+5|)&BSD)pGK6meIzMVeKuIEwv`uggJnf^Ohf13E{t)+ba?R@_D_&E3A)6YNu z^ysf&e*Ja-@XcUwWn?A(=IqFdeFdLEh?*oT)+27;G<=(x86f;=BnSLtv>3QV8w%H+ zhS|tl;Y{Msbd=PO>4$0_A}KXqfjUNz{&tn>s+15Cp{^G>!m)|2nu!<7#v7h~y1t}@ zgIzBwI#=H~F)+Ys7}xN)-P~#cU(A**htCpJGhxb^JvD-(;$%ZrQ4 zi_7cl>)HI$`X`4=U*>N^qOQ$Dy{)kpWn>KxJM1GEe0*giNtE0(ZFeEBvuW|dZB{1S zW`j3ysvg*c4_${NONQp=q;SVCrocl~p^!?alU})qyDl}io8dRr+z@k1U*ai;i_cUP z^AwGB^^GNEobK*tlurZUmG#XR_`C|vm|Q9y>{6A14n9m0=hcMKK^sxOns(03MF}Iq zCMOMp4C2KG-N<-p#u3eAavO!rwM?N<$lUt=+uM7)Ki#_XRXV-y`QejyKYM<4@fDQ4 zwY8OAPN&n^d_JGu-vG|<2iPmdmdS267~Rpz>8>BHS?qyP-@MB`13y#S(*oK69Tdic zFQ%}~i_5OH0`Gu&=sK-tX{?HN_#Gr9y2{)N8QX3oC>g| zXU$OB6#RcscMw^Kv*~O17!*%$4sSn5uWzm2`tIvzpMB-o)yEfC zS5f@(@_KrG=}X+UU-EC{ckGr~cYMSi4bSp6msiLj;2dNjDu$sapwhfG|r#9TaG%npBZ&Y*wR__7PL^>hj{! zhSJLC#F_~K`?Cb1649CKGA>W^Dn~F;<|(Z&;_&32b|L?&+{`hD&N})jI)!MX7MB9v zR3?{!M5FiFNgC)>ByvrE|@PjEy=b-Tkq=Zw-B>wiqn3eAY9GuJ=o(q0QQg?kxmfzA}X_tOpOcW>u!zq_>b<9Ej= z7Z0|+$A+(>7``SsB%8%S6Mug<@ z_U9@EFYy)QV*D)4_2>9iMUC~B&+v=OMM{oLSrRVcs=E3IjZ#=mB^Nc-+X^+f;%C7}i4*&k=@UQ!y7VZb!M;2H&tOT;d zwMPWun}j;R#Ggt87z6!nY_{I(@M>WRTQTe@u-SzaITqDjA+8{EBM`W%DN03v>$DGP zifYEMOpS9C7rKjh`~gKV3WZ=99;hm+;*^x*qhU-bn;N?!mlV~6Zs_}U3u*{Kf1g8Y zq;pmr5gNr)>`zieO;)XyO@7pLKdsJWG8;hn%*Izge3X0b?caV#FMsq00PWqomS2C} z+xbGXzP069U*BTez78Ubw&$~7qI4v2kSKQh2nIe7S-E>}XXCHKjeQ^%@n(GN~bst8Gk zv^}ON<(3z7J={vqAV(uB?<{{+R54s!RD8MnOgX1iQzkA`@I1V+=7(idax=-rt|zDj zJh*yJoj9WS#cr^YO)|G@n$Hd23R`dQppMU!KCx7lAjU0~Lv><~( zR)y4#fw}FPoUC%e?Fg^z+?p<}J=66#)ITdnb`Ybn|1SX6^|F z&1eSc=uzx}EzriYEwckj;no(|Elv)0PS#iq2J7g)*=n=vW(p~)kVGnWb#Wv6F%bd$ zL69v(G6ly$BNz&S4>b;g4Vqg3OqO|ZVwhnD1^PIVIbg8Uq%2<6ESr_LUMzQMhA&<; z)Xpoq+9Ao|YQF{-9GKxzyYJk1xGO0Q07&TG`2bdNVU1f_U+P?6`l_Kd79t@Yc&Icu zD7M*H4$R%_dFry)->(J86Uv+rQ1}ReP!JKs1Vzhn;K0ctArSPA36XVd#!f=APZ%wj z%%U>@qpM>uf?baWM&Yunu|TzziGgJ`PGTbb~05fO#S>Cx;DFzWV-e>SdLCJx8S}7zx{Zv{UQYY#S7-kNwt?-Tcxc@T!3r2Qs8377nzGH zE}xqZ#SaEJ2zbD;fq{At;{A10mGp5?Z9qgk;6j`a(4G!`4L**?F`=2EkOD&gjF6d1 zW`s0>XgGus$)eK=pj;(0QbdemLap=wn;Qu>uAAbmzLy_ODPtXjj z2lIsT1+B1C|4=caxpjATJ>o-Cd)I{@Z~f=>c3535La-0az;#tS-t&?Vg}s4`f>aV2 zd~A%bk3-})yi(XCC7~Q7%2Jodmx16euPg}I*0LZ7`~Xx?0dfXF$38%nb7a3LpWMP^ zeB6lw@^Q%e$T~k_fe$S*B!n1=_uI3V;ep#^>w>p;am3nStT65XKSz7)b)sUeQyi%n zM^f@$yq6``$>bqgGPJ9KL|34T?Z$8jBLp*nNlsvcCK5J+gph;~IzmMJ{MeBRad|LE z!NN;c9ut|O7`J%~u;~JdyF4XJjCU*y*3OG0J z44B5#e#xn9h)t8kN?T>XNz^XQgVUuFAf?cmJ|FnF%CDf@)h0n#Q%~z^UoXpp?p_-Z zP%D707NPw5p*%#a;bN; z2Tsue6a{-7FwR?TtZWWYx42_0tSDRdkQ{+w##p!(6xK!hve^fjG#WdM+!PnVgdhhk zE=Lr~q0>U?en>>X#|e2bO~URRFlKtNYSac9mSf{P7ss_P=3XqkP|n?6n=%HdYv)Zc z&p^Q6ZHIa0;dZ(b>F&mOZZkQrn$Z-#l9Fvq2PU7!x+xN z082&|oIuENO)P{(rW2Z=)FT`=B80IHA_2-CCn16W%4A_)xoJ-QXPa?;_K{9#?C&2m zDM!@mGPQ9eZR}C}eWSu)FkQRVbqgB%H7IizFW!Km2Cj833PATr_zk0A?x>V21vnaI zX29pL$w0}^IW&LhP-|XVUfKK$W4lf+hg}`+k89ugEl9nn))s$_y<2~7QXfN)D&!Qh zXe)_?( z<V}u8invj{s)^GKhDyeJdBx z15F*R@B2SBSw0!c}C!c-R)*O|2u#nh76OfxS zKncajV1S;c7*9$8B{bE^!`ssX>tt1eLQEk(^&sYU^*>3Jn61DZ}9 zP+MlWV3OwvBg8BO5{{W5H1~EDUAlDFtK*V)J@2HFUV8Z0;ZK{7eH#1H_liA`2kj*$5(lN6!%o1&CjZsBdUisW9tJ3Sp4k zJZLTtFqx-;cbK0q4;ULe0u0&5dAgv5T-4`x1_sbbpMimOVBqg*zN`mwy&+%Hlk=6V zb=PR6Od?gG7vwr9OQD^k;@a}Xua_a%KN#$kqet9n)=YU<)x*xs%jTV|xqZDQ{a8%Q zCvDdcx3#n!ON?obilGq;X{^FTRn zt*g9KFk9?NR*s%nU#f4lH6WONb#9R-SSOGs;93aq5a=9)AZGgsLy=H2!Uj|_4i+_3 zyCgg=pDpgXq*R;`Bjw^w+2g_?kHdOY!tmEXg}xjM^zGuOvUF*xKQACC4rpu(2*p=)S?{h?nJ~wwmd|x&@A_M z@h$~=dKMMce>XHYH`m|acDR4I?|O?*>0w&iXKlw~XrC6x96MZ?OLQTVLDwBd!5_{2 z+{MNx%_6!G>F=ojwEixyKK!m{RsG44{)(Ch=O^c;e)j)<>a)Yw zzwj%LE=?uwtWIVGlM16^aG8uuP_*x1WRP5O7^-b<(Wlu(MbUPE+1OfJVh&h=JQzo! zI1_Q3DVsLgSl}66j7WD;=s}?$S-cy80-8+ch&XVIL_$si1Og)D2z>-dZ~}Q}gudOS z{YC!;=wbbGwMO6f$MWLF!zUv*^b3aRq_o%5)MaV%TD9TEjVBK$z}XWMPr&V3fMaC& zNitQXET?ibsZw%?4@3kXjd%$<&8M|WVQ~XgB2I0b)j^zh4yp}Cn*GdE&~LRUd`SPow+4*`|gHqVR$=w@X_Oi6YY;hr3xNXL}?J20+TtEm8CF9r}LIQyWdSD+i^Z0Ip zh{57;(m5glB7lk?3Fx~R+MNDz;B949efHFprWaApu8fS_U!ttNxUgoJrH{9M1;ASD zduj0_7w$Zqm;tX(47^(0))&SvOY1*=Z`|{2R?cLsS~_jt?qF?+-R!Z|0fR}gx3Tnc zv87N*pfJV|8L6R7VJ8w`M@6-1AqdnqA5mgd-(kJEH(eAeM1&%=u?g60(a-&6^KyOk zvHF!+Jx8Hgm^IFuW(^O~QGMDlAOCJ6=x5$BXu;plC*bR0+`z=ZlZ7YaGPJ6rxjmZC zg^y84dQ~MLRg%$GZi9qd2@F*HSnc%MoI)o?Ezg(8%F04K_N|aa|M~KJ;lYU8V4JjbM8Sq z+i-V}Dy#5p=V&UZrl|I|7%I-5LUE!{d~p=Q9yTDmO$F#{B_~d>VUUdo>J$k2MkeRx z^u5xZ@*Ti3&@*a zn0|s*Hz;#Z-Pz+y@BS^7E?wsLr1b!umQ>jQaC919C6Tp$wXyM6Qa-4pK`sgFTAyxM zqf20m&9gk7VRCZy%%A&tHDB(p0JF3FOWr6c>4vkdySt?1_n%I`QF1yftK0uf$-UdR z=lW8EiK&q5(AbaeVK` zwXdsdVu25fLlEv3!bS}1Famw8RI$8r?%cUajY6R?r^6g4>>GO8JEdRg{rTtBOT2Hx zr(Q%1z9>|xwZ^rzsc|JBuWREV2~r;#n;+LgVMjy$`OMWDzb$QyFC=lf@4+bZOa}gj zI9Ewqfp<}D{GooN|4X{7^<_Rlv6ti1?rV*Z>|(`QJ#Tf2cmCA9Q~OV!^4||9YoGrc zZ)}5m8$5xMH_mP=DLGqm<;vOan>YP$-aOM`rqL69`byK&n~RGB1E~&FFDlj1+SwO4 zCwLjc*4fU%5>OkAGsa@eQ5$Q##byegQHLj!@u6fIA(Vx#f=3YsEkV$Su=M(>qAFh1 z$#ds;9V`6`p+dR5I<>qyq*U}j=(yC;vGREJk-}is=+flI1%pw$b_ckIrKEQcjlHim zY@q&zA_snlxPLe@`Vv~2tS5(is3Ephs)F!GOZ?LGqx&;6kH#h3*tFK##@ct@7Iz8} zv(l^>=GClroUAzo4nJSI4N0@-~&5Ot|!i)Me4|u$jypwSAfLEA;UFEiy=YwO-ZFZ3YBk9c=WLC0w5Qrp z9lX7>v#C|#ftXycz})6&-*6Ho5I}3+OgfH32qyRiGt!d_qkf+3Eln?NnLBm<`h(Sb3;XDv?N%%BAI%5@_-83ebk~>T@RGwG$Vw-qJSiT3FEP z{#Y<5hu1E7dCh&>aqq#?@6i9~pM^Sj+nZ<4g5Ccg_z|o=y92(TJqw=i2It?*I&<^P znKL)De(3)+)xtKnnOfxJbk4IV+Z$w(ILqzO-0d*dHh60W-qj6{PjPh2ZT=|g)2No_ z^y@M7QXjDS%8>m&PR7_^Yku>hp;K?Z#+B&Ms9CEa_iee(l||{MSG&#gBc) z?-{>y_2I<8KzsWPkhJTy+Tq2qmHK~~xc0Cn>nJ?#7ZE`q!4v^?6v3Kgk&i_*77q~? z1414GvI#^YY($PGd!~aJw}%aJlb914EH26#A><%Q0^=HD$W1U*KoLO!#qe6a-xk%` zw+s7&Z|`@`dC%o{eqVjQl*OV7cpP5yjq4%?557+E6f-?NJ)m?T)vEp5Z=w3_+wsI_ zToWg!k|OB-B;dRog z^%m>bS-ks6tc8~)3IV!0fnG>g(}z4yitqQPoLion17apFIR(%OA+ABPNDSN}9#5*| zm7x*SpFJ+QIl6TGvj5r9{@RAl+B**)jOE5OE;gcEJJoaIX=SKiT>8Vyqn(`#8SyW7 zd>q*E#es;7^!8n?Wp60POO>Xl>gDsJrMG^6dQc!AJg8(j7c)34*--N}c$g=X$t2jk z#K{BLR@_{Ncm+B%|IgP&S}94Me!a+JNK>6d02lK4QMLj48#W@wZQZ+-MCC(rl6=!_ z;Ok+uFmh5fndTmy6&)Q`m@t29h%(iCZECv2(-W$O1OYle>t4h`GKM$^k(MQv>K2)n znwP$Q<@n{kHiWm%*2k4`s=O-`NMaWoXCFUJeURJU9@p8{x%l=(MY`V>|9DIg#O1|w zv@Q0JOU66fuF7lce;dD3Cn-*1v4nhNFd{L9fru>@F=QY(oF2b|IJu7Db>abcCxGi< z!}y8ILvX@L&*}R^w@Q|WI0agf<>VLh6MdbjW|2lHTS==(_N&&}SeTeZ3E6CFrjW}P z(%5Viz%+FNw;`vu6eTx3^p17uXjKK%y<*D)_ z`nv0DC5pPbHiB+1X0@pM5PkYRE#GvYS@HQ?zKuKj=m&{t%|3JBAm zo_eIA%-t)1ax^gdf}F&}99!E>k(Q=wEDbjxs$1!Y2LwdLCdI}^Me*4o!mO;!LOMHv zoxtU*s|(b<%|GX8TBeFTa84MymSk`cdWZXg{onJuB%{}6iieEduCqct^(np179=wy{~ zCAH_2Wh|*&AlNI&AJKr^f`DI4sGPZ?@a_M(I^K2AbymM(?Fe>|=|^)6j#yKm)p}wM z#MU=5U{k;beLGV-QfRfE`B2|4^N&ZHP>}goJe*yu z?H|1|q34kHNf1` z+|tZo(}p)m&dyXMdd8&i@HC6(9gV}t#$FQ;mgub=xMj_5m z=pFVCJA^(!bTXCzYl}VKb)5R>c*FUg%iV2bJ$)FLscd?XSNRxCn#W(nv`3_>o?(M_ zQ{4Lpki@9c|CsSle^A+1qmY-Dw$}ArJyj!}tdZ|kyeU;4%vWM0qnO8Gh{Uk?AVgFc zJiJYd9l#+vl>(vTy<0?J7H*=!i1yUZ@GOtnJ67_dOWnm zCx$(8cnl4)yxzLw!{2=K<1cq^7D{@$D^*A1;`*AZ;+j-#zy5kW%K+#CUB@ZJB)Z?xm}8IZIlm+$$*K9Fua2M~-oh!PF@Pui*ekK)Aoj zbV`Qawce&fOvsALaS%e7`nMh}_m*$n$5+eusyP~srXYu3Pz~^W-$be}_BfesG_}R* zi%p;YkG|L1HlvxuQk}eFr6Lp~K{~M5FU{ zoz+8hA9N`Vk<>Z0+@=h*OwSF?wJ-=L*FK53&bOuVsR3q2tMyl}F)}hU+(@!=TW9yK z)oM&xJ^$qkn6uj!wQY~hTE~#AtOW49kSpX?bGa9qmy?}}TAGJ?h3cPsZxlV+?g86N zCW>ZM6$LB-kLBz#_|q>xb{wBQ|JLQYhFZm$)GMQ%ss#-FS5)OLl*hEkS1sh_rm6xD zRpf>4%d1fNEq=Oq>HP6$7ZtUF`cmcmhZ9S!1IlWp;2=*a6CcbM33x%GW60QHZn}_4 zq!U_((-HehNMB+1`;Q(?FE2m3Q6ReaX#QHkg&d(!2nWX-4t}I%W@Lbao`Igdsl5To zj*4tf-_lH)BXXc)59zW66$5

^J3SC{O=CWxCY&tzNKiT7Ed?5&{U3B&KGl|Qi^kMOQv-cdv&|b# zHv+SZnT-wAe#7(YZP%L^B$3jDwEgJu(xPef1bPBj%~dC;>1=x8>E5aNpVdk9wEbN6 znfaFOK%PuQ9ON7bZ#)?~79(fcCXQqA`D`Z^Rgu8`diJp@{pdoRYN4v4B4!~qJ-xju zz9IuzeC7N8f2iUny2fVW&qlO$b@fXohTE2YkVtuxm^Lfs2*8}h`MmELTD7An)$top z>)iW4A+RHqf!yXsIQ;4yji&n6bje&nP9`W_hdwjbH)&I*Wh8ZLl=GX0)U9S4oXxg6 zZ{12VGBnnQ1(;YF+gRC~?6xwY(n4ZEb7U-Fc{#E{b-*pmQcv9y{)P@%LPCS`v-JaK zT8IV_uYiNZn#0rZdHL1O0GRqoE^pN`*{DwiyuB!#aE=KF62E}$cw>RQ+gAg zsYe&`UP`U3`0(qQqqLS-DIYLd2FV&Z7OZ9beu-$Fy5@4Pb z6%`PyADnHMZKoHEky+BJHLEtSH`ZHcVG(Ar7F!#4+W1&I9@$}i^N1`Z}+u zyi=Qw=EXF5SA_bhQsc@)(<>q}u&VxP-`GS?*T*03`fjmreyMNxr#i(*y+SY|FB7<- zD&PpDJk~K?2M(O7O=WZpM`W%ZI&sp{EfdLxXo|~@txkZj&oI8f*6T%cbPRVShlPZM z#D<5PS=s3u8DSG|fYF-ZZ2e%+oP!-UfH)X$UQIF%U!9HeWsmU-pG8@J7J`j}&tbIQ z+S<{5tvflT?#xdObSDT|o*GbB3%T4RuJ9Z)`NCCN zY)F{#>hap_GezrY3Wg~|+7OjT3*K0kle_;}|XMc1yy z$2TV>jf%nkGC}`HjgpA$0<@fqWrFW{_|MQg1>#9aGQhu16cF2;{t<%wz=60#_pdGA zQYR#Ex%{7)qSI_)Y)E7XEs7QyYn7N}a?r%~O%u#hSUOW(Tx@r5^^M)@>+4KfV_;-p zVn{O9vr4itNlJ3tZ*K0D7T_2{^9rMxxJSiC(=r>_v}kiWo1c=zEli*{@X2IqA-7<@ zh)L1fBhoDf*e-}C;vkz>3ah^5K?(!o;_$)KVhple11Wk?gIgQTKrF(Zh{Bw!Q8r!I#@`l`!c zi87)Hf^SQ-jfv!w_vWru=OAUhaDO0CSm46;%@k5IU0hBHAa`bPTpq*eA77VFTTbKCQR$>Gl|b{yVw~P=d z3=WBRgDu98<0@Q&37mDX67^AAcaqNd*F>^iooNO>OPEi{rzytxqraRR!ji z@2WTy5$7M1TD7Iz`+zDi=$U9%U8o5M@M-iZal% zBN^G5t}c6CZY*#!^&6N=h@@7dR~*C@GVH9bPHo@K{nFELN^ijCYQ;XLNq^q|ZAdG;UY> z7yj)T54L-~<*q85t>WG@_0-w!Jhz$v$g?NSA(AGJaSUK24kyaZS z6S~$92FY)>vopnp=HNBKo3o9wadS3{FW-IFWY1@M*ztZC8($6|w*Knyw!^q_A0}^K z!IJZ~BZSs>ypnPRAIOfU2cF#Hh|#6wKmeNXc@1bj)45FYd})7AS5Irj<+0)MEA7w9 z;{q!V>}vWvFx6ibxa-0DGgY52e!jR^{_xqK{ffq#$yyYxW&LtQHK|-9Rce$x@cTjM zVsxJwFf3HaI%mff*uFyUcxtuI#N~%=FvaJt-x9KELUuSilg6fj*J&1CW{2BnuUVa~ zA0BL%9gMpX8Ll=Ax4?^Au!Ef$QMo~EoNbc$Nl~_L25xBv_GzT`ULotq`@?tInERwf zoiN$oKqK$ZjHV}?E(|*%bajnAolvd5aPM9+n3u`K`BB*sZi$vHPg9I^zO3eV(s*6P z<+i>jqZzNp9O@`PkP+{HH1yM|R}Y{&^YZ&0!*?@g(2NA;Nu>f?BnFiT=PaItB|G;> z=ES5--_}esVNF_g15yalbVaU?7pNT%0zLHZS;BU$*E=+RI`!3C1&z7ahRpK z>^67a?SlKSP#s*HF&1pR*V64E>CHEd4hGng0vt#VHs(gbdaDuOOh^`MNzd=m!v+HE zD8L;$$e(PpUb_?ffUI4~m`-tb-)a3^iqFny*FrU2-4a9;t#C9k;pssL@;nVoIwGi% zl%lU(+t~fEGriI;9f>>E7xUsUD^%%M?jP^nG1C$8hyTo9fBntVmB%$*#^H@!>>f;H z12$xXjbIXJvXT&*vtSJZW&;HlM}#`=iGi$$h{MWFXAp=MA{BH%fgGiiL(Iz1C`GbE zR8Uu>r9t)Sdxr(_A z0$UfPC8dZcl(ZzN#zR9#%1#wA=?srh4F{cOwo4h4=Bf15d&YWG0|S{`x3a>Y$-p$H z8?=qwpyaoDb@T%dtae+y_h4!S*hBKvy(bTvOs2lsMYIgp4JZ;GI6d@13nO>8Ihnw( zet+?si)Wu)SGw-;xWjSUEtS>#FqvK15w)%B?&_#hKb82;|NZwLf4z06;@zoh7cU(u z1iob+KlIu0fm1$Rst>+3>tN^bI(ha%i^i8c-a}-fMQ_l@CS3MGm}FT zDxgbhRgF$nmkuAN^i~pCUW_u9hD{{YGkFvymndb|OOvE9c%U>C0voo@CbH`JYyqE7 z%S*2CEYRyKWO)@8%8G)#0=-IQsxhgJs9}m~dUI5UT_#zrsl2nc`@0bQVt8IBOba)c zwHV+~a<&1XMEP>;%lS3hn4{W`(k-Q>>(*@BxA}#2G0(>Pw?tJxaO$VvkN*7g?>|33 zG+_Va=g@QZm+}uBXc(M0^6J}fUmE&uMab~b(-&!1cwxpKmO9=0;@?UnC8JJmX1X`b%C`tvlhL}z%z@rEp7uuDZ7 zo<$$Gl;1khlF5Gfo?GK1HdUIjMwb_wuBu7T)bOZ~Tw`L;hv&=lkuZdzzQXkZ$$kOC z$n|O2%Od>He+ zohpx~R0@=t*jO32zFt~Z&u0-Un6P*$5f7P6p=*2yOmdP7kqd<;9*vs97ZN?`PQEOS z0NO0yRiEsu;4|cWb#%HxohH|zLm`Vc%A-{V6Hxle+s-{><48G?%;1a)tMU&70hT^} z43z$k2jSn}*#(yY^;73UVfY7*$tZ=!MTowV<%pH|F1s}$2=HwIR1x^e{OC0 z==YwU>9-rI4wb}6dk-~kZ7eEWud(0*sOyS8&; zc&>Ms5jMW7Hm9%#P*g$kGGWj%1|tX;-jz!ANJ3nPfAb)+rED@Y$q7btLenH^X(>V- zEmT0GS75%AEa3B4L{GN2CoO|U#ZW=`{o?SzFtIpHrVtzC^1KK|pFwX@mk(aXnP+7! z8oRT6vox9u^V{1bMypCAsl8zxw9* z$7fHUzH+7K`1Y^H9{#jzwEEgW|MluLNK{Q8PkB*QTBEsab^$1(E8@Ar7 zF7ND~xl@e5>WnXlzl~NL(oVkvRRz~ZbB}@73dU#flck&A*xUi>(3tHVTJ5%HgCE_p zCU?X3(x{_x4}NcSH*R!K8P!F3=#l2h#C*M{ zx4_$r=HM<%Wf?kF*Kfs@hPs9Xj83f#Uj=x8$lpTJ#r-uU-IhES#r%?&+mEGiN| zt>f3^g$h-n1)&8TPSG+lmm~r^)Pv#bL4iUxh0l~S$xNavmCW^^Q?sF=>cU~r1+FQc z$pWf`&vj)$Zr9h7%kbjyyr_JyVCyMF7E3_jQRyB8 zj#Nlbqthidz8Z-rNuuG1D3Jkv=)TmG>nRjAJBdiFFJqL&l9BV)ds0$(z-TEzZorgx z7evP@#6^4cM!8xXT`up_^_lAA>T&~6!2Y2d-|g7lT$nxS_JG^Ty$2t<*l=Rgqo+3H zLOc|rO3w!G>(Kfi-Wa@YyW_!9d=bQjhaD%6o~-`%D#l&gfW#eWKh)6NFol=@L@7@<{w?&jLA*2zBB*-$ey~||AJ@Q%<>a}Q@s8j`f z9XNn|0fEKl)t9lU0u~oyYAm8hJ(Ec!N{P7pJ`9dX6tFXtK$cK_m?SQbz~zH4D@mb+ z(geb?ydZairy$5PnZyesxeJ1}dMcFqt%|%%gDgxPW&rg-A(NS8261oi$c^K(0H*v# znwkzaVI1(Tu^wnQtSxyorg}@qzK(71aSKmY#xHE{S}18bdb1__e77nA1hADi`t7&u!?%Zj`)z6KO9|{!E|=v5EvO0AUu!;2abZ;J!%oR}qy-Fz*@Pb{W6cI&AVUi?h!Dy01 zDH`aA)9C3W&U(6VXAXTmQzFbGpwZ$*Lr2Q%{&4SSFbR(_st9-3y4p=1CYQ;>6nTIu z4Jz9=#|JL?9Y`Md;;Ge7J2T$Fm#b791N(tK;HhP91BF zIu_pAbk zS-S(1U)(zGyJgmX&TgtxtI-lx$z;Hv-Q9Ii5@oV@JcKS^Ave;6;RE;0b0zWp7#hEH zjt~*tg(&rK@%8g1Joz^3n4M9Yxc$keSe!`>p3!Pa!G>b%cH>%*z1Klykpcl7wEe`);MN3~k)xMMy( zc)oODzO*Z5Avf27F%E^};Dsq66dVdIW~+H;L%U^vW1@L~R^oe!AuC?lvGSKshgYCF zFK%3kt3F<3o|+wAdHc0R@csJS+}vybb~=ZLC&zmSdu^S%U9~!tl{$4@C?b#&Ghc#0 z&sdr_i-+9Yg9y41)rUl<`-;+bl6(S0bQcL-D9TyyD4&vr z18HC8cCGOr{p63cXECSTv1NXrzr!C9E!P3HfyYj@mUJmnqocY88qB*7Ou^dQ3lSX5 z2~#0p<~3XoNf<0nFyF8@6gHb18bcCS+SQkm{W{N#&)vK7<$LbAetUXwdUz#V-1U%g z`|qIqcXroxmm6yhIw?(H5HLGL2_)6*Vb5Nmm=IvvHZTh zvIp*49vybyeXHd!rrwo$R~X3Rtvv%6Xd9R~5_D|MT~TWHJVWZ?f+${KVeVR?mfl7 z-0piizZ~=@>l{q{-a9kXgPnVZ?u0l~8vB_cm1muL$X;%<88P>x(&_6|>FBla^}?JW zjy{0z?Lz|-6z9z#ijc=ZFx`bK(ulYaX(15n^VyhgBqed!n0;Y08H^n0!=q7^EQu5_ z2xU|VchTxuWs5P+J2o%Y9kC-EZ3%qEPIOqRTeL#av^ua!X=oAyyMZXj@hZu;S3cQv zSIdP*$4+gC(w1ob7fRwC{>Qc>Y0q6a)%EBCUe(Q~4t~*}xU;#c%C8;mR15m{K-aAA zCA`^aS&`Lvz4+c6{j0Ke?Hbc2 zd5&>-&X}SuLI$f=DBLqMV#B>-Gh&&sEEXY!$q|yXef@Sy0wmmJWQGQOp>!$R!wJxc z=yZG`0D;S)`vzpY?i7+Dd0bHtTObq&7+!2HE;|Dv2g%7n1VNb~7AZZ-S2(<|5t-HlSzI(7e0Zj5c*b;o$Y_mWDxVqO}v=Zv56rL1F*J)No^O?Ik0Y ze(0A~*2(gkBDL6PFdR<+tqZQs}x>hCBz5#V8BBqIu=AgDw{1J z2v})Mz9^K#$qrZ+8Q?34qz3u1T^NxJczcnb$d%3^Xeb^O3Q-^-5;+7egnCFkBC1va zgF$2D=yM8WLRyeOuY?;>gsJ6jXhALCyF4t_xd7Zm;N#xtgO4=zoE~W(Go?QA(Abx! z$DWFUf@pk8+@_lg59gLdJ#yjZrlx~y@4HK{?;0rF{dDvG#=`61Wi&VMPq2c3idWE> zXjy?9Uwr%Wg#F}QDRSE`paQtiioV&91f;A6gTZ$2xs!8tOLOD6EmIa~f>Odcl|C<1 zta(Ps$gHSvqn9aJK`8`2bhU&OK7~Z(feR~QQlxBbkEhZ2Nz-<6BeNs3G3Vy$=i=*u zP(X!NIFm>&i*@zlk6i_B}5 zZR&JE#YByX|9p=6t-B>8@SXF1-+OzW=l%GjZ_nKG^k2|+$3Tnji;p~X@k@L3;>FtP z?aCs$YYT7qR-a#f7e4K-xh|aY+*DT=>e;yQE*%fc`2JSKoTVw+fw3cr^jfAZCa^X6)+U@~PL)O)#Ma@_ zk-BMk#wIB@7&nPzav9!lP!c4N$Tum(0Rxg*x0UOz#uw6zVCQt=}b3M%P<#DO}=^wwQJyno{aG_O#npRTrR>&@&f{mYzm+QQUoCqb{!~0gC_;(m9y-x@ zGIj!GjuVlcW*yquNi=Ex;gtW~ptjZngsWi%$)zqL6%*92e@$1MtIBvKBE3Y}7+ zCirS2m?6;8KiP1<=>E3G@m7(8GE$-Vc;Yk$jo3gW>%@4ol@>5WAP5zW7CYKcf$jR< z`|n>?UHKmCHSVjQzSn*G@!O9)a(t@2_srzo4}?FYQq|1xam)5XR}N_pkn1CJBW!SX z$Jx2{vj7|eQZWVCec=mNd-J)np8?;hx)|;Fd~d5vQRQ}~W1iaHDOZ?gv(8@$``_O> z+M6~Hj`lmu;nOM2#2pE>O{(_DiMk@Xf=_1Lne}RlWv*C5R__yBoFl(Er)B; zb7iDNA{O(SR6=7=frD<8RuNSpOPt4%fF5O;4w1YtkEp3T-Ij3H&euS(7L6zf8iL(# z@AO0;=vcy;pLf~jPfhmT-G1uMjkmrRqpR}PYu~^2^N-&>c;>Hrx{n{ZxN>}E1yVoJ zUVAtyDpq!{?OxtL+}!y6@7vfqHXuWN=q(qLR~9l?rg96Ffhawi_GY7C8HPNQ2?lh& zbP1u<#`fl=3XLWxy?yCM_1<2^6LP@0)j1RmpmZk3MV3epGE?NKD71?S4#`((b*+fDY-!8hMZ_H9$>L@8byigVrD+5X!j{F_-7#D>IgePfb`w5sTcy0i;qQ zwtxrr#A$XaL@UI+TE}ZdI%S;)o{cGbI%aEGQdsR0v^71Mk!tV6Q1#~RNlL>SE?CkPMOhGRU+#i zf1)ma;=~ET6DRrnNN^|}% zzVo%_9w8BSG>juMktjF{u22BBu8OA$$^t=?P~-FYjP8DGM9kyFd_t*If+lmos_vKh zcy1F3B0pgjNM)ibC~K=ZgqSbm%k&n#$xBA+rS-7;L}NWVG7c!9u%gO#mI!9+)X`BL ztxI`yOgW^}v5=#$fQuONx!;(Ih{YDu>o2@H}ZlV-Ij@E;vLpK`idVg2^v{@m5g z%Kq8)&CM@DDF< zz7YUvOcFgup8*vH-XFIjuocFj%EaXw_;LfGSF4js(l8z&2sW7!iR#deX@-O{jd=s% z5XGy(ejT=U8&t%jo+xhkB31M->GbB=97sZi!qfs&w7q47ce%x`!c-=Au(zfRhs!RHISMnfN9|AvSh9QI zLgv9kqv*u;SC3WV8{1oz-QRv-KL7J@^S4_+EiNx_?e=*0;>}M8>c&ZZBx!ZKNrN!h zUlr6=Nn?DmSR*!wtsF(hs}>uR7>FPxs>mQuC2!)gLmdrLq0GW}TS%Y9q>fFitvqDA zb&wuB(a_WIgrm+F4iTY72jy^eOt#dr2H#G3pvxCFqjZ7d6?$>m&9fsJ@PRTu!|>G0 z5yR_OED&gcud96B-Tihi#@;=!vNQqN@kw(hV{U0~on^ju8*nWQxu*;Zxi=&W8*SlY zI28@iblhz2cbOF~nxb3`?SWt{)9xyJvfG=0bou>`neDAn@3hY`xVw3U zh$x;sp*kT|#mSzWAy6=glPW$J!<_^w+;MV~Po|N;)=2ak^!Y#Uo!dvFWbrwa9G{W~^2>PbSlv zFw_i6n;ENtE0kmQlTfLbgX_!H2o*+!+ejq&GB=QB5v8RLvsxS5+A!Fyrg6BgXFMFH zU1oD_2Oa_>rEN?qA5P^%-n@5g?B?phr9PGn$9AJY5EFSmy&iOE|&5hx!Mn#pR3Uv!a@LI&J zq%tWnka{am&*A6=$YGGjYr*d3Sw-X4NMtBtGVzjDiJAl2A4e#CMmP@VhMSHjs>7(a zfdOZ=4TBRCE(-4VD*z# zNh(HQII#jfxCV$lxmp3EqFpFWQeJ%0*)b-aH-jFBrw{!67eD=9C&%mW>RMmyLSDYx zGU~E7uF&UuYdh|S;_p39XKxz!cadt_e!P%;ys$X3Siq-{dv|Z`^R4UKlv5Y=z%1+@ zT=GtEO=+`E_iR4xW&D0Bn{tHE6v&R2E?+vlus*jxT%P;=8c3=`R_hG-OECfjW_3T= zPg;3$4PWj9S6>^G2@3&;uJJi?0}p3i9MniPY$iYC)9}bDkya|#i?t@ToG;`^)uxmI z_r0}0E>h|e=s%+8UN_JTpo+*G3h7{s9Xe-iEtO5{vi|YWHI_Q?EVjRYlif4BmPgLQ z>T!jYoavH1)lq^(R`gDUeRmf<6J}Q%sy+8#&5c}n90w1sFlQL~>ae)GKeyxYhIQVW zM5?;lHjhcXY#3p4MYAsa-w~oxgIO5BaN_eDxeR=1;b>>`X#JL;rw2bO&{FOs8Plo+ zQf{0b0zk%MrkFMoAZ0k}Ds99>YV=Jp#5QhU@|=Xv#ZCq6h2Y}~v{g#uI38C9Gd+1? zxC$ZScSMNwpty_b@C;hpXh@0M=J8`B9OfFjCdJSc8gY=zSpDkxRd9?B{(kH~FyAZa z!!CB+(RY0VCw3lF*H)a+s_dP(yBjiYQM>0QWGBDP}(GzkarYYh?rCjHA)TGl%*)e+wBj>RD%j*Ti5V^v7;VTf=%W*<20$3;%Gm3?J zlOzc}HNCV-5@Z{VVu{9@F&K@Sq!{pE=*Y_50dQfE$BVg|02I@OZaG4kq+6^}6Odaa z;N4*RBDFMvo&-k$qj$7n?r~y(mA!#SccmE@n(Z@r?@Sh0#npd5V}rQr{*_Z;0anYb zz`~^xqOu~w6uZvjY_q#uEr4TE@DPxe!51$Be#O$n3)lA2X5IF}@-CCWX`*d57l!%R z;Z1A22%siHc0@IfaJ7wULx_KQe-0;v-TgX#Eza%iPWOA+R(gyinvjheG#rglD}f(Z z3%R(^3`%2wi@24S(aVw?+yN%ORm_)T+8GQ&#w!ScAhd{^xTFlqd>kbqtJ4}S2Eu9) zHPqF&wY56f$(V^SokFQ1p{VxK9@-YxnE@;UGI@0sTW8mP9~wi;iw|FTcyS%OpWDha zB!GE}Lbj|Mt%P_5DQ1P#h&Nt)6 zYsY*Wlq$jrue!#I`b1^n@eAu%7ykc^KexUDqw85c*)LNf<(4b8e6%5CVw7xf)$xg> z*raWeD0qA$8NgeYsPr5XnuBhAl2m3C3Tu$i5M;Qi0Dw7Z4`kr zK!kKcI^5`V=&EaR--XjUGt{nXY&Is%i~`fK%C3X!7w)*w*N2}5O!7PSE8BU*qzLzm z9yTy#7d(}{$fQeYJThz@3r4@(_tSxYaOTE~*AMbuzc;R<<90e89S*r@q_1=~)la(+ zEhBjy1Z437yYMX*3+osDTd%;wtv-A1Szl&I4q(PF zEfa`Qs?cOepMfMn`inQ25X%Y`G9^c*!iZ|fOrsnrsy_+8CQ_?J^}@Qk`V&esWcS0T z?}tq7zBe1wRm3u|$%YjJCjVH|9;3N5W-KqF8E42=ZL`tE!E6Yj>*y#N ztOxrnIe#7d1ylY1H~-jeET0hs<)NYB3<->wMr?v`a!^22srWeQZiyRmb9_~VgtnxZ zBr{grX2{mH@*vO`$tGEHIO*o|2m&U-=gZ|nk@}=sWR#?o1kQS6Rr6_J>RN3;*PzMc zBv6-z;+amD_QO>FJ?>bWM}3RzT3*Lz%j-{%tx;YxlP(YX(_z*@+lpx_no6g!^|7(t zo9ve^!?7*w>ZZf~)w184&Fa9i)PaXVowqyB!=WO4s2U& z`}haeZNGrI%5t+oc4C7%nM}q<1xm<^LtwEd5X1$57p=~iK;qZCwI;ci-^7>mtuk&V z7AwRJG6fF0M#fVK|EZ!VJQA7~*Am03C)o*upc9*$){oeO`@BQBUy>GX__i|0_qxU@A z`VA0BaO}62r>6&Z{`>$Zf~e+$r#`s&q;ws83sR6>2q=JcnBErJd+5`V>8+qI`1Dl_ z*f{||eGb%Xgsqhn-L_CnHaWyFU0(N^YZFz~xnwL((xgBg6131ZdDYSl70^e|Z~^jp8?99- zf+o;bJW~dCD#F$h5hBYll9cI)w3yu^67@um1tC;_QQQT8bOYyu(^yQQB0NG5>GIQC zPle|QpnLVzPjSd)tqT9Q6S7TL@bj8eeFwdl;kI#8rmG>0H)Q1Re7XuZcm@DCo(4-) zj~klk^ma<#uG89G-MDeH1!KQC4FUD&;%Dp?JHEH)XYoB;e?Y|w1?$mx0Y#^vrX?fQ zqtl!*Xu9KTa-8C66UjQsg?C-g4=l?9&M7uW>frFAgi2F-(J;6HYLNs{iKeJYSgK9T zr8&iBscd$mg9nth#gMSt9-+@-G+Cmz;TXmYls`pZ%h~y@5ASUpD(BB{?BLwo)vkxQ z{~c{-YZvRC(#}XL4@2>2Yk4+Z{sKMp;mLPj;_rTIhz$nA<8XdJ8Bn^l9$qe|wKZ*M zr)Y?T(sp?YY4*jR&qA*K=dZv1_1Di2W9#AGANT_&9{xUB9FEa2D;Rn^D&PT(SI`_T zHwRsKZK@c>u2E#hT}PFfE5y=dJgz25lgiJefdM~=dr{z%JV;$?u5*CIL%bP=}=a;KtaNQrRra(og&9(q=AOpm(RTIf#V|n{_C_%XR z`Qbl*{R`#Sqn|GR{tGQ;5cB>T+WP@8eu3Yz{Y-O4xs;NQPnuA1Lh(UyLScZ?qQOwa z0OfT)Miyz3)77F%(O?+T_sbt};bLcGGDFtfT6E1_JCKFSmu+1pR;XDd5=H&d&L zcqs*s5a2dyVZHZYxI8*IJy?Eq=ZQC-1E+rZ%iS-ukIPsq*gLrU^_^YxnqS3XLR!)< zjR1|SRqICS?6Z$P`R0@BH~L$3q z7r*`S=bx`09o@e5+fP3}5N`eFyN@5e6>c8eKmBD|w2;NP$X{Zr8Rf50vTWwlF(xnB zU~CD#kkl#FQuRE*zI{lMvo@ut^-!PndX7}{r`J#6M}Toh_aw@% zzVPaE&mBGYI5a3vUHlztxc_+Y=--V$fsrJ4ep)WnisfZvYt#vXdL6<(I$bmisv-%D zO`uoOR%C@UY+)eKFGb^AnpTTNGuE`oLDW!r-t&??i;@h-`f`QGu5-`lG8y!gAF4DjR0kRMZr@qvaw;kP1C+&JGI({(3E~=Skg5 z+l(=;*n%2Mb_oflPMh5Ugn-#ZHkFOU3n9$0IjK`ACjmQXGaKY z?%etiQT62)UmxGRQG&TwtDS1Kj7Je+?8x+9Tn|rk2aOq>P6q)&38~61Dwp^k{;)O* zJ=(}&=JAcncCNjJ(q65f(`q%xA32bghorz0w{hKHeeRxVFYxE>7cMU^PoKb%W9!XO zzx>6szug{>Ay=llZ9bXL<5n}Vg22rXttxSvXdVs@JsIu-`&)a=O}WRIeOAR@%9G<+1wx4{g0&-FdHH#U3>@gCLH<8@TB09RkftxYpb7 zgIDWULwRX+jz;BNVN%KE_P6KPM-V9ew@y!C?>Of%_USGU4(@)t7#}T;76%6t*!x%C zo_~D6T#HeraN>K>sMl*-oJw9Jl>##`b(0Vj+6Kz2a*QWwb<7E~cH50c3rT{@>*z2{ z32KVryL8BNVwwp@Nlm_zVY8vZ1L{Yt?>iPhvCzC#^H$EvIreV`r@vof>p$LUVAe}( zRc^pi{mzbtG;F<&Q-1{M>mztD?S2ptRdBiZyc)p3N4K164UoBAV-P1rH}{BoW@BHh z?>!x^{mnW?=P8r9+^~Eg%OYF{;TkuWFQKb;arVbwf#tdjkW<{@?Ci&jPY)Kcq9CPa zi8c~5j`P4srf6N^lAK&Y=4Oz#>n16~hO(P#Mp>av%5BC-n+j!CKzD$++Cgh>D{SRyg&fsye_-o(ZbBW_DpxnJS7GpF$SF{| zz&pR#`Mrf_xe%OUVaRhCugtu>D?(az72qkNBO8GuRhQ;_Jm#T_Vou!KM1?a zH;}Z!WLJ~c)L#r2i_vl<24F1Ce|qEHJ70h}L_=G@-$DK{*N|?n=N{X{E8&lBJ-WO3 zc7N+JaZ7_veib;Hd!<&p;y7Zb-`^CsH|n_^dMTx2e32K}!R{H+()Oe}DPz-F6(zYjeEdl^$kpscN30$e0ZZPK^~6 z@a)21aOfL4MX8(_L);S?FwL1ODAyz!t>e1dmQB_~>PrhsC6$%3y`CZa_C!HYlj-O7 zYAlE_ZwklO3be)u*wn%}-%o%1;KOG>Z2-A%0LXTyqsAy0l}BQ~ysm9uspFZ7^7>Wa zeHf(y=5WzR>)Ya^b@3r>Tg-@&TneEb7&2$F?ztd$!MF?VcLq``uvZ}K%uAEWVm=8-l#|wg*Yin&Mq?daA$SEE=()TW4@=J343&{s#}A~& zy*URCu(wlNIhug%?Y9r#ci$gU9pz58+YW^{pz9 zZY7Gl;GH&iVC$Rv;W$jhii(&KuB2Fz&y3g&tlUOve}6yq{A99x#-A0erWN?hMH2=O zg_kWi7nUx&NYavwKpFn{`?E3K_GDfj$B9^)_GgwW@LW3S@j8*`p?5L~({!i&6CNl3^kx<8S0G8(+tSyD5tbJO3o%3)HK>lmIX^kWjQ-;rVwesJ@p$Sr{@hV z%UL!cL74`~C*M6EPMzbDgj5SI`8q~-Yfwf$(g(5i8s3lYzo*sj7eVH?MlH+Hq$^@) zd*oo-`?>u(n9pr7ThHw5Z{*P2WP%Epn7zzC5Z;-%!D0f7p9PDtbvTADbul*l1@8Dj zE)-0@?dyUfnZ7Rw7G&y#AMd$QQgta$p4f8CZO0-M4JEUU!c(!yH3x<+I|2h>i^i@+ zT+e_JA!ubN5*2xp(IpTWN=%_BHu1_N5*bj2HJ{AUNvCzfn5SV4{YFsr8h!9aD25!I zfB4~#A0Hq0!)~_Px`&X|Z(Q;EAl2AXsfM=t{^pKWeOj!C>WY@^^u6`|_KV`))4e(l zoXPPWB#C^*scndxn|pxwM7GNoC`rhyIlW%n_bssOiohEK|73h}B+H9yNnQ!8=FIYK zo}keY>bgwNx5m~$kldcsW?WTJx?IJkRLbNqx}i&OwhrqVOhDe|i*YVmk-PFtYQqtN zsRY(jN>>$BicC^0#8Ujk=sv>}1S`D~N#IXuUYX2&WNniMme+Dtojzn{%ex=k`gU=1 zQR7>UPNy^ywd*Sw{Q7IJq1_M*I#Iy;I$lq|TGcQKM%+U6w!B%@#Lj#)8cCyQB1ejQ z<0=pyA=MngBL?Tx_xBPKV@$?lO844|tEdJ#95GGokSom0@R^4q9CKkjwr$oX;+*Tc zV>Vjwe2Dv8zg|=2gE+Mq>V7e z9;mk4uf5ja-0EW(hSq3iOrGjA_@**rT$s~2i$z~T`8hdku`i&%`+tj|qYpaNs3l z(WE3PNLyzzqY|?w*-Yk(BnS+l;M+akgwiz&}U@7Q?QWT}=tit7$bRukmqULN90$RTVB`UY5qa*s9xR2McYi$hM&i~E4prOsJ0oRM5gWb! zQ1qOtr-hFfR2!YGRJDUlESQc&shUf?oQXV?%E61XsZ=(D>ZVuQ$Pl@DCYS3}x*&^y zJM3PD@dR`XFrEk5`Qga{R2*cIv7&83m>HB2c6}FJANu7&P#6pONbwbD9nxxEiI{Vl z7u+_vM)6UBJ0y}S?z#}|mG31xwKz`?j_4Pw@qY7=BM-ELyZUMi9&72RN?G;3QrPtGA&PU8d(y&|)MAk$G2 zF+6AH2b4AI>M=3~^(Xq~6nM;J3^NU4#U#yBf=#FbB(Efcep*U5Q{z;HsnF0&xILnB z)?9{Kai1NHY8`3R8_mzgH-jTopT219=YVIuvM81T@uNBb3_)2AacXTlA?|fHLt0Y| z|1&4To!7TSQ9~gohkvqr8{sUpST04Z3E?MSsjv)~;l%SE%AMB))~o3 z)-nhtN)A!?Ry~2|^dzmsd$qZg%T+p(S7n_lsLhc!!jPY^bej}wUO9s?{<#_gyfu@Ev4vb2#*4xizdX^%)ETV1Nvd5URB1~u=FVlvTqmOFeA;7=$78UE*t=saXJmvTiqJp-X$Z}_G!jXXl|a!J2(nN{ZxIp&$jvK3 z;@@(d1q$v<#(BRM?|Uh~`ugQ-WGQePH-yKC`)cBbLf^fISFq3S zKKb~=4-wF-xI`MU_3CgJsn2;9l{m9`KA?=uuAhGWvic(eA{ z4`~#gyc>2eEpbw8IVmg==ii33iFD+kj^Yg`d3-Q#vqmp}e0=(H_@SvDpK*!$c>nNz zh8t7-^2he~@1MVTzxd?-^ZK(-KF2L+K8nAEJ|jgTPi1$X!kb@bHU56T5I%#fe+YxN ze}fpf`?`4fVe`@)p0^vm(S?l*Nc1>rV;*pQAlqKjJ~}=cGdbp4pYt>NuH3f?lZb%J z3e^rg{5tCZRIa%~A{qg|47p`BCO^PkhIAV!b;IiESt99qq_zzp4`Fn9x+I zBp)J%|3%MQVoz1N9iH|?NGqt`pi0c2t2CyjE{`v@c}e;G;qcStx9#)OSMMG_e;41Y z_?!aJx8HvI?pG-IVfUZjEr6Gsqd(l;;u_Fv4Bvc%d&OsqmaXa)%H-@NTiLJc`h^yX z zdbo>>9#4yxG~&4x-VdcTG>^dWq?!z+~;V$UdQhi!-Wo9r-Q9N z|K=NP$SRHs1XK|(zomaMvVy;bXh;#`Js$4{{v)cqyEvoHw#p{)x^MRVunsPlEZ@E9 zFYA-s zxqI)E?-n7i@38^cgazBb&$zCSXoK*jpab>QT)(qU@V(=;y3OG+0&9J{2~IX|hm(b2=8MRE(@kPy}(F2o+qxmnupIO&6Evx6WT-~E0yI-hH7RWf#`y1iEx%+g9`5Vta1?`uUU<6zYuh;Qnw5~VD zto}61ZeB+&*%U>gNfbp$sFR6`JO#aXsdYq-Y3}n&yM7Z`+f`MUKW%@!ti^K@#UVJG zd$TJ@KTW}Cn>_EDB%=92g^=?#@x2(V?a{bJt(hvK8|l!YCqxG+o#*SOqq2n`8_C#^ z4;>_iYzXHdSUf-k8$u!~j`N(YNKKE$0v*5S<3qDRN2wL5&ft9CKeZ5|dgpws_GGhEoPujA;bY?P0 zZOf`I?(He@e!n3ifBW@f{vaML1N{f7;7 ziu|@ui+gm|85j+;48AnRtTg-zS3hK*!o#nYEite>Rtwt^)DZ}@i6V68*a|$x<0BDV zD99Y8)(Xb#X~LXVhQO?)v>;4*-(8}^o^>6rR$O+;d8kTBtvh(p(H(JvGlw~Q+*Kay zpAtnFE=CM*8YKNKKSM1g`nKiL#g(?2vVv4mCq_x7c0nPuP$rzfJkljq|3+{wMhA^0 zR+54ja3C)!jpGP@B~QasTGUH$-!1GOfnkM5gkiDct3lu5qBbToc(2G_zvfuP$7MHT zQDC6Q@vCKS!U)WAVxfGeDMElF6s5C>b!j347WJPp4L##x_sSWaw>=dHvAUeeFD*#TiIR&DsL3(3mJNkic0@xc9BCP=5XOSI@|Z z1-2^QC4PhylQ=sG`=)l0<~(4#4v;J3P}2B4BE;?U{%i)FwrpnE^-Z%oWV4$NIiZTU z&@wtp>ilk3@`85~6`Y0?Zo@sEqi*DS7+f@~s9 zSLGu2uvK=2-7Uk6C+y)qzQ5@}nSxFNpbL@RUBMO}ixH>Tg48uiC8|`jF%#p81veQ= zly8F*mhhd=&zr;g@K?8f6ts|?SNxE_iTB^x}tLrx2Nn-?w(nPdEFv24!tyhdyL9o1I!nP5lXY@qM1v-L~$JEeG z_gEYe#4cOvk*mm#6tEV-$5kf8Gr}8|&8DW=JexV2R|Vb!cDPn+3X3?BxQpllT}LDV z+xf^Wfy;6ygya(LzzK&mWm)UhroXh@SImMK3N5yWzKPQ`MGbS8&BTo6Rz~5lgYwP3 zP>uI|Pu>hxczy3zm2$9i6GdZV?d)bpgo`&X#p8bDD}0 zGTU)!Rx6#+Xk71_$RNwnhlSV=={@?IMdmQTOtGl-t#FA;TECjjU_ig5bOWOnLuO`C zj%@Ka>f1;(xnG*`nM#KjmTJ9pFG-Mur*HTBU@hl)*Qtn%p;f!C+%9rZU&pB36Qhl2 z0LQJX)=zBvsqfOOHWdCK0&~s`X4+a zNklAA1HZ9x1a~BoX4y*>(He=2KESRI_Bv zO}HKBfU|~1NdihUCL=0k#h8%77zwQrl12#Q{_^JW(F@;oETrH-dx|2%(abf%0mW$M zGF|6P(wX=rE%oc6iCWo`wr3Z;-66M`XrevpqH7eWmO5(k#L3x6m^)4qE*C@z)$WxF z%0pkfrh&q=*4oqy5W{FJ*Tii^Gl6glYr2S*)gb z^9Ehqju71?)@5)}Btw#%#!)6nZcY(!KRD?GZ)~^gd7CUxwP;W-tO|m(QahFo+olkj zGCI{=!nt%aBP6MsCK+r;c+dY7jhqT*g{sf9OXjP)LzZMNrU?AmOok{)4T)@`fHPF8 zYV+0-+aby<#Lh|0C>BfQ0=-t0E72ttv?2#Z$@KVo0|dptBKom z3v>mj3&VgIcXeKGY-ArdDSJIV?6g2^iZ%4%VmXac@YcUt}E&?3f9K0 z9+)o-D-v9cT(8O7OUS2Z&fvD?`w=rFIr0@!YQ~hj(km5AU#FD`-cHlR6pAJrN#1*} z+JZo77-Viz3k2%SVodA*pwF++VgEq~?8UHjvK%5n7q8GU0ev;L%(g%WLipA?Bw4Hw z!pm@GA_igJiefrmwn?8Scz<7YjdHFT1|^ZdRYzhwN$%s!nXaj>lhKTkP50uNKUz`_ z{!H?<8-jl>wpCP_2X@s7ul=1t+Qi0B*20g5GBHuRH11wN-58oBMIr))cUG#Uw0d2u z`zJ!pe1nb+_&;>0Hvlh~WdzNH0eT^D{vYW2)$6zE3=|&FC36;D4?#+8*sSR^P7~fI z_+~>o%D_4#@y?E_^IWw|AQ)}L3f4NP6D2L3qeA6L6wQ-zqvs;`)+V$kz6x8Nzljo= zEv2uGI;;Soslz8{ji84Uu~NA#lzD|%55#d5>;gTYRj>}wDOU84*TW3_sBf;>40#I~ zeT7~da9A(U$zqNWetQMS3!J~117wY-SdPGX#0VD#w?KEV(5ap*1y$hfA|6kHB|t8^ zG4Y)ejZa#pFmG#_pbj#j?K}x8xe!80F+=6mx!JS{8wgvIzf__p8koI;Ac8$$)sn5Q z8nhzwJn67xcq5pCi-oW~bd$9qEHyk7sC5pkkEH$=Ix_~CF$qSqKwr$*8pyF^0u!&$ zg?)uyup3^Oi(a8Kz1Yp`k#r2uCH}qtpo1J@C{ryF3?$__SN_~C#jYPJB?wb3!3>O9 s>SmKTFz#xX%2+j_#T4;&ea^-9Z+8#z7el$et^fc407*qoM6N<$f?|Tx;{X5v diff --git a/taskman-server/vendor/github.com/go-playground/locales/rules.go b/taskman-server/vendor/github.com/go-playground/locales/rules.go deleted file mode 100644 index 92029001..00000000 --- a/taskman-server/vendor/github.com/go-playground/locales/rules.go +++ /dev/null @@ -1,293 +0,0 @@ -package locales - -import ( - "strconv" - "time" - - "github.com/go-playground/locales/currency" -) - -// // ErrBadNumberValue is returned when the number passed for -// // plural rule determination cannot be parsed -// type ErrBadNumberValue struct { -// NumberValue string -// InnerError error -// } - -// // Error returns ErrBadNumberValue error string -// func (e *ErrBadNumberValue) Error() string { -// return fmt.Sprintf("Invalid Number Value '%s' %s", e.NumberValue, e.InnerError) -// } - -// var _ error = new(ErrBadNumberValue) - -// PluralRule denotes the type of plural rules -type PluralRule int - -// PluralRule's -const ( - PluralRuleUnknown PluralRule = iota - PluralRuleZero // zero - PluralRuleOne // one - singular - PluralRuleTwo // two - dual - PluralRuleFew // few - paucal - PluralRuleMany // many - also used for fractions if they have a separate class - PluralRuleOther // other - required—general plural form—also used if the language only has a single form -) - -const ( - pluralsString = "UnknownZeroOneTwoFewManyOther" -) - -// Translator encapsulates an instance of a locale -// NOTE: some values are returned as a []byte just in case the caller -// wishes to add more and can help avoid allocations; otherwise just cast as string -type Translator interface { - - // The following Functions are for overriding, debugging or developing - // with a Translator Locale - - // Locale returns the string value of the translator - Locale() string - - // returns an array of cardinal plural rules associated - // with this translator - PluralsCardinal() []PluralRule - - // returns an array of ordinal plural rules associated - // with this translator - PluralsOrdinal() []PluralRule - - // returns an array of range plural rules associated - // with this translator - PluralsRange() []PluralRule - - // returns the cardinal PluralRule given 'num' and digits/precision of 'v' for locale - CardinalPluralRule(num float64, v uint64) PluralRule - - // returns the ordinal PluralRule given 'num' and digits/precision of 'v' for locale - OrdinalPluralRule(num float64, v uint64) PluralRule - - // returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for locale - RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) PluralRule - - // returns the locales abbreviated month given the 'month' provided - MonthAbbreviated(month time.Month) string - - // returns the locales abbreviated months - MonthsAbbreviated() []string - - // returns the locales narrow month given the 'month' provided - MonthNarrow(month time.Month) string - - // returns the locales narrow months - MonthsNarrow() []string - - // returns the locales wide month given the 'month' provided - MonthWide(month time.Month) string - - // returns the locales wide months - MonthsWide() []string - - // returns the locales abbreviated weekday given the 'weekday' provided - WeekdayAbbreviated(weekday time.Weekday) string - - // returns the locales abbreviated weekdays - WeekdaysAbbreviated() []string - - // returns the locales narrow weekday given the 'weekday' provided - WeekdayNarrow(weekday time.Weekday) string - - // WeekdaysNarrowreturns the locales narrow weekdays - WeekdaysNarrow() []string - - // returns the locales short weekday given the 'weekday' provided - WeekdayShort(weekday time.Weekday) string - - // returns the locales short weekdays - WeekdaysShort() []string - - // returns the locales wide weekday given the 'weekday' provided - WeekdayWide(weekday time.Weekday) string - - // returns the locales wide weekdays - WeekdaysWide() []string - - // The following Functions are common Formatting functionsfor the Translator's Locale - - // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' - FmtNumber(num float64, v uint64) string - - // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' - // NOTE: 'num' passed into FmtPercent is assumed to be in percent already - FmtPercent(num float64, v uint64) string - - // returns the currency representation of 'num' with digits/precision of 'v' for locale - FmtCurrency(num float64, v uint64, currency currency.Type) string - - // returns the currency representation of 'num' with digits/precision of 'v' for locale - // in accounting notation. - FmtAccounting(num float64, v uint64, currency currency.Type) string - - // returns the short date representation of 't' for locale - FmtDateShort(t time.Time) string - - // returns the medium date representation of 't' for locale - FmtDateMedium(t time.Time) string - - // returns the long date representation of 't' for locale - FmtDateLong(t time.Time) string - - // returns the full date representation of 't' for locale - FmtDateFull(t time.Time) string - - // returns the short time representation of 't' for locale - FmtTimeShort(t time.Time) string - - // returns the medium time representation of 't' for locale - FmtTimeMedium(t time.Time) string - - // returns the long time representation of 't' for locale - FmtTimeLong(t time.Time) string - - // returns the full time representation of 't' for locale - FmtTimeFull(t time.Time) string -} - -// String returns the string value of PluralRule -func (p PluralRule) String() string { - - switch p { - case PluralRuleZero: - return pluralsString[7:11] - case PluralRuleOne: - return pluralsString[11:14] - case PluralRuleTwo: - return pluralsString[14:17] - case PluralRuleFew: - return pluralsString[17:20] - case PluralRuleMany: - return pluralsString[20:24] - case PluralRuleOther: - return pluralsString[24:] - default: - return pluralsString[:7] - } -} - -// -// Precision Notes: -// -// must specify a precision >= 0, and here is why https://play.golang.org/p/LyL90U0Vyh -// -// v := float64(3.141) -// i := float64(int64(v)) -// -// fmt.Println(v - i) -// -// or -// -// s := strconv.FormatFloat(v-i, 'f', -1, 64) -// fmt.Println(s) -// -// these will not print what you'd expect: 0.14100000000000001 -// and so this library requires a precision to be specified, or -// inaccurate plural rules could be applied. -// -// -// -// n - absolute value of the source number (integer and decimals). -// i - integer digits of n. -// v - number of visible fraction digits in n, with trailing zeros. -// w - number of visible fraction digits in n, without trailing zeros. -// f - visible fractional digits in n, with trailing zeros. -// t - visible fractional digits in n, without trailing zeros. -// -// -// Func(num float64, v uint64) // v = digits/precision and prevents -1 as a special case as this can lead to very unexpected behaviour, see precision note's above. -// -// n := math.Abs(num) -// i := int64(n) -// v := v -// -// -// w := strconv.FormatFloat(num-float64(i), 'f', int(v), 64) // then parse backwards on string until no more zero's.... -// f := strconv.FormatFloat(n, 'f', int(v), 64) // then turn everything after decimal into an int64 -// t := strconv.FormatFloat(n, 'f', int(v), 64) // then parse backwards on string until no more zero's.... -// -// -// -// General Inclusion Rules -// - v will always be available inherently -// - all require n -// - w requires i -// - -// W returns the number of visible fraction digits in N, without trailing zeros. -func W(n float64, v uint64) (w int64) { - - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - - // with either be '0' or '0.xxxx', so if 1 then w will be zero - // otherwise need to parse - if len(s) != 1 { - - s = s[2:] - end := len(s) + 1 - - for i := end; i >= 0; i-- { - if s[i] != '0' { - end = i + 1 - break - } - } - - w = int64(len(s[:end])) - } - - return -} - -// F returns the visible fractional digits in N, with trailing zeros. -func F(n float64, v uint64) (f int64) { - - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - - // with either be '0' or '0.xxxx', so if 1 then f will be zero - // otherwise need to parse - if len(s) != 1 { - - // ignoring error, because it can't fail as we generated - // the string internally from a real number - f, _ = strconv.ParseInt(s[2:], 10, 64) - } - - return -} - -// T returns the visible fractional digits in N, without trailing zeros. -func T(n float64, v uint64) (t int64) { - - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - - // with either be '0' or '0.xxxx', so if 1 then t will be zero - // otherwise need to parse - if len(s) != 1 { - - s = s[2:] - end := len(s) + 1 - - for i := end; i >= 0; i-- { - if s[i] != '0' { - end = i + 1 - break - } - } - - // ignoring error, because it can't fail as we generated - // the string internally from a real number - t, _ = strconv.ParseInt(s[:end], 10, 64) - } - - return -} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/.gitignore b/taskman-server/vendor/github.com/go-playground/universal-translator/.gitignore deleted file mode 100644 index bc4e07f3..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -*.coverprofile \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/.travis.yml b/taskman-server/vendor/github.com/go-playground/universal-translator/.travis.yml deleted file mode 100644 index 39b8b923..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/.travis.yml +++ /dev/null @@ -1,27 +0,0 @@ -language: go -go: - - 1.13.4 - - tip -matrix: - allow_failures: - - go: tip - -notifications: - email: - recipients: dean.karn@gmail.com - on_success: change - on_failure: always - -before_install: - - go install github.com/mattn/goveralls - -# Only clone the most recent commit. -git: - depth: 1 - -script: - - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... - -after_success: | - [ $TRAVIS_GO_VERSION = 1.13.4 ] && - goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/LICENSE b/taskman-server/vendor/github.com/go-playground/universal-translator/LICENSE deleted file mode 100644 index 8d8aba15..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Go Playground - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/README.md b/taskman-server/vendor/github.com/go-playground/universal-translator/README.md deleted file mode 100644 index 071f33ab..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/README.md +++ /dev/null @@ -1,89 +0,0 @@ -## universal-translator -![Project status](https://img.shields.io/badge/version-0.17.0-green.svg) -[![Build Status](https://travis-ci.org/go-playground/universal-translator.svg?branch=master)](https://travis-ci.org/go-playground/universal-translator) -[![Coverage Status](https://coveralls.io/repos/github/go-playground/universal-translator/badge.svg)](https://coveralls.io/github/go-playground/universal-translator) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/universal-translator)](https://goreportcard.com/report/github.com/go-playground/universal-translator) -[![GoDoc](https://godoc.org/github.com/go-playground/universal-translator?status.svg)](https://godoc.org/github.com/go-playground/universal-translator) -![License](https://img.shields.io/dub/l/vibe-d.svg) -[![Gitter](https://badges.gitter.im/go-playground/universal-translator.svg)](https://gitter.im/go-playground/universal-translator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -Universal Translator is an i18n Translator for Go/Golang using CLDR data + pluralization rules - -Why another i18n library? --------------------------- -Because none of the plural rules seem to be correct out there, including the previous implementation of this package, -so I took it upon myself to create [locales](https://github.com/go-playground/locales) for everyone to use; this package -is a thin wrapper around [locales](https://github.com/go-playground/locales) in order to store and translate text for -use in your applications. - -Features --------- -- [x] Rules generated from the [CLDR](http://cldr.unicode.org/index/downloads) data, v30.0.3 -- [x] Contains Cardinal, Ordinal and Range Plural Rules -- [x] Contains Month, Weekday and Timezone translations built in -- [x] Contains Date & Time formatting functions -- [x] Contains Number, Currency, Accounting and Percent formatting functions -- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) -- [x] Support loading translations from files -- [x] Exporting translations to file(s), mainly for getting them professionally translated -- [ ] Code Generation for translation files -> Go code.. i.e. after it has been professionally translated -- [ ] Tests for all languages, I need help with this, please see [here](https://github.com/go-playground/locales/issues/1) - -Installation ------------ - -Use go get - -```shell -go get github.com/go-playground/universal-translator -``` - -Usage & Documentation -------- - -Please see https://godoc.org/github.com/go-playground/universal-translator for usage docs - -##### Examples: - -- [Basic](https://github.com/go-playground/universal-translator/tree/master/_examples/basic) -- [Full - no files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-no-files) -- [Full - with files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-with-files) - -File formatting --------------- -All types, Plain substitution, Cardinal, Ordinal and Range translations can all be contained withing the same file(s); -they are only separated for easy viewing. - -##### Examples: - -- [Formats](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) - -##### Basic Makeup -NOTE: not all fields are needed for all translation types, see [examples](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) -```json -{ - "locale": "en", - "key": "days-left", - "trans": "You have {0} day left.", - "type": "Cardinal", - "rule": "One", - "override": false -} -``` -|Field|Description| -|---|---| -|locale|The locale for which the translation is for.| -|key|The translation key that will be used to store and lookup each translation; normally it is a string or integer.| -|trans|The actual translation text.| -|type|The type of translation Cardinal, Ordinal, Range or "" for a plain substitution(not required to be defined if plain used)| -|rule|The plural rule for which the translation is for eg. One, Two, Few, Many or Other.(not required to be defined if plain used)| -|override|If you wish to override an existing translation that has already been registered, set this to 'true'. 99% of the time there is no need to define it.| - -Help With Tests ---------------- -To anyone interesting in helping or contributing, I sure could use some help creating tests for each language. -Please see issue [here](https://github.com/go-playground/locales/issues/1) for details. - -License ------- -Distributed under MIT License, please see license file in code for more details. diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/errors.go b/taskman-server/vendor/github.com/go-playground/universal-translator/errors.go deleted file mode 100644 index 38b163b6..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/errors.go +++ /dev/null @@ -1,148 +0,0 @@ -package ut - -import ( - "errors" - "fmt" - - "github.com/go-playground/locales" -) - -var ( - // ErrUnknowTranslation indicates the translation could not be found - ErrUnknowTranslation = errors.New("Unknown Translation") -) - -var _ error = new(ErrConflictingTranslation) -var _ error = new(ErrRangeTranslation) -var _ error = new(ErrOrdinalTranslation) -var _ error = new(ErrCardinalTranslation) -var _ error = new(ErrMissingPluralTranslation) -var _ error = new(ErrExistingTranslator) - -// ErrExistingTranslator is the error representing a conflicting translator -type ErrExistingTranslator struct { - locale string -} - -// Error returns ErrExistingTranslator's internal error text -func (e *ErrExistingTranslator) Error() string { - return fmt.Sprintf("error: conflicting translator for locale '%s'", e.locale) -} - -// ErrConflictingTranslation is the error representing a conflicting translation -type ErrConflictingTranslation struct { - locale string - key interface{} - rule locales.PluralRule - text string -} - -// Error returns ErrConflictingTranslation's internal error text -func (e *ErrConflictingTranslation) Error() string { - - if _, ok := e.key.(string); !ok { - return fmt.Sprintf("error: conflicting key '%#v' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) - } - - return fmt.Sprintf("error: conflicting key '%s' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) -} - -// ErrRangeTranslation is the error representing a range translation error -type ErrRangeTranslation struct { - text string -} - -// Error returns ErrRangeTranslation's internal error text -func (e *ErrRangeTranslation) Error() string { - return e.text -} - -// ErrOrdinalTranslation is the error representing an ordinal translation error -type ErrOrdinalTranslation struct { - text string -} - -// Error returns ErrOrdinalTranslation's internal error text -func (e *ErrOrdinalTranslation) Error() string { - return e.text -} - -// ErrCardinalTranslation is the error representing a cardinal translation error -type ErrCardinalTranslation struct { - text string -} - -// Error returns ErrCardinalTranslation's internal error text -func (e *ErrCardinalTranslation) Error() string { - return e.text -} - -// ErrMissingPluralTranslation is the error signifying a missing translation given -// the locales plural rules. -type ErrMissingPluralTranslation struct { - locale string - key interface{} - rule locales.PluralRule - translationType string -} - -// Error returns ErrMissingPluralTranslation's internal error text -func (e *ErrMissingPluralTranslation) Error() string { - - if _, ok := e.key.(string); !ok { - return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%#v' and locale '%s'", e.translationType, e.rule, e.key, e.locale) - } - - return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%s' and locale '%s'", e.translationType, e.rule, e.key, e.locale) -} - -// ErrMissingBracket is the error representing a missing bracket in a translation -// eg. This is a {0 <-- missing ending '}' -type ErrMissingBracket struct { - locale string - key interface{} - text string -} - -// Error returns ErrMissingBracket error message -func (e *ErrMissingBracket) Error() string { - return fmt.Sprintf("error: missing bracket '{}', in translation. locale: '%s' key: '%v' text: '%s'", e.locale, e.key, e.text) -} - -// ErrBadParamSyntax is the error representing a bad parameter definition in a translation -// eg. This is a {must-be-int} -type ErrBadParamSyntax struct { - locale string - param string - key interface{} - text string -} - -// Error returns ErrBadParamSyntax error message -func (e *ErrBadParamSyntax) Error() string { - return fmt.Sprintf("error: bad parameter syntax, missing parameter '%s' in translation. locale: '%s' key: '%v' text: '%s'", e.param, e.locale, e.key, e.text) -} - -// import/export errors - -// ErrMissingLocale is the error representing an expected locale that could -// not be found aka locale not registered with the UniversalTranslator Instance -type ErrMissingLocale struct { - locale string -} - -// Error returns ErrMissingLocale's internal error text -func (e *ErrMissingLocale) Error() string { - return fmt.Sprintf("error: locale '%s' not registered.", e.locale) -} - -// ErrBadPluralDefinition is the error representing an incorrect plural definition -// usually found within translations defined within files during the import process. -type ErrBadPluralDefinition struct { - tl translation -} - -// Error returns ErrBadPluralDefinition's internal error text -func (e *ErrBadPluralDefinition) Error() string { - return fmt.Sprintf("error: bad plural definition '%#v'", e.tl) -} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/go.mod b/taskman-server/vendor/github.com/go-playground/universal-translator/go.mod deleted file mode 100644 index 8079590f..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/go.mod +++ /dev/null @@ -1,5 +0,0 @@ -module github.com/go-playground/universal-translator - -go 1.13 - -require github.com/go-playground/locales v0.13.0 diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/go.sum b/taskman-server/vendor/github.com/go-playground/universal-translator/go.sum deleted file mode 100644 index cbbf3241..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/import_export.go b/taskman-server/vendor/github.com/go-playground/universal-translator/import_export.go deleted file mode 100644 index 7bd76f26..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/import_export.go +++ /dev/null @@ -1,274 +0,0 @@ -package ut - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "io" - - "github.com/go-playground/locales" -) - -type translation struct { - Locale string `json:"locale"` - Key interface{} `json:"key"` // either string or integer - Translation string `json:"trans"` - PluralType string `json:"type,omitempty"` - PluralRule string `json:"rule,omitempty"` - OverrideExisting bool `json:"override,omitempty"` -} - -const ( - cardinalType = "Cardinal" - ordinalType = "Ordinal" - rangeType = "Range" -) - -// ImportExportFormat is the format of the file import or export -type ImportExportFormat uint8 - -// supported Export Formats -const ( - FormatJSON ImportExportFormat = iota -) - -// Export writes the translations out to a file on disk. -// -// NOTE: this currently only works with string or int translations keys. -func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) error { - - _, err := os.Stat(dirname) - fmt.Println(dirname, err, os.IsNotExist(err)) - if err != nil { - - if !os.IsNotExist(err) { - return err - } - - if err = os.MkdirAll(dirname, 0744); err != nil { - return err - } - } - - // build up translations - var trans []translation - var b []byte - var ext string - - for _, locale := range t.translators { - - for k, v := range locale.(*translator).translations { - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k, - Translation: v.text, - }) - } - - for k, pluralTrans := range locale.(*translator).cardinalTanslations { - - for i, plural := range pluralTrans { - - // leave enough for all plural rules - // but not all are set for all languages. - if plural == nil { - continue - } - - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k.(string), - Translation: plural.text, - PluralType: cardinalType, - PluralRule: locales.PluralRule(i).String(), - }) - } - } - - for k, pluralTrans := range locale.(*translator).ordinalTanslations { - - for i, plural := range pluralTrans { - - // leave enough for all plural rules - // but not all are set for all languages. - if plural == nil { - continue - } - - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k.(string), - Translation: plural.text, - PluralType: ordinalType, - PluralRule: locales.PluralRule(i).String(), - }) - } - } - - for k, pluralTrans := range locale.(*translator).rangeTanslations { - - for i, plural := range pluralTrans { - - // leave enough for all plural rules - // but not all are set for all languages. - if plural == nil { - continue - } - - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k.(string), - Translation: plural.text, - PluralType: rangeType, - PluralRule: locales.PluralRule(i).String(), - }) - } - } - - switch format { - case FormatJSON: - b, err = json.MarshalIndent(trans, "", " ") - ext = ".json" - } - - if err != nil { - return err - } - - err = ioutil.WriteFile(filepath.Join(dirname, fmt.Sprintf("%s%s", locale.Locale(), ext)), b, 0644) - if err != nil { - return err - } - - trans = trans[0:0] - } - - return nil -} - -// Import reads the translations out of a file or directory on disk. -// -// NOTE: this currently only works with string or int translations keys. -func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilename string) error { - - fi, err := os.Stat(dirnameOrFilename) - if err != nil { - return err - } - - processFn := func(filename string) error { - - f, err := os.Open(filename) - if err != nil { - return err - } - defer f.Close() - - return t.ImportByReader(format, f) - } - - if !fi.IsDir() { - return processFn(dirnameOrFilename) - } - - // recursively go through directory - walker := func(path string, info os.FileInfo, err error) error { - - if info.IsDir() { - return nil - } - - switch format { - case FormatJSON: - // skip non JSON files - if filepath.Ext(info.Name()) != ".json" { - return nil - } - } - - return processFn(path) - } - - return filepath.Walk(dirnameOrFilename, walker) -} - -// ImportByReader imports the the translations found within the contents read from the supplied reader. -// -// NOTE: generally used when assets have been embedded into the binary and are already in memory. -func (t *UniversalTranslator) ImportByReader(format ImportExportFormat, reader io.Reader) error { - - b, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - - var trans []translation - - switch format { - case FormatJSON: - err = json.Unmarshal(b, &trans) - } - - if err != nil { - return err - } - - for _, tl := range trans { - - locale, found := t.FindTranslator(tl.Locale) - if !found { - return &ErrMissingLocale{locale: tl.Locale} - } - - pr := stringToPR(tl.PluralRule) - - if pr == locales.PluralRuleUnknown { - - err = locale.Add(tl.Key, tl.Translation, tl.OverrideExisting) - if err != nil { - return err - } - - continue - } - - switch tl.PluralType { - case cardinalType: - err = locale.AddCardinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) - case ordinalType: - err = locale.AddOrdinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) - case rangeType: - err = locale.AddRange(tl.Key, tl.Translation, pr, tl.OverrideExisting) - default: - return &ErrBadPluralDefinition{tl: tl} - } - - if err != nil { - return err - } - } - - return nil -} - -func stringToPR(s string) locales.PluralRule { - - switch s { - case "One": - return locales.PluralRuleOne - case "Two": - return locales.PluralRuleTwo - case "Few": - return locales.PluralRuleFew - case "Many": - return locales.PluralRuleMany - case "Other": - return locales.PluralRuleOther - default: - return locales.PluralRuleUnknown - } - -} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/logo.png b/taskman-server/vendor/github.com/go-playground/universal-translator/logo.png deleted file mode 100644 index a37aa8c0cd0f6e1b98e0be3eb2531ebc6ac6717b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16598 zcmV(yK*U_<=i=1Q$^7;0v#+eDrK0%p z>%6(N%f`XBv#;pk-N3xJlaY`9`tZ@r#>d0H&B?^Dtf>F`_3`TEoSK)csHK;dl)1LD z{xUb9o}0zMyZALSjf{%1BqI0!{{5jc`1SO`zPq8KpwB5MBz`@`DJHxnB>jUjr=XpP zhJ*ceGX0V>qah&tt}xmxDK3XPA9F;SA|8N$duRs?{%JJ*T{HG>5AcL8I*&O1Ju^KN z1^!Yp@h&apFDzno38}29au*Y6VF#%(B=Pd^`t{{04g#CPRH8PEL>89OH1Y4=wM`?Y+cnsCD|dZGb#-yb zPbYsY6v#U#TTlf1)HKmxCR88|TWkfi;WgJmEa>U!iH1CPzc%zlFUrZIxOpL50SAW2 zHrkRe-Bv8!+}rP-U23*Bp`mB-jzz%dHuKoF($TRq)t%&MEAPFIet}u?$D-;-NTfd? zqGBFudL7@{$H>RCmXS~SDk-e2cr(q3b}2D4;I^fdk8wf@!NHcex`pmIGxX}ykX2Zk zP#l(MXu)GF(Pvk zb5n$3uu@QfLrR3XE#bH{zmF;My}ImfZ|eE@n0GU+i65iC#kVv_JUkHP6q^ z=b4$1KRnawHnN9;XOVD+dTcU@PWtQI+{V7)vVb@}2{~W|d768ob{*KawLyATCMyBY zhk?3y?SQh*YZ(!U#KDNg9qaM-(p?CZPE$X(8z(y`Rk002FaNkl8uC7fajE|-h>jHG2b9lbevz(KOfu`z+X2)PND2t1w1WGFmB z;BZ@Tf}w8eW!d6lVUNJlhe<3w@VLAr5!hqYo=(frj?qrXhNe@r$z?o#)_BC$c#6Tn zw%ibJSrePzu1EE-o7FRWE@Bmr=0#t-W8=a(6GTqoYvcqTWN@=@*0!nMye8HIu2(T+Ak@9J5Z~>D99iw*`m8V%yP8G^_lKA3_-39D4+I+C1zz z%PxAIjtxqC6rEeEoK;TYRK5moFT3e)S;c473ltAKvc{hCWlVc;gKFP7(_^pP+TQSQ zjTnnuLBc{Sdb7KSnYy{T8Mi%*-`7X=bnva_VNVf!d<1rL=-JH6uuGF1?^y5f9AB6q zotFt+&fvKN9wTt?2px9TxG)4b)AV}%MO>l#`PSCbhc8CH z(ahGS3jt5QrHGrvLqpybTd3aT!_Ma3C?0!8iS}-@N4$|3Vjk~Odfkur_B2j4Q=ai9 zwCdFE-MgodJ$v@--@hOJdcD5T)wQs^+~2>veB#83lSsEgpFKBQ8LAYfrz?!j@VGrK zfD?mhnuhu zc6A*>`uqE-yqo0c(WA$Y&khU>p!`akr_C16;qx9(K3}Q48GMs(2|#W(U+C>U+gs?p z^6}jBk0WP#6@}XUG1|MFxifa;Gu`Gf@{^8r3D0vJ&-0ExB2Qql!KaO@u%q%RuxCa- z=nDq{@3OWa?o`}pF?bNzz;Q^nz?4c2d1Yzhk<6eIWaeu#=B8Cm810v^Rke)+e)?h zH``r9!+0zn64TyHj(U9NCw8Ir?OU83bm-%VH;0Wb>dWQso<4o4T$akBA7WgT3iz&_ zN#||w+mrl%lwSPt^Vg61UR6`~YFWHi_l{!JcULueSU zuU#7-U!wAd^F!yiGqsgYce}fpeBa&ns10GwH=8Hj)>BVDk~}BH;~@vhCnx{=D_1_h z9(z4@+Q`0r`z}a*NhgoKotri}dCcg8TMu47d)M~vT^slBr56_$zkgrMPE@N|O(WZ! zsLQ%0YpP1+LKrd6^35*)GUSB5)MzwrJS8#U4D>#RSz-pt?c=lJXO zeSaQ*)aC{sacalkE(o<+>1c~WPfGnKtu-k`2YJOl(N%r)u4fVPB7smYkR!~c!2?5` z13>TVn~)3sx0VVE3qQ8?KZ&MxkE4I%0~`Az9FB(`>c8OVKkXPppkEAHPbYRdx2|$6 zf*j~H;Ex?orIrKyj}eYAQ%S`h#fdpw@Cz<58T?>}2zx?ZT|%y(T{~Xpi=gkZTF;#e z3F=$F{`}PNFa>wR$HyM5Ztd#os_vSakjh6}Iy<|C2zX8|>ielr&R9gEe{Fo0|8gK| zkY8VlfcpEtiRi!U(S93Z-L~--2kINT8Vb8(?fP;$%dGar++*t=TX-4CqacXL~rY1d|=Z=r( zT@Q{j(+PIADfOvY)=!t^b(wRg^=0R7n8aR zGu)okchJ@@r~V1+Ujz8JBY#ZBac;u{>vE*5fRzYXDa*3>N)mKP)O|L;_+)+@W$#W_ z1HCSw0BPQbdWUK^n3k3~2){GaaiQou{J~fvivE1qGekZm14C^s_>uYe_~`Zew$6dh z&dz2jY$hilM;G9l1sq4)7Rn-P`H|OEqLr&S14g)DnOR!8zA!U0bMNinM7RaVpGDl; zY-jGh@Wtt|F$}V_tG&EfzS=j}cU7%lLF4S~p35Z7OJBR(*!bOV-xB?PmY6P)N+eR& zm~-CP8no)@pwxKED3P8YEr^+%?8q=F+vn#4EnG5nUJd7iSCx$h8STYo>M5XqKb%>U znOOtZDR(?fN4Uox1Ub*XkD$wZHf)e>(EIqv@I>f+HsGnMd7^oAVqjvh1vQ|K6RZ%6 zS(agDR(SBQc^!rdmzN8vK88rJqp)LqgEnqF@z805HGQJ@1$%=?VI znx@@zXBFMuwRP&sqPpVZvLw6xjS9oC{Zv}oug2jiu%}ZIcF@Ph^RCBI+pC^=W&^+h zj2nbIz;VS1L`O&K^(`$vP;`|5u!wLu!{jbqrQrBbaLVo`2m4qAM6qoVHq>>S?SyR` z*c}LXS5Tn6g}o`iI4?0VQ5zK%Rio1xlm=zWuo0G1 z^py0Jec*;-d4*BepMTH?oH9ZSY$|#H{6GG`^dbW~(Tbd;`3i5jm;5kK&YSMhLvC&3 zHVlp9eiusn*^WX_1XErv-9)w42ysdA?Q+H zW2CX6=ZBNdm?l$Xli3vMR5s}}x+#0!T+v)!UV9=H(9Y8J_>rsU{BkbR#TC3Ak&M^yN+acyB-!s$e-Ut;vL8ySlm4a z;eC8dRw94`tf=X%Uv6%$8=aRI9J<1TIMbMW6^gFu(4jHQl%}SF=r%{bpn^hWvR;$u# z?d{>=gnV=2*2E~n{(eP81u1Vp-=CRI+4rUIi{BUTb=|}MLKVTK$?cJhCIQZa#yajY zS(}2N?bT>;%*x8uf2KJB_nPh{ry9GsF6g#rFPyoz{6b}Ux%JHA;^J%)xNpWt!c`tW z{u(CNPsL)vuD!{O6hY2%>I8qZSX5O>PtGWEy~`Lmb<%8B>Xe$#4z(JbN}bN!q|z#P z103ko^(ZQx!H{Jz7!K^;PuL-zok!n77@PpuN3`=QIJaXNJwN>xw8No`D|!K~UHql+Qv5HWo# zB}cT^)aaC12QmqJ`hK3=ZTlv`6W5{ViSOGfIrW*|Np9;)2Kq```l9tRy)3$O^iF?{ zPUxJ75m{!I-KK-QaAxVc*K(Nd4R;SXqMht4{NEVX+)5Xg*@A@Hq<~LB?(fg+E!|uH zU3PZ%u1f#x_XH9a#ZAHrAeO}~uDGbkZnqajX~LVrJ32BtOdr;k&6(!Li-vb=RcYZo z`qr(9iCZ7x(X%SDkm@`-$X^FI#FKA=?VA8jd`GrF3{<|9@ts|UOIx>`TRl)x)i(4! zVqK1178248PoY+zy&b-K_%Oy7g$1LI+PVzSss7D$wDbGdl?MTRO~_3yx};tzTQz$r zSe*>=WM;>E0%_2DZ|vGpUk`K^A_F2WgkGGN_tjVSqN1X_;l#xEe>Y_`nRX?JRuvab z&g~`&C+yn9tq{;bzH_ItrY6OpN)iIAqhPS4RrcG0}H-ItzJ63yu82&@oOwU+_mf1X}n+g2RO*VZncK44<-BB z+G+Yq=F+7-dwvP<@5T-$&i;rIO9hgIw?BI0!*bRmde8z!{OebMCn_45k1IEu%%;5w zZ2pLs8`5bugFNbyN1`6vx%0719fnqA*1>c_p8opl;C9=-g_85G(`0|)akx&hT0i8E z*A@6EL~^dPMBnD8U_geo*8BDX#{gcTd}-NoZ9(W=)2}TPcDLmocn>*d*J+ov2jn5X zXFPA=Qd371{#Zkjvdg7$5|ZN*kx0rQ<9P{LJPXA|<1mAld=H zeF6pxh+y>)4x?&9&JdUXE;854k?u3tb-luOx$vDg{YKA04)&K8U7-bQ)+Wt*$g!p+ zd>R)h=2(eXDrI1_slN=}1S%ohp zYxPt}n<|U+ZLLX3DU^`n%%gKDue)jSGZ|@jXG+Vz=eq5l&YUz)X3nM`O}_;8bW6G= z_o!T>E7p}a=o+%+4G~%088Lh6<#L=(cY(ZrFR_KH+jR%FgZ+7u*Ku0ym53ZDlD%;M zDK00U$79jCFr3=+e>+Zd8Kbx^y8rpdw;+ePi0(rEcF{vXXUH9M*J=IbOtmtzv9U2p zZ8n=LDb51T5%B!EI7_u9F0HyYe&&bWyDz1GlxsT+qsKmW{8-WTmSZB|aUiV( zp-$K&$n7N5VfYthn(2a0mpq8WDj|Q##oe9cXkS151>`UX`LAYm5)73sDbrS_7t)At z*5MiTSA0^HksSw%*X)LU1ay357LSh~J$h6Zm8R3Ap?k~D-LOHIy{AFm-Px^**;QYa zRWHuV0((CzdpO8}4s*y3Xwud&^^FK$SLZ;dLr&F+Ft25_rg2cGMHE*=P(hwTxPLCH!Q#wALd+)uu>YY1x z@80P^ABRO1AI(Ks%hl*K+3~t~e6n@AtgJn{^)dCj`q*8&RP*TJAcw=-+1WIg>Og-! zi0R>uof>t-y6A!jjiN=dZvEf4lN?@2@VXN~XWf0N=0ImPpPrm-n>8vX&)n@Ol2R#B znbf1LwNQFh?-AAi|L(|>>jb9nKL5a# z9Oin*V%Hps8x@|4J7>=Pz-uLu-d02$AM6y*6+OQCyoDT5;^I)icc$llc4<5}_oyZ} z9q6GAFnMu9vAj6DbA5(iJ=DU~vNpz>?Ab;zfJ01KKV`b&+4+RMK#-yA2MrCG_ zjasUD`OG&}adz8*Hiir*E=5IYiqq0M(?ZkbGuepsVqLeqJEOB(2kKohauw41-dFoo zTMPU9LH@!E;jl%)zA-iRc}Di9+Jk~xPK8|TB|^jN?%g<&O~C;*1>ZTr|1HqT^~&AZ zt2|$RWm0odWs$lF-$Id8uw<=`?m#1}vaQK}T3tBj~iK{rDR^4%a1L}Fip6pKf zo^E+P(CcIO@2Z!pRH`=%LEgUw>`rv2>e~rA)5v2sH_8=VnBt-*_gW4*wPuqbAjy{F zg8t9slNhyMMJprJo3Y9#Q_FY~k2ZAkutg4!9=0@%*iP77rNsdba<2F7igPm&jID>o z#Kgo_Rqc*a9xqlw4X(wq?9avVNq zlfWb>_yT3k)!mnn1Ko?Cg6jldkn@@v0Zpnql3mf#LUJI^Vez+xlB;b|b15a~Lmi@X zJWG2YK1tUT^v0&MU$F+&){6@@u6Tr zjdB19{%^XtMFoAbLxMTGeca3`Dl2Pk)9Z^WWs<-7woPeKX~Znm6;#ut=)i4DZGI`h zOUtV7N~y{@4xQgO_dr`{X@zvA z9J2{nIpTZ?Ix9NJfxgt`Nv!vrR&C#Sx@&moL?lHYuRFE;i^icGLGYMgK=2as!*F+y zzYB7^=2C^ii(DQ062r07cvB{%yjs=fMwz`zF6@(vkk(-#is~cOIV0CsxT=)reLM7O z{`m-UPzCo=aF7%BcH;2FTvT^-HCu;GT{Si0(*uFSLtPj@?fr^guIS!|F@Y(-mgIM0 zaW8WisqhzQofDQsa1z#?_ca*OC3#HY)*TC(}?XH@?&Z-WxtL~JYjrGCdlLMQysqz8SfFa-G>$_VQx`Nh36<)yN?DnC)#7fB z!>_%4IZIsJ+?=ICB0tL7{@(1QvYaHs45Uw{tXPiEHi zq;9v>)C6A~O&ks3E?4zOPYwjEGlgLhcHN7M-5uy4zvVcsRg7q(#oprRXf3(HQ)IUJ z(u5qhYprT2kK(wXIgT4Cestix!M$rbb2e+FyM>a9riL|Pi${b zWYL!fd*tdHml<@G>e3Yo=eHL4-U>46j7L+xp|&jsyRdcav_GR z?TLwOu)`KNH6uRBVLeKlQl-)kmWV=@sXCVuBE7nXm4b>5UH&(vkkqhs7x<)`RO!=hk@B#+>Rab5%2HV z@qUDT;C_V5J-1;)dF|B@?)S7eM0aW)%WxBPyXuLse{y(u{0LS@BmIVYYLo{hWD2@W zboZVy!GJQ!6dA~Det&WKgV$KiKP2R^X|e|>@v@5htOl`G9KBCW0iDKWi+vohILtX5 z^p*J^*^es_9A7ZZoR6G~M`F*2FVBc^fIH)yC5P$^JM5o4eyi0V`;&p#WgX~oN6;>J z0et0m>jc5dfw0Ihzd--h$)=yy!QEN%TWxJW>+df)pr5|OSDf3oFFG2ZXzc}>q&b_B zMpg&^BI6+advZH0JMHW&ICIl5U)0LyHUE0eet<6}U*hm=L-*YCgZ@xG46Ceyo+d7D zd3%z`xob`i3j~46u;DJPA=%%@|0kPmUi4qEJc4B@?^XHJXFAqO`V1r1zKLtsR*;NE zNzF#Pd#CU{q(+zR9chQO!m{&Hv4xPQX#j3VXTf1#kFu$KhQ1i<)SPUJuM zj6L-LfC+56y*~W^lm#th`;^yuyU3>Y=Bs#gX zxN*THx|cicONSWMm{YK(W-A(|v90N^r041!rU`A>rg4C?uVnZw%yymDml4p z^m^gTU=MovKC&c}*us#r9&ZPCq7Nqfe2aR-pda$Z&s?U*NA?7pOv(Y%6~k)7gUQK0 zPXzxS#^$&-EO5FRvD@!aGJV(U+5=erBbz^6`zYjanHk5nd2`k^-vU{R(Sp&GUG>oM zZ5lf{)4a0iGhRQkVSen#&u&g#tE(%ltE+q2en+0jqO)y0J_P+)(#k#;`K>=vJhLjj zDUys|mm@j;KfzeA0IK^LwAwBofAX$JdD#!-1bxj)vM1(_E%vq6zP{+w){!n8mrh3; zP?>3?t*o`RwXLm94=ZA`CPfMH&zg&g9c98Cs=H{;pvT01{ONu+!|ngfTKN5O>D1Ks z9zV8_B>{)%4%Nf)K|f~~9kP!c9En^VwmOiYuRDl&ySn`A%x**wgO0!UE)4c?Ms(|g2CMy12+&Pq_u%a! ziOWhQZw%-Gfyx`CR6=wgpC=AI^yt$zfZw|H0Q}u;1(u~|^$B3tVn=nvYQ4ed2zgxS zE>vK*U!tfik_qSiodN)Tp2_W+;!qadsW~ZX1U+VRZAlf|$MhE>%)cUcmcFa5x76XP zJduPuW)*eUUzl&>!y);g^^r$>h9i^xfsWT$ICA<@{~MmBOC;O{I_0brprKJlb|J+N zgZ&Vmu|4|e&9I`IX0;XsGxg9iuu zuqIF5#P}!U6;uFJ7mT4u{r~d{{YO5J)tr*#)Qq8zwfTvo#i?CPtTX5!huvS|)--)a zw#q}{A!(XCZ|$>Mts^5NR&tLlRg*lYuGAyZt6S$YJjeGH{cYSNYBb}WgdFH;5svdY zJ~6}?^eSp<6xf?_U?H9R$5?|PZITxa^q>|(e$2hsyTr=+`}M~s1`m^+} zk2rdWpck2C5|LhA$x9JQGc#F_$6+?9IdeQ+jvIysW^EuLAuqlmuUj6mzB@0AxVyL$ z4qu-aJCQT;`sS@0+g~r-xOdA*nUt*3k`V|&2YJh}RphC_r-R6Ig#F?g!ysM&;#ElG zL7#6|M+Tbw0&44d(q-Q%l06rGzZ+>}TLX6*pw|{x?0MNM(^eHS2w6q_?+H`NP_lgzP>mx6aB=_u_k3P+) z?qe7vNjYG^WP0@gS$Q~#=Lw3FI z^kQ#lUte#p+rA4F$6!E4qNPdBj>arwkE;qgrLh@`!#X>ea{d=7=N{8m702;%aa^D< zV6csc@^TEk>mZD>DT%9=&`nn;gh)mlB7!rdB9AJME`b_S!eiwj ztdeHfL{c_bjmTcch>`u}|Hkh*x3{+)Iw$_<;Qj;ar@!axl#^7s(}uH{Y;^fAa2w@GE+?S3Ep z{Oz~%^F4tvUh2BKPS&D;Oly$Rx%c=!JlS~bVug~%%PXR^tFgEVUFh02#JbG1Hj4fs zK|iWiefYX6=Vd3lDs^3Z}T+Ya;&Ni@f!YgQA1J`fWyK%5;X(4!FEX-yLqx}StO zvq`UuOHP2T0^S!C>=UXTiWi?HgPSd*;fB$KaJ9bkRLETcolYqut+(&mx3K>6{O>(6 z(xBB&wIz3z1iCvgYY78VLd(Bg2Z+2ir8OlLRQf6^D$l010h^$|1oUdv`+2I5dGy!v zw0Uo7b($(eu6+&YXc+P65lgLzaR@ILFc;IX>f_gL+Az^7-f8e=hu$F%q3A7}estPl zClWei9YrA0N6X`Y}!prk%Okx6*BdR;WvleVA97X%R&DC&^KGs4G%(E9BPQ3WVdbTMFDE;wHAn3hB92y`<(J4RpFY&niX{j{c{56Ajx2`3ml z3fQ;c>p4Jo)B2IDr>0~gI!SKW&s+)ExP68iybs8Cn>KJ{GmNBl7`%LMaDv`qk|)q8 zHxsyH^j%19*lhfyv{Tm^M^|oc=wK(aO{nJfg)QB^NrbM+Cg#s=d3U|a7w%$7!w0WjnU;tsxcgfeU z!?dyx7KV9G__}WK*;7dg`FeRQjqo#4cN+G;pa+uVW{6GJVKT>Y@9r}s&UvEy?;{8Q z&z$ienRm*$b0Z@-4u%F5>Am6&pQ(Y?1u=tp?;Tih9fz8ispN9RXD5#@M; zUofRC52d6oL`9K%EKJWmrz2O^$de5Sa+{ki%nln=5G-1gS{}57_x38x_&7y$jFZ## zx)WV0t*op2e!iCY`o#BDyx=f6mT!;;VjCm~uFlJ6-XzA55Fs*gIpRz!<4JhY;1C}BLr<47kbpwp6LEtidvj$ud5s%uc(|KfsBujHs zu&DiuCeolf92|`Gx_Pw4UJ1D9V@qY-!+W&I#AW{29FwE2=PFt>@h#h zt83>+6l!>Rt$O|(1e@nSZo3i;tX{b|f1ug3=c{HsbI`g!Gpgm$tGA*1!O`1o2iI&x ze~V5d{Gu)+_2JOdQD)kZ&6#$XrqM%POeS3#xfef}x)b&Uawo^A)iBnHv>qa$3)#(Y zR|nLNF`uH5`Pw=Zv9=FJftcKx8M3trvP+}!MTCi;sSA~5@A^0wGD`#u@a zPY`s4>LQPxrPgNUXj3-qyEOLw<+i9bTa1v~Ku*z7&4C=f5?|kSQ)=pZSd@+)E_k?i zT4z2LVvRNH_2KEyau{9QA$#!gq;zw5EY|%xY(Y?Tu#1U(cRSU3Gql}Tr)Y!D;p>R+ zw(%-nUWEudt==&Ci0tMwJzX_LXTGT6u(Dv*>;aNd?bVmxQmIcUh_B~$Q*>zk{BFCy z%pTQYi!|7RM07$f6{4IEt}wZ~n3}pV7`B(#d)`p&b9#qEXHK?S^3&g(9w0+5GT9D{ zo{2i14x5j6bdF8;-V3=)J5(Y%&2B&sX#e?~Q^vo)NsRsGcy@L+4^NhF5{B*of!({N zr1aDBlG4(W&u9R;Zx5Bg*H2tkDNxI_=3$*$U6)m$%_z_Y_}WHCZGMPxqc+5MF~Ead zK!>mIj*LSIZ(1DGV+O=DsDIvc4_o5X4y&biF6F@NB*$Env3I157c78za&+`6tm$S$ ze7FT2*N~7?+Y>w32|7|a0vn=R8TE4rzCm92=1_5cNsWYotuwTg^)7#}SqeWW=VL&W z&F(X5U%YriMdV_JR;AL`W#y~TvkAJeX|ru=?%Td#qwm~S^`r3rdWmkw(A_ZEroDXB-mrlx2GAF?s==(t${^?w zUiWO9p;$Nv7+M5$C|z)MitbC$BcpUVD^JsFOHju4S{?LWD!ggyMk3}wPEN{}u3wi8 zkUd1N|8nb6fB#&6Z@)!7hCdi0E?dJqLVU;gxrsU|WE*0l z%F)~gbllSvYF?;4p6^DdPo+Iefy}C|^Ia#!LicZx|=kx;>#>W*m5$35-OP}~2($)sWSM+5L zV}#I2OF4kVH+~tA(W`!DFJ@7pL)Lh~OgZ6=68MPisZB)3;w5VTVLA2y%=mIR^!oVN za9o=7%<|Go>#b`m-M`^#21YutbVv5&T}nwX)w)%$9r>>m^wyho>i54Tc5$@-0|-^qv5389|oe03Z9LVZLDo@$A6KChyh0HFb zH|ekA^*^-Xq<(=~-FL`Hb?zd+to(?BY9G`5mrZ$+6K9vnVpwKiz>6mbx@hn2sV$OM zx`58#I~W^2XUVr*-@~%AlU^LLIT;BlEKM=)I%iqUKdFR$1L*kb*CV^R%J|T279Vra znbN;OkGa_B0*5r+_(=H?N}9)@vyFLnOlern>=agSth1P*!@GE9=pzJ1!2Y8(j?VDtI3JWOqCdKV*>@q}he~y2-0s-K{cKKo9a*x=?b8&f7b>u^^`# z%sPvuKfgeogGi~_NSvZWKRhb=lQR0m(e&}y`hKv*ItTLp1ie~L)Q%>VE6@SmrS>9S zop8E9eaLtW=m4kEnA=l$nS}C3RVZb_Q zLr^-sTY=1-lhBT_YrJoOi%O^Huy^;Q?o>K=1xUtEJY7?Lw5zbeUY7t>e@cVp)&9rjhRZL@fiLU zrln!fK{?De4Re>ji@tQZr)STlo*U5|+k?w_7{SVxy8+FklYbz`r^BqH6dUm7(J8rS zCC8(KT(EbX@d`PmvtZT@qCVohi>Ld*B$kaXduBN)RY5fS4+&j-@}B`Z#sT6_jg1|5 zQ#-m;e1nd%<0_h=PNX#j&POZG76Kd8g+`pxtWE^ zON@Zd>}y5+D#o}g10)b5_$AIpgIp6BNR=*F+*~lm}B~8kn%Sz?&C8hFo&_{(Bb_!y|k|xpJD$#tM6v`FKZc zQ~INxPFy{1I_G(iQ*?DcnQ5hw1GXa-K4flvSxOT1azhW<|(3Ixh;XVH5*TL2eCp0E53{WhKEG`gQ5;{d6>n1~Y%ma5 ze%K}aNC~DK+Vp_bAjJX&l~pX!HM@JUkSiCE6(PF9szj`{VmUYnXKNuyYDA-?mnbI= zsh~ZyRfU{fDpf5|C4zE^Q2q(TcV>4o9$LVOR9;-yQ7`@Y`{vD?H?#AWj`#f-Tvb8Q zUxWKlaGD_9;s-W;cL!JpYxaX9{H|njNAxrP{08)3)lS)azB%(9Qkr}U?AFTRqbo-b zTZUFDhsq_bTvp4Lx;{EpLvo`M^rK}B=xpIG%i}ZL;Rk1KDR4;S-xqIb96ccCbGjfp zVqD)Z!Ce(JzK^vBkLS;AqgJx}6XJ(3+PUn0kpH{vllyxveEH@X`^Y5bH zJ^uSU3>{aL@axuK2%L&cu2tNv0bO7hWcOYE(F<#j|L_L}`pfU;&!0?zdu64RR?CK= zOP65uu<`3BHspiAXcZJDAca~fGrg@ zXaUNypPzhv!T|cGVXbP_jO{5Sw?W=(En_)N(2?B$eXCq1IZZ<^LUX_)o>TO(4;^ez zlZuqxP(hyLE{ivC?6?#-Q@L5-8-bNImmP%IEA*pTR~CjEX8 z>A)_?&e&qn8IoWk7-CsWpnHEm4E)p9JqzF|z|j9S{59x_T{BPGjLSp#~jHQiDq zsGg;YW;(C;L2N8*xG7Ur(2`b z8bu!(CFsatG1p-T$UZs|9U086-xhmRX~Aq@w%2m8^k#3-ZFF_ndLtHP`GtGq!0v zF(NuA?-t2{4)Wg*ku4V(*eCs~(j&iZ!r?(axGLfd-NZEC>G{!N$R4mC5ZNI+Vej5I zn}=C>ihe7XZ|1j>Eu(4}O4({!B`sA-!_$vinp{q`q;;za^stn1OfTsG&iSKXRNxrc%gd^^9xB5b@^qq~|8u$i?VRV;s)e zf3rCiOXGobOKn<)Va2d;l?Zwhi&p#<);vsZwwX=Nn-#}|`{(8h+MJ%4vvZD?gEOtE0_g@+bTz-JE3tKTXm%mBT z^LK7yBdUL~7w|#fgS3hXN=v3Unl-gnBF?@MADXTjHBuFI^^8Owlkn`cr-xk~GHVT6 z#mn>-^h(q-l*t_jANT-SAV8EK@>Q9n2(Ueq}&dkrOkQyCnK;ggPO| z!yt^^*Ig{wK!&^Lanorve**{f19reCeD?G>rPnliRX8yXIZHf5&~vKoNYWQ(*fz-* z;M!rwjoWTUpPSd?b=&sliR6qt&>W%*1D%m$NS>BNOZ>WuaL+ZDw=a%ugIoqxhoO$i zPT7Ip&JOh1>l3g~w^?jVcxVAZ8$PIk`gn^Ic*!H^URYH!r*tQ3yJ=+Z`dpMqp7Gq=oE`nlZHw)q z<}8`Pyv9Ty7BW^A+L-Fd;#SWMUWE3$YX$SzC9eC9%Tsndasz)S=<92=XoJ-|7oJLw z{ubjnFh|C`N(Vmp@h9Zzu?)~L%jvq8Fy|4~qlIEtuefH^p6h8iEpuL&)dX@RGsN9F z`N);~?C60q#6BxMSIPP{#5UbJp5PceOX}Lf{8tqHgB#sJ!AgJ^y4)AOy<2b!$cE8t%=oOIDMpsA~@74TSHqZwM`NJLD9VqXm`O76C)V;u~ zRZEY*_`}3`kgxeg8yII7;h9nLG|;s=vi7XrsO$6fLN-&V7xe|#?6KXt9?95quH7GD z)A{Y2ocy^Uxcj0H_yc`-JoMifd%DEn8K5(EA=JU=ucIf&ylJtPPZ13ae}EbQrV zV26r&v4U421KtMG8GFGj7VWNxQ_yGk`{d-P)Sm!n`72G`LEb*lp9=jK8G`zrYrqR+?Y^hyzW7cvbqA4f-Sr5ueUzLvaeN$c zN4~mq=gtS4q#5s%SFUt3c+fwz)XZ9+$XWABkh2YCQFBE14o3Rk8(kf|4|{N)uJ1bFF9hp%-l;Rvb+;eJ;5k1mnn*vn zRR5`tmENP7u0(G#8I97WR;;HNeh)bt=Pb5U&1rCd;(_ZHiyEwno#Y`YP z=)oSiJ!{S?@Z$sdh<6zNiBL0eLe3l2ve3@Qxsb|0^hxP~+r$6B&T?ARtbF0Q@`N77 z;R&Z;nSQP}xQPjUTE$82e&nx658Oi1fxoe{+C1BsAngAEz5qf00MAd3Cq<=4x Z{{;$xH 0 && tarr[rule] != nil && !override { - return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} - } - - } else { - tarr = make([]*transText, 7, 7) - t.cardinalTanslations[key] = tarr - } - - trans := &transText{ - text: text, - indexes: make([]int, 2, 2), - } - - tarr[rule] = trans - - idx := strings.Index(text, paramZero) - if idx == -1 { - tarr[rule] = nil - return &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} - } - - trans.indexes[0] = idx - trans.indexes[1] = idx + len(paramZero) - - return nil -} - -// AddOrdinal adds an ordinal plural translation for a particular language/locale -// {0} is the only replacement type accepted and only one variable is accepted as -// multiple cannot be used for a plural rule determination, unless it is a range; -// see AddRange below. -// eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - 1st, 2nd, 3rd... -func (t *translator) AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error { - - var verified bool - - // verify plural rule exists for locale - for _, pr := range t.PluralsOrdinal() { - if pr == rule { - verified = true - break - } - } - - if !verified { - return &ErrOrdinalTranslation{text: fmt.Sprintf("error: ordinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} - } - - tarr, ok := t.ordinalTanslations[key] - if ok { - // verify not adding a conflicting record - if len(tarr) > 0 && tarr[rule] != nil && !override { - return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} - } - - } else { - tarr = make([]*transText, 7, 7) - t.ordinalTanslations[key] = tarr - } - - trans := &transText{ - text: text, - indexes: make([]int, 2, 2), - } - - tarr[rule] = trans - - idx := strings.Index(text, paramZero) - if idx == -1 { - tarr[rule] = nil - return &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} - } - - trans.indexes[0] = idx - trans.indexes[1] = idx + len(paramZero) - - return nil -} - -// AddRange adds a range plural translation for a particular language/locale -// {0} and {1} are the only replacement types accepted and only these are accepted. -// eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left' -func (t *translator) AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error { - - var verified bool - - // verify plural rule exists for locale - for _, pr := range t.PluralsRange() { - if pr == rule { - verified = true - break - } - } - - if !verified { - return &ErrRangeTranslation{text: fmt.Sprintf("error: range plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} - } - - tarr, ok := t.rangeTanslations[key] - if ok { - // verify not adding a conflicting record - if len(tarr) > 0 && tarr[rule] != nil && !override { - return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} - } - - } else { - tarr = make([]*transText, 7, 7) - t.rangeTanslations[key] = tarr - } - - trans := &transText{ - text: text, - indexes: make([]int, 4, 4), - } - - tarr[rule] = trans - - idx := strings.Index(text, paramZero) - if idx == -1 { - tarr[rule] = nil - return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation? locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} - } - - trans.indexes[0] = idx - trans.indexes[1] = idx + len(paramZero) - - idx = strings.Index(text, paramOne) - if idx == -1 { - tarr[rule] = nil - return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters. locale: '%s' key: '%v' text: '%s'", paramOne, t.Locale(), key, text)} - } - - trans.indexes[2] = idx - trans.indexes[3] = idx + len(paramOne) - - return nil -} - -// T creates the translation for the locale given the 'key' and params passed in -func (t *translator) T(key interface{}, params ...string) (string, error) { - - trans, ok := t.translations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - b := make([]byte, 0, 64) - - var start, end, count int - - for i := 0; i < len(trans.indexes); i++ { - end = trans.indexes[i] - b = append(b, trans.text[start:end]...) - b = append(b, params[count]...) - i++ - start = trans.indexes[i] - count++ - } - - b = append(b, trans.text[start:]...) - - return string(b), nil -} - -// C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in -func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) { - - tarr, ok := t.cardinalTanslations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - rule := t.CardinalPluralRule(num, digits) - - trans := tarr[rule] - - b := make([]byte, 0, 64) - b = append(b, trans.text[:trans.indexes[0]]...) - b = append(b, param...) - b = append(b, trans.text[trans.indexes[1]:]...) - - return string(b), nil -} - -// O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in -func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) { - - tarr, ok := t.ordinalTanslations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - rule := t.OrdinalPluralRule(num, digits) - - trans := tarr[rule] - - b := make([]byte, 0, 64) - b = append(b, trans.text[:trans.indexes[0]]...) - b = append(b, param...) - b = append(b, trans.text[trans.indexes[1]:]...) - - return string(b), nil -} - -// R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments -// and 'param1' and 'param2' passed in -func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) { - - tarr, ok := t.rangeTanslations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - rule := t.RangePluralRule(num1, digits1, num2, digits2) - - trans := tarr[rule] - - b := make([]byte, 0, 64) - b = append(b, trans.text[:trans.indexes[0]]...) - b = append(b, param1...) - b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...) - b = append(b, param2...) - b = append(b, trans.text[trans.indexes[3]:]...) - - return string(b), nil -} - -// VerifyTranslations checks to ensures that no plural rules have been -// missed within the translations. -func (t *translator) VerifyTranslations() error { - - for k, v := range t.cardinalTanslations { - - for _, rule := range t.PluralsCardinal() { - - if v[rule] == nil { - return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k} - } - } - } - - for k, v := range t.ordinalTanslations { - - for _, rule := range t.PluralsOrdinal() { - - if v[rule] == nil { - return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k} - } - } - } - - for k, v := range t.rangeTanslations { - - for _, rule := range t.PluralsRange() { - - if v[rule] == nil { - return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k} - } - } - } - - return nil -} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/universal_translator.go b/taskman-server/vendor/github.com/go-playground/universal-translator/universal_translator.go deleted file mode 100644 index dbf707f5..00000000 --- a/taskman-server/vendor/github.com/go-playground/universal-translator/universal_translator.go +++ /dev/null @@ -1,113 +0,0 @@ -package ut - -import ( - "strings" - - "github.com/go-playground/locales" -) - -// UniversalTranslator holds all locale & translation data -type UniversalTranslator struct { - translators map[string]Translator - fallback Translator -} - -// New returns a new UniversalTranslator instance set with -// the fallback locale and locales it should support -func New(fallback locales.Translator, supportedLocales ...locales.Translator) *UniversalTranslator { - - t := &UniversalTranslator{ - translators: make(map[string]Translator), - } - - for _, v := range supportedLocales { - - trans := newTranslator(v) - t.translators[strings.ToLower(trans.Locale())] = trans - - if fallback.Locale() == v.Locale() { - t.fallback = trans - } - } - - if t.fallback == nil && fallback != nil { - t.fallback = newTranslator(fallback) - } - - return t -} - -// FindTranslator trys to find a Translator based on an array of locales -// and returns the first one it can find, otherwise returns the -// fallback translator. -func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator, found bool) { - - for _, locale := range locales { - - if trans, found = t.translators[strings.ToLower(locale)]; found { - return - } - } - - return t.fallback, false -} - -// GetTranslator returns the specified translator for the given locale, -// or fallback if not found -func (t *UniversalTranslator) GetTranslator(locale string) (trans Translator, found bool) { - - if trans, found = t.translators[strings.ToLower(locale)]; found { - return - } - - return t.fallback, false -} - -// GetFallback returns the fallback locale -func (t *UniversalTranslator) GetFallback() Translator { - return t.fallback -} - -// AddTranslator adds the supplied translator, if it already exists the override param -// will be checked and if false an error will be returned, otherwise the translator will be -// overridden; if the fallback matches the supplied translator it will be overridden as well -// NOTE: this is normally only used when translator is embedded within a library -func (t *UniversalTranslator) AddTranslator(translator locales.Translator, override bool) error { - - lc := strings.ToLower(translator.Locale()) - _, ok := t.translators[lc] - if ok && !override { - return &ErrExistingTranslator{locale: translator.Locale()} - } - - trans := newTranslator(translator) - - if t.fallback.Locale() == translator.Locale() { - - // because it's optional to have a fallback, I don't impose that limitation - // don't know why you wouldn't but... - if !override { - return &ErrExistingTranslator{locale: translator.Locale()} - } - - t.fallback = trans - } - - t.translators[lc] = trans - - return nil -} - -// VerifyTranslations runs through all locales and identifies any issues -// eg. missing plural rules for a locale -func (t *UniversalTranslator) VerifyTranslations() (err error) { - - for _, trans := range t.translators { - err = trans.VerifyTranslations() - if err != nil { - return - } - } - - return -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/.gitignore b/taskman-server/vendor/github.com/go-playground/validator/v10/.gitignore deleted file mode 100644 index 6e43fac0..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -bin - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -*.test -*.out -*.txt -cover.html -README.html diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/.travis.yml b/taskman-server/vendor/github.com/go-playground/validator/v10/.travis.yml deleted file mode 100644 index 85a7be34..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -language: go -go: - - 1.15.2 - - tip -matrix: - allow_failures: - - go: tip - -notifications: - email: - recipients: dean.karn@gmail.com - on_success: change - on_failure: always - -before_install: - - go install github.com/mattn/goveralls - - mkdir -p $GOPATH/src/gopkg.in - - ln -s $GOPATH/src/github.com/$TRAVIS_REPO_SLUG $GOPATH/src/gopkg.in/validator.v9 - -# Only clone the most recent commit. -git: - depth: 1 - -script: - - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... - -after_success: | - [ $TRAVIS_GO_VERSION = 1.15.2 ] && - goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/LICENSE b/taskman-server/vendor/github.com/go-playground/validator/v10/LICENSE deleted file mode 100644 index 6a2ae9aa..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Dean Karn - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/Makefile b/taskman-server/vendor/github.com/go-playground/validator/v10/Makefile deleted file mode 100644 index 19c91ed7..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -GOCMD=GO111MODULE=on go - -linters-install: - @golangci-lint --version >/dev/null 2>&1 || { \ - echo "installing linting tools..."; \ - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.21.0; \ - } - -lint: linters-install - $(PWD)/bin/golangci-lint run - -test: - $(GOCMD) test -cover -race ./... - -bench: - $(GOCMD) test -bench=. -benchmem ./... - -.PHONY: test lint linters-install \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/README.md b/taskman-server/vendor/github.com/go-playground/validator/v10/README.md deleted file mode 100644 index 04fbb3c8..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/README.md +++ /dev/null @@ -1,299 +0,0 @@ -Package validator -================ -[![Join the chat at https://gitter.im/go-playground/validator](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-playground/validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -![Project status](https://img.shields.io/badge/version-10.4.1-green.svg) -[![Build Status](https://travis-ci.org/go-playground/validator.svg?branch=master)](https://travis-ci.org/go-playground/validator) -[![Coverage Status](https://coveralls.io/repos/go-playground/validator/badge.svg?branch=master&service=github)](https://coveralls.io/github/go-playground/validator?branch=master) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/validator)](https://goreportcard.com/report/github.com/go-playground/validator) -[![GoDoc](https://godoc.org/github.com/go-playground/validator?status.svg)](https://pkg.go.dev/github.com/go-playground/validator/v10) -![License](https://img.shields.io/dub/l/vibe-d.svg) - -Package validator implements value validations for structs and individual fields based on tags. - -It has the following **unique** features: - -- Cross Field and Cross Struct validations by using validation tags or custom validators. -- Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated. -- Ability to dive into both map keys and values for validation -- Handles type interface by determining it's underlying type prior to validation. -- Handles custom field types such as sql driver Valuer see [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29) -- Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs -- Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError -- Customizable i18n aware error messages. -- Default validator for the [gin](https://github.com/gin-gonic/gin) web framework; upgrading from v8 to v9 in gin see [here](https://github.com/go-playground/validator/tree/master/_examples/gin-upgrading-overriding) - -Installation ------------- - -Use go get. - - go get github.com/go-playground/validator/v10 - -Then import the validator package into your own code. - - import "github.com/go-playground/validator/v10" - -Error Return Value -------- - -Validation functions return type error - -They return type error to avoid the issue discussed in the following, where err is always != nil: - -* http://stackoverflow.com/a/29138676/3158232 -* https://github.com/go-playground/validator/issues/134 - -Validator only InvalidValidationError for bad validation input, nil or ValidationErrors as type error; so, in your code all you need to do is check if the error returned is not nil, and if it's not check if error is InvalidValidationError ( if necessary, most of the time it isn't ) type cast it to type ValidationErrors like so: - -```go -err := validate.Struct(mystruct) -validationErrors := err.(validator.ValidationErrors) - ``` - -Usage and documentation ------- - -Please see https://godoc.org/github.com/go-playground/validator for detailed usage docs. - -##### Examples: - -- [Simple](https://github.com/go-playground/validator/blob/master/_examples/simple/main.go) -- [Custom Field Types](https://github.com/go-playground/validator/blob/master/_examples/custom/main.go) -- [Struct Level](https://github.com/go-playground/validator/blob/master/_examples/struct-level/main.go) -- [Translations & Custom Errors](https://github.com/go-playground/validator/blob/master/_examples/translations/main.go) -- [Gin upgrade and/or override validator](https://github.com/go-playground/validator/tree/v9/_examples/gin-upgrading-overriding) -- [wash - an example application putting it all together](https://github.com/bluesuncorp/wash) - -Baked-in Validations ------- - -### Fields: - -| Tag | Description | -| - | - | -| eqcsfield | Field Equals Another Field (relative)| -| eqfield | Field Equals Another Field | -| fieldcontains | NOT DOCUMENTED IN doc.go | -| fieldexcludes | NOT DOCUMENTED IN doc.go | -| gtcsfield | Field Greater Than Another Relative Field | -| gtecsfield | Field Greater Than or Equal To Another Relative Field | -| gtefield | Field Greater Than or Equal To Another Field | -| gtfield | Field Greater Than Another Field | -| ltcsfield | Less Than Another Relative Field | -| ltecsfield | Less Than or Equal To Another Relative Field | -| ltefield | Less Than or Equal To Another Field | -| ltfield | Less Than Another Field | -| necsfield | Field Does Not Equal Another Field (relative) | -| nefield | Field Does Not Equal Another Field | - -### Network: - -| Tag | Description | -| - | - | -| cidr | Classless Inter-Domain Routing CIDR | -| cidrv4 | Classless Inter-Domain Routing CIDRv4 | -| cidrv6 | Classless Inter-Domain Routing CIDRv6 | -| datauri | Data URL | -| fqdn | Full Qualified Domain Name (FQDN) | -| hostname | Hostname RFC 952 | -| hostname_port | HostPort | -| hostname_rfc1123 | Hostname RFC 1123 | -| ip | Internet Protocol Address IP | -| ip4_addr | Internet Protocol Address IPv4 | -| ip6_addr |Internet Protocol Address IPv6 | -| ip_addr | Internet Protocol Address IP | -| ipv4 | Internet Protocol Address IPv4 | -| ipv6 | Internet Protocol Address IPv6 | -| mac | Media Access Control Address MAC | -| tcp4_addr | Transmission Control Protocol Address TCPv4 | -| tcp6_addr | Transmission Control Protocol Address TCPv6 | -| tcp_addr | Transmission Control Protocol Address TCP | -| udp4_addr | User Datagram Protocol Address UDPv4 | -| udp6_addr | User Datagram Protocol Address UDPv6 | -| udp_addr | User Datagram Protocol Address UDP | -| unix_addr | Unix domain socket end point Address | -| uri | URI String | -| url | URL String | -| url_encoded | URL Encoded | -| urn_rfc2141 | Urn RFC 2141 String | - -### Strings: - -| Tag | Description | -| - | - | -| alpha | Alpha Only | -| alphanum | Alphanumeric | -| alphanumunicode | Alphanumeric Unicode | -| alphaunicode | Alpha Unicode | -| ascii | ASCII | -| contains | Contains | -| containsany | Contains Any | -| containsrune | Contains Rune | -| endswith | Ends With | -| lowercase | Lowercase | -| multibyte | Multi-Byte Characters | -| number | NOT DOCUMENTED IN doc.go | -| numeric | Numeric | -| printascii | Printable ASCII | -| startswith | Starts With | -| uppercase | Uppercase | - -### Format: -| Tag | Description | -| - | - | -| base64 | Base64 String | -| base64url | Base64URL String | -| btc_addr | Bitcoin Address | -| btc_addr_bech32 | Bitcoin Bech32 Address (segwit) | -| datetime | Datetime | -| e164 | e164 formatted phone number | -| email | E-mail String -| eth_addr | Ethereum Address | -| hexadecimal | Hexadecimal String | -| hexcolor | Hexcolor String | -| hsl | HSL String | -| hsla | HSLA String | -| html | HTML Tags | -| html_encoded | HTML Encoded | -| isbn | International Standard Book Number | -| isbn10 | International Standard Book Number 10 | -| isbn13 | International Standard Book Number 13 | -| json | JSON | -| latitude | Latitude | -| longitude | Longitude | -| rgb | RGB String | -| rgba | RGBA String | -| ssn | Social Security Number SSN | -| uuid | Universally Unique Identifier UUID | -| uuid3 | Universally Unique Identifier UUID v3 | -| uuid3_rfc4122 | Universally Unique Identifier UUID v3 RFC4122 | -| uuid4 | Universally Unique Identifier UUID v4 | -| uuid4_rfc4122 | Universally Unique Identifier UUID v4 RFC4122 | -| uuid5 | Universally Unique Identifier UUID v5 | -| uuid5_rfc4122 | Universally Unique Identifier UUID v5 RFC4122 | -| uuid_rfc4122 | Universally Unique Identifier UUID RFC4122 | - -### Comparisons: -| Tag | Description | -| - | - | -| eq | Equals | -| gt | Greater than| -| gte |Greater than or equal | -| lt | Less Than | -| lte | Less Than or Equal | -| ne | Not Equal | - -### Other: -| Tag | Description | -| - | - | -| dir | Directory | -| endswith | Ends With | -| excludes | Excludes | -| excludesall | Excludes All | -| excludesrune | Excludes Rune | -| file | File path | -| isdefault | Is Default | -| len | Length | -| max | Maximum | -| min | Minimum | -| oneof | One Of | -| required | Required | -| required_if | Required If | -| required_unless | Required Unless | -| required_with | Required With | -| required_with_all | Required With All | -| required_without | Required Without | -| required_without_all | Required Without All | -| excluded_with | Excluded With | -| excluded_with_all | Excluded With All | -| excluded_without | Excluded Without | -| excluded_without_all | Excluded Without All | -| unique | Unique | - -Benchmarks ------- -###### Run on MacBook Pro (15-inch, 2017) go version go1.10.2 darwin/amd64 -```go -goos: darwin -goarch: amd64 -pkg: github.com/go-playground/validator -BenchmarkFieldSuccess-8 20000000 83.6 ns/op 0 B/op 0 allocs/op -BenchmarkFieldSuccessParallel-8 50000000 26.8 ns/op 0 B/op 0 allocs/op -BenchmarkFieldFailure-8 5000000 291 ns/op 208 B/op 4 allocs/op -BenchmarkFieldFailureParallel-8 20000000 107 ns/op 208 B/op 4 allocs/op -BenchmarkFieldArrayDiveSuccess-8 2000000 623 ns/op 201 B/op 11 allocs/op -BenchmarkFieldArrayDiveSuccessParallel-8 10000000 237 ns/op 201 B/op 11 allocs/op -BenchmarkFieldArrayDiveFailure-8 2000000 859 ns/op 412 B/op 16 allocs/op -BenchmarkFieldArrayDiveFailureParallel-8 5000000 335 ns/op 413 B/op 16 allocs/op -BenchmarkFieldMapDiveSuccess-8 1000000 1292 ns/op 432 B/op 18 allocs/op -BenchmarkFieldMapDiveSuccessParallel-8 3000000 467 ns/op 432 B/op 18 allocs/op -BenchmarkFieldMapDiveFailure-8 1000000 1082 ns/op 512 B/op 16 allocs/op -BenchmarkFieldMapDiveFailureParallel-8 5000000 425 ns/op 512 B/op 16 allocs/op -BenchmarkFieldMapDiveWithKeysSuccess-8 1000000 1539 ns/op 480 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysSuccessParallel-8 3000000 613 ns/op 480 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysFailure-8 1000000 1413 ns/op 721 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysFailureParallel-8 3000000 575 ns/op 721 B/op 21 allocs/op -BenchmarkFieldCustomTypeSuccess-8 10000000 216 ns/op 32 B/op 2 allocs/op -BenchmarkFieldCustomTypeSuccessParallel-8 20000000 82.2 ns/op 32 B/op 2 allocs/op -BenchmarkFieldCustomTypeFailure-8 5000000 274 ns/op 208 B/op 4 allocs/op -BenchmarkFieldCustomTypeFailureParallel-8 20000000 116 ns/op 208 B/op 4 allocs/op -BenchmarkFieldOrTagSuccess-8 2000000 740 ns/op 16 B/op 1 allocs/op -BenchmarkFieldOrTagSuccessParallel-8 3000000 474 ns/op 16 B/op 1 allocs/op -BenchmarkFieldOrTagFailure-8 3000000 471 ns/op 224 B/op 5 allocs/op -BenchmarkFieldOrTagFailureParallel-8 3000000 414 ns/op 224 B/op 5 allocs/op -BenchmarkStructLevelValidationSuccess-8 10000000 213 ns/op 32 B/op 2 allocs/op -BenchmarkStructLevelValidationSuccessParallel-8 20000000 91.8 ns/op 32 B/op 2 allocs/op -BenchmarkStructLevelValidationFailure-8 3000000 473 ns/op 304 B/op 8 allocs/op -BenchmarkStructLevelValidationFailureParallel-8 10000000 234 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCustomTypeSuccess-8 5000000 385 ns/op 32 B/op 2 allocs/op -BenchmarkStructSimpleCustomTypeSuccessParallel-8 10000000 161 ns/op 32 B/op 2 allocs/op -BenchmarkStructSimpleCustomTypeFailure-8 2000000 640 ns/op 424 B/op 9 allocs/op -BenchmarkStructSimpleCustomTypeFailureParallel-8 5000000 318 ns/op 440 B/op 10 allocs/op -BenchmarkStructFilteredSuccess-8 2000000 597 ns/op 288 B/op 9 allocs/op -BenchmarkStructFilteredSuccessParallel-8 10000000 266 ns/op 288 B/op 9 allocs/op -BenchmarkStructFilteredFailure-8 3000000 454 ns/op 256 B/op 7 allocs/op -BenchmarkStructFilteredFailureParallel-8 10000000 214 ns/op 256 B/op 7 allocs/op -BenchmarkStructPartialSuccess-8 3000000 502 ns/op 256 B/op 6 allocs/op -BenchmarkStructPartialSuccessParallel-8 10000000 225 ns/op 256 B/op 6 allocs/op -BenchmarkStructPartialFailure-8 2000000 702 ns/op 480 B/op 11 allocs/op -BenchmarkStructPartialFailureParallel-8 5000000 329 ns/op 480 B/op 11 allocs/op -BenchmarkStructExceptSuccess-8 2000000 793 ns/op 496 B/op 12 allocs/op -BenchmarkStructExceptSuccessParallel-8 10000000 193 ns/op 240 B/op 5 allocs/op -BenchmarkStructExceptFailure-8 2000000 639 ns/op 464 B/op 10 allocs/op -BenchmarkStructExceptFailureParallel-8 5000000 300 ns/op 464 B/op 10 allocs/op -BenchmarkStructSimpleCrossFieldSuccess-8 3000000 417 ns/op 72 B/op 3 allocs/op -BenchmarkStructSimpleCrossFieldSuccessParallel-8 10000000 163 ns/op 72 B/op 3 allocs/op -BenchmarkStructSimpleCrossFieldFailure-8 2000000 645 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCrossFieldFailureParallel-8 5000000 285 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldSuccess-8 3000000 588 ns/op 80 B/op 4 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel-8 10000000 221 ns/op 80 B/op 4 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldFailure-8 2000000 868 ns/op 320 B/op 9 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldFailureParallel-8 5000000 337 ns/op 320 B/op 9 allocs/op -BenchmarkStructSimpleSuccess-8 5000000 260 ns/op 0 B/op 0 allocs/op -BenchmarkStructSimpleSuccessParallel-8 20000000 90.6 ns/op 0 B/op 0 allocs/op -BenchmarkStructSimpleFailure-8 2000000 619 ns/op 424 B/op 9 allocs/op -BenchmarkStructSimpleFailureParallel-8 5000000 296 ns/op 424 B/op 9 allocs/op -BenchmarkStructComplexSuccess-8 1000000 1454 ns/op 128 B/op 8 allocs/op -BenchmarkStructComplexSuccessParallel-8 3000000 579 ns/op 128 B/op 8 allocs/op -BenchmarkStructComplexFailure-8 300000 4140 ns/op 3041 B/op 53 allocs/op -BenchmarkStructComplexFailureParallel-8 1000000 2127 ns/op 3041 B/op 53 allocs/op -BenchmarkOneof-8 10000000 140 ns/op 0 B/op 0 allocs/op -BenchmarkOneofParallel-8 20000000 70.1 ns/op 0 B/op 0 allocs/op -``` - -Complementary Software ----------------------- - -Here is a list of software that complements using this library either pre or post validation. - -* [form](https://github.com/go-playground/form) - Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support. -* [mold](https://github.com/go-playground/mold) - A general library to help modify or set data within data structures and other objects - -How to Contribute ------- - -Make a pull request... - -License ------- -Distributed under MIT License, please see license file within the code for more details. diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/baked_in.go b/taskman-server/vendor/github.com/go-playground/validator/v10/baked_in.go deleted file mode 100644 index 6ce762d1..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/baked_in.go +++ /dev/null @@ -1,2285 +0,0 @@ -package validator - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "fmt" - "net" - "net/url" - "os" - "reflect" - "strconv" - "strings" - "sync" - "time" - "unicode/utf8" - - "golang.org/x/crypto/sha3" - - urn "github.com/leodido/go-urn" -) - -// Func accepts a FieldLevel interface for all validation needs. The return -// value should be true when validation succeeds. -type Func func(fl FieldLevel) bool - -// FuncCtx accepts a context.Context and FieldLevel interface for all -// validation needs. The return value should be true when validation succeeds. -type FuncCtx func(ctx context.Context, fl FieldLevel) bool - -// wrapFunc wraps noramal Func makes it compatible with FuncCtx -func wrapFunc(fn Func) FuncCtx { - if fn == nil { - return nil // be sure not to wrap a bad function. - } - return func(ctx context.Context, fl FieldLevel) bool { - return fn(fl) - } -} - -var ( - restrictedTags = map[string]struct{}{ - diveTag: {}, - keysTag: {}, - endKeysTag: {}, - structOnlyTag: {}, - omitempty: {}, - skipValidationTag: {}, - utf8HexComma: {}, - utf8Pipe: {}, - noStructLevelTag: {}, - requiredTag: {}, - isdefault: {}, - } - - // BakedInAliasValidators is a default mapping of a single validation tag that - // defines a common or complex set of validation(s) to simplify - // adding validation to structs. - bakedInAliases = map[string]string{ - "iscolor": "hexcolor|rgb|rgba|hsl|hsla", - "country_code": "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric", - } - - // BakedInValidators is the default map of ValidationFunc - // you can add, remove or even replace items to suite your needs, - // or even disregard and use your own map if so desired. - bakedInValidators = map[string]Func{ - "required": hasValue, - "required_if": requiredIf, - "required_unless": requiredUnless, - "required_with": requiredWith, - "required_with_all": requiredWithAll, - "required_without": requiredWithout, - "required_without_all": requiredWithoutAll, - "excluded_with": excludedWith, - "excluded_with_all": excludedWithAll, - "excluded_without": excludedWithout, - "excluded_without_all": excludedWithoutAll, - "isdefault": isDefault, - "len": hasLengthOf, - "min": hasMinOf, - "max": hasMaxOf, - "eq": isEq, - "ne": isNe, - "lt": isLt, - "lte": isLte, - "gt": isGt, - "gte": isGte, - "eqfield": isEqField, - "eqcsfield": isEqCrossStructField, - "necsfield": isNeCrossStructField, - "gtcsfield": isGtCrossStructField, - "gtecsfield": isGteCrossStructField, - "ltcsfield": isLtCrossStructField, - "ltecsfield": isLteCrossStructField, - "nefield": isNeField, - "gtefield": isGteField, - "gtfield": isGtField, - "ltefield": isLteField, - "ltfield": isLtField, - "fieldcontains": fieldContains, - "fieldexcludes": fieldExcludes, - "alpha": isAlpha, - "alphanum": isAlphanum, - "alphaunicode": isAlphaUnicode, - "alphanumunicode": isAlphanumUnicode, - "numeric": isNumeric, - "number": isNumber, - "hexadecimal": isHexadecimal, - "hexcolor": isHEXColor, - "rgb": isRGB, - "rgba": isRGBA, - "hsl": isHSL, - "hsla": isHSLA, - "e164": isE164, - "email": isEmail, - "url": isURL, - "uri": isURI, - "urn_rfc2141": isUrnRFC2141, // RFC 2141 - "file": isFile, - "base64": isBase64, - "base64url": isBase64URL, - "contains": contains, - "containsany": containsAny, - "containsrune": containsRune, - "excludes": excludes, - "excludesall": excludesAll, - "excludesrune": excludesRune, - "startswith": startsWith, - "endswith": endsWith, - "startsnotwith": startsNotWith, - "endsnotwith": endsNotWith, - "isbn": isISBN, - "isbn10": isISBN10, - "isbn13": isISBN13, - "eth_addr": isEthereumAddress, - "btc_addr": isBitcoinAddress, - "btc_addr_bech32": isBitcoinBech32Address, - "uuid": isUUID, - "uuid3": isUUID3, - "uuid4": isUUID4, - "uuid5": isUUID5, - "uuid_rfc4122": isUUIDRFC4122, - "uuid3_rfc4122": isUUID3RFC4122, - "uuid4_rfc4122": isUUID4RFC4122, - "uuid5_rfc4122": isUUID5RFC4122, - "ascii": isASCII, - "printascii": isPrintableASCII, - "multibyte": hasMultiByteCharacter, - "datauri": isDataURI, - "latitude": isLatitude, - "longitude": isLongitude, - "ssn": isSSN, - "ipv4": isIPv4, - "ipv6": isIPv6, - "ip": isIP, - "cidrv4": isCIDRv4, - "cidrv6": isCIDRv6, - "cidr": isCIDR, - "tcp4_addr": isTCP4AddrResolvable, - "tcp6_addr": isTCP6AddrResolvable, - "tcp_addr": isTCPAddrResolvable, - "udp4_addr": isUDP4AddrResolvable, - "udp6_addr": isUDP6AddrResolvable, - "udp_addr": isUDPAddrResolvable, - "ip4_addr": isIP4AddrResolvable, - "ip6_addr": isIP6AddrResolvable, - "ip_addr": isIPAddrResolvable, - "unix_addr": isUnixAddrResolvable, - "mac": isMAC, - "hostname": isHostnameRFC952, // RFC 952 - "hostname_rfc1123": isHostnameRFC1123, // RFC 1123 - "fqdn": isFQDN, - "unique": isUnique, - "oneof": isOneOf, - "html": isHTML, - "html_encoded": isHTMLEncoded, - "url_encoded": isURLEncoded, - "dir": isDir, - "json": isJSON, - "hostname_port": isHostnamePort, - "lowercase": isLowercase, - "uppercase": isUppercase, - "datetime": isDatetime, - "timezone": isTimeZone, - "iso3166_1_alpha2": isIso3166Alpha2, - "iso3166_1_alpha3": isIso3166Alpha3, - "iso3166_1_alpha_numeric": isIso3166AlphaNumeric, - } -) - -var oneofValsCache = map[string][]string{} -var oneofValsCacheRWLock = sync.RWMutex{} - -func parseOneOfParam2(s string) []string { - oneofValsCacheRWLock.RLock() - vals, ok := oneofValsCache[s] - oneofValsCacheRWLock.RUnlock() - if !ok { - oneofValsCacheRWLock.Lock() - vals = splitParamsRegex.FindAllString(s, -1) - for i := 0; i < len(vals); i++ { - vals[i] = strings.Replace(vals[i], "'", "", -1) - } - oneofValsCache[s] = vals - oneofValsCacheRWLock.Unlock() - } - return vals -} - -func isURLEncoded(fl FieldLevel) bool { - return uRLEncodedRegex.MatchString(fl.Field().String()) -} - -func isHTMLEncoded(fl FieldLevel) bool { - return hTMLEncodedRegex.MatchString(fl.Field().String()) -} - -func isHTML(fl FieldLevel) bool { - return hTMLRegex.MatchString(fl.Field().String()) -} - -func isOneOf(fl FieldLevel) bool { - vals := parseOneOfParam2(fl.Param()) - - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - for i := 0; i < len(vals); i++ { - if vals[i] == v { - return true - } - } - return false -} - -// isUnique is the validation function for validating if each array|slice|map value is unique -func isUnique(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - v := reflect.ValueOf(struct{}{}) - - switch field.Kind() { - case reflect.Slice, reflect.Array: - elem := field.Type().Elem() - if elem.Kind() == reflect.Ptr { - elem = elem.Elem() - } - - if param == "" { - m := reflect.MakeMap(reflect.MapOf(elem, v.Type())) - - for i := 0; i < field.Len(); i++ { - m.SetMapIndex(reflect.Indirect(field.Index(i)), v) - } - return field.Len() == m.Len() - } - - sf, ok := elem.FieldByName(param) - if !ok { - panic(fmt.Sprintf("Bad field name %s", param)) - } - - sfTyp := sf.Type - if sfTyp.Kind() == reflect.Ptr { - sfTyp = sfTyp.Elem() - } - - m := reflect.MakeMap(reflect.MapOf(sfTyp, v.Type())) - for i := 0; i < field.Len(); i++ { - m.SetMapIndex(reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param)), v) - } - return field.Len() == m.Len() - case reflect.Map: - m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) - - for _, k := range field.MapKeys() { - m.SetMapIndex(field.MapIndex(k), v) - } - return field.Len() == m.Len() - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } -} - -// IsMAC is the validation function for validating if the field's value is a valid MAC address. -func isMAC(fl FieldLevel) bool { - - _, err := net.ParseMAC(fl.Field().String()) - - return err == nil -} - -// IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. -func isCIDRv4(fl FieldLevel) bool { - - ip, _, err := net.ParseCIDR(fl.Field().String()) - - return err == nil && ip.To4() != nil -} - -// IsCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address. -func isCIDRv6(fl FieldLevel) bool { - - ip, _, err := net.ParseCIDR(fl.Field().String()) - - return err == nil && ip.To4() == nil -} - -// IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address. -func isCIDR(fl FieldLevel) bool { - - _, _, err := net.ParseCIDR(fl.Field().String()) - - return err == nil -} - -// IsIPv4 is the validation function for validating if a value is a valid v4 IP address. -func isIPv4(fl FieldLevel) bool { - - ip := net.ParseIP(fl.Field().String()) - - return ip != nil && ip.To4() != nil -} - -// IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address. -func isIPv6(fl FieldLevel) bool { - - ip := net.ParseIP(fl.Field().String()) - - return ip != nil && ip.To4() == nil -} - -// IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address. -func isIP(fl FieldLevel) bool { - - ip := net.ParseIP(fl.Field().String()) - - return ip != nil -} - -// IsSSN is the validation function for validating if the field's value is a valid SSN. -func isSSN(fl FieldLevel) bool { - - field := fl.Field() - - if field.Len() != 11 { - return false - } - - return sSNRegex.MatchString(field.String()) -} - -// IsLongitude is the validation function for validating if the field's value is a valid longitude coordinate. -func isLongitude(fl FieldLevel) bool { - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - case reflect.Float32: - v = strconv.FormatFloat(field.Float(), 'f', -1, 32) - case reflect.Float64: - v = strconv.FormatFloat(field.Float(), 'f', -1, 64) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - - return longitudeRegex.MatchString(v) -} - -// IsLatitude is the validation function for validating if the field's value is a valid latitude coordinate. -func isLatitude(fl FieldLevel) bool { - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - case reflect.Float32: - v = strconv.FormatFloat(field.Float(), 'f', -1, 32) - case reflect.Float64: - v = strconv.FormatFloat(field.Float(), 'f', -1, 64) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - - return latitudeRegex.MatchString(v) -} - -// IsDataURI is the validation function for validating if the field's value is a valid data URI. -func isDataURI(fl FieldLevel) bool { - - uri := strings.SplitN(fl.Field().String(), ",", 2) - - if len(uri) != 2 { - return false - } - - if !dataURIRegex.MatchString(uri[0]) { - return false - } - - return base64Regex.MatchString(uri[1]) -} - -// HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. -func hasMultiByteCharacter(fl FieldLevel) bool { - - field := fl.Field() - - if field.Len() == 0 { - return true - } - - return multibyteRegex.MatchString(field.String()) -} - -// IsPrintableASCII is the validation function for validating if the field's value is a valid printable ASCII character. -func isPrintableASCII(fl FieldLevel) bool { - return printableASCIIRegex.MatchString(fl.Field().String()) -} - -// IsASCII is the validation function for validating if the field's value is a valid ASCII character. -func isASCII(fl FieldLevel) bool { - return aSCIIRegex.MatchString(fl.Field().String()) -} - -// IsUUID5 is the validation function for validating if the field's value is a valid v5 UUID. -func isUUID5(fl FieldLevel) bool { - return uUID5Regex.MatchString(fl.Field().String()) -} - -// IsUUID4 is the validation function for validating if the field's value is a valid v4 UUID. -func isUUID4(fl FieldLevel) bool { - return uUID4Regex.MatchString(fl.Field().String()) -} - -// IsUUID3 is the validation function for validating if the field's value is a valid v3 UUID. -func isUUID3(fl FieldLevel) bool { - return uUID3Regex.MatchString(fl.Field().String()) -} - -// IsUUID is the validation function for validating if the field's value is a valid UUID of any version. -func isUUID(fl FieldLevel) bool { - return uUIDRegex.MatchString(fl.Field().String()) -} - -// IsUUID5RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v5 UUID. -func isUUID5RFC4122(fl FieldLevel) bool { - return uUID5RFC4122Regex.MatchString(fl.Field().String()) -} - -// IsUUID4RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v4 UUID. -func isUUID4RFC4122(fl FieldLevel) bool { - return uUID4RFC4122Regex.MatchString(fl.Field().String()) -} - -// IsUUID3RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v3 UUID. -func isUUID3RFC4122(fl FieldLevel) bool { - return uUID3RFC4122Regex.MatchString(fl.Field().String()) -} - -// IsUUIDRFC4122 is the validation function for validating if the field's value is a valid RFC4122 UUID of any version. -func isUUIDRFC4122(fl FieldLevel) bool { - return uUIDRFC4122Regex.MatchString(fl.Field().String()) -} - -// IsISBN is the validation function for validating if the field's value is a valid v10 or v13 ISBN. -func isISBN(fl FieldLevel) bool { - return isISBN10(fl) || isISBN13(fl) -} - -// IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. -func isISBN13(fl FieldLevel) bool { - - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4) - - if !iSBN13Regex.MatchString(s) { - return false - } - - var checksum int32 - var i int32 - - factor := []int32{1, 3} - - for i = 0; i < 12; i++ { - checksum += factor[i%2] * int32(s[i]-'0') - } - - return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0 -} - -// IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. -func isISBN10(fl FieldLevel) bool { - - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3) - - if !iSBN10Regex.MatchString(s) { - return false - } - - var checksum int32 - var i int32 - - for i = 0; i < 9; i++ { - checksum += (i + 1) * int32(s[i]-'0') - } - - if s[9] == 'X' { - checksum += 10 * 10 - } else { - checksum += 10 * int32(s[9]-'0') - } - - return checksum%11 == 0 -} - -// IsEthereumAddress is the validation function for validating if the field's value is a valid Ethereum address. -func isEthereumAddress(fl FieldLevel) bool { - address := fl.Field().String() - - if !ethAddressRegex.MatchString(address) { - return false - } - - if ethaddressRegexUpper.MatchString(address) || ethAddressRegexLower.MatchString(address) { - return true - } - - // Checksum validation. Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md - address = address[2:] // Skip "0x" prefix. - h := sha3.NewLegacyKeccak256() - // hash.Hash's io.Writer implementation says it never returns an error. https://golang.org/pkg/hash/#Hash - _, _ = h.Write([]byte(strings.ToLower(address))) - hash := hex.EncodeToString(h.Sum(nil)) - - for i := 0; i < len(address); i++ { - if address[i] <= '9' { // Skip 0-9 digits: they don't have upper/lower-case. - continue - } - if hash[i] > '7' && address[i] >= 'a' || hash[i] <= '7' && address[i] <= 'F' { - return false - } - } - - return true -} - -// IsBitcoinAddress is the validation function for validating if the field's value is a valid btc address -func isBitcoinAddress(fl FieldLevel) bool { - address := fl.Field().String() - - if !btcAddressRegex.MatchString(address) { - return false - } - - alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") - - decode := [25]byte{} - - for _, n := range []byte(address) { - d := bytes.IndexByte(alphabet, n) - - for i := 24; i >= 0; i-- { - d += 58 * int(decode[i]) - decode[i] = byte(d % 256) - d /= 256 - } - } - - h := sha256.New() - _, _ = h.Write(decode[:21]) - d := h.Sum([]byte{}) - h = sha256.New() - _, _ = h.Write(d) - - validchecksum := [4]byte{} - computedchecksum := [4]byte{} - - copy(computedchecksum[:], h.Sum(d[:0])) - copy(validchecksum[:], decode[21:]) - - return validchecksum == computedchecksum -} - -// IsBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address -func isBitcoinBech32Address(fl FieldLevel) bool { - address := fl.Field().String() - - if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) { - return false - } - - am := len(address) % 8 - - if am == 0 || am == 3 || am == 5 { - return false - } - - address = strings.ToLower(address) - - alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l" - - hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc - addr := address[3:] - dp := make([]int, 0, len(addr)) - - for _, c := range addr { - dp = append(dp, strings.IndexRune(alphabet, c)) - } - - ver := dp[0] - - if ver < 0 || ver > 16 { - return false - } - - if ver == 0 { - if len(address) != 42 && len(address) != 62 { - return false - } - } - - values := append(hr, dp...) - - GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} - - p := 1 - - for _, v := range values { - b := p >> 25 - p = (p&0x1ffffff)<<5 ^ v - - for i := 0; i < 5; i++ { - if (b>>uint(i))&1 == 1 { - p ^= GEN[i] - } - } - } - - if p != 1 { - return false - } - - b := uint(0) - acc := 0 - mv := (1 << 5) - 1 - var sw []int - - for _, v := range dp[1 : len(dp)-6] { - acc = (acc << 5) | v - b += 5 - for b >= 8 { - b -= 8 - sw = append(sw, (acc>>b)&mv) - } - } - - if len(sw) < 2 || len(sw) > 40 { - return false - } - - return true -} - -// ExcludesRune is the validation function for validating that the field's value does not contain the rune specified within the param. -func excludesRune(fl FieldLevel) bool { - return !containsRune(fl) -} - -// ExcludesAll is the validation function for validating that the field's value does not contain any of the characters specified within the param. -func excludesAll(fl FieldLevel) bool { - return !containsAny(fl) -} - -// Excludes is the validation function for validating that the field's value does not contain the text specified within the param. -func excludes(fl FieldLevel) bool { - return !contains(fl) -} - -// ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. -func containsRune(fl FieldLevel) bool { - - r, _ := utf8.DecodeRuneInString(fl.Param()) - - return strings.ContainsRune(fl.Field().String(), r) -} - -// ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param. -func containsAny(fl FieldLevel) bool { - return strings.ContainsAny(fl.Field().String(), fl.Param()) -} - -// Contains is the validation function for validating that the field's value contains the text specified within the param. -func contains(fl FieldLevel) bool { - return strings.Contains(fl.Field().String(), fl.Param()) -} - -// StartsWith is the validation function for validating that the field's value starts with the text specified within the param. -func startsWith(fl FieldLevel) bool { - return strings.HasPrefix(fl.Field().String(), fl.Param()) -} - -// EndsWith is the validation function for validating that the field's value ends with the text specified within the param. -func endsWith(fl FieldLevel) bool { - return strings.HasSuffix(fl.Field().String(), fl.Param()) -} - -// StartsNotWith is the validation function for validating that the field's value does not start with the text specified within the param. -func startsNotWith(fl FieldLevel) bool { - return !startsWith(fl) -} - -// EndsNotWith is the validation function for validating that the field's value does not end with the text specified within the param. -func endsNotWith(fl FieldLevel) bool { - return !endsWith(fl) -} - -// FieldContains is the validation function for validating if the current field's value contains the field specified by the param's value. -func fieldContains(fl FieldLevel) bool { - field := fl.Field() - - currentField, _, ok := fl.GetStructFieldOK() - - if !ok { - return false - } - - return strings.Contains(field.String(), currentField.String()) -} - -// FieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value. -func fieldExcludes(fl FieldLevel) bool { - field := fl.Field() - - currentField, _, ok := fl.GetStructFieldOK() - if !ok { - return true - } - - return !strings.Contains(field.String(), currentField.String()) -} - -// IsNeField is the validation function for validating if the current field's value is not equal to the field specified by the param's value. -func isNeField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - - if !ok || currentKind != kind { - return true - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() != currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() != currentField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() != currentField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) != int64(currentField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return true - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return !fieldTime.Equal(t) - } - - } - - // default reflect.String: - return field.String() != currentField.String() -} - -// IsNe is the validation function for validating that the field's value does not equal the provided param value. -func isNe(fl FieldLevel) bool { - return !isEq(fl) -} - -// IsLteCrossStructField is the validation function for validating if the current field's value is less than or equal to the field, within a separate struct, specified by the param's value. -func isLteCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() <= topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() <= topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() <= topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) <= int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.Before(topTime) || fieldTime.Equal(topTime) - } - } - - // default reflect.String: - return field.String() <= topField.String() -} - -// IsLtCrossStructField is the validation function for validating if the current field's value is less than the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func isLtCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() < topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() < topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() < topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) < int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.Before(topTime) - } - } - - // default reflect.String: - return field.String() < topField.String() -} - -// IsGteCrossStructField is the validation function for validating if the current field's value is greater than or equal to the field, within a separate struct, specified by the param's value. -func isGteCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() >= topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() >= topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() >= topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) >= int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.After(topTime) || fieldTime.Equal(topTime) - } - } - - // default reflect.String: - return field.String() >= topField.String() -} - -// IsGtCrossStructField is the validation function for validating if the current field's value is greater than the field, within a separate struct, specified by the param's value. -func isGtCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() > topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() > topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() > topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) > int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - fieldTime := field.Interface().(time.Time) - topTime := topField.Interface().(time.Time) - - return fieldTime.After(topTime) - } - } - - // default reflect.String: - return field.String() > topField.String() -} - -// IsNeCrossStructField is the validation function for validating that the current field's value is not equal to the field, within a separate struct, specified by the param's value. -func isNeCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return true - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return topField.Int() != field.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return topField.Uint() != field.Uint() - - case reflect.Float32, reflect.Float64: - return topField.Float() != field.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(topField.Len()) != int64(field.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return true - } - - if fieldType == timeType { - - t := field.Interface().(time.Time) - fieldTime := topField.Interface().(time.Time) - - return !fieldTime.Equal(t) - } - } - - // default reflect.String: - return topField.String() != field.String() -} - -// IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value. -func isEqCrossStructField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return topField.Int() == field.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return topField.Uint() == field.Uint() - - case reflect.Float32, reflect.Float64: - return topField.Float() == field.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(topField.Len()) == int64(field.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - - if fieldType == timeType { - - t := field.Interface().(time.Time) - fieldTime := topField.Interface().(time.Time) - - return fieldTime.Equal(t) - } - } - - // default reflect.String: - return topField.String() == field.String() -} - -// IsEqField is the validation function for validating if the current field's value is equal to the field specified by the param's value. -func isEqField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() == currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() == currentField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() == currentField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) == int64(currentField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.Equal(t) - } - - } - - // default reflect.String: - return field.String() == currentField.String() -} - -// IsEq is the validation function for validating if the current field's value is equal to the param's value. -func isEq(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - return field.String() == param - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) == p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() == p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() == p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() == p - - case reflect.Bool: - p := asBool(param) - - return field.Bool() == p - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsBase64 is the validation function for validating if the current field's value is a valid base 64. -func isBase64(fl FieldLevel) bool { - return base64Regex.MatchString(fl.Field().String()) -} - -// IsBase64URL is the validation function for validating if the current field's value is a valid base64 URL safe string. -func isBase64URL(fl FieldLevel) bool { - return base64URLRegex.MatchString(fl.Field().String()) -} - -// IsURI is the validation function for validating if the current field's value is a valid URI. -func isURI(fl FieldLevel) bool { - - field := fl.Field() - - switch field.Kind() { - - case reflect.String: - - s := field.String() - - // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 - // emulate browser and strip the '#' suffix prior to validation. see issue-#237 - if i := strings.Index(s, "#"); i > -1 { - s = s[:i] - } - - if len(s) == 0 { - return false - } - - _, err := url.ParseRequestURI(s) - - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsURL is the validation function for validating if the current field's value is a valid URL. -func isURL(fl FieldLevel) bool { - - field := fl.Field() - - switch field.Kind() { - - case reflect.String: - - var i int - s := field.String() - - // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 - // emulate browser and strip the '#' suffix prior to validation. see issue-#237 - if i = strings.Index(s, "#"); i > -1 { - s = s[:i] - } - - if len(s) == 0 { - return false - } - - url, err := url.ParseRequestURI(s) - - if err != nil || url.Scheme == "" { - return false - } - - return true - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. -func isUrnRFC2141(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - - case reflect.String: - - str := field.String() - - _, match := urn.Parse([]byte(str)) - - return match - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsFile is the validation function for validating if the current field's value is a valid file path. -func isFile(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - case reflect.String: - fileInfo, err := os.Stat(field.String()) - if err != nil { - return false - } - - return !fileInfo.IsDir() - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number. -func isE164(fl FieldLevel) bool { - return e164Regex.MatchString(fl.Field().String()) -} - -// IsEmail is the validation function for validating if the current field's value is a valid email address. -func isEmail(fl FieldLevel) bool { - return emailRegex.MatchString(fl.Field().String()) -} - -// IsHSLA is the validation function for validating if the current field's value is a valid HSLA color. -func isHSLA(fl FieldLevel) bool { - return hslaRegex.MatchString(fl.Field().String()) -} - -// IsHSL is the validation function for validating if the current field's value is a valid HSL color. -func isHSL(fl FieldLevel) bool { - return hslRegex.MatchString(fl.Field().String()) -} - -// IsRGBA is the validation function for validating if the current field's value is a valid RGBA color. -func isRGBA(fl FieldLevel) bool { - return rgbaRegex.MatchString(fl.Field().String()) -} - -// IsRGB is the validation function for validating if the current field's value is a valid RGB color. -func isRGB(fl FieldLevel) bool { - return rgbRegex.MatchString(fl.Field().String()) -} - -// IsHEXColor is the validation function for validating if the current field's value is a valid HEX color. -func isHEXColor(fl FieldLevel) bool { - return hexcolorRegex.MatchString(fl.Field().String()) -} - -// IsHexadecimal is the validation function for validating if the current field's value is a valid hexadecimal. -func isHexadecimal(fl FieldLevel) bool { - return hexadecimalRegex.MatchString(fl.Field().String()) -} - -// IsNumber is the validation function for validating if the current field's value is a valid number. -func isNumber(fl FieldLevel) bool { - switch fl.Field().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: - return true - default: - return numberRegex.MatchString(fl.Field().String()) - } -} - -// IsNumeric is the validation function for validating if the current field's value is a valid numeric value. -func isNumeric(fl FieldLevel) bool { - switch fl.Field().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: - return true - default: - return numericRegex.MatchString(fl.Field().String()) - } -} - -// IsAlphanum is the validation function for validating if the current field's value is a valid alphanumeric value. -func isAlphanum(fl FieldLevel) bool { - return alphaNumericRegex.MatchString(fl.Field().String()) -} - -// IsAlpha is the validation function for validating if the current field's value is a valid alpha value. -func isAlpha(fl FieldLevel) bool { - return alphaRegex.MatchString(fl.Field().String()) -} - -// IsAlphanumUnicode is the validation function for validating if the current field's value is a valid alphanumeric unicode value. -func isAlphanumUnicode(fl FieldLevel) bool { - return alphaUnicodeNumericRegex.MatchString(fl.Field().String()) -} - -// IsAlphaUnicode is the validation function for validating if the current field's value is a valid alpha unicode value. -func isAlphaUnicode(fl FieldLevel) bool { - return alphaUnicodeRegex.MatchString(fl.Field().String()) -} - -// isDefault is the opposite of required aka hasValue -func isDefault(fl FieldLevel) bool { - return !hasValue(fl) -} - -// HasValue is the validation function for validating if the current field's value is not the default static value. -func hasValue(fl FieldLevel) bool { - field := fl.Field() - switch field.Kind() { - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: - return !field.IsNil() - default: - if fl.(*validate).fldIsPointer && field.Interface() != nil { - return true - } - return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() - } -} - -// requireCheckField is a func for check field kind -func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue bool) bool { - field := fl.Field() - kind := field.Kind() - var nullable, found bool - if len(param) > 0 { - field, kind, nullable, found = fl.GetStructFieldOKAdvanced2(fl.Parent(), param) - if !found { - return defaultNotFoundValue - } - } - switch kind { - case reflect.Invalid: - return defaultNotFoundValue - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: - return field.IsNil() - default: - if nullable && field.Interface() != nil { - return false - } - return field.IsValid() && field.Interface() == reflect.Zero(field.Type()).Interface() - } -} - -// requireCheckFieldValue is a func for check field value -func requireCheckFieldValue(fl FieldLevel, param string, value string, defaultNotFoundValue bool) bool { - field, kind, _, found := fl.GetStructFieldOKAdvanced2(fl.Parent(), param) - if !found { - return defaultNotFoundValue - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() == asInt(value) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() == asUint(value) - - case reflect.Float32, reflect.Float64: - return field.Float() == asFloat(value) - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) == asInt(value) - } - - // default reflect.String: - return field.String() == value -} - -// requiredIf is the validation function -// The field under validation must be present and not empty only if all the other specified fields are equal to the value following with the specified field. -func requiredIf(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - if len(params)%2 != 0 { - panic(fmt.Sprintf("Bad param number for required_if %s", fl.FieldName())) - } - for i := 0; i < len(params); i += 2 { - if !requireCheckFieldValue(fl, params[i], params[i+1], false) { - return true - } - } - return hasValue(fl) -} - -// requiredUnless is the validation function -// The field under validation must be present and not empty only unless all the other specified fields are equal to the value following with the specified field. -func requiredUnless(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - if len(params)%2 != 0 { - panic(fmt.Sprintf("Bad param number for required_unless %s", fl.FieldName())) - } - - for i := 0; i < len(params); i += 2 { - if requireCheckFieldValue(fl, params[i], params[i+1], false) { - return true - } - } - return hasValue(fl) -} - -// ExcludedWith is the validation function -// The field under validation must not be present or is empty if any of the other specified fields are present. -func excludedWith(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return !hasValue(fl) - } - } - return true -} - -// RequiredWith is the validation function -// The field under validation must be present and not empty only if any of the other specified fields are present. -func requiredWith(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return hasValue(fl) - } - } - return true -} - -// ExcludedWithAll is the validation function -// The field under validation must not be present or is empty if all of the other specified fields are present. -func excludedWithAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if requireCheckFieldKind(fl, param, true) { - return true - } - } - return !hasValue(fl) -} - -// RequiredWithAll is the validation function -// The field under validation must be present and not empty only if all of the other specified fields are present. -func requiredWithAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if requireCheckFieldKind(fl, param, true) { - return true - } - } - return hasValue(fl) -} - -// ExcludedWithout is the validation function -// The field under validation must not be present or is empty when any of the other specified fields are not present. -func excludedWithout(fl FieldLevel) bool { - if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { - return !hasValue(fl) - } - return true -} - -// RequiredWithout is the validation function -// The field under validation must be present and not empty only when any of the other specified fields are not present. -func requiredWithout(fl FieldLevel) bool { - if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { - return hasValue(fl) - } - return true -} - -// RequiredWithoutAll is the validation function -// The field under validation must not be present or is empty when all of the other specified fields are not present. -func excludedWithoutAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return true - } - } - return !hasValue(fl) -} - -// RequiredWithoutAll is the validation function -// The field under validation must be present and not empty only when all of the other specified fields are not present. -func requiredWithoutAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return true - } - } - return hasValue(fl) -} - -// IsGteField is the validation function for validating if the current field's value is greater than or equal to the field specified by the param's value. -func isGteField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() >= currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() >= currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() >= currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.After(t) || fieldTime.Equal(t) - } - } - - // default reflect.String - return len(field.String()) >= len(currentField.String()) -} - -// IsGtField is the validation function for validating if the current field's value is greater than the field specified by the param's value. -func isGtField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() > currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() > currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() > currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.After(t) - } - } - - // default reflect.String - return len(field.String()) > len(currentField.String()) -} - -// IsGte is the validation function for validating if the current field's value is greater than or equal to the param's value. -func isGte(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) >= p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) >= p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() >= p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() >= p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() >= p - - case reflect.Struct: - - if field.Type() == timeType { - - now := time.Now().UTC() - t := field.Interface().(time.Time) - - return t.After(now) || t.Equal(now) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsGt is the validation function for validating if the current field's value is greater than the param's value. -func isGt(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) > p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) > p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() > p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() > p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() > p - case reflect.Struct: - - if field.Type() == timeType { - - return field.Interface().(time.Time).After(time.Now().UTC()) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// HasLengthOf is the validation function for validating if the current field's value is equal to the param's value. -func hasLengthOf(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) == p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) == p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() == p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() == p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() == p - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// HasMinOf is the validation function for validating if the current field's value is greater than or equal to the param's value. -func hasMinOf(fl FieldLevel) bool { - return isGte(fl) -} - -// IsLteField is the validation function for validating if the current field's value is less than or equal to the field specified by the param's value. -func isLteField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() <= currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() <= currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() <= currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.Before(t) || fieldTime.Equal(t) - } - } - - // default reflect.String - return len(field.String()) <= len(currentField.String()) -} - -// IsLtField is the validation function for validating if the current field's value is less than the field specified by the param's value. -func isLtField(fl FieldLevel) bool { - - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() < currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() < currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() < currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - - if fieldType == timeType { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return fieldTime.Before(t) - } - } - - // default reflect.String - return len(field.String()) < len(currentField.String()) -} - -// IsLte is the validation function for validating if the current field's value is less than or equal to the param's value. -func isLte(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) <= p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) <= p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() <= p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() <= p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() <= p - - case reflect.Struct: - - if field.Type() == timeType { - - now := time.Now().UTC() - t := field.Interface().(time.Time) - - return t.Before(now) || t.Equal(now) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// IsLt is the validation function for validating if the current field's value is less than the param's value. -func isLt(fl FieldLevel) bool { - - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) < p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) < p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() < p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() < p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() < p - - case reflect.Struct: - - if field.Type() == timeType { - - return field.Interface().(time.Time).Before(time.Now().UTC()) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// HasMaxOf is the validation function for validating if the current field's value is less than or equal to the param's value. -func hasMaxOf(fl FieldLevel) bool { - return isLte(fl) -} - -// IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. -func isTCP4AddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp4", fl.Field().String()) - return err == nil -} - -// IsTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address. -func isTCP6AddrResolvable(fl FieldLevel) bool { - - if !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp6", fl.Field().String()) - - return err == nil -} - -// IsTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address. -func isTCPAddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) && !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp", fl.Field().String()) - - return err == nil -} - -// IsUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address. -func isUDP4AddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp4", fl.Field().String()) - - return err == nil -} - -// IsUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address. -func isUDP6AddrResolvable(fl FieldLevel) bool { - - if !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp6", fl.Field().String()) - - return err == nil -} - -// IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. -func isUDPAddrResolvable(fl FieldLevel) bool { - - if !isIP4Addr(fl) && !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp", fl.Field().String()) - - return err == nil -} - -// IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. -func isIP4AddrResolvable(fl FieldLevel) bool { - - if !isIPv4(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip4", fl.Field().String()) - - return err == nil -} - -// IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. -func isIP6AddrResolvable(fl FieldLevel) bool { - - if !isIPv6(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip6", fl.Field().String()) - - return err == nil -} - -// IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. -func isIPAddrResolvable(fl FieldLevel) bool { - - if !isIP(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip", fl.Field().String()) - - return err == nil -} - -// IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. -func isUnixAddrResolvable(fl FieldLevel) bool { - - _, err := net.ResolveUnixAddr("unix", fl.Field().String()) - - return err == nil -} - -func isIP4Addr(fl FieldLevel) bool { - - val := fl.Field().String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - val = val[0:idx] - } - - ip := net.ParseIP(val) - - return ip != nil && ip.To4() != nil -} - -func isIP6Addr(fl FieldLevel) bool { - - val := fl.Field().String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - if idx != 0 && val[idx-1:idx] == "]" { - val = val[1 : idx-1] - } - } - - ip := net.ParseIP(val) - - return ip != nil && ip.To4() == nil -} - -func isHostnameRFC952(fl FieldLevel) bool { - return hostnameRegexRFC952.MatchString(fl.Field().String()) -} - -func isHostnameRFC1123(fl FieldLevel) bool { - return hostnameRegexRFC1123.MatchString(fl.Field().String()) -} - -func isFQDN(fl FieldLevel) bool { - val := fl.Field().String() - - if val == "" { - return false - } - - return fqdnRegexRFC1123.MatchString(val) -} - -// IsDir is the validation function for validating if the current field's value is a valid directory. -func isDir(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - fileInfo, err := os.Stat(field.String()) - if err != nil { - return false - } - - return fileInfo.IsDir() - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isJSON is the validation function for validating if the current field's value is a valid json string. -func isJSON(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - val := field.String() - return json.Valid([]byte(val)) - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isHostnamePort validates a : combination for fields typically used for socket address. -func isHostnamePort(fl FieldLevel) bool { - val := fl.Field().String() - host, port, err := net.SplitHostPort(val) - if err != nil { - return false - } - // Port must be a iny <= 65535. - if portNum, err := strconv.ParseInt(port, 10, 32); err != nil || portNum > 65535 || portNum < 1 { - return false - } - - // If host is specified, it should match a DNS name - if host != "" { - return hostnameRegexRFC1123.MatchString(host) - } - return true -} - -// isLowercase is the validation function for validating if the current field's value is a lowercase string. -func isLowercase(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - if field.String() == "" { - return false - } - return field.String() == strings.ToLower(field.String()) - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isUppercase is the validation function for validating if the current field's value is an uppercase string. -func isUppercase(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - if field.String() == "" { - return false - } - return field.String() == strings.ToUpper(field.String()) - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isDatetime is the validation function for validating if the current field's value is a valid datetime string. -func isDatetime(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - if field.Kind() == reflect.String { - _, err := time.Parse(param, field.String()) - - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isTimeZone is the validation function for validating if the current field's value is a valid time zone string. -func isTimeZone(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - // empty value is converted to UTC by time.LoadLocation but disallow it as it is not a valid time zone name - if field.String() == "" { - return false - } - - // Local value is converted to the current system time zone by time.LoadLocation but disallow it as it is not a valid time zone name - if strings.ToLower(field.String()) == "local" { - return false - } - - _, err := time.LoadLocation(field.String()) - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-2 country code. -func isIso3166Alpha2(fl FieldLevel) bool { - val := fl.Field().String() - return iso3166_1_alpha2[val] -} - -// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-3 country code. -func isIso3166Alpha3(fl FieldLevel) bool { - val := fl.Field().String() - return iso3166_1_alpha3[val] -} - -// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-numeric country code. -func isIso3166AlphaNumeric(fl FieldLevel) bool { - field := fl.Field() - - var code int - switch field.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - code = int(field.Int() % 1000) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - code = int(field.Uint() % 1000) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - return iso3166_1_alpha_numeric[code] -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/cache.go b/taskman-server/vendor/github.com/go-playground/validator/v10/cache.go deleted file mode 100644 index 0d18d6ec..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/cache.go +++ /dev/null @@ -1,322 +0,0 @@ -package validator - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type tagType uint8 - -const ( - typeDefault tagType = iota - typeOmitEmpty - typeIsDefault - typeNoStructLevel - typeStructOnly - typeDive - typeOr - typeKeys - typeEndKeys -) - -const ( - invalidValidation = "Invalid validation tag on field '%s'" - undefinedValidation = "Undefined validation function '%s' on field '%s'" - keysTagNotDefined = "'" + endKeysTag + "' tag encountered without a corresponding '" + keysTag + "' tag" -) - -type structCache struct { - lock sync.Mutex - m atomic.Value // map[reflect.Type]*cStruct -} - -func (sc *structCache) Get(key reflect.Type) (c *cStruct, found bool) { - c, found = sc.m.Load().(map[reflect.Type]*cStruct)[key] - return -} - -func (sc *structCache) Set(key reflect.Type, value *cStruct) { - m := sc.m.Load().(map[reflect.Type]*cStruct) - nm := make(map[reflect.Type]*cStruct, len(m)+1) - for k, v := range m { - nm[k] = v - } - nm[key] = value - sc.m.Store(nm) -} - -type tagCache struct { - lock sync.Mutex - m atomic.Value // map[string]*cTag -} - -func (tc *tagCache) Get(key string) (c *cTag, found bool) { - c, found = tc.m.Load().(map[string]*cTag)[key] - return -} - -func (tc *tagCache) Set(key string, value *cTag) { - m := tc.m.Load().(map[string]*cTag) - nm := make(map[string]*cTag, len(m)+1) - for k, v := range m { - nm[k] = v - } - nm[key] = value - tc.m.Store(nm) -} - -type cStruct struct { - name string - fields []*cField - fn StructLevelFuncCtx -} - -type cField struct { - idx int - name string - altName string - namesEqual bool - cTags *cTag -} - -type cTag struct { - tag string - aliasTag string - actualAliasTag string - param string - keys *cTag // only populated when using tag's 'keys' and 'endkeys' for map key validation - next *cTag - fn FuncCtx - typeof tagType - hasTag bool - hasAlias bool - hasParam bool // true if parameter used eg. eq= where the equal sign has been set - isBlockEnd bool // indicates the current tag represents the last validation in the block - runValidationWhenNil bool -} - -func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStruct { - v.structCache.lock.Lock() - defer v.structCache.lock.Unlock() // leave as defer! because if inner panics, it will never get unlocked otherwise! - - typ := current.Type() - - // could have been multiple trying to access, but once first is done this ensures struct - // isn't parsed again. - cs, ok := v.structCache.Get(typ) - if ok { - return cs - } - - cs = &cStruct{name: sName, fields: make([]*cField, 0), fn: v.structLevelFuncs[typ]} - - numFields := current.NumField() - - var ctag *cTag - var fld reflect.StructField - var tag string - var customName string - - for i := 0; i < numFields; i++ { - - fld = typ.Field(i) - - if !fld.Anonymous && len(fld.PkgPath) > 0 { - continue - } - - tag = fld.Tag.Get(v.tagName) - - if tag == skipValidationTag { - continue - } - - customName = fld.Name - - if v.hasTagNameFunc { - name := v.tagNameFunc(fld) - if len(name) > 0 { - customName = name - } - } - - // NOTE: cannot use shared tag cache, because tags may be equal, but things like alias may be different - // and so only struct level caching can be used instead of combined with Field tag caching - - if len(tag) > 0 { - ctag, _ = v.parseFieldTagsRecursive(tag, fld.Name, "", false) - } else { - // even if field doesn't have validations need cTag for traversing to potential inner/nested - // elements of the field. - ctag = new(cTag) - } - - cs.fields = append(cs.fields, &cField{ - idx: i, - name: fld.Name, - altName: customName, - cTags: ctag, - namesEqual: fld.Name == customName, - }) - } - v.structCache.Set(typ, cs) - return cs -} - -func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias string, hasAlias bool) (firstCtag *cTag, current *cTag) { - var t string - noAlias := len(alias) == 0 - tags := strings.Split(tag, tagSeparator) - - for i := 0; i < len(tags); i++ { - t = tags[i] - if noAlias { - alias = t - } - - // check map for alias and process new tags, otherwise process as usual - if tagsVal, found := v.aliases[t]; found { - if i == 0 { - firstCtag, current = v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) - } else { - next, curr := v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) - current.next, current = next, curr - - } - continue - } - - var prevTag tagType - - if i == 0 { - current = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true, typeof: typeDefault} - firstCtag = current - } else { - prevTag = current.typeof - current.next = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} - current = current.next - } - - switch t { - case diveTag: - current.typeof = typeDive - continue - - case keysTag: - current.typeof = typeKeys - - if i == 0 || prevTag != typeDive { - panic(fmt.Sprintf("'%s' tag must be immediately preceded by the '%s' tag", keysTag, diveTag)) - } - - current.typeof = typeKeys - - // need to pass along only keys tag - // need to increment i to skip over the keys tags - b := make([]byte, 0, 64) - - i++ - - for ; i < len(tags); i++ { - - b = append(b, tags[i]...) - b = append(b, ',') - - if tags[i] == endKeysTag { - break - } - } - - current.keys, _ = v.parseFieldTagsRecursive(string(b[:len(b)-1]), fieldName, "", false) - continue - - case endKeysTag: - current.typeof = typeEndKeys - - // if there are more in tags then there was no keysTag defined - // and an error should be thrown - if i != len(tags)-1 { - panic(keysTagNotDefined) - } - return - - case omitempty: - current.typeof = typeOmitEmpty - continue - - case structOnlyTag: - current.typeof = typeStructOnly - continue - - case noStructLevelTag: - current.typeof = typeNoStructLevel - continue - - default: - if t == isdefault { - current.typeof = typeIsDefault - } - // if a pipe character is needed within the param you must use the utf8Pipe representation "0x7C" - orVals := strings.Split(t, orSeparator) - - for j := 0; j < len(orVals); j++ { - vals := strings.SplitN(orVals[j], tagKeySeparator, 2) - if noAlias { - alias = vals[0] - current.aliasTag = alias - } else { - current.actualAliasTag = t - } - - if j > 0 { - current.next = &cTag{aliasTag: alias, actualAliasTag: current.actualAliasTag, hasAlias: hasAlias, hasTag: true} - current = current.next - } - current.hasParam = len(vals) > 1 - - current.tag = vals[0] - if len(current.tag) == 0 { - panic(strings.TrimSpace(fmt.Sprintf(invalidValidation, fieldName))) - } - - if wrapper, ok := v.validations[current.tag]; ok { - current.fn = wrapper.fn - current.runValidationWhenNil = wrapper.runValidatinOnNil - } else { - panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, current.tag, fieldName))) - } - - if len(orVals) > 1 { - current.typeof = typeOr - } - - if len(vals) > 1 { - current.param = strings.Replace(strings.Replace(vals[1], utf8HexComma, ",", -1), utf8Pipe, "|", -1) - } - } - current.isBlockEnd = true - } - } - return -} - -func (v *Validate) fetchCacheTag(tag string) *cTag { - // find cached tag - ctag, found := v.tagCache.Get(tag) - if !found { - v.tagCache.lock.Lock() - defer v.tagCache.lock.Unlock() - - // could have been multiple trying to access, but once first is done this ensures tag - // isn't parsed again. - ctag, found = v.tagCache.Get(tag) - if !found { - ctag, _ = v.parseFieldTagsRecursive(tag, "", "", false) - v.tagCache.Set(tag, ctag) - } - } - return ctag -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/country_codes.go b/taskman-server/vendor/github.com/go-playground/validator/v10/country_codes.go deleted file mode 100644 index ef81eada..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/country_codes.go +++ /dev/null @@ -1,162 +0,0 @@ -package validator - -var iso3166_1_alpha2 = map[string]bool{ - // see: https://www.iso.org/iso-3166-country-codes.html - "AF": true, "AX": true, "AL": true, "DZ": true, "AS": true, - "AD": true, "AO": true, "AI": true, "AQ": true, "AG": true, - "AR": true, "AM": true, "AW": true, "AU": true, "AT": true, - "AZ": true, "BS": true, "BH": true, "BD": true, "BB": true, - "BY": true, "BE": true, "BZ": true, "BJ": true, "BM": true, - "BT": true, "BO": true, "BQ": true, "BA": true, "BW": true, - "BV": true, "BR": true, "IO": true, "BN": true, "BG": true, - "BF": true, "BI": true, "KH": true, "CM": true, "CA": true, - "CV": true, "KY": true, "CF": true, "TD": true, "CL": true, - "CN": true, "CX": true, "CC": true, "CO": true, "KM": true, - "CG": true, "CD": true, "CK": true, "CR": true, "CI": true, - "HR": true, "CU": true, "CW": true, "CY": true, "CZ": true, - "DK": true, "DJ": true, "DM": true, "DO": true, "EC": true, - "EG": true, "SV": true, "GQ": true, "ER": true, "EE": true, - "ET": true, "FK": true, "FO": true, "FJ": true, "FI": true, - "FR": true, "GF": true, "PF": true, "TF": true, "GA": true, - "GM": true, "GE": true, "DE": true, "GH": true, "GI": true, - "GR": true, "GL": true, "GD": true, "GP": true, "GU": true, - "GT": true, "GG": true, "GN": true, "GW": true, "GY": true, - "HT": true, "HM": true, "VA": true, "HN": true, "HK": true, - "HU": true, "IS": true, "IN": true, "ID": true, "IR": true, - "IQ": true, "IE": true, "IM": true, "IL": true, "IT": true, - "JM": true, "JP": true, "JE": true, "JO": true, "KZ": true, - "KE": true, "KI": true, "KP": true, "KR": true, "KW": true, - "KG": true, "LA": true, "LV": true, "LB": true, "LS": true, - "LR": true, "LY": true, "LI": true, "LT": true, "LU": true, - "MO": true, "MK": true, "MG": true, "MW": true, "MY": true, - "MV": true, "ML": true, "MT": true, "MH": true, "MQ": true, - "MR": true, "MU": true, "YT": true, "MX": true, "FM": true, - "MD": true, "MC": true, "MN": true, "ME": true, "MS": true, - "MA": true, "MZ": true, "MM": true, "NA": true, "NR": true, - "NP": true, "NL": true, "NC": true, "NZ": true, "NI": true, - "NE": true, "NG": true, "NU": true, "NF": true, "MP": true, - "NO": true, "OM": true, "PK": true, "PW": true, "PS": true, - "PA": true, "PG": true, "PY": true, "PE": true, "PH": true, - "PN": true, "PL": true, "PT": true, "PR": true, "QA": true, - "RE": true, "RO": true, "RU": true, "RW": true, "BL": true, - "SH": true, "KN": true, "LC": true, "MF": true, "PM": true, - "VC": true, "WS": true, "SM": true, "ST": true, "SA": true, - "SN": true, "RS": true, "SC": true, "SL": true, "SG": true, - "SX": true, "SK": true, "SI": true, "SB": true, "SO": true, - "ZA": true, "GS": true, "SS": true, "ES": true, "LK": true, - "SD": true, "SR": true, "SJ": true, "SZ": true, "SE": true, - "CH": true, "SY": true, "TW": true, "TJ": true, "TZ": true, - "TH": true, "TL": true, "TG": true, "TK": true, "TO": true, - "TT": true, "TN": true, "TR": true, "TM": true, "TC": true, - "TV": true, "UG": true, "UA": true, "AE": true, "GB": true, - "US": true, "UM": true, "UY": true, "UZ": true, "VU": true, - "VE": true, "VN": true, "VG": true, "VI": true, "WF": true, - "EH": true, "YE": true, "ZM": true, "ZW": true, -} - -var iso3166_1_alpha3 = map[string]bool{ - // see: https://www.iso.org/iso-3166-country-codes.html - "AFG": true, "ALB": true, "DZA": true, "ASM": true, "AND": true, - "AGO": true, "AIA": true, "ATA": true, "ATG": true, "ARG": true, - "ARM": true, "ABW": true, "AUS": true, "AUT": true, "AZE": true, - "BHS": true, "BHR": true, "BGD": true, "BRB": true, "BLR": true, - "BEL": true, "BLZ": true, "BEN": true, "BMU": true, "BTN": true, - "BOL": true, "BES": true, "BIH": true, "BWA": true, "BVT": true, - "BRA": true, "IOT": true, "BRN": true, "BGR": true, "BFA": true, - "BDI": true, "CPV": true, "KHM": true, "CMR": true, "CAN": true, - "CYM": true, "CAF": true, "TCD": true, "CHL": true, "CHN": true, - "CXR": true, "CCK": true, "COL": true, "COM": true, "COD": true, - "COG": true, "COK": true, "CRI": true, "HRV": true, "CUB": true, - "CUW": true, "CYP": true, "CZE": true, "CIV": true, "DNK": true, - "DJI": true, "DMA": true, "DOM": true, "ECU": true, "EGY": true, - "SLV": true, "GNQ": true, "ERI": true, "EST": true, "SWZ": true, - "ETH": true, "FLK": true, "FRO": true, "FJI": true, "FIN": true, - "FRA": true, "GUF": true, "PYF": true, "ATF": true, "GAB": true, - "GMB": true, "GEO": true, "DEU": true, "GHA": true, "GIB": true, - "GRC": true, "GRL": true, "GRD": true, "GLP": true, "GUM": true, - "GTM": true, "GGY": true, "GIN": true, "GNB": true, "GUY": true, - "HTI": true, "HMD": true, "VAT": true, "HND": true, "HKG": true, - "HUN": true, "ISL": true, "IND": true, "IDN": true, "IRN": true, - "IRQ": true, "IRL": true, "IMN": true, "ISR": true, "ITA": true, - "JAM": true, "JPN": true, "JEY": true, "JOR": true, "KAZ": true, - "KEN": true, "KIR": true, "PRK": true, "KOR": true, "KWT": true, - "KGZ": true, "LAO": true, "LVA": true, "LBN": true, "LSO": true, - "LBR": true, "LBY": true, "LIE": true, "LTU": true, "LUX": true, - "MAC": true, "MDG": true, "MWI": true, "MYS": true, "MDV": true, - "MLI": true, "MLT": true, "MHL": true, "MTQ": true, "MRT": true, - "MUS": true, "MYT": true, "MEX": true, "FSM": true, "MDA": true, - "MCO": true, "MNG": true, "MNE": true, "MSR": true, "MAR": true, - "MOZ": true, "MMR": true, "NAM": true, "NRU": true, "NPL": true, - "NLD": true, "NCL": true, "NZL": true, "NIC": true, "NER": true, - "NGA": true, "NIU": true, "NFK": true, "MKD": true, "MNP": true, - "NOR": true, "OMN": true, "PAK": true, "PLW": true, "PSE": true, - "PAN": true, "PNG": true, "PRY": true, "PER": true, "PHL": true, - "PCN": true, "POL": true, "PRT": true, "PRI": true, "QAT": true, - "ROU": true, "RUS": true, "RWA": true, "REU": true, "BLM": true, - "SHN": true, "KNA": true, "LCA": true, "MAF": true, "SPM": true, - "VCT": true, "WSM": true, "SMR": true, "STP": true, "SAU": true, - "SEN": true, "SRB": true, "SYC": true, "SLE": true, "SGP": true, - "SXM": true, "SVK": true, "SVN": true, "SLB": true, "SOM": true, - "ZAF": true, "SGS": true, "SSD": true, "ESP": true, "LKA": true, - "SDN": true, "SUR": true, "SJM": true, "SWE": true, "CHE": true, - "SYR": true, "TWN": true, "TJK": true, "TZA": true, "THA": true, - "TLS": true, "TGO": true, "TKL": true, "TON": true, "TTO": true, - "TUN": true, "TUR": true, "TKM": true, "TCA": true, "TUV": true, - "UGA": true, "UKR": true, "ARE": true, "GBR": true, "UMI": true, - "USA": true, "URY": true, "UZB": true, "VUT": true, "VEN": true, - "VNM": true, "VGB": true, "VIR": true, "WLF": true, "ESH": true, - "YEM": true, "ZMB": true, "ZWE": true, "ALA": true, -} -var iso3166_1_alpha_numeric = map[int]bool{ - // see: https://www.iso.org/iso-3166-country-codes.html - 4: true, 8: true, 12: true, 16: true, 20: true, - 24: true, 660: true, 10: true, 28: true, 32: true, - 51: true, 533: true, 36: true, 40: true, 31: true, - 44: true, 48: true, 50: true, 52: true, 112: true, - 56: true, 84: true, 204: true, 60: true, 64: true, - 68: true, 535: true, 70: true, 72: true, 74: true, - 76: true, 86: true, 96: true, 100: true, 854: true, - 108: true, 132: true, 116: true, 120: true, 124: true, - 136: true, 140: true, 148: true, 152: true, 156: true, - 162: true, 166: true, 170: true, 174: true, 180: true, - 178: true, 184: true, 188: true, 191: true, 192: true, - 531: true, 196: true, 203: true, 384: true, 208: true, - 262: true, 212: true, 214: true, 218: true, 818: true, - 222: true, 226: true, 232: true, 233: true, 748: true, - 231: true, 238: true, 234: true, 242: true, 246: true, - 250: true, 254: true, 258: true, 260: true, 266: true, - 270: true, 268: true, 276: true, 288: true, 292: true, - 300: true, 304: true, 308: true, 312: true, 316: true, - 320: true, 831: true, 324: true, 624: true, 328: true, - 332: true, 334: true, 336: true, 340: true, 344: true, - 348: true, 352: true, 356: true, 360: true, 364: true, - 368: true, 372: true, 833: true, 376: true, 380: true, - 388: true, 392: true, 832: true, 400: true, 398: true, - 404: true, 296: true, 408: true, 410: true, 414: true, - 417: true, 418: true, 428: true, 422: true, 426: true, - 430: true, 434: true, 438: true, 440: true, 442: true, - 446: true, 450: true, 454: true, 458: true, 462: true, - 466: true, 470: true, 584: true, 474: true, 478: true, - 480: true, 175: true, 484: true, 583: true, 498: true, - 492: true, 496: true, 499: true, 500: true, 504: true, - 508: true, 104: true, 516: true, 520: true, 524: true, - 528: true, 540: true, 554: true, 558: true, 562: true, - 566: true, 570: true, 574: true, 807: true, 580: true, - 578: true, 512: true, 586: true, 585: true, 275: true, - 591: true, 598: true, 600: true, 604: true, 608: true, - 612: true, 616: true, 620: true, 630: true, 634: true, - 642: true, 643: true, 646: true, 638: true, 652: true, - 654: true, 659: true, 662: true, 663: true, 666: true, - 670: true, 882: true, 674: true, 678: true, 682: true, - 686: true, 688: true, 690: true, 694: true, 702: true, - 534: true, 703: true, 705: true, 90: true, 706: true, - 710: true, 239: true, 728: true, 724: true, 144: true, - 729: true, 740: true, 744: true, 752: true, 756: true, - 760: true, 158: true, 762: true, 834: true, 764: true, - 626: true, 768: true, 772: true, 776: true, 780: true, - 788: true, 792: true, 795: true, 796: true, 798: true, - 800: true, 804: true, 784: true, 826: true, 581: true, - 840: true, 858: true, 860: true, 548: true, 862: true, - 704: true, 92: true, 850: true, 876: true, 732: true, - 887: true, 894: true, 716: true, 248: true, -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/doc.go b/taskman-server/vendor/github.com/go-playground/validator/v10/doc.go deleted file mode 100644 index a816c20a..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/doc.go +++ /dev/null @@ -1,1308 +0,0 @@ -/* -Package validator implements value validations for structs and individual fields -based on tags. - -It can also handle Cross-Field and Cross-Struct validation for nested structs -and has the ability to dive into arrays and maps of any type. - -see more examples https://github.com/go-playground/validator/tree/master/_examples - -Validation Functions Return Type error - -Doing things this way is actually the way the standard library does, see the -file.Open method here: - - https://golang.org/pkg/os/#Open. - -The authors return type "error" to avoid the issue discussed in the following, -where err is always != nil: - - http://stackoverflow.com/a/29138676/3158232 - https://github.com/go-playground/validator/issues/134 - -Validator only InvalidValidationError for bad validation input, nil or -ValidationErrors as type error; so, in your code all you need to do is check -if the error returned is not nil, and if it's not check if error is -InvalidValidationError ( if necessary, most of the time it isn't ) type cast -it to type ValidationErrors like so err.(validator.ValidationErrors). - -Custom Validation Functions - -Custom Validation functions can be added. Example: - - // Structure - func customFunc(fl validator.FieldLevel) bool { - - if fl.Field().String() == "invalid" { - return false - } - - return true - } - - validate.RegisterValidation("custom tag name", customFunc) - // NOTES: using the same tag name as an existing function - // will overwrite the existing one - -Cross-Field Validation - -Cross-Field Validation can be done via the following tags: - - eqfield - - nefield - - gtfield - - gtefield - - ltfield - - ltefield - - eqcsfield - - necsfield - - gtcsfield - - gtecsfield - - ltcsfield - - ltecsfield - -If, however, some custom cross-field validation is required, it can be done -using a custom validation. - -Why not just have cross-fields validation tags (i.e. only eqcsfield and not -eqfield)? - -The reason is efficiency. If you want to check a field within the same struct -"eqfield" only has to find the field on the same struct (1 level). But, if we -used "eqcsfield" it could be multiple levels down. Example: - - type Inner struct { - StartDate time.Time - } - - type Outer struct { - InnerStructField *Inner - CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"` - } - - now := time.Now() - - inner := &Inner{ - StartDate: now, - } - - outer := &Outer{ - InnerStructField: inner, - CreatedAt: now, - } - - errs := validate.Struct(outer) - - // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed - // into the function - // when calling validate.VarWithValue(val, field, tag) val will be - // whatever you pass, struct, field... - // when calling validate.Field(field, tag) val will be nil - -Multiple Validators - -Multiple validators on a field will process in the order defined. Example: - - type Test struct { - Field `validate:"max=10,min=1"` - } - - // max will be checked then min - -Bad Validator definitions are not handled by the library. Example: - - type Test struct { - Field `validate:"min=10,max=0"` - } - - // this definition of min max will never succeed - -Using Validator Tags - -Baked In Cross-Field validation only compares fields on the same struct. -If Cross-Field + Cross-Struct validation is needed you should implement your -own custom validator. - -Comma (",") is the default separator of validation tags. If you wish to -have a comma included within the parameter (i.e. excludesall=,) you will need to -use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma, -so the above will become excludesall=0x2C. - - type Test struct { - Field `validate:"excludesall=,"` // BAD! Do not include a comma. - Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation. - } - -Pipe ("|") is the 'or' validation tags deparator. If you wish to -have a pipe included within the parameter i.e. excludesall=| you will need to -use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe, -so the above will become excludesall=0x7C - - type Test struct { - Field `validate:"excludesall=|"` // BAD! Do not include a a pipe! - Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation. - } - - -Baked In Validators and Tags - -Here is a list of the current built in validators: - - -Skip Field - -Tells the validation to skip this struct field; this is particularly -handy in ignoring embedded structs from being validated. (Usage: -) - Usage: - - - -Or Operator - -This is the 'or' operator allowing multiple validators to be used and -accepted. (Usage: rgb|rgba) <-- this would allow either rgb or rgba -colors to be accepted. This can also be combined with 'and' for example -( Usage: omitempty,rgb|rgba) - - Usage: | - -StructOnly - -When a field that is a nested struct is encountered, and contains this flag -any validation on the nested struct will be run, but none of the nested -struct fields will be validated. This is useful if inside of your program -you know the struct will be valid, but need to verify it has been assigned. -NOTE: only "required" and "omitempty" can be used on a struct itself. - - Usage: structonly - -NoStructLevel - -Same as structonly tag except that any struct level validations will not run. - - Usage: nostructlevel - -Omit Empty - -Allows conditional validation, for example if a field is not set with -a value (Determined by the "required" validator) then other validation -such as min or max won't run, but if a value is set validation will run. - - Usage: omitempty - -Dive - -This tells the validator to dive into a slice, array or map and validate that -level of the slice, array or map with the validation tags that follow. -Multidimensional nesting is also supported, each level you wish to dive will -require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see -the Keys & EndKeys section just below. - - Usage: dive - -Example #1 - - [][]string with validation tag "gt=0,dive,len=1,dive,required" - // gt=0 will be applied to [] - // len=1 will be applied to []string - // required will be applied to string - -Example #2 - - [][]string with validation tag "gt=0,dive,dive,required" - // gt=0 will be applied to [] - // []string will be spared validation - // required will be applied to string - -Keys & EndKeys - -These are to be used together directly after the dive tag and tells the validator -that anything between 'keys' and 'endkeys' applies to the keys of a map and not the -values; think of it like the 'dive' tag, but for map keys instead of values. -Multidimensional nesting is also supported, each level you wish to validate will -require another 'keys' and 'endkeys' tag. These tags are only valid for maps. - - Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags - -Example #1 - - map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required" - // gt=0 will be applied to the map itself - // eg=1|eq=2 will be applied to the map keys - // required will be applied to map values - -Example #2 - - map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required" - // gt=0 will be applied to the map itself - // eg=1|eq=2 will be applied to each array element in the the map keys - // required will be applied to map values - -Required - -This validates that the value is not the data types default zero value. -For numbers ensures value is not zero. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required - -Required If - -The field under validation must be present and not empty only if all -the other specified fields are equal to the value following the specified -field. For strings ensures value is not "". For slices, maps, pointers, -interfaces, channels and functions ensures the value is not nil. - - Usage: required_if - -Examples: - - // require the field if the Field1 is equal to the parameter given: - Usage: required_if=Field1 foobar - - // require the field if the Field1 and Field2 is equal to the value respectively: - Usage: required_if=Field1 foo Field2 bar - -Required Unless - -The field under validation must be present and not empty unless all -the other specified fields are equal to the value following the specified -field. For strings ensures value is not "". For slices, maps, pointers, -interfaces, channels and functions ensures the value is not nil. - - Usage: required_unless - -Examples: - - // require the field unless the Field1 is equal to the parameter given: - Usage: required_unless=Field1 foobar - - // require the field unless the Field1 and Field2 is equal to the value respectively: - Usage: required_unless=Field1 foo Field2 bar - -Required With - -The field under validation must be present and not empty only if any -of the other specified fields are present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_with - -Examples: - - // require the field if the Field1 is present: - Usage: required_with=Field1 - - // require the field if the Field1 or Field2 is present: - Usage: required_with=Field1 Field2 - -Required With All - -The field under validation must be present and not empty only if all -of the other specified fields are present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_with_all - -Example: - - // require the field if the Field1 and Field2 is present: - Usage: required_with_all=Field1 Field2 - -Required Without - -The field under validation must be present and not empty only when any -of the other specified fields are not present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_without - -Examples: - - // require the field if the Field1 is not present: - Usage: required_without=Field1 - - // require the field if the Field1 or Field2 is not present: - Usage: required_without=Field1 Field2 - -Required Without All - -The field under validation must be present and not empty only when all -of the other specified fields are not present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_without_all - -Example: - - // require the field if the Field1 and Field2 is not present: - Usage: required_without_all=Field1 Field2 - -Is Default - -This validates that the value is the default value and is almost the -opposite of required. - - Usage: isdefault - -Length - -For numbers, length will ensure that the value is -equal to the parameter given. For strings, it checks that -the string length is exactly that number of characters. For slices, -arrays, and maps, validates the number of items. - -Example #1 - - Usage: len=10 - -Example #2 (time.Duration) - -For time.Duration, len will ensure that the value is equal to the duration given -in the parameter. - - Usage: len=1h30m - -Maximum - -For numbers, max will ensure that the value is -less than or equal to the parameter given. For strings, it checks -that the string length is at most that number of characters. For -slices, arrays, and maps, validates the number of items. - -Example #1 - - Usage: max=10 - -Example #2 (time.Duration) - -For time.Duration, max will ensure that the value is less than or equal to the -duration given in the parameter. - - Usage: max=1h30m - -Minimum - -For numbers, min will ensure that the value is -greater or equal to the parameter given. For strings, it checks that -the string length is at least that number of characters. For slices, -arrays, and maps, validates the number of items. - -Example #1 - - Usage: min=10 - -Example #2 (time.Duration) - -For time.Duration, min will ensure that the value is greater than or equal to -the duration given in the parameter. - - Usage: min=1h30m - -Equals - -For strings & numbers, eq will ensure that the value is -equal to the parameter given. For slices, arrays, and maps, -validates the number of items. - -Example #1 - - Usage: eq=10 - -Example #2 (time.Duration) - -For time.Duration, eq will ensure that the value is equal to the duration given -in the parameter. - - Usage: eq=1h30m - -Not Equal - -For strings & numbers, ne will ensure that the value is not -equal to the parameter given. For slices, arrays, and maps, -validates the number of items. - -Example #1 - - Usage: ne=10 - -Example #2 (time.Duration) - -For time.Duration, ne will ensure that the value is not equal to the duration -given in the parameter. - - Usage: ne=1h30m - -One Of - -For strings, ints, and uints, oneof will ensure that the value -is one of the values in the parameter. The parameter should be -a list of values separated by whitespace. Values may be -strings or numbers. To match strings with spaces in them, include -the target string between single quotes. - - Usage: oneof=red green - oneof='red green' 'blue yellow' - oneof=5 7 9 - -Greater Than - -For numbers, this will ensure that the value is greater than the -parameter given. For strings, it checks that the string length -is greater than that number of characters. For slices, arrays -and maps it validates the number of items. - -Example #1 - - Usage: gt=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is greater than time.Now.UTC(). - - Usage: gt - -Example #3 (time.Duration) - -For time.Duration, gt will ensure that the value is greater than the duration -given in the parameter. - - Usage: gt=1h30m - -Greater Than or Equal - -Same as 'min' above. Kept both to make terminology with 'len' easier. - -Example #1 - - Usage: gte=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is greater than or equal to time.Now.UTC(). - - Usage: gte - -Example #3 (time.Duration) - -For time.Duration, gte will ensure that the value is greater than or equal to -the duration given in the parameter. - - Usage: gte=1h30m - -Less Than - -For numbers, this will ensure that the value is less than the parameter given. -For strings, it checks that the string length is less than that number of -characters. For slices, arrays, and maps it validates the number of items. - -Example #1 - - Usage: lt=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is less than time.Now.UTC(). - - Usage: lt - -Example #3 (time.Duration) - -For time.Duration, lt will ensure that the value is less than the duration given -in the parameter. - - Usage: lt=1h30m - -Less Than or Equal - -Same as 'max' above. Kept both to make terminology with 'len' easier. - -Example #1 - - Usage: lte=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is less than or equal to time.Now.UTC(). - - Usage: lte - -Example #3 (time.Duration) - -For time.Duration, lte will ensure that the value is less than or equal to the -duration given in the parameter. - - Usage: lte=1h30m - -Field Equals Another Field - -This will validate the field value against another fields value either within -a struct or passed in field. - -Example #1: - - // Validation on Password field using: - Usage: eqfield=ConfirmPassword - -Example #2: - - // Validating by field: - validate.VarWithValue(password, confirmpassword, "eqfield") - -Field Equals Another Field (relative) - -This does the same as eqfield except that it validates the field provided relative -to the top level struct. - - Usage: eqcsfield=InnerStructField.Field) - -Field Does Not Equal Another Field - -This will validate the field value against another fields value either within -a struct or passed in field. - -Examples: - - // Confirm two colors are not the same: - // - // Validation on Color field: - Usage: nefield=Color2 - - // Validating by field: - validate.VarWithValue(color1, color2, "nefield") - -Field Does Not Equal Another Field (relative) - -This does the same as nefield except that it validates the field provided -relative to the top level struct. - - Usage: necsfield=InnerStructField.Field - -Field Greater Than Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(gtfield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "gtfield") - -Field Greater Than Another Relative Field - -This does the same as gtfield except that it validates the field provided -relative to the top level struct. - - Usage: gtcsfield=InnerStructField.Field - -Field Greater Than or Equal To Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(gtefield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "gtefield") - -Field Greater Than or Equal To Another Relative Field - -This does the same as gtefield except that it validates the field provided relative -to the top level struct. - - Usage: gtecsfield=InnerStructField.Field - -Less Than Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(ltfield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "ltfield") - -Less Than Another Relative Field - -This does the same as ltfield except that it validates the field provided relative -to the top level struct. - - Usage: ltcsfield=InnerStructField.Field - -Less Than or Equal To Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(ltefield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "ltefield") - -Less Than or Equal To Another Relative Field - -This does the same as ltefield except that it validates the field provided relative -to the top level struct. - - Usage: ltecsfield=InnerStructField.Field - -Field Contains Another Field - -This does the same as contains except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. - - Usage: containsfield=InnerStructField.Field - -Field Excludes Another Field - -This does the same as excludes except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. - - Usage: excludesfield=InnerStructField.Field - -Unique - -For arrays & slices, unique will ensure that there are no duplicates. -For maps, unique will ensure that there are no duplicate values. -For slices of struct, unique will ensure that there are no duplicate values -in a field of the struct specified via a parameter. - - // For arrays, slices, and maps: - Usage: unique - - // For slices of struct: - Usage: unique=field - -Alpha Only - -This validates that a string value contains ASCII alpha characters only - - Usage: alpha - -Alphanumeric - -This validates that a string value contains ASCII alphanumeric characters only - - Usage: alphanum - -Alpha Unicode - -This validates that a string value contains unicode alpha characters only - - Usage: alphaunicode - -Alphanumeric Unicode - -This validates that a string value contains unicode alphanumeric characters only - - Usage: alphanumunicode - -Number - -This validates that a string value contains number values only. -For integers or float it returns true. - - Usage: number - -Numeric - -This validates that a string value contains a basic numeric value. -basic excludes exponents etc... -for integers or float it returns true. - - Usage: numeric - -Hexadecimal String - -This validates that a string value contains a valid hexadecimal. - - Usage: hexadecimal - -Hexcolor String - -This validates that a string value contains a valid hex color including -hashtag (#) - - Usage: hexcolor - -Lowercase String - -This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string. - - Usage: lowercase - -Uppercase String - -This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string. - - Usage: uppercase - -RGB String - -This validates that a string value contains a valid rgb color - - Usage: rgb - -RGBA String - -This validates that a string value contains a valid rgba color - - Usage: rgba - -HSL String - -This validates that a string value contains a valid hsl color - - Usage: hsl - -HSLA String - -This validates that a string value contains a valid hsla color - - Usage: hsla - -E.164 Phone Number String - -This validates that a string value contains a valid E.164 Phone number -https://en.wikipedia.org/wiki/E.164 (ex. +1123456789) - - Usage: e164 - -E-mail String - -This validates that a string value contains a valid email -This may not conform to all possibilities of any rfc standard, but neither -does any email provider accept all possibilities. - - Usage: email - -JSON String - -This validates that a string value is valid JSON - - Usage: json - -File path - -This validates that a string value contains a valid file path and that -the file exists on the machine. -This is done using os.Stat, which is a platform independent function. - - Usage: file - -URL String - -This validates that a string value contains a valid url -This will accept any url the golang request uri accepts but must contain -a schema for example http:// or rtmp:// - - Usage: url - -URI String - -This validates that a string value contains a valid uri -This will accept any uri the golang request uri accepts - - Usage: uri - -Urn RFC 2141 String - -This validataes that a string value contains a valid URN -according to the RFC 2141 spec. - - Usage: urn_rfc2141 - -Base64 String - -This validates that a string value contains a valid base64 value. -Although an empty string is valid base64 this will report an empty string -as an error, if you wish to accept an empty string as valid you can use -this with the omitempty tag. - - Usage: base64 - -Base64URL String - -This validates that a string value contains a valid base64 URL safe value -according the the RFC4648 spec. -Although an empty string is a valid base64 URL safe value, this will report -an empty string as an error, if you wish to accept an empty string as valid -you can use this with the omitempty tag. - - Usage: base64url - -Bitcoin Address - -This validates that a string value contains a valid bitcoin address. -The format of the string is checked to ensure it matches one of the three formats -P2PKH, P2SH and performs checksum validation. - - Usage: btc_addr - -Bitcoin Bech32 Address (segwit) - -This validates that a string value contains a valid bitcoin Bech32 address as defined -by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) -Special thanks to Pieter Wuille for providng reference implementations. - - Usage: btc_addr_bech32 - -Ethereum Address - -This validates that a string value contains a valid ethereum address. -The format of the string is checked to ensure it matches the standard Ethereum address format. - - Usage: eth_addr - -Contains - -This validates that a string value contains the substring value. - - Usage: contains=@ - -Contains Any - -This validates that a string value contains any Unicode code points -in the substring value. - - Usage: containsany=!@#? - -Contains Rune - -This validates that a string value contains the supplied rune value. - - Usage: containsrune=@ - -Excludes - -This validates that a string value does not contain the substring value. - - Usage: excludes=@ - -Excludes All - -This validates that a string value does not contain any Unicode code -points in the substring value. - - Usage: excludesall=!@#? - -Excludes Rune - -This validates that a string value does not contain the supplied rune value. - - Usage: excludesrune=@ - -Starts With - -This validates that a string value starts with the supplied string value - - Usage: startswith=hello - -Ends With - -This validates that a string value ends with the supplied string value - - Usage: endswith=goodbye - -Does Not Start With - -This validates that a string value does not start with the supplied string value - - Usage: startsnotwith=hello - -Does Not End With - -This validates that a string value does not end with the supplied string value - - Usage: endsnotwith=goodbye - -International Standard Book Number - -This validates that a string value contains a valid isbn10 or isbn13 value. - - Usage: isbn - -International Standard Book Number 10 - -This validates that a string value contains a valid isbn10 value. - - Usage: isbn10 - -International Standard Book Number 13 - -This validates that a string value contains a valid isbn13 value. - - Usage: isbn13 - -Universally Unique Identifier UUID - -This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead. - - Usage: uuid - -Universally Unique Identifier UUID v3 - -This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead. - - Usage: uuid3 - -Universally Unique Identifier UUID v4 - -This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead. - - Usage: uuid4 - -Universally Unique Identifier UUID v5 - -This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead. - - Usage: uuid5 - -ASCII - -This validates that a string value contains only ASCII characters. -NOTE: if the string is blank, this validates as true. - - Usage: ascii - -Printable ASCII - -This validates that a string value contains only printable ASCII characters. -NOTE: if the string is blank, this validates as true. - - Usage: printascii - -Multi-Byte Characters - -This validates that a string value contains one or more multibyte characters. -NOTE: if the string is blank, this validates as true. - - Usage: multibyte - -Data URL - -This validates that a string value contains a valid DataURI. -NOTE: this will also validate that the data portion is valid base64 - - Usage: datauri - -Latitude - -This validates that a string value contains a valid latitude. - - Usage: latitude - -Longitude - -This validates that a string value contains a valid longitude. - - Usage: longitude - -Social Security Number SSN - -This validates that a string value contains a valid U.S. Social Security Number. - - Usage: ssn - -Internet Protocol Address IP - -This validates that a string value contains a valid IP Address. - - Usage: ip - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid v4 IP Address. - - Usage: ipv4 - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid v6 IP Address. - - Usage: ipv6 - -Classless Inter-Domain Routing CIDR - -This validates that a string value contains a valid CIDR Address. - - Usage: cidr - -Classless Inter-Domain Routing CIDRv4 - -This validates that a string value contains a valid v4 CIDR Address. - - Usage: cidrv4 - -Classless Inter-Domain Routing CIDRv6 - -This validates that a string value contains a valid v6 CIDR Address. - - Usage: cidrv6 - -Transmission Control Protocol Address TCP - -This validates that a string value contains a valid resolvable TCP Address. - - Usage: tcp_addr - -Transmission Control Protocol Address TCPv4 - -This validates that a string value contains a valid resolvable v4 TCP Address. - - Usage: tcp4_addr - -Transmission Control Protocol Address TCPv6 - -This validates that a string value contains a valid resolvable v6 TCP Address. - - Usage: tcp6_addr - -User Datagram Protocol Address UDP - -This validates that a string value contains a valid resolvable UDP Address. - - Usage: udp_addr - -User Datagram Protocol Address UDPv4 - -This validates that a string value contains a valid resolvable v4 UDP Address. - - Usage: udp4_addr - -User Datagram Protocol Address UDPv6 - -This validates that a string value contains a valid resolvable v6 UDP Address. - - Usage: udp6_addr - -Internet Protocol Address IP - -This validates that a string value contains a valid resolvable IP Address. - - Usage: ip_addr - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid resolvable v4 IP Address. - - Usage: ip4_addr - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid resolvable v6 IP Address. - - Usage: ip6_addr - -Unix domain socket end point Address - -This validates that a string value contains a valid Unix Address. - - Usage: unix_addr - -Media Access Control Address MAC - -This validates that a string value contains a valid MAC Address. - - Usage: mac - -Note: See Go's ParseMAC for accepted formats and types: - - http://golang.org/src/net/mac.go?s=866:918#L29 - -Hostname RFC 952 - -This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952 - - Usage: hostname - -Hostname RFC 1123 - -This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123 - - Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias. - -Full Qualified Domain Name (FQDN) - -This validates that a string value contains a valid FQDN. - - Usage: fqdn - -HTML Tags - -This validates that a string value appears to be an HTML element tag -including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element - - Usage: html - -HTML Encoded - -This validates that a string value is a proper character reference in decimal -or hexadecimal format - - Usage: html_encoded - -URL Encoded - -This validates that a string value is percent-encoded (URL encoded) according -to https://tools.ietf.org/html/rfc3986#section-2.1 - - Usage: url_encoded - -Directory - -This validates that a string value contains a valid directory and that -it exists on the machine. -This is done using os.Stat, which is a platform independent function. - - Usage: dir - -HostPort - -This validates that a string value contains a valid DNS hostname and port that -can be used to valiate fields typically passed to sockets and connections. - - Usage: hostname_port - -Datetime - -This validates that a string value is a valid datetime based on the supplied datetime format. -Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/ - - Usage: datetime=2006-01-02 - -Iso3166-1 alpha-2 - -This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard. -see: https://www.iso.org/iso-3166-country-codes.html - - Usage: iso3166_1_alpha2 - -Iso3166-1 alpha-3 - -This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard. -see: https://www.iso.org/iso-3166-country-codes.html - - Usage: iso3166_1_alpha3 - -Iso3166-1 alpha-numeric - -This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard. -see: https://www.iso.org/iso-3166-country-codes.html - - Usage: iso3166_1_alpha3 - -TimeZone - -This validates that a string value is a valid time zone based on the time zone database present on the system. -Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator. -More information on https://golang.org/pkg/time/#LoadLocation - - Usage: timezone - - -Alias Validators and Tags - -NOTE: When returning an error, the tag returned in "FieldError" will be -the alias tag unless the dive tag is part of the alias. Everything after the -dive tag is not reported as the alias tag. Also, the "ActualTag" in the before -case will be the actual tag within the alias that failed. - -Here is a list of the current built in alias tags: - - "iscolor" - alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor) - "country_code" - alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code) - -Validator notes: - - regex - a regex validator won't be added because commas and = signs can be part - of a regex which conflict with the validation definitions. Although - workarounds can be made, they take away from using pure regex's. - Furthermore it's quick and dirty but the regex's become harder to - maintain and are not reusable, so it's as much a programming philosophy - as anything. - - In place of this new validator functions should be created; a regex can - be used within the validator function and even be precompiled for better - efficiency within regexes.go. - - And the best reason, you can submit a pull request and we can keep on - adding to the validation library of this package! - -Non standard validators - -A collection of validation rules that are frequently needed but are more -complex than the ones found in the baked in validators. -A non standard validator must be registered manually like you would -with your own custom validation functions. - -Example of registration and use: - - type Test struct { - TestField string `validate:"yourtag"` - } - - t := &Test{ - TestField: "Test" - } - - validate := validator.New() - validate.RegisterValidation("yourtag", validators.NotBlank) - -Here is a list of the current non standard validators: - - NotBlank - This validates that the value is not blank or with length zero. - For strings ensures they do not contain only spaces. For channels, maps, slices and arrays - ensures they don't have zero length. For others, a non empty value is required. - - Usage: notblank - -Panics - -This package panics when bad input is provided, this is by design, bad code like -that should not make it to production. - - type Test struct { - TestField string `validate:"nonexistantfunction=1"` - } - - t := &Test{ - TestField: "Test" - } - - validate.Struct(t) // this will panic -*/ -package validator diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/errors.go b/taskman-server/vendor/github.com/go-playground/validator/v10/errors.go deleted file mode 100644 index 63293cf9..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/errors.go +++ /dev/null @@ -1,275 +0,0 @@ -package validator - -import ( - "bytes" - "fmt" - "reflect" - "strings" - - ut "github.com/go-playground/universal-translator" -) - -const ( - fieldErrMsg = "Key: '%s' Error:Field validation for '%s' failed on the '%s' tag" -) - -// ValidationErrorsTranslations is the translation return type -type ValidationErrorsTranslations map[string]string - -// InvalidValidationError describes an invalid argument passed to -// `Struct`, `StructExcept`, StructPartial` or `Field` -type InvalidValidationError struct { - Type reflect.Type -} - -// Error returns InvalidValidationError message -func (e *InvalidValidationError) Error() string { - - if e.Type == nil { - return "validator: (nil)" - } - - return "validator: (nil " + e.Type.String() + ")" -} - -// ValidationErrors is an array of FieldError's -// for use in custom error messages post validation. -type ValidationErrors []FieldError - -// Error is intended for use in development + debugging and not intended to be a production error message. -// It allows ValidationErrors to subscribe to the Error interface. -// All information to create an error message specific to your application is contained within -// the FieldError found within the ValidationErrors array -func (ve ValidationErrors) Error() string { - - buff := bytes.NewBufferString("") - - var fe *fieldError - - for i := 0; i < len(ve); i++ { - - fe = ve[i].(*fieldError) - buff.WriteString(fe.Error()) - buff.WriteString("\n") - } - - return strings.TrimSpace(buff.String()) -} - -// Translate translates all of the ValidationErrors -func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { - - trans := make(ValidationErrorsTranslations) - - var fe *fieldError - - for i := 0; i < len(ve); i++ { - fe = ve[i].(*fieldError) - - // // in case an Anonymous struct was used, ensure that the key - // // would be 'Username' instead of ".Username" - // if len(fe.ns) > 0 && fe.ns[:1] == "." { - // trans[fe.ns[1:]] = fe.Translate(ut) - // continue - // } - - trans[fe.ns] = fe.Translate(ut) - } - - return trans -} - -// FieldError contains all functions to get error details -type FieldError interface { - - // returns the validation tag that failed. if the - // validation was an alias, this will return the - // alias name and not the underlying tag that failed. - // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" - // will return "iscolor" - Tag() string - - // returns the validation tag that failed, even if an - // alias the actual tag within the alias will be returned. - // If an 'or' validation fails the entire or will be returned. - // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" - // will return "hexcolor|rgb|rgba|hsl|hsla" - ActualTag() string - - // returns the namespace for the field error, with the tag - // name taking precedence over the field's actual name. - // - // eg. JSON name "User.fname" - // - // See StructNamespace() for a version that returns actual names. - // - // NOTE: this field can be blank when validating a single primitive field - // using validate.Field(...) as there is no way to extract it's name - Namespace() string - - // returns the namespace for the field error, with the field's - // actual name. - // - // eq. "User.FirstName" see Namespace for comparison - // - // NOTE: this field can be blank when validating a single primitive field - // using validate.Field(...) as there is no way to extract its name - StructNamespace() string - - // returns the fields name with the tag name taking precedence over the - // field's actual name. - // - // eq. JSON name "fname" - // see StructField for comparison - Field() string - - // returns the field's actual name from the struct, when able to determine. - // - // eq. "FirstName" - // see Field for comparison - StructField() string - - // returns the actual field's value in case needed for creating the error - // message - Value() interface{} - - // returns the param value, in string form for comparison; this will also - // help with generating an error message - Param() string - - // Kind returns the Field's reflect Kind - // - // eg. time.Time's kind is a struct - Kind() reflect.Kind - - // Type returns the Field's reflect Type - // - // // eg. time.Time's type is time.Time - Type() reflect.Type - - // returns the FieldError's translated error - // from the provided 'ut.Translator' and registered 'TranslationFunc' - // - // NOTE: if no registered translator can be found it returns the same as - // calling fe.Error() - Translate(ut ut.Translator) string - - // Error returns the FieldError's message - Error() string -} - -// compile time interface checks -var _ FieldError = new(fieldError) -var _ error = new(fieldError) - -// fieldError contains a single field's validation error along -// with other properties that may be needed for error message creation -// it complies with the FieldError interface -type fieldError struct { - v *Validate - tag string - actualTag string - ns string - structNs string - fieldLen uint8 - structfieldLen uint8 - value interface{} - param string - kind reflect.Kind - typ reflect.Type -} - -// Tag returns the validation tag that failed. -func (fe *fieldError) Tag() string { - return fe.tag -} - -// ActualTag returns the validation tag that failed, even if an -// alias the actual tag within the alias will be returned. -func (fe *fieldError) ActualTag() string { - return fe.actualTag -} - -// Namespace returns the namespace for the field error, with the tag -// name taking precedence over the field's actual name. -func (fe *fieldError) Namespace() string { - return fe.ns -} - -// StructNamespace returns the namespace for the field error, with the field's -// actual name. -func (fe *fieldError) StructNamespace() string { - return fe.structNs -} - -// Field returns the field's name with the tag name taking precedence over the -// field's actual name. -func (fe *fieldError) Field() string { - - return fe.ns[len(fe.ns)-int(fe.fieldLen):] - // // return fe.field - // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] - - // log.Println("FLD:", fld) - - // if len(fld) > 0 && fld[:1] == "." { - // return fld[1:] - // } - - // return fld -} - -// returns the field's actual name from the struct, when able to determine. -func (fe *fieldError) StructField() string { - // return fe.structField - return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):] -} - -// Value returns the actual field's value in case needed for creating the error -// message -func (fe *fieldError) Value() interface{} { - return fe.value -} - -// Param returns the param value, in string form for comparison; this will -// also help with generating an error message -func (fe *fieldError) Param() string { - return fe.param -} - -// Kind returns the Field's reflect Kind -func (fe *fieldError) Kind() reflect.Kind { - return fe.kind -} - -// Type returns the Field's reflect Type -func (fe *fieldError) Type() reflect.Type { - return fe.typ -} - -// Error returns the fieldError's error message -func (fe *fieldError) Error() string { - return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag) -} - -// Translate returns the FieldError's translated error -// from the provided 'ut.Translator' and registered 'TranslationFunc' -// -// NOTE: if no registered translation can be found, it returns the original -// untranslated error message. -func (fe *fieldError) Translate(ut ut.Translator) string { - - m, ok := fe.v.transTagFunc[ut] - if !ok { - return fe.Error() - } - - fn, ok := m[fe.tag] - if !ok { - return fe.Error() - } - - return fn(ut, fe) -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/field_level.go b/taskman-server/vendor/github.com/go-playground/validator/v10/field_level.go deleted file mode 100644 index f0e2a9a8..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/field_level.go +++ /dev/null @@ -1,119 +0,0 @@ -package validator - -import "reflect" - -// FieldLevel contains all the information and helper functions -// to validate a field -type FieldLevel interface { - // returns the top level struct, if any - Top() reflect.Value - - // returns the current fields parent struct, if any or - // the comparison value if called 'VarWithValue' - Parent() reflect.Value - - // returns current field for validation - Field() reflect.Value - - // returns the field's name with the tag - // name taking precedence over the fields actual name. - FieldName() string - - // returns the struct field's name - StructFieldName() string - - // returns param for validation against current field - Param() string - - // GetTag returns the current validations tag name - GetTag() string - - // ExtractType gets the actual underlying type of field value. - // It will dive into pointers, customTypes and return you the - // underlying value and it's kind. - ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) - - // traverses the parent struct to retrieve a specific field denoted by the provided namespace - // in the param and returns the field, field kind and whether is was successful in retrieving - // the field at all. - // - // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field - // could not be retrieved because it didn't exist. - // - // Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. - GetStructFieldOK() (reflect.Value, reflect.Kind, bool) - - // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for - // the field and namespace allowing more extensibility for validators. - // - // Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. - GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) - - // traverses the parent struct to retrieve a specific field denoted by the provided namespace - // in the param and returns the field, field kind, if it's a nullable type and whether is was successful in retrieving - // the field at all. - // - // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field - // could not be retrieved because it didn't exist. - GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) - - // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for - // the field and namespace allowing more extensibility for validators. - GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) -} - -var _ FieldLevel = new(validate) - -// Field returns current field for validation -func (v *validate) Field() reflect.Value { - return v.flField -} - -// FieldName returns the field's name with the tag -// name taking precedence over the fields actual name. -func (v *validate) FieldName() string { - return v.cf.altName -} - -// GetTag returns the current validations tag name -func (v *validate) GetTag() string { - return v.ct.tag -} - -// StructFieldName returns the struct field's name -func (v *validate) StructFieldName() string { - return v.cf.name -} - -// Param returns param for validation against current field -func (v *validate) Param() string { - return v.ct.param -} - -// GetStructFieldOK returns Param returns param for validation against current field -// -// Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. -func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) { - current, kind, _, found := v.getStructFieldOKInternal(v.slflParent, v.ct.param) - return current, kind, found -} - -// GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for -// the field and namespace allowing more extensibility for validators. -// -// Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. -func (v *validate) GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) { - current, kind, _, found := v.GetStructFieldOKAdvanced2(val, namespace) - return current, kind, found -} - -// GetStructFieldOK returns Param returns param for validation against current field -func (v *validate) GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) { - return v.getStructFieldOKInternal(v.slflParent, v.ct.param) -} - -// GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for -// the field and namespace allowing more extensibility for validators. -func (v *validate) GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) { - return v.getStructFieldOKInternal(val, namespace) -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/go.mod b/taskman-server/vendor/github.com/go-playground/validator/v10/go.mod deleted file mode 100644 index d457100e..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/go-playground/validator/v10 - -go 1.13 - -require ( - github.com/go-playground/assert/v2 v2.0.1 - github.com/go-playground/locales v0.13.0 - github.com/go-playground/universal-translator v0.17.0 - github.com/leodido/go-urn v1.2.0 - golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 -) diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/go.sum b/taskman-server/vendor/github.com/go-playground/validator/v10/go.sum deleted file mode 100644 index 01526427..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/go.sum +++ /dev/null @@ -1,28 +0,0 @@ -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/logo.png b/taskman-server/vendor/github.com/go-playground/validator/v10/logo.png deleted file mode 100644 index 355000f5247d50e979cf5db5de38188ef4649a34..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13443 zcmbVz^LHiB^LK39wrv|5-`KWoTN~T9%?&s9Mte8f*xWeZ`~Lg^&kxU>)6-|>Om|IH zcUM=vsybFxSr!?A009gP3|U@IN*z>Z{#W2&KzAW<*L_e0I`lYd#@osT8GH952<>}$=#%H%txCM^!YLYIPG*~?*PoX}XfpXD#$r$vg% zUJ@M8Sa6}E0bs?J()q&Aj2!Xx^!*X7wf45!j09TZ!t8tmiZrhYa~rM!hkOgG3jNOL z$t%hsiEZp{`uZS=pUq3db%5@e>LpqUR%RzF4Fp&XYtszH3NMj(x&yBfN!B@dDe(i*$ zFaI9z`VK(*+SzZ3Km$V|gFS(NfPUS&ND}#zKM&MsZR;zy@SJwDwy5moK{eH84yz0`{Dhd+jynpps_Wzr*Rl)ctU%7jk!=>D(g}(sK zP}YV(B1|d_4NeR~4qlx?36qk5ng9u-wt+@fOTlvqhk>WQ%HxtjxBspSS(-6OpP;_x z73LX72W9oA=yUj&B*sjt0z}2U44ACNztdo!tbwR&pl8vCLjf!@HDwcP;p{h$JYsrk zE3Pp7L^A>!xwNPSX+2zrQgJ8|CCr11n`u|=C}{? zlHLN%{DxBD;+;&!6Se$BciUB@EQ~Y8_ZT-Q&4p}|A3l`R=AVR9Kt+V~a3a3V{l=)gHBK2op+X}BW7o(X1K2eRTZ^; ziO?#OmuWkXeCj2*{H(1C#qnQ>tz|Kq>*#cF7g)+?3G3(pVB@N37)9YHmYxa}CVb-% z@SHf5CnrEMiI6-&fkkOb9ema$%-Ld}qN54xNf|CDt?#e@Aec&IEcEEpu3Ak5Y z>0@s)b7yHEr~UCsek0JVuF%66MBgBxj-d!wQu4Evlx;p|pZG{&=4VV)*pIE{{f=SO z;V$)QC5ae=-6(Nc68{(S;2ymNVxIiwAs9}A@vA2?55kfV(qK>S6caF|bywd&p8ydL zB}xJ~6Di7u^Xl{s1E&b!{FXH0#>1$=MTNA7+vd;Pm*#B`iYRecX>5H7^iqDqQ{GQH zKNNh0?p}h?nEjh_Ft*^M`+(a;L*rKgPp=E!!}stvVxG|YKY=Yh25?+RloCoyT3T~2 zr1!?YL58}YTlyj1sTl_H(oBl48zJPwJFr9|r(>T7Npe$Hyl7Pm(dZ}|x;n!X(4wtZ zeNCCz4LTygy(gl;pV;dp+-Lpq=weiOW2Z_Lt@RNd_s43tZ>$@23^%6`T}rfexq!%# z)e|oR;kRY~2fW@V(in6QZzE*6TubN0<>|v2xiX)v6->d$no+&np8 z=DZPj>yPVL2Y2U^MJuW`R8R{2@Rg&}`S+$yEgsGihuW$3 z2y*A5Rm-TCh*xaY#R1q)HfzQS_%fPHCL7200}u=S#u`m zvW%z6F_UcmBq~g~s|d}v6$Q?noL`Z(X;@Q$i>kw^bF}I3A8QQyAE_nz-`H~a9o2}- ztPUs0q(DTZ^Yx3oA6C5I?{nHCX0qfW&C2r}h~~slhe!$_Hh1WB`w?_|D{JsF#zpgf z;F^yDTZs-$?`myzyDj@=x}@L4b~_KtUWzV+uiL${48Qh^ZdoywlRNR<*WLFY>v0fq zeWQS`g6{8q<#x){FrCbZlcTAh?+fw^gB-2LpRnlF^}`$D;(KxTOLn;dXs3Yl(uW$g6hyw3{wZdTVg|kdSet`n+SACG=!&%#r zl+Ha_MzD$G>iQb%tW~Uus7-zOMPI__Qo92dK3VKkGgR#;-!`uw++~l5J?MT+BUCv3 zcItfZO)uKXlipj1XD?F|>3frjQWA;$JV>TcHHrcrR=Ql;-B}Bb4;f|uVo(S7xL(QP zE%c8{bnchCJ%aG)3x8gx0`Hqq`eapfWqK`~Ec6Mea`v0{J?4~x(S2D#-7sMBR1X;{ zO-QlMUsyD!#jI^8v6y2J8TinHz_zsU@;3|?TfT0F2b2A7aX&aEQGc;IZ>UV*cToht z27rX9TA$h1ZMxk`KX|$6o$)=$PxIM3k^FhGmiJMaA3fBM6(M#efLJ9ucfbo2TkroP zxE4Dv?B_Nkef;0LYVj3nk|C9-MLv{y^-tY`SD(5phR2KMn}9@?I@SQ^#m* zu>9T8l>)311+yf)qc`Zp%3Cp9FS4PN18t5zZGy-!{f^5eJQA&Fb>Llf4kF^OZ}Tu z=jyadHyzlQLaf@_eAf{CFb}_v=Gj*BLc$VrMAe%hAL@6JaXkt^p&>`#SXjBAX!3#; zZ(sPdwtkoS08=HP@lruhHm*fIlu{y~LTu@+@;u*LBUU~nbQ7S{eH09xc5^_Xtu!q@ z6^P#P!A-(qwW30Th;TBWNp{b1+lP1D!2Y2In`HJ8=DTs8;1)Y~TE2Tco&agHaJGJRtE&{R2y^@Gnpny|$qxXc2=Ps$@$~9mxET{1Q$%i!i#frlzo0UOe_Y zMxNvLk98G99Jhl+-rMB_{OyQsE?70nTDUTZf%>P_;7WAz0a+FG*4EALUD*p3UWt_( z3yZrIM%L#2dleC=K}bD*)-@4195ctqtgM0iQACxJ?F&0O<{t?%^dK1pMJo*-dHj;E z%Vt=-^pa?Z(eb%_rx~$m@yuyvX^t!IvZZ&&LJtY`#;x+PXT-Gb~(3>gv;tf~4N37#aCX z-tW%A@AM^Cf&WBJl*|wp9s0RGq_rCL)=Klfe3e8BUY|7FGZM)#ZdT04zyZ#{*|<&8 z+dsxt9B+krqDfJbykPO==|6C|yAi)*jkV&C{Du7Y#drV0`{jGeFSFOANIz#B-ncz= zB?v}IR2j5eCJ`2>yNMN9<}h!(e$i><|KSPd(Ff^lC-7pg&G~QJ8T0JD-37gq1-K+V z;1?GW_CVrGX3V0m%yvW#+uGLl^01=9zyGrgZ5fJ6GeeULS25^4)YCL=-Z!w`r$tH= zj-ikdG|nI;y1wvvk2)h7^hL0Xvnxw)Y1u}&9Vv%k1};Z0IqW?AQ8)B@QOUa?ayt31 zX^`u?pa(0F6YpbrT;e2^auw#%0BX_ub?}_ieYF;4rGRd*1_vX-+Xv9I&yR@ zZF(3;`kXg0vHdTn$5Ie;gpS4@djPPJ60-Z_1?!DwQz9NO2jKDbkZ^oJbQVc?6v#&0 zAW|kWVx3>tw#eTFT> z$S^|&ZWo)7Lyes7r)@VL=2A|$JW1nr)ed9~F&(_uHC1f;YO_5oj&Afj!0(9M)7c*f z$rra8Ji?1Bc%e|v^CcS{(B7RRCc7Wrrs=I7)f#8IE{rDM)o~`?Y8!;pSaL!lLHCZ% z2RHV1+l?QSk}_AkH)`_s#(xKJ?jwKC`csy*aOGtV&`hmHIG<5hXtzm+=iQkb{pyZ< z%;RxAP~z<%lTo;vNWd4mn;*jW+1tVM*tJ0j)}5|LR4#M7r{PkXJaW;yHBr@9pIuiG z8V1M4Ci1&Z6T1I>(C@#6rJT=}4_MR%kp=0LFD)iInpDCFQ;rm ziA+yF-c%|NyQ8);!vM6)#xu8qylq9(nieBl!@e}S5}R@)8LEU)Q|o0z)Z3vP);l2n zvCG7gtlR2XtjF1}fhC?!r{BZ4#sNRJi-Kgt?Rd(rePR;wmE}rqM-z^#fA_=ptrRR~ zqS-A)prf=s19gdfPBn?#&j;!a+e1!wX7|RMt|@0KQ_^z7My)2imN}+? z&Ro$-#EC#FN(11}WJ|$X)eQ0hf7Xye3AhvowX$0|1+x+uY~g?ccTKswq+io;vFNd6 zr7#C9z4;>@b-tg$UzV@9U5hK{mDW{6%YjDa>FJu9Z8hZyN}pshPN=W>uI!^Q$kMqm z+}IiQA9sdYvoB1IiBfX#m0axM;6c8}N>K$tD8kW56>r1h5t8J!3X0YAj1|Aw&~l@A zxf2^V`F;A0W?i!7*yQ+#;?4!!1ZQrBEI$9+-N z6P_sTrV&}s7MX}77Nq}~KmQy&5T&0ZWX--y(<$MEOLGIm!7k)jQOWggN0!Rg^`Bj3z7;;PquhhFnoqJeAbUfHR~d2;C{_De_Ogp81i65*qU(X5fweyv+B#w>RW0 zm&_w7Zm z`YWfGxm^7MK^A>0nDITy;gz^Lzudv@BC>+^JOVExD%|?aa0W#9qe``&CHjF6vqV zB8&tSqdhz{r4(|w3!g-DZKg>^k=!a74kk`D{P(2>&R~8kXP)^Ns3jTlnM7|b=I@?W z*3YW^eW^H83@t)lUE4LAm#(ICbAZTgW?ohHU;Ok91QJvMGp6fHL|&TQb|ICaXi{OO zrD__`B5>e)a6orX^!P5CsJZqQhI9-E6v4*!cC1vUi2?G|44quG+rfLS+7ZX;meFoT zMa+fb0pH+x{|o<7L^;cM5J4}K*7m~l#N2_qa(YL%G9rt7(fo;z(CaJOODkCKPA9`Bop?dIYFl3wBU&l zdqN~tz4k#i1&+HT_N>0Qm%uxG;}xqfaciIXXK|67VNTu0yzMz6pt6)m~ z7y^EZ+(wMlK9yMiwkhp&>cmXQoRzGf`o{MmkrGaxJY*%s0Dza_WczOvC8IXtY4zGE zoAfaSy~MQoF^;l5RWb}DJq*S_&wp|_lkCAaR~iQkooeXo>yX+1hRw(?%#&k0 zm|IG1?>%mpBmLr(*DC>|Vr>bN;nKsdZLlS4*_h%G1n`;;6|sE0rg^T9KG)Swoz!z& zJra776~H1@daS@C;jzI*0~;x5(E1Fpo!nLAV=SmM;Q>*#bxdaC<;wO{!IV4ONwN}f z8NK=|T>UjQ5%%_C3KAVb1}wC~Feno-GH|l>&?HI*RX~t*0XtJ~S0R6Kst$kD*7mw& z{mR31-KopNO5bKJqku0*PjnBKFE_1y_|tmDtiN7SF!NZpwNb5#sV6w^bu9#1B5K7# z0N}))422cqc#^(uW?wJU*^KLe?VU&(*c6j;U6^LZcQoK4POU1{yKSH^?k2$VGLEWB zog!7!3_Kl%apr)=%d3Rpw_4BDLZf!1tIdN&D;Yg?X2&jp0vSBqbz)XX`Wu2%`IWJS1s3lhZ7H--?PJxQLg$XONw$8qE z@4G(S5}8yFwM`{Rdz9E__ZH{{Gusj%$t#w4+ac&G3wkM0n&qZPP}J9r*av-Zq- z%NdhH1sgs~Oq9{PLkkxDiK6MQo36OTZrr&F7k6+F*a}5hV<;1u+B`QQSF#ti5`pI3 z@gvRFovLjNAri8~54co-plD$yQSX*b95r9t@B%~eI2r9NqXw{mGRKtdG5*|wk~yO zW)?msL*Rlpy{X4OLKx;RTX5`t1RY4!(bJ`a7rJ?=xM7fwcCL;k7j%-*cj9NLfbojM= zsFk;>hWcz(m*MFBO66YXrs>D4!BqdqWy_oZ>c&}P@|L*1a zVk(-?<3wy?;t9XLM*dyTj^XbicaVIM%BJouomO8jaqzV51LbTf>Ywq=#cXFtO*-oC z$O(ezf}G*);p^d{5Cc9apUxWE7RHp-F$ne9h?~C!5ok6%glp3JFOLJd2A-Fm@I}Id-s z30mMGUBh}2LTd&+z4*b8fB8hNy+ke`kmJbFXYm9=Ud96znCvs;Xa*GB`{*jEPp($~+DX+RP*)$prD03Z~ zot>}r&YE}7>5Wkie5E(*NC^ihU`EdF6Ezw%Y_=C72{{2}2gipm z*Kp)Aa`c2J&xYYZ876z^z{Zt5pR2|?72(fT&g8MYt4OgJ8>+ZDr_oB=>9xhEw%27Y zdZWI$a9GrD@5Los+iFbyl507c-TMRH3x)MMT{uczOKy3!ra7;z>2})#CRqJW`Jr@s z)uA36KCgr8c)q);G>N2B3p4kyV4NWuoxzls;Xqq+eg~fI$A3otuea;KAQGd#L@`_H zA12vy0BVLhln8XMstlX5M43pjjcZzAO3GUc$zV-2^wq;7JE(EwPLoa!*2(XgxwSlx z2_J0xvN3`hnHWW^kuO7z`%AW8B~t4yhgSPHzS%y%$=}V7s+fZJ0#{k0^O+*L0|Zg4 zfX#xMrgl!s6Xo=iNk_&jq83fy!YAvDSuT8GO6%m58Pi*2YUR|;TQb;TdN=rqTpKIZ z-p&;$N{lIA6N##--%mV~CtEEa4=)@J`4YoT@$9}xH&qcX>lvW>wj*s%n1(JbS$r*d zK9ca~LMdTQ7v!Y34Q6Zh;50&tLX-E@$j3m@9%{iLEyrjeeM_lyMFuI6_pPMcUemdp z%6;iM!PP84B5GQ70B|+R^|BqipYC7_%BZRXP;eo#KZ6EBvBzlpn}@P3p}|8#I(4 zul0x<>TxI(s0g?8v|a89+n1)Jx##kH*g@FY*niUw?{Sqmm)Xi-;WBKlUieBT&& zR3bfdZ|yI{!e~+H2q@uF@=N3k*$H|RZpj@5hvmw~_Py+wV14-k8ynOVi-{@1gB;!g zop(C8F2W!)$gD|@VYtF3M2`gl44ny?45baF7yCBl4PB@{E_nNFz6{2b zr3nxXdd~S*FLLzzO#wytqw(3PI0_%D56fEkMQPca=JX$gqH9aJ{ZpKvk8&kz zVxpVpl56nj^P5R4Lm_KK_6WeFW0cD?IY zZu%H?$YfA5eBYF>2g^}+ig>LD^PgW_C#jRJ$|LNXlubK_b)pT9uqy)nlg?;4DG*(P@1w56aN4^TZM6bWUyCM1*1Czy}HIA#1w25=*y73 z^<0dmnQg(qFmL~t3lPYXx1H8~Zxg@d(x{4t40F=4{->PSRp{RzUszJHDlXejc7G)lY;8~fKsU-hk(590&9v& zFxr}ZKJqco?V2qb5bnkeLoQVbyu32=?$Kwh?;N0OiGN|7=6`RkdoJ(JT@djZ8dUCb za?z#~&v8Fm?V}L${Zr&aQ8JC0EF>X56u4pkjt-w^+1bG$r9f1OrJ$<6qE&iV7_}kN zQweT&?sbJOanV*#E0|bLjkCC(vOm|{V<5MsimhiSt-uxzjxz9SMUvMQK{`~RZ+v_m ztb%l8kCZHm@?oa?Mb$L;Bv2$(K*V=w5SD>$*ITQ!W*n%SOXJlQO>pLoRxLI#%aHpA zmYUE<8T)d$P6F=j$+`7W&dSV^FR;c5cvU=igm6$Q0Bz?EE|?msF@JEX89DoMOUuTr z`R{3)%|h-VtA7`wTgs8)s;PQ6$6IvQTsUzrO=Y6G!D)=Xx9w0$Gba6n1y?{dK@SoK ze54vzFH|9D2~QbpUTb_H)IYDfa|J}Lq9?%CFHbsIB8(vc1WUKbA`4uL=6b&iurle2 zi(4jg{2hA5K*7uKNnBA0KV4x*3NO0jb^QuEWV&39?%#Ve9aEQ)AWUUwycBSf_o%|` zTcm^fRU(B}U8I(N*#z&8fsGAkKpBAt5@UnRa>N{07@%qaw@bs$K2R5VP#c$2^Q%RQ zVuW0slT(*~U8kk?duR;_jOTpmwrrbx->n}JX^_|@zO|a)Ik@>X7HOQ(!z(#CF@`^7JGf2aEfn1S0v}oHKo%uVUMDjl3<>f#kD$hfw(^nW(aRB6AaG-TDAh%oHjEJ=J$;2s zNEtTUsuZa{ji(_8)1j8gUOb~B9fXBSc)M%Hfsu<`&aJGt{{#rePUQ zno1K;1#~H`?Rd#V$}MtvkS~UOgsP~@^u^u{ua{D3V=Fa{2IKwI7>|!cOUteP#X!Z_ z0=9Z(Y!#lhZpJ0TKxMl6%R?6~lt!EvNztb>dbADO5-ZkYS1f(TlqF6|c^Euh&Dojz z>7lTs0ClkTp5>|*~0 z_E{QdSna;}KOcu@*xbF3xyhffB&XIT`p{6hS*F))v#>=YEtJB9Cr*b2YtK$qd9@hS zP$+_%N43)URxgAF_fx!4#yRV$Y6W06mtQ<`6RwW>A*AaHVyEylR` z2)a@71;tKHeL9Ik*CB!~)Qw;=Fl6gGLG;?;LTeerep>@XsgVh4FN73z`?Z=yj9;v% zBxr{}l;h6)J_enD_Xs$w_!zAMpK(;B2{L7;9924=)DeQQG^=eR>S_sq&5Q6tF?!ZR z5Qknd!5HirCsnTIK}aSQLQ_)EQtb#JSG@QUVD}mpOr(idOXutsza|QP5K1WjdsWrs zkY855Sph`j8nzw^f)v# zwC?)Bwo9-}lWq~G9ow>)3->q?FnXQ<$)Y*Vq?hu8MmH8aL1yGrPXCBBQZxc2c}gM_ zazx&=nWtc(!DSU&y7M>VVWHK|f42Z4$ zgM>V`3TB$s+ZXAeFq65x>B{Mdc~^YySq_px;%mpmr2Huz$C}=8-KJN$50%RxgBJ`5 zP&~~O#I1B_1NXRe11=!ZG+8?m1fW)N1v3M~LuJCB_sLZ){E+CtNyJ{zEW!m2t6~4F z%H681*4phFkdH+Wb0LC&2rz`YF05QDpj#b^CS9c1iNN6yizQhsjIRb7ouDlN!>cKa zg7n0;K8z}XHxXi2Ecua32b&VylFo$*L~5$eud(~1>99o0y8R!-= zN_$<&9xytjEu>6segSMd2}6=@3VVB@GhvK>e5(3kr&=sV&}-F69b-m9?Ip^S&_1rK z)REQFT(LR2P6B9EqR$$Fjhw z@@PRbM9s{1I>jgtQ$A{Too_2xnL(GQD!IAjpSUUis4yB{sY$2}MT}d+!IfS_pu32*B z(%fM}`E)&K1vl5$L@*MaDwYf>96D4c;kb|PKTS;+YgrY9Ko@0Q)3$VlDZzF2D5qzp z3ooIC#iZNaZ8P4)aA|hlnC{a}TPrb~vTu2a+lFss)C;W1zZ926mndG{GXR|B)WfV} z(w*ugyn0Rs7_}^z1)X+M+)NXwrEUSMFwNFX_HD7RuV z!p-X54t?QhInx8)RxXg9Gk>_MaF-=XqAoa3dpy^>ZnMr+Cdt={MR4L zlI?2b=gsG3&Ijqpwy~pkv)Y=9n_|E|4ghMbhOV!U-CR;Kg+YdeFwVdfiyc*SZ33P= z$^Lo3LKgdGzEro#sbQm;1h}cbE=gD;VPV$RSAC(NX#P3$r*wNcQV1ac_8s?7<*v7Pd5{UE zcj<@b8s(}ugB+l6X(Y2RciZYZr@$lnh&EYVD&Q;@IV#m~)&N`>i%eC8QGg&uMXI=s zQLp~@6So9V;*{|ZngyWwRLWwzOCrXEh&`MazZ2wm)kNAKFDMMTX_jGA!oO_hJ-YRa z$^tLI^PHPVUu(o9eNPBKBkY8oY*JvIpawcN$Hq>rF`BD0kq%ngOwjI!^ei&^{U1>= z!^&Yoa|y-vSLjPKIP(7C?$zHcE6TomiB6zAM~x|S=v76w%>=hQ$rVordZSPGH_r!u za~NE4L)9W;Zi;ur8=N=;g2x`9ew-T?zd44CWDowkmcCKC2ZEkwyy{Cgf?DBwA)VTz zfJ;~J*q-_{>l2=#Z#w%BHa5yiZUb#89mRN|$!s*X41Sj}m@%Y%D8!j#oex}HpuLkT zi_70a875WHbj(&5q=Cb3*-Fn-b_=@DxVxh?M%~C#aO%I9A zfDhFlS)5h5m^sgc`qgo&LB;4CbJ+4Do$EQJL-i45cQ|%b4D${*iHS6$Z!lFja4{Z& zm_cQ;+$jmX_Ipjb?|qoQbz3TEQd@UgHO-t8i&2#uH*%Y+@t8HptKD;^>9mRb|w53r?9PIIfP$v|io_ z*cIdNpF96_?%r4O-CUdtgPsVgQ7~>`(Iv=~Vz&=N0I0@6UyQtkp156a;eRI#QPSg> zAcDjr+gD33>K!@@N;gSJr1%xowp?n{?=lK{fWo0V0xrMs(WD=)!hLrQ-FS z@!mYs_Wz~@&+paJijML41V^ce^;23KtbY_xNJKz@7&zTeFEoHm7;$(UI=YQFs#$@ptk!EQ42Y4FfxEf@TOsVt37 z}4AVbnC9Ri){mLjd@o@_vA;wzpV8G_ypN3Y=M08M6ZfM2Xtkpu^=A9}u!A?A z)0NYU%Y#TSSE#tnm?KTmo4 zd|UY(Tqjl;m?`7^R${$QG*ZIW=)p?(%lWYXyf8k9{rdP=)z$ty1cAPSJfgXTOPXN1 z^D-Pknjk$jWsP@0+o&sn#8=lA=)a-i-j|YE5DwZ9s#vk3w-c?}%C?C;Q@<(1;-i>L zl}SN#MAX*71GGR14&RiPaHe@3srrMMPYHjml+|aGSDU_fRi{h1_NlT;MHYR@D(IR3 zt6;N#m)Tdz?)V=$7s!&Z;ZdmJFd0m>InR~Umqz^)eM=coLx(q4tw%~Z0U73ho^=Mj zF)fREGIOlh6`*ARYk?K%ir!a_Yvw9snW){J#zyP<3!#qD8Q_2~d|so+(Xc54smil}_4kGqEK^l7mVKQmM+ zBR70H=a2QXGB!3jg`P(Kg~lE^KQr-y_EVJi%}cMMzb+f?)6-|yp{QzpZdk)-9EhXzQpEZ(ZuvkddnL`d4Y{JQ>J+Eg}}BSGkUqgbqYuem+;8++@MM(|;Eh?pTI_O&4Gy6PBOnIB)^cWfo! V^Rh-@K?jDw` - splitParamsRegexString = `'[^']*'|\S+` -) - -var ( - alphaRegex = regexp.MustCompile(alphaRegexString) - alphaNumericRegex = regexp.MustCompile(alphaNumericRegexString) - alphaUnicodeRegex = regexp.MustCompile(alphaUnicodeRegexString) - alphaUnicodeNumericRegex = regexp.MustCompile(alphaUnicodeNumericRegexString) - numericRegex = regexp.MustCompile(numericRegexString) - numberRegex = regexp.MustCompile(numberRegexString) - hexadecimalRegex = regexp.MustCompile(hexadecimalRegexString) - hexcolorRegex = regexp.MustCompile(hexcolorRegexString) - rgbRegex = regexp.MustCompile(rgbRegexString) - rgbaRegex = regexp.MustCompile(rgbaRegexString) - hslRegex = regexp.MustCompile(hslRegexString) - hslaRegex = regexp.MustCompile(hslaRegexString) - e164Regex = regexp.MustCompile(e164RegexString) - emailRegex = regexp.MustCompile(emailRegexString) - base64Regex = regexp.MustCompile(base64RegexString) - base64URLRegex = regexp.MustCompile(base64URLRegexString) - iSBN10Regex = regexp.MustCompile(iSBN10RegexString) - iSBN13Regex = regexp.MustCompile(iSBN13RegexString) - uUID3Regex = regexp.MustCompile(uUID3RegexString) - uUID4Regex = regexp.MustCompile(uUID4RegexString) - uUID5Regex = regexp.MustCompile(uUID5RegexString) - uUIDRegex = regexp.MustCompile(uUIDRegexString) - uUID3RFC4122Regex = regexp.MustCompile(uUID3RFC4122RegexString) - uUID4RFC4122Regex = regexp.MustCompile(uUID4RFC4122RegexString) - uUID5RFC4122Regex = regexp.MustCompile(uUID5RFC4122RegexString) - uUIDRFC4122Regex = regexp.MustCompile(uUIDRFC4122RegexString) - aSCIIRegex = regexp.MustCompile(aSCIIRegexString) - printableASCIIRegex = regexp.MustCompile(printableASCIIRegexString) - multibyteRegex = regexp.MustCompile(multibyteRegexString) - dataURIRegex = regexp.MustCompile(dataURIRegexString) - latitudeRegex = regexp.MustCompile(latitudeRegexString) - longitudeRegex = regexp.MustCompile(longitudeRegexString) - sSNRegex = regexp.MustCompile(sSNRegexString) - hostnameRegexRFC952 = regexp.MustCompile(hostnameRegexStringRFC952) - hostnameRegexRFC1123 = regexp.MustCompile(hostnameRegexStringRFC1123) - fqdnRegexRFC1123 = regexp.MustCompile(fqdnRegexStringRFC1123) - btcAddressRegex = regexp.MustCompile(btcAddressRegexString) - btcUpperAddressRegexBech32 = regexp.MustCompile(btcAddressUpperRegexStringBech32) - btcLowerAddressRegexBech32 = regexp.MustCompile(btcAddressLowerRegexStringBech32) - ethAddressRegex = regexp.MustCompile(ethAddressRegexString) - ethaddressRegexUpper = regexp.MustCompile(ethAddressUpperRegexString) - ethAddressRegexLower = regexp.MustCompile(ethAddressLowerRegexString) - uRLEncodedRegex = regexp.MustCompile(uRLEncodedRegexString) - hTMLEncodedRegex = regexp.MustCompile(hTMLEncodedRegexString) - hTMLRegex = regexp.MustCompile(hTMLRegexString) - splitParamsRegex = regexp.MustCompile(splitParamsRegexString) -) diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/struct_level.go b/taskman-server/vendor/github.com/go-playground/validator/v10/struct_level.go deleted file mode 100644 index 57691ee3..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/struct_level.go +++ /dev/null @@ -1,175 +0,0 @@ -package validator - -import ( - "context" - "reflect" -) - -// StructLevelFunc accepts all values needed for struct level validation -type StructLevelFunc func(sl StructLevel) - -// StructLevelFuncCtx accepts all values needed for struct level validation -// but also allows passing of contextual validation information via context.Context. -type StructLevelFuncCtx func(ctx context.Context, sl StructLevel) - -// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx -func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx { - return func(ctx context.Context, sl StructLevel) { - fn(sl) - } -} - -// StructLevel contains all the information and helper functions -// to validate a struct -type StructLevel interface { - - // returns the main validation object, in case one wants to call validations internally. - // this is so you don't have to use anonymous functions to get access to the validate - // instance. - Validator() *Validate - - // returns the top level struct, if any - Top() reflect.Value - - // returns the current fields parent struct, if any - Parent() reflect.Value - - // returns the current struct. - Current() reflect.Value - - // ExtractType gets the actual underlying type of field value. - // It will dive into pointers, customTypes and return you the - // underlying value and its kind. - ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) - - // reports an error just by passing the field and tag information - // - // NOTES: - // - // fieldName and altName get appended to the existing namespace that - // validator is on. e.g. pass 'FirstName' or 'Names[0]' depending - // on the nesting - // - // tag can be an existing validation tag or just something you make up - // and process on the flip side it's up to you. - ReportError(field interface{}, fieldName, structFieldName string, tag, param string) - - // reports an error just by passing ValidationErrors - // - // NOTES: - // - // relativeNamespace and relativeActualNamespace get appended to the - // existing namespace that validator is on. - // e.g. pass 'User.FirstName' or 'Users[0].FirstName' depending - // on the nesting. most of the time they will be blank, unless you validate - // at a level lower the the current field depth - ReportValidationErrors(relativeNamespace, relativeActualNamespace string, errs ValidationErrors) -} - -var _ StructLevel = new(validate) - -// Top returns the top level struct -// -// NOTE: this can be the same as the current struct being validated -// if not is a nested struct. -// -// this is only called when within Struct and Field Level validation and -// should not be relied upon for an acurate value otherwise. -func (v *validate) Top() reflect.Value { - return v.top -} - -// Parent returns the current structs parent -// -// NOTE: this can be the same as the current struct being validated -// if not is a nested struct. -// -// this is only called when within Struct and Field Level validation and -// should not be relied upon for an acurate value otherwise. -func (v *validate) Parent() reflect.Value { - return v.slflParent -} - -// Current returns the current struct. -func (v *validate) Current() reflect.Value { - return v.slCurrent -} - -// Validator returns the main validation object, in case one want to call validations internally. -func (v *validate) Validator() *Validate { - return v.v -} - -// ExtractType gets the actual underlying type of field value. -func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) { - return v.extractTypeInternal(field, false) -} - -// ReportError reports an error just by passing the field and tag information -func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { - - fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) - - if len(structFieldName) == 0 { - structFieldName = fieldName - } - - v.str1 = string(append(v.ns, fieldName...)) - - if v.v.hasTagNameFunc || fieldName != structFieldName { - v.str2 = string(append(v.actualNs, structFieldName...)) - } else { - v.str2 = v.str1 - } - - if kind == reflect.Invalid { - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tag, - actualTag: tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(fieldName)), - structfieldLen: uint8(len(structFieldName)), - param: param, - kind: kind, - }, - ) - return - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tag, - actualTag: tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(fieldName)), - structfieldLen: uint8(len(structFieldName)), - value: fv.Interface(), - param: param, - kind: kind, - typ: fv.Type(), - }, - ) -} - -// ReportValidationErrors reports ValidationErrors obtained from running validations within the Struct Level validation. -// -// NOTE: this function prepends the current namespace to the relative ones. -func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors) { - - var err *fieldError - - for i := 0; i < len(errs); i++ { - - err = errs[i].(*fieldError) - err.ns = string(append(append(v.ns, relativeNamespace...), err.ns...)) - err.structNs = string(append(append(v.actualNs, relativeStructNamespace...), err.structNs...)) - - v.errs = append(v.errs, err) - } -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/translations.go b/taskman-server/vendor/github.com/go-playground/validator/v10/translations.go deleted file mode 100644 index 4d9d75c1..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/translations.go +++ /dev/null @@ -1,11 +0,0 @@ -package validator - -import ut "github.com/go-playground/universal-translator" - -// TranslationFunc is the function type used to register or override -// custom translations -type TranslationFunc func(ut ut.Translator, fe FieldError) string - -// RegisterTranslationsFunc allows for registering of translations -// for a 'ut.Translator' for use within the 'TranslationFunc' -type RegisterTranslationsFunc func(ut ut.Translator) error diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/util.go b/taskman-server/vendor/github.com/go-playground/validator/v10/util.go deleted file mode 100644 index 56420f43..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/util.go +++ /dev/null @@ -1,288 +0,0 @@ -package validator - -import ( - "reflect" - "strconv" - "strings" - "time" -) - -// extractTypeInternal gets the actual underlying type of field value. -// It will dive into pointers, customTypes and return you the -// underlying value and it's kind. -func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { - -BEGIN: - switch current.Kind() { - case reflect.Ptr: - - nullable = true - - if current.IsNil() { - return current, reflect.Ptr, nullable - } - - current = current.Elem() - goto BEGIN - - case reflect.Interface: - - nullable = true - - if current.IsNil() { - return current, reflect.Interface, nullable - } - - current = current.Elem() - goto BEGIN - - case reflect.Invalid: - return current, reflect.Invalid, nullable - - default: - - if v.v.hasCustomFuncs { - - if fn, ok := v.v.customFuncs[current.Type()]; ok { - current = reflect.ValueOf(fn(current)) - goto BEGIN - } - } - - return current, current.Kind(), nullable - } -} - -// getStructFieldOKInternal traverses a struct to retrieve a specific field denoted by the provided namespace and -// returns the field, field kind and whether is was successful in retrieving the field at all. -// -// NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field -// could not be retrieved because it didn't exist. -func (v *validate) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, nullable bool, found bool) { - -BEGIN: - current, kind, nullable = v.ExtractType(val) - if kind == reflect.Invalid { - return - } - - if namespace == "" { - found = true - return - } - - switch kind { - - case reflect.Ptr, reflect.Interface: - return - - case reflect.Struct: - - typ := current.Type() - fld := namespace - var ns string - - if typ != timeType { - - idx := strings.Index(namespace, namespaceSeparator) - - if idx != -1 { - fld = namespace[:idx] - ns = namespace[idx+1:] - } else { - ns = "" - } - - bracketIdx := strings.Index(fld, leftBracket) - if bracketIdx != -1 { - fld = fld[:bracketIdx] - - ns = namespace[bracketIdx:] - } - - val = current.FieldByName(fld) - namespace = ns - goto BEGIN - } - - case reflect.Array, reflect.Slice: - idx := strings.Index(namespace, leftBracket) - idx2 := strings.Index(namespace, rightBracket) - - arrIdx, _ := strconv.Atoi(namespace[idx+1 : idx2]) - - if arrIdx >= current.Len() { - return - } - - startIdx := idx2 + 1 - - if startIdx < len(namespace) { - if namespace[startIdx:startIdx+1] == namespaceSeparator { - startIdx++ - } - } - - val = current.Index(arrIdx) - namespace = namespace[startIdx:] - goto BEGIN - - case reflect.Map: - idx := strings.Index(namespace, leftBracket) + 1 - idx2 := strings.Index(namespace, rightBracket) - - endIdx := idx2 - - if endIdx+1 < len(namespace) { - if namespace[endIdx+1:endIdx+2] == namespaceSeparator { - endIdx++ - } - } - - key := namespace[idx:idx2] - - switch current.Type().Key().Kind() { - case reflect.Int: - i, _ := strconv.Atoi(key) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Int8: - i, _ := strconv.ParseInt(key, 10, 8) - val = current.MapIndex(reflect.ValueOf(int8(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int16: - i, _ := strconv.ParseInt(key, 10, 16) - val = current.MapIndex(reflect.ValueOf(int16(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int32: - i, _ := strconv.ParseInt(key, 10, 32) - val = current.MapIndex(reflect.ValueOf(int32(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int64: - i, _ := strconv.ParseInt(key, 10, 64) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Uint: - i, _ := strconv.ParseUint(key, 10, 0) - val = current.MapIndex(reflect.ValueOf(uint(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint8: - i, _ := strconv.ParseUint(key, 10, 8) - val = current.MapIndex(reflect.ValueOf(uint8(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint16: - i, _ := strconv.ParseUint(key, 10, 16) - val = current.MapIndex(reflect.ValueOf(uint16(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint32: - i, _ := strconv.ParseUint(key, 10, 32) - val = current.MapIndex(reflect.ValueOf(uint32(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint64: - i, _ := strconv.ParseUint(key, 10, 64) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Float32: - f, _ := strconv.ParseFloat(key, 32) - val = current.MapIndex(reflect.ValueOf(float32(f))) - namespace = namespace[endIdx+1:] - - case reflect.Float64: - f, _ := strconv.ParseFloat(key, 64) - val = current.MapIndex(reflect.ValueOf(f)) - namespace = namespace[endIdx+1:] - - case reflect.Bool: - b, _ := strconv.ParseBool(key) - val = current.MapIndex(reflect.ValueOf(b)) - namespace = namespace[endIdx+1:] - - // reflect.Type = string - default: - val = current.MapIndex(reflect.ValueOf(key)) - namespace = namespace[endIdx+1:] - } - - goto BEGIN - } - - // if got here there was more namespace, cannot go any deeper - panic("Invalid field namespace") -} - -// asInt returns the parameter as a int64 -// or panics if it can't convert -func asInt(param string) int64 { - i, err := strconv.ParseInt(param, 0, 64) - panicIf(err) - - return i -} - -// asIntFromTimeDuration parses param as time.Duration and returns it as int64 -// or panics on error. -func asIntFromTimeDuration(param string) int64 { - d, err := time.ParseDuration(param) - if err != nil { - // attempt parsing as an an integer assuming nanosecond precision - return asInt(param) - } - return int64(d) -} - -// asIntFromType calls the proper function to parse param as int64, -// given a field's Type t. -func asIntFromType(t reflect.Type, param string) int64 { - switch t { - case timeDurationType: - return asIntFromTimeDuration(param) - default: - return asInt(param) - } -} - -// asUint returns the parameter as a uint64 -// or panics if it can't convert -func asUint(param string) uint64 { - - i, err := strconv.ParseUint(param, 0, 64) - panicIf(err) - - return i -} - -// asFloat returns the parameter as a float64 -// or panics if it can't convert -func asFloat(param string) float64 { - - i, err := strconv.ParseFloat(param, 64) - panicIf(err) - - return i -} - -// asBool returns the parameter as a bool -// or panics if it can't convert -func asBool(param string) bool { - - i, err := strconv.ParseBool(param) - panicIf(err) - - return i -} - -func panicIf(err error) { - if err != nil { - panic(err.Error()) - } -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/validator.go b/taskman-server/vendor/github.com/go-playground/validator/v10/validator.go deleted file mode 100644 index f097f394..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/validator.go +++ /dev/null @@ -1,477 +0,0 @@ -package validator - -import ( - "context" - "fmt" - "reflect" - "strconv" -) - -// per validate construct -type validate struct { - v *Validate - top reflect.Value - ns []byte - actualNs []byte - errs ValidationErrors - includeExclude map[string]struct{} // reset only if StructPartial or StructExcept are called, no need otherwise - ffn FilterFunc - slflParent reflect.Value // StructLevel & FieldLevel - slCurrent reflect.Value // StructLevel & FieldLevel - flField reflect.Value // StructLevel & FieldLevel - cf *cField // StructLevel & FieldLevel - ct *cTag // StructLevel & FieldLevel - misc []byte // misc reusable - str1 string // misc reusable - str2 string // misc reusable - fldIsPointer bool // StructLevel & FieldLevel - isPartial bool - hasExcludes bool -} - -// parent and current will be the same the first run of validateStruct -func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) { - - cs, ok := v.v.structCache.Get(typ) - if !ok { - cs = v.v.extractStructCache(current, typ.Name()) - } - - if len(ns) == 0 && len(cs.name) != 0 { - - ns = append(ns, cs.name...) - ns = append(ns, '.') - - structNs = append(structNs, cs.name...) - structNs = append(structNs, '.') - } - - // ct is nil on top level struct, and structs as fields that have no tag info - // so if nil or if not nil and the structonly tag isn't present - if ct == nil || ct.typeof != typeStructOnly { - - var f *cField - - for i := 0; i < len(cs.fields); i++ { - - f = cs.fields[i] - - if v.isPartial { - - if v.ffn != nil { - // used with StructFiltered - if v.ffn(append(structNs, f.name...)) { - continue - } - - } else { - // used with StructPartial & StructExcept - _, ok = v.includeExclude[string(append(structNs, f.name...))] - - if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) { - continue - } - } - } - - v.traverseField(ctx, parent, current.Field(f.idx), ns, structNs, f, f.cTags) - } - } - - // check if any struct level validations, after all field validations already checked. - // first iteration will have no info about nostructlevel tag, and is checked prior to - // calling the next iteration of validateStruct called from traverseField. - if cs.fn != nil { - - v.slflParent = parent - v.slCurrent = current - v.ns = ns - v.actualNs = structNs - - cs.fn(ctx, v) - } -} - -// traverseField validates any field, be it a struct or single field, ensures it's validity and passes it along to be validated via it's tag options -func (v *validate) traverseField(ctx context.Context, parent reflect.Value, current reflect.Value, ns []byte, structNs []byte, cf *cField, ct *cTag) { - var typ reflect.Type - var kind reflect.Kind - - current, kind, v.fldIsPointer = v.extractTypeInternal(current, false) - - switch kind { - case reflect.Ptr, reflect.Interface, reflect.Invalid: - - if ct == nil { - return - } - - if ct.typeof == typeOmitEmpty || ct.typeof == typeIsDefault { - return - } - - if ct.hasTag { - if kind == reflect.Invalid { - v.str1 = string(append(ns, cf.altName...)) - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - param: ct.param, - kind: kind, - }, - ) - return - } - - v.str1 = string(append(ns, cf.altName...)) - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - if !ct.runValidationWhenNil { - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: current.Type(), - }, - ) - return - } - } - - case reflect.Struct: - - typ = current.Type() - - if typ != timeType { - - if ct != nil { - - if ct.typeof == typeStructOnly { - goto CONTINUE - } else if ct.typeof == typeIsDefault { - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !ct.fn(ctx, v) { - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - return - } - } - - ct = ct.next - } - - if ct != nil && ct.typeof == typeNoStructLevel { - return - } - - CONTINUE: - // if len == 0 then validating using 'Var' or 'VarWithValue' - // Var - doesn't make much sense to do it that way, should call 'Struct', but no harm... - // VarWithField - this allows for validating against each field within the struct against a specific value - // pretty handy in certain situations - if len(cf.name) > 0 { - ns = append(append(ns, cf.altName...), '.') - structNs = append(append(structNs, cf.name...), '.') - } - - v.validateStruct(ctx, current, current, typ, ns, structNs, ct) - return - } - } - - if !ct.hasTag { - return - } - - typ = current.Type() - -OUTER: - for { - if ct == nil { - return - } - - switch ct.typeof { - - case typeOmitEmpty: - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !hasValue(v) { - return - } - - ct = ct.next - continue - - case typeEndKeys: - return - - case typeDive: - - ct = ct.next - - // traverse slice or map here - // or panic ;) - switch kind { - case reflect.Slice, reflect.Array: - - var i64 int64 - reusableCF := &cField{} - - for i := 0; i < current.Len(); i++ { - - i64 = int64(i) - - v.misc = append(v.misc[0:0], cf.name...) - v.misc = append(v.misc, '[') - v.misc = strconv.AppendInt(v.misc, i64, 10) - v.misc = append(v.misc, ']') - - reusableCF.name = string(v.misc) - - if cf.namesEqual { - reusableCF.altName = reusableCF.name - } else { - - v.misc = append(v.misc[0:0], cf.altName...) - v.misc = append(v.misc, '[') - v.misc = strconv.AppendInt(v.misc, i64, 10) - v.misc = append(v.misc, ']') - - reusableCF.altName = string(v.misc) - } - v.traverseField(ctx, parent, current.Index(i), ns, structNs, reusableCF, ct) - } - - case reflect.Map: - - var pv string - reusableCF := &cField{} - - for _, key := range current.MapKeys() { - - pv = fmt.Sprintf("%v", key.Interface()) - - v.misc = append(v.misc[0:0], cf.name...) - v.misc = append(v.misc, '[') - v.misc = append(v.misc, pv...) - v.misc = append(v.misc, ']') - - reusableCF.name = string(v.misc) - - if cf.namesEqual { - reusableCF.altName = reusableCF.name - } else { - v.misc = append(v.misc[0:0], cf.altName...) - v.misc = append(v.misc, '[') - v.misc = append(v.misc, pv...) - v.misc = append(v.misc, ']') - - reusableCF.altName = string(v.misc) - } - - if ct != nil && ct.typeof == typeKeys && ct.keys != nil { - v.traverseField(ctx, parent, key, ns, structNs, reusableCF, ct.keys) - // can be nil when just keys being validated - if ct.next != nil { - v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct.next) - } - } else { - v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct) - } - } - - default: - // throw error, if not a slice or map then should not have gotten here - // bad dive tag - panic("dive error! can't dive on a non slice or map") - } - - return - - case typeOr: - - v.misc = v.misc[0:0] - - for { - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if ct.fn(ctx, v) { - - // drain rest of the 'or' values, then continue or leave - for { - - ct = ct.next - - if ct == nil { - return - } - - if ct.typeof != typeOr { - continue OUTER - } - } - } - - v.misc = append(v.misc, '|') - v.misc = append(v.misc, ct.tag...) - - if ct.hasParam { - v.misc = append(v.misc, '=') - v.misc = append(v.misc, ct.param...) - } - - if ct.isBlockEnd || ct.next == nil { - // if we get here, no valid 'or' value and no more tags - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - if ct.hasAlias { - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.actualAliasTag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - - } else { - - tVal := string(v.misc)[1:] - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tVal, - actualTag: tVal, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - } - - return - } - - ct = ct.next - } - - default: - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !ct.fn(ctx, v) { - - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - - return - } - ct = ct.next - } - } - -} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/validator_instance.go b/taskman-server/vendor/github.com/go-playground/validator/v10/validator_instance.go deleted file mode 100644 index fe6a4877..00000000 --- a/taskman-server/vendor/github.com/go-playground/validator/v10/validator_instance.go +++ /dev/null @@ -1,619 +0,0 @@ -package validator - -import ( - "context" - "errors" - "fmt" - "reflect" - "strings" - "sync" - "time" - - ut "github.com/go-playground/universal-translator" -) - -const ( - defaultTagName = "validate" - utf8HexComma = "0x2C" - utf8Pipe = "0x7C" - tagSeparator = "," - orSeparator = "|" - tagKeySeparator = "=" - structOnlyTag = "structonly" - noStructLevelTag = "nostructlevel" - omitempty = "omitempty" - isdefault = "isdefault" - requiredWithoutAllTag = "required_without_all" - requiredWithoutTag = "required_without" - requiredWithTag = "required_with" - requiredWithAllTag = "required_with_all" - requiredIfTag = "required_if" - requiredUnlessTag = "required_unless" - skipValidationTag = "-" - diveTag = "dive" - keysTag = "keys" - endKeysTag = "endkeys" - requiredTag = "required" - namespaceSeparator = "." - leftBracket = "[" - rightBracket = "]" - restrictedTagChars = ".[],|=+()`~!@#$%^&*\\\"/?<>{}" - restrictedAliasErr = "Alias '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" - restrictedTagErr = "Tag '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" -) - -var ( - timeDurationType = reflect.TypeOf(time.Duration(0)) - timeType = reflect.TypeOf(time.Time{}) - - defaultCField = &cField{namesEqual: true} -) - -// FilterFunc is the type used to filter fields using -// StructFiltered(...) function. -// returning true results in the field being filtered/skiped from -// validation -type FilterFunc func(ns []byte) bool - -// CustomTypeFunc allows for overriding or adding custom field type handler functions -// field = field value of the type to return a value to be validated -// example Valuer from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29 -type CustomTypeFunc func(field reflect.Value) interface{} - -// TagNameFunc allows for adding of a custom tag name parser -type TagNameFunc func(field reflect.StructField) string - -type internalValidationFuncWrapper struct { - fn FuncCtx - runValidatinOnNil bool -} - -// Validate contains the validator settings and cache -type Validate struct { - tagName string - pool *sync.Pool - hasCustomFuncs bool - hasTagNameFunc bool - tagNameFunc TagNameFunc - structLevelFuncs map[reflect.Type]StructLevelFuncCtx - customFuncs map[reflect.Type]CustomTypeFunc - aliases map[string]string - validations map[string]internalValidationFuncWrapper - transTagFunc map[ut.Translator]map[string]TranslationFunc // map[]map[]TranslationFunc - tagCache *tagCache - structCache *structCache -} - -// New returns a new instance of 'validate' with sane defaults. -func New() *Validate { - - tc := new(tagCache) - tc.m.Store(make(map[string]*cTag)) - - sc := new(structCache) - sc.m.Store(make(map[reflect.Type]*cStruct)) - - v := &Validate{ - tagName: defaultTagName, - aliases: make(map[string]string, len(bakedInAliases)), - validations: make(map[string]internalValidationFuncWrapper, len(bakedInValidators)), - tagCache: tc, - structCache: sc, - } - - // must copy alias validators for separate validations to be used in each validator instance - for k, val := range bakedInAliases { - v.RegisterAlias(k, val) - } - - // must copy validators for separate validations to be used in each instance - for k, val := range bakedInValidators { - - switch k { - // these require that even if the value is nil that the validation should run, omitempty still overrides this behaviour - case requiredIfTag, requiredUnlessTag, requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag: - _ = v.registerValidation(k, wrapFunc(val), true, true) - default: - // no need to error check here, baked in will always be valid - _ = v.registerValidation(k, wrapFunc(val), true, false) - } - } - - v.pool = &sync.Pool{ - New: func() interface{} { - return &validate{ - v: v, - ns: make([]byte, 0, 64), - actualNs: make([]byte, 0, 64), - misc: make([]byte, 32), - } - }, - } - - return v -} - -// SetTagName allows for changing of the default tag name of 'validate' -func (v *Validate) SetTagName(name string) { - v.tagName = name -} - -// RegisterTagNameFunc registers a function to get alternate names for StructFields. -// -// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names: -// -// validate.RegisterTagNameFunc(func(fld reflect.StructField) string { -// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] -// if name == "-" { -// return "" -// } -// return name -// }) -func (v *Validate) RegisterTagNameFunc(fn TagNameFunc) { - v.tagNameFunc = fn - v.hasTagNameFunc = true -} - -// RegisterValidation adds a validation with the given tag -// -// NOTES: -// - if the key already exists, the previous validation function will be replaced. -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool) error { - return v.RegisterValidationCtx(tag, wrapFunc(fn), callValidationEvenIfNull...) -} - -// RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation -// allowing context.Context validation support. -func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, callValidationEvenIfNull ...bool) error { - var nilCheckable bool - if len(callValidationEvenIfNull) > 0 { - nilCheckable = callValidationEvenIfNull[0] - } - return v.registerValidation(tag, fn, false, nilCheckable) -} - -func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilCheckable bool) error { - if len(tag) == 0 { - return errors.New("Function Key cannot be empty") - } - - if fn == nil { - return errors.New("Function cannot be empty") - } - - _, ok := restrictedTags[tag] - if !bakedIn && (ok || strings.ContainsAny(tag, restrictedTagChars)) { - panic(fmt.Sprintf(restrictedTagErr, tag)) - } - v.validations[tag] = internalValidationFuncWrapper{fn: fn, runValidatinOnNil: nilCheckable} - return nil -} - -// RegisterAlias registers a mapping of a single validation tag that -// defines a common or complex set of validation(s) to simplify adding validation -// to structs. -// -// NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterAlias(alias, tags string) { - - _, ok := restrictedTags[alias] - - if ok || strings.ContainsAny(alias, restrictedTagChars) { - panic(fmt.Sprintf(restrictedAliasErr, alias)) - } - - v.aliases[alias] = tags -} - -// RegisterStructValidation registers a StructLevelFunc against a number of types. -// -// NOTE: -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{}) { - v.RegisterStructValidationCtx(wrapStructLevelFunc(fn), types...) -} - -// RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing -// of contextual validation information via context.Context. -// -// NOTE: -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) { - - if v.structLevelFuncs == nil { - v.structLevelFuncs = make(map[reflect.Type]StructLevelFuncCtx) - } - - for _, t := range types { - tv := reflect.ValueOf(t) - if tv.Kind() == reflect.Ptr { - t = reflect.Indirect(tv).Interface() - } - - v.structLevelFuncs[reflect.TypeOf(t)] = fn - } -} - -// RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types -// -// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { - - if v.customFuncs == nil { - v.customFuncs = make(map[reflect.Type]CustomTypeFunc) - } - - for _, t := range types { - v.customFuncs[reflect.TypeOf(t)] = fn - } - - v.hasCustomFuncs = true -} - -// RegisterTranslation registers translations against the provided tag. -func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) { - - if v.transTagFunc == nil { - v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc) - } - - if err = registerFn(trans); err != nil { - return - } - - m, ok := v.transTagFunc[trans] - if !ok { - m = make(map[string]TranslationFunc) - v.transTagFunc[trans] = m - } - - m[tag] = translationFn - - return -} - -// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) Struct(s interface{}) error { - return v.StructCtx(context.Background(), s) -} - -// StructCtx validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified -// and also allows passing of context.Context for contextual validation information. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error) { - - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = false - // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept - - vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructFiltered validates a structs exposed fields, that pass the FilterFunc check and automatically validates -// nested structs, unless otherwise specified. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error { - return v.StructFilteredCtx(context.Background(), s, fn) -} - -// StructFilteredCtx validates a structs exposed fields, that pass the FilterFunc check and automatically validates -// nested structs, unless otherwise specified and also allows passing of contextual validation information via -// context.Context -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = fn - // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept - - vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructPartial validates the fields passed in only, ignoring all others. -// Fields may be provided in a namespaced fashion relative to the struct provided -// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructPartial(s interface{}, fields ...string) error { - return v.StructPartialCtx(context.Background(), s, fields...) -} - -// StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual -// validation validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided -// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = nil - vd.hasExcludes = false - vd.includeExclude = make(map[string]struct{}) - - typ := val.Type() - name := typ.Name() - - for _, k := range fields { - - flds := strings.Split(k, namespaceSeparator) - if len(flds) > 0 { - - vd.misc = append(vd.misc[0:0], name...) - vd.misc = append(vd.misc, '.') - - for _, s := range flds { - - idx := strings.Index(s, leftBracket) - - if idx != -1 { - for idx != -1 { - vd.misc = append(vd.misc, s[:idx]...) - vd.includeExclude[string(vd.misc)] = struct{}{} - - idx2 := strings.Index(s, rightBracket) - idx2++ - vd.misc = append(vd.misc, s[idx:idx2]...) - vd.includeExclude[string(vd.misc)] = struct{}{} - s = s[idx2:] - idx = strings.Index(s, leftBracket) - } - } else { - - vd.misc = append(vd.misc, s...) - vd.includeExclude[string(vd.misc)] = struct{}{} - } - - vd.misc = append(vd.misc, '.') - } - } - } - - vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructExcept validates all fields except the ones passed in. -// Fields may be provided in a namespaced fashion relative to the struct provided -// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructExcept(s interface{}, fields ...string) error { - return v.StructExceptCtx(context.Background(), s, fields...) -} - -// StructExceptCtx validates all fields except the ones passed in and allows passing of contextual -// validation validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided -// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type() == timeType { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = nil - vd.hasExcludes = true - vd.includeExclude = make(map[string]struct{}) - - typ := val.Type() - name := typ.Name() - - for _, key := range fields { - - vd.misc = vd.misc[0:0] - - if len(name) > 0 { - vd.misc = append(vd.misc, name...) - vd.misc = append(vd.misc, '.') - } - - vd.misc = append(vd.misc, key...) - vd.includeExclude[string(vd.misc)] = struct{}{} - } - - vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// Var validates a single variable using tag style validation. -// eg. -// var i int -// validate.Var(i, "gt=1,lt=10") -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) Var(field interface{}, tag string) error { - return v.VarCtx(context.Background(), field, tag) -} - -// VarCtx validates a single variable using tag style validation and allows passing of contextual -// validation validation information via context.Context. -// eg. -// var i int -// validate.Var(i, "gt=1,lt=10") -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) (err error) { - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - - ctag := v.fetchCacheTag(tag) - val := reflect.ValueOf(field) - vd := v.pool.Get().(*validate) - vd.top = val - vd.isPartial = false - vd.traverseField(ctx, val, val, vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - v.pool.Put(vd) - return -} - -// VarWithValue validates a single variable, against another variable/field's value using tag style validation -// eg. -// s1 := "abcd" -// s2 := "abcd" -// validate.VarWithValue(s1, s2, "eqcsfield") // returns true -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error { - return v.VarWithValueCtx(context.Background(), field, other, tag) -} - -// VarWithValueCtx validates a single variable, against another variable/field's value using tag style validation and -// allows passing of contextual validation validation information via context.Context. -// eg. -// s1 := "abcd" -// s2 := "abcd" -// validate.VarWithValue(s1, s2, "eqcsfield") // returns true -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error) { - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - ctag := v.fetchCacheTag(tag) - otherVal := reflect.ValueOf(other) - vd := v.pool.Get().(*validate) - vd.top = otherVal - vd.isPartial = false - vd.traverseField(ctx, otherVal, reflect.ValueOf(field), vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - v.pool.Put(vd) - return -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/.gitignore b/taskman-server/vendor/github.com/go-sql-driver/mysql/.gitignore deleted file mode 100644 index 2de28da1..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -.DS_Store -.DS_Store? -._* -.Spotlight-V100 -.Trashes -Icon? -ehthumbs.db -Thumbs.db -.idea diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/AUTHORS b/taskman-server/vendor/github.com/go-sql-driver/mysql/AUTHORS deleted file mode 100644 index 50afa2c8..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/AUTHORS +++ /dev/null @@ -1,117 +0,0 @@ -# This is the official list of Go-MySQL-Driver authors for copyright purposes. - -# If you are submitting a patch, please add your name or the name of the -# organization which holds the copyright to this list in alphabetical order. - -# Names should be added to this file as -# Name -# The email address is not required for organizations. -# Please keep the list sorted. - - -# Individual Persons - -Aaron Hopkins -Achille Roussel -Alex Snast -Alexey Palazhchenko -Andrew Reid -Animesh Ray -Arne Hormann -Ariel Mashraki -Asta Xie -Bulat Gaifullin -Caine Jette -Carlos Nieto -Chris Moos -Craig Wilson -Daniel Montoya -Daniel Nichter -Daniël van Eeden -Dave Protasowski -DisposaBoy -Egor Smolyakov -Erwan Martin -Evan Shaw -Frederick Mayle -Gustavo Kristic -Hajime Nakagami -Hanno Braun -Henri Yandell -Hirotaka Yamamoto -Huyiguang -ICHINOSE Shogo -Ilia Cimpoes -INADA Naoki -Jacek Szwec -James Harr -Jeff Hodges -Jeffrey Charles -Jerome Meyer -Jiajia Zhong -Jian Zhen -Joshua Prunier -Julien Lefevre -Julien Schmidt -Justin Li -Justin Nuß -Kamil Dziedzic -Kei Kamikawa -Kevin Malachowski -Kieron Woodhouse -Lennart Rudolph -Leonardo YongUk Kim -Linh Tran Tuan -Lion Yang -Luca Looz -Lucas Liu -Luke Scott -Maciej Zimnoch -Michael Woolnough -Nathanial Murphy -Nicola Peduzzi -Olivier Mengué -oscarzhao -Paul Bonser -Peter Schultz -Rebecca Chin -Reed Allman -Richard Wilkes -Robert Russell -Runrioter Wung -Sho Iizuka -Sho Ikeda -Shuode Li -Simon J Mudd -Soroush Pour -Stan Putrya -Stanley Gunawan -Steven Hartland -Tan Jinhua <312841925 at qq.com> -Thomas Wodarek -Tim Ruffles -Tom Jenkinson -Vladimir Kovpak -Vladyslav Zhelezniak -Xiangyu Hu -Xiaobing Jiang -Xiuming Chen -Xuehong Chan -Zhenye Xie -Zhixin Wen - -# Organizations - -Barracuda Networks, Inc. -Counting Ltd. -DigitalOcean Inc. -Facebook Inc. -GitHub Inc. -Google Inc. -InfoSum Ltd. -Keybase Inc. -Multiplay Ltd. -Percona LLC -Pivotal Inc. -Stripe Inc. -Zendesk Inc. diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md b/taskman-server/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md deleted file mode 100644 index 72a738ed..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md +++ /dev/null @@ -1,232 +0,0 @@ -## Version 1.6 (2021-04-01) - -Changes: - - - Migrate the CI service from travis-ci to GitHub Actions (#1176, #1183, #1190) - - `NullTime` is deprecated (#960, #1144) - - Reduce allocations when building SET command (#1111) - - Performance improvement for time formatting (#1118) - - Performance improvement for time parsing (#1098, #1113) - -New Features: - - - Implement `driver.Validator` interface (#1106, #1174) - - Support returning `uint64` from `Valuer` in `ConvertValue` (#1143) - - Add `json.RawMessage` for converter and prepared statement (#1059) - - Interpolate `json.RawMessage` as `string` (#1058) - - Implements `CheckNamedValue` (#1090) - -Bugfixes: - - - Stop rounding times (#1121, #1172) - - Put zero filler into the SSL handshake packet (#1066) - - Fix checking cancelled connections back into the connection pool (#1095) - - Fix remove last 0 byte for mysql_old_password when password is empty (#1133) - - -## Version 1.5 (2020-01-07) - -Changes: - - - Dropped support Go 1.9 and lower (#823, #829, #886, #1016, #1017) - - Improve buffer handling (#890) - - Document potentially insecure TLS configs (#901) - - Use a double-buffering scheme to prevent data races (#943) - - Pass uint64 values without converting them to string (#838, #955) - - Update collations and make utf8mb4 default (#877, #1054) - - Make NullTime compatible with sql.NullTime in Go 1.13+ (#995) - - Removed CloudSQL support (#993, #1007) - - Add Go Module support (#1003) - -New Features: - - - Implement support of optional TLS (#900) - - Check connection liveness (#934, #964, #997, #1048, #1051, #1052) - - Implement Connector Interface (#941, #958, #1020, #1035) - -Bugfixes: - - - Mark connections as bad on error during ping (#875) - - Mark connections as bad on error during dial (#867) - - Fix connection leak caused by rapid context cancellation (#1024) - - Mark connections as bad on error during Conn.Prepare (#1030) - - -## Version 1.4.1 (2018-11-14) - -Bugfixes: - - - Fix TIME format for binary columns (#818) - - Fix handling of empty auth plugin names (#835) - - Fix caching_sha2_password with empty password (#826) - - Fix canceled context broke mysqlConn (#862) - - Fix OldAuthSwitchRequest support (#870) - - Fix Auth Response packet for cleartext password (#887) - -## Version 1.4 (2018-06-03) - -Changes: - - - Documentation fixes (#530, #535, #567) - - Refactoring (#575, #579, #580, #581, #603, #615, #704) - - Cache column names (#444) - - Sort the DSN parameters in DSNs generated from a config (#637) - - Allow native password authentication by default (#644) - - Use the default port if it is missing in the DSN (#668) - - Removed the `strict` mode (#676) - - Do not query `max_allowed_packet` by default (#680) - - Dropped support Go 1.6 and lower (#696) - - Updated `ConvertValue()` to match the database/sql/driver implementation (#760) - - Document the usage of `0000-00-00T00:00:00` as the time.Time zero value (#783) - - Improved the compatibility of the authentication system (#807) - -New Features: - - - Multi-Results support (#537) - - `rejectReadOnly` DSN option (#604) - - `context.Context` support (#608, #612, #627, #761) - - Transaction isolation level support (#619, #744) - - Read-Only transactions support (#618, #634) - - `NewConfig` function which initializes a config with default values (#679) - - Implemented the `ColumnType` interfaces (#667, #724) - - Support for custom string types in `ConvertValue` (#623) - - Implemented `NamedValueChecker`, improving support for uint64 with high bit set (#690, #709, #710) - - `caching_sha2_password` authentication plugin support (#794, #800, #801, #802) - - Implemented `driver.SessionResetter` (#779) - - `sha256_password` authentication plugin support (#808) - -Bugfixes: - - - Use the DSN hostname as TLS default ServerName if `tls=true` (#564, #718) - - Fixed LOAD LOCAL DATA INFILE for empty files (#590) - - Removed columns definition cache since it sometimes cached invalid data (#592) - - Don't mutate registered TLS configs (#600) - - Make RegisterTLSConfig concurrency-safe (#613) - - Handle missing auth data in the handshake packet correctly (#646) - - Do not retry queries when data was written to avoid data corruption (#302, #736) - - Cache the connection pointer for error handling before invalidating it (#678) - - Fixed imports for appengine/cloudsql (#700) - - Fix sending STMT_LONG_DATA for 0 byte data (#734) - - Set correct capacity for []bytes read from length-encoded strings (#766) - - Make RegisterDial concurrency-safe (#773) - - -## Version 1.3 (2016-12-01) - -Changes: - - - Go 1.1 is no longer supported - - Use decimals fields in MySQL to format time types (#249) - - Buffer optimizations (#269) - - TLS ServerName defaults to the host (#283) - - Refactoring (#400, #410, #437) - - Adjusted documentation for second generation CloudSQL (#485) - - Documented DSN system var quoting rules (#502) - - Made statement.Close() calls idempotent to avoid errors in Go 1.6+ (#512) - -New Features: - - - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249) - - Support for returning table alias on Columns() (#289, #359, #382) - - Placeholder interpolation, can be actived with the DSN parameter `interpolateParams=true` (#309, #318, #490) - - Support for uint64 parameters with high bit set (#332, #345) - - Cleartext authentication plugin support (#327) - - Exported ParseDSN function and the Config struct (#403, #419, #429) - - Read / Write timeouts (#401) - - Support for JSON field type (#414) - - Support for multi-statements and multi-results (#411, #431) - - DSN parameter to set the driver-side max_allowed_packet value manually (#489) - - Native password authentication plugin support (#494, #524) - -Bugfixes: - - - Fixed handling of queries without columns and rows (#255) - - Fixed a panic when SetKeepAlive() failed (#298) - - Handle ERR packets while reading rows (#321) - - Fixed reading NULL length-encoded integers in MySQL 5.6+ (#349) - - Fixed absolute paths support in LOAD LOCAL DATA INFILE (#356) - - Actually zero out bytes in handshake response (#378) - - Fixed race condition in registering LOAD DATA INFILE handler (#383) - - Fixed tests with MySQL 5.7.9+ (#380) - - QueryUnescape TLS config names (#397) - - Fixed "broken pipe" error by writing to closed socket (#390) - - Fixed LOAD LOCAL DATA INFILE buffering (#424) - - Fixed parsing of floats into float64 when placeholders are used (#434) - - Fixed DSN tests with Go 1.7+ (#459) - - Handle ERR packets while waiting for EOF (#473) - - Invalidate connection on error while discarding additional results (#513) - - Allow terminating packets of length 0 (#516) - - -## Version 1.2 (2014-06-03) - -Changes: - - - We switched back to a "rolling release". `go get` installs the current master branch again - - Version v1 of the driver will not be maintained anymore. Go 1.0 is no longer supported by this driver - - Exported errors to allow easy checking from application code - - Enabled TCP Keepalives on TCP connections - - Optimized INFILE handling (better buffer size calculation, lazy init, ...) - - The DSN parser also checks for a missing separating slash - - Faster binary date / datetime to string formatting - - Also exported the MySQLWarning type - - mysqlConn.Close returns the first error encountered instead of ignoring all errors - - writePacket() automatically writes the packet size to the header - - readPacket() uses an iterative approach instead of the recursive approach to merge splitted packets - -New Features: - - - `RegisterDial` allows the usage of a custom dial function to establish the network connection - - Setting the connection collation is possible with the `collation` DSN parameter. This parameter should be preferred over the `charset` parameter - - Logging of critical errors is configurable with `SetLogger` - - Google CloudSQL support - -Bugfixes: - - - Allow more than 32 parameters in prepared statements - - Various old_password fixes - - Fixed TestConcurrent test to pass Go's race detection - - Fixed appendLengthEncodedInteger for large numbers - - Renamed readLengthEnodedString to readLengthEncodedString and skipLengthEnodedString to skipLengthEncodedString (fixed typo) - - -## Version 1.1 (2013-11-02) - -Changes: - - - Go-MySQL-Driver now requires Go 1.1 - - Connections now use the collation `utf8_general_ci` by default. Adding `&charset=UTF8` to the DSN should not be necessary anymore - - Made closing rows and connections error tolerant. This allows for example deferring rows.Close() without checking for errors - - `[]byte(nil)` is now treated as a NULL value. Before, it was treated like an empty string / `[]byte("")` - - DSN parameter values must now be url.QueryEscape'ed. This allows text values to contain special characters, such as '&'. - - Use the IO buffer also for writing. This results in zero allocations (by the driver) for most queries - - Optimized the buffer for reading - - stmt.Query now caches column metadata - - New Logo - - Changed the copyright header to include all contributors - - Improved the LOAD INFILE documentation - - The driver struct is now exported to make the driver directly accessible - - Refactored the driver tests - - Added more benchmarks and moved all to a separate file - - Other small refactoring - -New Features: - - - Added *old_passwords* support: Required in some cases, but must be enabled by adding `allowOldPasswords=true` to the DSN since it is insecure - - Added a `clientFoundRows` parameter: Return the number of matching rows instead of the number of rows changed on UPDATEs - - Added TLS/SSL support: Use a TLS/SSL encrypted connection to the server. Custom TLS configs can be registered and used - -Bugfixes: - - - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification - - Convert to DB timezone when inserting `time.Time` - - Splitted packets (more than 16MB) are now merged correctly - - Fixed false positive `io.EOF` errors when the data was fully read - - Avoid panics on reuse of closed connections - - Fixed empty string producing false nil values - - Fixed sign byte for positive TIME fields - - -## Version 1.0 (2013-05-14) - -Initial Release diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/LICENSE b/taskman-server/vendor/github.com/go-sql-driver/mysql/LICENSE deleted file mode 100644 index 14e2f777..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/README.md b/taskman-server/vendor/github.com/go-sql-driver/mysql/README.md deleted file mode 100644 index 0b13154f..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/README.md +++ /dev/null @@ -1,520 +0,0 @@ -# Go-MySQL-Driver - -A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) package - -![Go-MySQL-Driver logo](https://raw.github.com/wiki/go-sql-driver/mysql/gomysql_m.png "Golang Gopher holding the MySQL Dolphin") - ---------------------------------------- - * [Features](#features) - * [Requirements](#requirements) - * [Installation](#installation) - * [Usage](#usage) - * [DSN (Data Source Name)](#dsn-data-source-name) - * [Password](#password) - * [Protocol](#protocol) - * [Address](#address) - * [Parameters](#parameters) - * [Examples](#examples) - * [Connection pool and timeouts](#connection-pool-and-timeouts) - * [context.Context Support](#contextcontext-support) - * [ColumnType Support](#columntype-support) - * [LOAD DATA LOCAL INFILE support](#load-data-local-infile-support) - * [time.Time support](#timetime-support) - * [Unicode support](#unicode-support) - * [Testing / Development](#testing--development) - * [License](#license) - ---------------------------------------- - -## Features - * Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance") - * Native Go implementation. No C-bindings, just pure Go - * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](https://godoc.org/github.com/go-sql-driver/mysql#DialFunc) - * Automatic handling of broken connections - * Automatic Connection Pooling *(by database/sql package)* - * Supports queries larger than 16MB - * Full [`sql.RawBytes`](https://golang.org/pkg/database/sql/#RawBytes) support. - * Intelligent `LONG DATA` handling in prepared statements - * Secure `LOAD DATA LOCAL INFILE` support with file allowlisting and `io.Reader` support - * Optional `time.Time` parsing - * Optional placeholder interpolation - -## Requirements - * Go 1.10 or higher. We aim to support the 3 latest versions of Go. - * MySQL (4.1+), MariaDB, Percona Server, Google CloudSQL or Sphinx (2.2.3+) - ---------------------------------------- - -## Installation -Simple install the package to your [$GOPATH](https://github.com/golang/go/wiki/GOPATH "GOPATH") with the [go tool](https://golang.org/cmd/go/ "go command") from shell: -```bash -$ go get -u github.com/go-sql-driver/mysql -``` -Make sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`. - -## Usage -_Go MySQL Driver_ is an implementation of Go's `database/sql/driver` interface. You only need to import the driver and can use the full [`database/sql`](https://golang.org/pkg/database/sql/) API then. - -Use `mysql` as `driverName` and a valid [DSN](#dsn-data-source-name) as `dataSourceName`: - -```go -import ( - "database/sql" - "time" - - _ "github.com/go-sql-driver/mysql" -) - -// ... - -db, err := sql.Open("mysql", "user:password@/dbname") -if err != nil { - panic(err) -} -// See "Important settings" section. -db.SetConnMaxLifetime(time.Minute * 3) -db.SetMaxOpenConns(10) -db.SetMaxIdleConns(10) -``` - -[Examples are available in our Wiki](https://github.com/go-sql-driver/mysql/wiki/Examples "Go-MySQL-Driver Examples"). - -### Important settings - -`db.SetConnMaxLifetime()` is required to ensure connections are closed by the driver safely before connection is closed by MySQL server, OS, or other middlewares. Since some middlewares close idle connections by 5 minutes, we recommend timeout shorter than 5 minutes. This setting helps load balancing and changing system variables too. - -`db.SetMaxOpenConns()` is highly recommended to limit the number of connection used by the application. There is no recommended limit number because it depends on application and MySQL server. - -`db.SetMaxIdleConns()` is recommended to be set same to (or greater than) `db.SetMaxOpenConns()`. When it is smaller than `SetMaxOpenConns()`, connections can be opened and closed very frequently than you expect. Idle connections can be closed by the `db.SetConnMaxLifetime()`. If you want to close idle connections more rapidly, you can use `db.SetConnMaxIdleTime()` since Go 1.15. - - -### DSN (Data Source Name) - -The Data Source Name has a common format, like e.g. [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php) uses it, but without type-prefix (optional parts marked by squared brackets): -``` -[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN] -``` - -A DSN in its fullest form: -``` -username:password@protocol(address)/dbname?param=value -``` - -Except for the databasename, all values are optional. So the minimal DSN is: -``` -/dbname -``` - -If you do not want to preselect a database, leave `dbname` empty: -``` -/ -``` -This has the same effect as an empty DSN string: -``` - -``` - -Alternatively, [Config.FormatDSN](https://godoc.org/github.com/go-sql-driver/mysql#Config.FormatDSN) can be used to create a DSN string by filling a struct. - -#### Password -Passwords can consist of any character. Escaping is **not** necessary. - -#### Protocol -See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available. -In general you should use an Unix domain socket if available and TCP otherwise for best performance. - -#### Address -For TCP and UDP networks, addresses have the form `host[:port]`. -If `port` is omitted, the default port will be used. -If `host` is a literal IPv6 address, it must be enclosed in square brackets. -The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form. - -For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. `/var/run/mysqld/mysqld.sock` or `/tmp/mysql.sock`. - -#### Parameters -*Parameters are case-sensitive!* - -Notice that any of `true`, `TRUE`, `True` or `1` is accepted to stand for a true boolean value. Not surprisingly, false can be specified as any of: `false`, `FALSE`, `False` or `0`. - -##### `allowAllFiles` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`allowAllFiles=true` disables the file allowlist for `LOAD DATA LOCAL INFILE` and allows *all* files. -[*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html) - -##### `allowCleartextPasswords` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`allowCleartextPasswords=true` allows using the [cleartext client side plugin](https://dev.mysql.com/doc/en/cleartext-pluggable-authentication.html) if required by an account, such as one defined with the [PAM authentication plugin](http://dev.mysql.com/doc/en/pam-authentication-plugin.html). Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include [TLS / SSL](#tls), IPsec, or a private network. - -##### `allowNativePasswords` - -``` -Type: bool -Valid Values: true, false -Default: true -``` -`allowNativePasswords=false` disallows the usage of MySQL native password method. - -##### `allowOldPasswords` - -``` -Type: bool -Valid Values: true, false -Default: false -``` -`allowOldPasswords=true` allows the usage of the insecure old password method. This should be avoided, but is necessary in some cases. See also [the old_passwords wiki page](https://github.com/go-sql-driver/mysql/wiki/old_passwords). - -##### `charset` - -``` -Type: string -Valid Values: -Default: none -``` - -Sets the charset used for client-server interaction (`"SET NAMES "`). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset failes. This enables for example support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers (`charset=utf8mb4,utf8`). - -Usage of the `charset` parameter is discouraged because it issues additional queries to the server. -Unless you need the fallback behavior, please use `collation` instead. - -##### `checkConnLiveness` - -``` -Type: bool -Valid Values: true, false -Default: true -``` - -On supported platforms connections retrieved from the connection pool are checked for liveness before using them. If the check fails, the respective connection is marked as bad and the query retried with another connection. -`checkConnLiveness=false` disables this liveness check of connections. - -##### `collation` - -``` -Type: string -Valid Values: -Default: utf8mb4_general_ci -``` - -Sets the collation used for client-server interaction on connection. In contrast to `charset`, `collation` does not issue additional queries. If the specified collation is unavailable on the target server, the connection will fail. - -A list of valid charsets for a server is retrievable with `SHOW COLLATION`. - -The default collation (`utf8mb4_general_ci`) is supported from MySQL 5.5. You should use an older collation (e.g. `utf8_general_ci`) for older MySQL. - -Collations for charset "ucs2", "utf16", "utf16le", and "utf32" can not be used ([ref](https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset)). - - -##### `clientFoundRows` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`clientFoundRows=true` causes an UPDATE to return the number of matching rows instead of the number of rows changed. - -##### `columnsWithAlias` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -When `columnsWithAlias` is true, calls to `sql.Rows.Columns()` will return the table alias and the column name separated by a dot. For example: - -``` -SELECT u.id FROM users as u -``` - -will return `u.id` instead of just `id` if `columnsWithAlias=true`. - -##### `interpolateParams` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -If `interpolateParams` is true, placeholders (`?`) in calls to `db.Query()` and `db.Exec()` are interpolated into a single query string with given parameters. This reduces the number of roundtrips, since the driver has to prepare a statement, execute it with given parameters and close the statement again with `interpolateParams=false`. - -*This can not be used together with the multibyte encodings BIG5, CP932, GB2312, GBK or SJIS. These are rejected as they may [introduce a SQL injection vulnerability](http://stackoverflow.com/a/12118602/3430118)!* - -##### `loc` - -``` -Type: string -Valid Values: -Default: UTC -``` - -Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](https://golang.org/pkg/time/#LoadLocation) for details. - -Note that this sets the location for time.Time values but does not change MySQL's [time_zone setting](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html). For that see the [time_zone system variable](#system-variables), which can also be set as a DSN parameter. - -Please keep in mind, that param values must be [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`. - -##### `maxAllowedPacket` -``` -Type: decimal number -Default: 4194304 -``` - -Max packet size allowed in bytes. The default value is 4 MiB and should be adjusted to match the server settings. `maxAllowedPacket=0` can be used to automatically fetch the `max_allowed_packet` variable from server *on every connection*. - -##### `multiStatements` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -Allow multiple statements in one query. While this allows batch queries, it also greatly increases the risk of SQL injections. Only the result of the first query is returned, all other results are silently discarded. - -When `multiStatements` is used, `?` parameters must only be used in the first statement. - -##### `parseTime` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - -`parseTime=true` changes the output type of `DATE` and `DATETIME` values to `time.Time` instead of `[]byte` / `string` -The date or datetime like `0000-00-00 00:00:00` is converted into zero value of `time.Time`. - - -##### `readTimeout` - -``` -Type: duration -Default: 0 -``` - -I/O read timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - -##### `rejectReadOnly` - -``` -Type: bool -Valid Values: true, false -Default: false -``` - - -`rejectReadOnly=true` causes the driver to reject read-only connections. This -is for a possible race condition during an automatic failover, where the mysql -client gets connected to a read-only replica after the failover. - -Note that this should be a fairly rare case, as an automatic failover normally -happens when the primary is down, and the race condition shouldn't happen -unless it comes back up online as soon as the failover is kicked off. On the -other hand, when this happens, a MySQL application can get stuck on a -read-only connection until restarted. It is however fairly easy to reproduce, -for example, using a manual failover on AWS Aurora's MySQL-compatible cluster. - -If you are not relying on read-only transactions to reject writes that aren't -supposed to happen, setting this on some MySQL providers (such as AWS Aurora) -is safer for failovers. - -Note that ERROR 1290 can be returned for a `read-only` server and this option will -cause a retry for that error. However the same error number is used for some -other cases. You should ensure your application will never cause an ERROR 1290 -except for `read-only` mode when enabling this option. - - -##### `serverPubKey` - -``` -Type: string -Valid Values: -Default: none -``` - -Server public keys can be registered with [`mysql.RegisterServerPubKey`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterServerPubKey), which can then be used by the assigned name in the DSN. -Public keys are used to transmit encrypted data, e.g. for authentication. -If the server's public key is known, it should be set manually to avoid expensive and potentially insecure transmissions of the public key from the server to the client each time it is required. - - -##### `timeout` - -``` -Type: duration -Default: OS default -``` - -Timeout for establishing connections, aka dial timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - - -##### `tls` - -``` -Type: bool / string -Valid Values: true, false, skip-verify, preferred, -Default: false -``` - -`tls=true` enables TLS / SSL encrypted connection to the server. Use `skip-verify` if you want to use a self-signed or invalid certificate (server side) or use `preferred` to use TLS only when advertised by the server. This is similar to `skip-verify`, but additionally allows a fallback to a connection which is not encrypted. Neither `skip-verify` nor `preferred` add any reliable security. You can use a custom TLS config after registering it with [`mysql.RegisterTLSConfig`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterTLSConfig). - - -##### `writeTimeout` - -``` -Type: duration -Default: 0 -``` - -I/O write timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. - - -##### System Variables - -Any other parameters are interpreted as system variables: - * `=`: `SET =` - * `=`: `SET =` - * `=%27%27`: `SET =''` - -Rules: -* The values for string variables must be quoted with `'`. -* The values must also be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed! - (which implies values of string variables must be wrapped with `%27`). - -Examples: - * `autocommit=1`: `SET autocommit=1` - * [`time_zone=%27Europe%2FParis%27`](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html): `SET time_zone='Europe/Paris'` - * [`transaction_isolation=%27REPEATABLE-READ%27`](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_transaction_isolation): `SET transaction_isolation='REPEATABLE-READ'` - - -#### Examples -``` -user@unix(/path/to/socket)/dbname -``` - -``` -root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local -``` - -``` -user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true -``` - -Treat warnings as errors by setting the system variable [`sql_mode`](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html): -``` -user:password@/dbname?sql_mode=TRADITIONAL -``` - -TCP via IPv6: -``` -user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci -``` - -TCP on a remote host, e.g. Amazon RDS: -``` -id:password@tcp(your-amazonaws-uri.com:3306)/dbname -``` - -Google Cloud SQL on App Engine: -``` -user:password@unix(/cloudsql/project-id:region-name:instance-name)/dbname -``` - -TCP using default port (3306) on localhost: -``` -user:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped -``` - -Use the default protocol (tcp) and host (localhost:3306): -``` -user:password@/dbname -``` - -No Database preselected: -``` -user:password@/ -``` - - -### Connection pool and timeouts -The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see `*DB.SetMaxOpenConns`, `*DB.SetMaxIdleConns`, and `*DB.SetConnMaxLifetime` in the [database/sql documentation](https://golang.org/pkg/database/sql/). The read, write, and dial timeouts for each individual connection are configured with the DSN parameters [`readTimeout`](#readtimeout), [`writeTimeout`](#writetimeout), and [`timeout`](#timeout), respectively. - -## `ColumnType` Support -This driver supports the [`ColumnType` interface](https://golang.org/pkg/database/sql/#ColumnType) introduced in Go 1.8, with the exception of [`ColumnType.Length()`](https://golang.org/pkg/database/sql/#ColumnType.Length), which is currently not supported. - -## `context.Context` Support -Go 1.8 added `database/sql` support for `context.Context`. This driver supports query timeouts and cancellation via contexts. -See [context support in the database/sql package](https://golang.org/doc/go1.8#database_sql) for more details. - - -### `LOAD DATA LOCAL INFILE` support -For this feature you need direct access to the package. Therefore you must change the import path (no `_`): -```go -import "github.com/go-sql-driver/mysql" -``` - -Files must be explicitly allowed by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the allowlist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html)). - -To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore. - -See the [godoc of Go-MySQL-Driver](https://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details. - - -### `time.Time` support -The default internal output type of MySQL `DATE` and `DATETIME` values is `[]byte` which allows you to scan the value into a `[]byte`, `string` or `sql.RawBytes` variable in your program. - -However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` variables, which is the logical equivalent in Go to `DATE` and `DATETIME` in MySQL. You can do that by changing the internal output type from `[]byte` to `time.Time` with the DSN parameter `parseTime=true`. You can set the default [`time.Time` location](https://golang.org/pkg/time/#Location) with the `loc` DSN parameter. - -**Caution:** As of Go 1.1, this makes `time.Time` the only variable type you can scan `DATE` and `DATETIME` values into. This breaks for example [`sql.RawBytes` support](https://github.com/go-sql-driver/mysql/wiki/Examples#rawbytes). - - -### Unicode support -Since version 1.5 Go-MySQL-Driver automatically uses the collation ` utf8mb4_general_ci` by default. - -Other collations / charsets can be set using the [`collation`](#collation) DSN parameter. - -Version 1.0 of the driver recommended adding `&charset=utf8` (alias for `SET NAMES utf8`) to the DSN to enable proper UTF-8 support. This is not necessary anymore. The [`collation`](#collation) parameter should be preferred to set another collation / charset than the default. - -See http://dev.mysql.com/doc/refman/8.0/en/charset-unicode.html for more details on MySQL's Unicode support. - -## Testing / Development -To run the driver tests you may need to adjust the configuration. See the [Testing Wiki-Page](https://github.com/go-sql-driver/mysql/wiki/Testing "Testing") for details. - -Go-MySQL-Driver is not feature-complete yet. Your help is very appreciated. -If you want to contribute, you can work on an [open issue](https://github.com/go-sql-driver/mysql/issues?state=open) or review a [pull request](https://github.com/go-sql-driver/mysql/pulls). - -See the [Contribution Guidelines](https://github.com/go-sql-driver/mysql/blob/master/.github/CONTRIBUTING.md) for details. - ---------------------------------------- - -## License -Go-MySQL-Driver is licensed under the [Mozilla Public License Version 2.0](https://raw.github.com/go-sql-driver/mysql/master/LICENSE) - -Mozilla summarizes the license scope as follows: -> MPL: The copyleft applies to any files containing MPLed code. - - -That means: - * You can **use** the **unchanged** source code both in private and commercially. - * When distributing, you **must publish** the source code of any **changed files** licensed under the MPL 2.0 under a) the MPL 2.0 itself or b) a compatible license (e.g. GPL 3.0 or Apache License 2.0). - * You **needn't publish** the source code of your library as long as the files licensed under the MPL 2.0 are **unchanged**. - -Please read the [MPL 2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) if you have further questions regarding the license. - -You can read the full terms here: [LICENSE](https://raw.github.com/go-sql-driver/mysql/master/LICENSE). - -![Go Gopher and MySQL Dolphin](https://raw.github.com/wiki/go-sql-driver/mysql/go-mysql-driver_m.jpg "Golang Gopher transporting the MySQL Dolphin in a wheelbarrow") diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/auth.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/auth.go deleted file mode 100644 index b2f19e8f..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/auth.go +++ /dev/null @@ -1,425 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - "crypto/x509" - "encoding/pem" - "fmt" - "sync" -) - -// server pub keys registry -var ( - serverPubKeyLock sync.RWMutex - serverPubKeyRegistry map[string]*rsa.PublicKey -) - -// RegisterServerPubKey registers a server RSA public key which can be used to -// send data in a secure manner to the server without receiving the public key -// in a potentially insecure way from the server first. -// Registered keys can afterwards be used adding serverPubKey= to the DSN. -// -// Note: The provided rsa.PublicKey instance is exclusively owned by the driver -// after registering it and may not be modified. -// -// data, err := ioutil.ReadFile("mykey.pem") -// if err != nil { -// log.Fatal(err) -// } -// -// block, _ := pem.Decode(data) -// if block == nil || block.Type != "PUBLIC KEY" { -// log.Fatal("failed to decode PEM block containing public key") -// } -// -// pub, err := x509.ParsePKIXPublicKey(block.Bytes) -// if err != nil { -// log.Fatal(err) -// } -// -// if rsaPubKey, ok := pub.(*rsa.PublicKey); ok { -// mysql.RegisterServerPubKey("mykey", rsaPubKey) -// } else { -// log.Fatal("not a RSA public key") -// } -// -func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) { - serverPubKeyLock.Lock() - if serverPubKeyRegistry == nil { - serverPubKeyRegistry = make(map[string]*rsa.PublicKey) - } - - serverPubKeyRegistry[name] = pubKey - serverPubKeyLock.Unlock() -} - -// DeregisterServerPubKey removes the public key registered with the given name. -func DeregisterServerPubKey(name string) { - serverPubKeyLock.Lock() - if serverPubKeyRegistry != nil { - delete(serverPubKeyRegistry, name) - } - serverPubKeyLock.Unlock() -} - -func getServerPubKey(name string) (pubKey *rsa.PublicKey) { - serverPubKeyLock.RLock() - if v, ok := serverPubKeyRegistry[name]; ok { - pubKey = v - } - serverPubKeyLock.RUnlock() - return -} - -// Hash password using pre 4.1 (old password) method -// https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c -type myRnd struct { - seed1, seed2 uint32 -} - -const myRndMaxVal = 0x3FFFFFFF - -// Pseudo random number generator -func newMyRnd(seed1, seed2 uint32) *myRnd { - return &myRnd{ - seed1: seed1 % myRndMaxVal, - seed2: seed2 % myRndMaxVal, - } -} - -// Tested to be equivalent to MariaDB's floating point variant -// http://play.golang.org/p/QHvhd4qved -// http://play.golang.org/p/RG0q4ElWDx -func (r *myRnd) NextByte() byte { - r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal - r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal - - return byte(uint64(r.seed1) * 31 / myRndMaxVal) -} - -// Generate binary hash from byte string using insecure pre 4.1 method -func pwHash(password []byte) (result [2]uint32) { - var add uint32 = 7 - var tmp uint32 - - result[0] = 1345345333 - result[1] = 0x12345671 - - for _, c := range password { - // skip spaces and tabs in password - if c == ' ' || c == '\t' { - continue - } - - tmp = uint32(c) - result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8) - result[1] += (result[1] << 8) ^ result[0] - add += tmp - } - - // Remove sign bit (1<<31)-1) - result[0] &= 0x7FFFFFFF - result[1] &= 0x7FFFFFFF - - return -} - -// Hash password using insecure pre 4.1 method -func scrambleOldPassword(scramble []byte, password string) []byte { - scramble = scramble[:8] - - hashPw := pwHash([]byte(password)) - hashSc := pwHash(scramble) - - r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1]) - - var out [8]byte - for i := range out { - out[i] = r.NextByte() + 64 - } - - mask := r.NextByte() - for i := range out { - out[i] ^= mask - } - - return out[:] -} - -// Hash password using 4.1+ method (SHA1) -func scramblePassword(scramble []byte, password string) []byte { - if len(password) == 0 { - return nil - } - - // stage1Hash = SHA1(password) - crypt := sha1.New() - crypt.Write([]byte(password)) - stage1 := crypt.Sum(nil) - - // scrambleHash = SHA1(scramble + SHA1(stage1Hash)) - // inner Hash - crypt.Reset() - crypt.Write(stage1) - hash := crypt.Sum(nil) - - // outer Hash - crypt.Reset() - crypt.Write(scramble) - crypt.Write(hash) - scramble = crypt.Sum(nil) - - // token = scrambleHash XOR stage1Hash - for i := range scramble { - scramble[i] ^= stage1[i] - } - return scramble -} - -// Hash password using MySQL 8+ method (SHA256) -func scrambleSHA256Password(scramble []byte, password string) []byte { - if len(password) == 0 { - return nil - } - - // XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble)) - - crypt := sha256.New() - crypt.Write([]byte(password)) - message1 := crypt.Sum(nil) - - crypt.Reset() - crypt.Write(message1) - message1Hash := crypt.Sum(nil) - - crypt.Reset() - crypt.Write(message1Hash) - crypt.Write(scramble) - message2 := crypt.Sum(nil) - - for i := range message1 { - message1[i] ^= message2[i] - } - - return message1 -} - -func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) { - plain := make([]byte, len(password)+1) - copy(plain, password) - for i := range plain { - j := i % len(seed) - plain[i] ^= seed[j] - } - sha1 := sha1.New() - return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil) -} - -func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error { - enc, err := encryptPassword(mc.cfg.Passwd, seed, pub) - if err != nil { - return err - } - return mc.writeAuthSwitchPacket(enc) -} - -func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) { - switch plugin { - case "caching_sha2_password": - authResp := scrambleSHA256Password(authData, mc.cfg.Passwd) - return authResp, nil - - case "mysql_old_password": - if !mc.cfg.AllowOldPasswords { - return nil, ErrOldPassword - } - if len(mc.cfg.Passwd) == 0 { - return nil, nil - } - // Note: there are edge cases where this should work but doesn't; - // this is currently "wontfix": - // https://github.com/go-sql-driver/mysql/issues/184 - authResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0) - return authResp, nil - - case "mysql_clear_password": - if !mc.cfg.AllowCleartextPasswords { - return nil, ErrCleartextPassword - } - // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html - // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html - return append([]byte(mc.cfg.Passwd), 0), nil - - case "mysql_native_password": - if !mc.cfg.AllowNativePasswords { - return nil, ErrNativePassword - } - // https://dev.mysql.com/doc/internals/en/secure-password-authentication.html - // Native password authentication only need and will need 20-byte challenge. - authResp := scramblePassword(authData[:20], mc.cfg.Passwd) - return authResp, nil - - case "sha256_password": - if len(mc.cfg.Passwd) == 0 { - return []byte{0}, nil - } - if mc.cfg.tls != nil || mc.cfg.Net == "unix" { - // write cleartext auth packet - return append([]byte(mc.cfg.Passwd), 0), nil - } - - pubKey := mc.cfg.pubKey - if pubKey == nil { - // request public key from server - return []byte{1}, nil - } - - // encrypted password - enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey) - return enc, err - - default: - errLog.Print("unknown auth plugin:", plugin) - return nil, ErrUnknownPlugin - } -} - -func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { - // Read Result Packet - authData, newPlugin, err := mc.readAuthResult() - if err != nil { - return err - } - - // handle auth plugin switch, if requested - if newPlugin != "" { - // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is - // sent and we have to keep using the cipher sent in the init packet. - if authData == nil { - authData = oldAuthData - } else { - // copy data from read buffer to owned slice - copy(oldAuthData, authData) - } - - plugin = newPlugin - - authResp, err := mc.auth(authData, plugin) - if err != nil { - return err - } - if err = mc.writeAuthSwitchPacket(authResp); err != nil { - return err - } - - // Read Result Packet - authData, newPlugin, err = mc.readAuthResult() - if err != nil { - return err - } - - // Do not allow to change the auth plugin more than once - if newPlugin != "" { - return ErrMalformPkt - } - } - - switch plugin { - - // https://insidemysql.com/preparing-your-community-connector-for-mysql-8-part-2-sha256/ - case "caching_sha2_password": - switch len(authData) { - case 0: - return nil // auth successful - case 1: - switch authData[0] { - case cachingSha2PasswordFastAuthSuccess: - if err = mc.readResultOK(); err == nil { - return nil // auth successful - } - - case cachingSha2PasswordPerformFullAuthentication: - if mc.cfg.tls != nil || mc.cfg.Net == "unix" { - // write cleartext auth packet - err = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0)) - if err != nil { - return err - } - } else { - pubKey := mc.cfg.pubKey - if pubKey == nil { - // request public key from server - data, err := mc.buf.takeSmallBuffer(4 + 1) - if err != nil { - return err - } - data[4] = cachingSha2PasswordRequestPublicKey - mc.writePacket(data) - - // parse public key - if data, err = mc.readPacket(); err != nil { - return err - } - - block, rest := pem.Decode(data[1:]) - if block == nil { - return fmt.Errorf("No Pem data found, data: %s", rest) - } - pkix, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return err - } - pubKey = pkix.(*rsa.PublicKey) - } - - // send encrypted password - err = mc.sendEncryptedPassword(oldAuthData, pubKey) - if err != nil { - return err - } - } - return mc.readResultOK() - - default: - return ErrMalformPkt - } - default: - return ErrMalformPkt - } - - case "sha256_password": - switch len(authData) { - case 0: - return nil // auth successful - default: - block, _ := pem.Decode(authData) - pub, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return err - } - - // send encrypted password - err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey)) - if err != nil { - return err - } - return mc.readResultOK() - } - - default: - return nil // auth successful - } - - return err -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/buffer.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/buffer.go deleted file mode 100644 index 0774c5c8..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/buffer.go +++ /dev/null @@ -1,182 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "io" - "net" - "time" -) - -const defaultBufSize = 4096 -const maxCachedBufSize = 256 * 1024 - -// A buffer which is used for both reading and writing. -// This is possible since communication on each connection is synchronous. -// In other words, we can't write and read simultaneously on the same connection. -// The buffer is similar to bufio.Reader / Writer but zero-copy-ish -// Also highly optimized for this particular use case. -// This buffer is backed by two byte slices in a double-buffering scheme -type buffer struct { - buf []byte // buf is a byte buffer who's length and capacity are equal. - nc net.Conn - idx int - length int - timeout time.Duration - dbuf [2][]byte // dbuf is an array with the two byte slices that back this buffer - flipcnt uint // flipccnt is the current buffer counter for double-buffering -} - -// newBuffer allocates and returns a new buffer. -func newBuffer(nc net.Conn) buffer { - fg := make([]byte, defaultBufSize) - return buffer{ - buf: fg, - nc: nc, - dbuf: [2][]byte{fg, nil}, - } -} - -// flip replaces the active buffer with the background buffer -// this is a delayed flip that simply increases the buffer counter; -// the actual flip will be performed the next time we call `buffer.fill` -func (b *buffer) flip() { - b.flipcnt += 1 -} - -// fill reads into the buffer until at least _need_ bytes are in it -func (b *buffer) fill(need int) error { - n := b.length - // fill data into its double-buffering target: if we've called - // flip on this buffer, we'll be copying to the background buffer, - // and then filling it with network data; otherwise we'll just move - // the contents of the current buffer to the front before filling it - dest := b.dbuf[b.flipcnt&1] - - // grow buffer if necessary to fit the whole packet. - if need > len(dest) { - // Round up to the next multiple of the default size - dest = make([]byte, ((need/defaultBufSize)+1)*defaultBufSize) - - // if the allocated buffer is not too large, move it to backing storage - // to prevent extra allocations on applications that perform large reads - if len(dest) <= maxCachedBufSize { - b.dbuf[b.flipcnt&1] = dest - } - } - - // if we're filling the fg buffer, move the existing data to the start of it. - // if we're filling the bg buffer, copy over the data - if n > 0 { - copy(dest[:n], b.buf[b.idx:]) - } - - b.buf = dest - b.idx = 0 - - for { - if b.timeout > 0 { - if err := b.nc.SetReadDeadline(time.Now().Add(b.timeout)); err != nil { - return err - } - } - - nn, err := b.nc.Read(b.buf[n:]) - n += nn - - switch err { - case nil: - if n < need { - continue - } - b.length = n - return nil - - case io.EOF: - if n >= need { - b.length = n - return nil - } - return io.ErrUnexpectedEOF - - default: - return err - } - } -} - -// returns next N bytes from buffer. -// The returned slice is only guaranteed to be valid until the next read -func (b *buffer) readNext(need int) ([]byte, error) { - if b.length < need { - // refill - if err := b.fill(need); err != nil { - return nil, err - } - } - - offset := b.idx - b.idx += need - b.length -= need - return b.buf[offset:b.idx], nil -} - -// takeBuffer returns a buffer with the requested size. -// If possible, a slice from the existing buffer is returned. -// Otherwise a bigger buffer is made. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeBuffer(length int) ([]byte, error) { - if b.length > 0 { - return nil, ErrBusyBuffer - } - - // test (cheap) general case first - if length <= cap(b.buf) { - return b.buf[:length], nil - } - - if length < maxPacketSize { - b.buf = make([]byte, length) - return b.buf, nil - } - - // buffer is larger than we want to store. - return make([]byte, length), nil -} - -// takeSmallBuffer is shortcut which can be used if length is -// known to be smaller than defaultBufSize. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeSmallBuffer(length int) ([]byte, error) { - if b.length > 0 { - return nil, ErrBusyBuffer - } - return b.buf[:length], nil -} - -// takeCompleteBuffer returns the complete existing buffer. -// This can be used if the necessary buffer size is unknown. -// cap and len of the returned buffer will be equal. -// Only one buffer (total) can be used at a time. -func (b *buffer) takeCompleteBuffer() ([]byte, error) { - if b.length > 0 { - return nil, ErrBusyBuffer - } - return b.buf, nil -} - -// store stores buf, an updated buffer, if its suitable to do so. -func (b *buffer) store(buf []byte) error { - if b.length > 0 { - return ErrBusyBuffer - } else if cap(buf) <= maxPacketSize && cap(buf) > cap(b.buf) { - b.buf = buf[:cap(buf)] - } - return nil -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/collations.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/collations.go deleted file mode 100644 index 326a9f7f..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/collations.go +++ /dev/null @@ -1,265 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2014 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -const defaultCollation = "utf8mb4_general_ci" -const binaryCollation = "binary" - -// A list of available collations mapped to the internal ID. -// To update this map use the following MySQL query: -// SELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS WHERE ID<256 ORDER BY ID -// -// Handshake packet have only 1 byte for collation_id. So we can't use collations with ID > 255. -// -// ucs2, utf16, and utf32 can't be used for connection charset. -// https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset -// They are commented out to reduce this map. -var collations = map[string]byte{ - "big5_chinese_ci": 1, - "latin2_czech_cs": 2, - "dec8_swedish_ci": 3, - "cp850_general_ci": 4, - "latin1_german1_ci": 5, - "hp8_english_ci": 6, - "koi8r_general_ci": 7, - "latin1_swedish_ci": 8, - "latin2_general_ci": 9, - "swe7_swedish_ci": 10, - "ascii_general_ci": 11, - "ujis_japanese_ci": 12, - "sjis_japanese_ci": 13, - "cp1251_bulgarian_ci": 14, - "latin1_danish_ci": 15, - "hebrew_general_ci": 16, - "tis620_thai_ci": 18, - "euckr_korean_ci": 19, - "latin7_estonian_cs": 20, - "latin2_hungarian_ci": 21, - "koi8u_general_ci": 22, - "cp1251_ukrainian_ci": 23, - "gb2312_chinese_ci": 24, - "greek_general_ci": 25, - "cp1250_general_ci": 26, - "latin2_croatian_ci": 27, - "gbk_chinese_ci": 28, - "cp1257_lithuanian_ci": 29, - "latin5_turkish_ci": 30, - "latin1_german2_ci": 31, - "armscii8_general_ci": 32, - "utf8_general_ci": 33, - "cp1250_czech_cs": 34, - //"ucs2_general_ci": 35, - "cp866_general_ci": 36, - "keybcs2_general_ci": 37, - "macce_general_ci": 38, - "macroman_general_ci": 39, - "cp852_general_ci": 40, - "latin7_general_ci": 41, - "latin7_general_cs": 42, - "macce_bin": 43, - "cp1250_croatian_ci": 44, - "utf8mb4_general_ci": 45, - "utf8mb4_bin": 46, - "latin1_bin": 47, - "latin1_general_ci": 48, - "latin1_general_cs": 49, - "cp1251_bin": 50, - "cp1251_general_ci": 51, - "cp1251_general_cs": 52, - "macroman_bin": 53, - //"utf16_general_ci": 54, - //"utf16_bin": 55, - //"utf16le_general_ci": 56, - "cp1256_general_ci": 57, - "cp1257_bin": 58, - "cp1257_general_ci": 59, - //"utf32_general_ci": 60, - //"utf32_bin": 61, - //"utf16le_bin": 62, - "binary": 63, - "armscii8_bin": 64, - "ascii_bin": 65, - "cp1250_bin": 66, - "cp1256_bin": 67, - "cp866_bin": 68, - "dec8_bin": 69, - "greek_bin": 70, - "hebrew_bin": 71, - "hp8_bin": 72, - "keybcs2_bin": 73, - "koi8r_bin": 74, - "koi8u_bin": 75, - "utf8_tolower_ci": 76, - "latin2_bin": 77, - "latin5_bin": 78, - "latin7_bin": 79, - "cp850_bin": 80, - "cp852_bin": 81, - "swe7_bin": 82, - "utf8_bin": 83, - "big5_bin": 84, - "euckr_bin": 85, - "gb2312_bin": 86, - "gbk_bin": 87, - "sjis_bin": 88, - "tis620_bin": 89, - //"ucs2_bin": 90, - "ujis_bin": 91, - "geostd8_general_ci": 92, - "geostd8_bin": 93, - "latin1_spanish_ci": 94, - "cp932_japanese_ci": 95, - "cp932_bin": 96, - "eucjpms_japanese_ci": 97, - "eucjpms_bin": 98, - "cp1250_polish_ci": 99, - //"utf16_unicode_ci": 101, - //"utf16_icelandic_ci": 102, - //"utf16_latvian_ci": 103, - //"utf16_romanian_ci": 104, - //"utf16_slovenian_ci": 105, - //"utf16_polish_ci": 106, - //"utf16_estonian_ci": 107, - //"utf16_spanish_ci": 108, - //"utf16_swedish_ci": 109, - //"utf16_turkish_ci": 110, - //"utf16_czech_ci": 111, - //"utf16_danish_ci": 112, - //"utf16_lithuanian_ci": 113, - //"utf16_slovak_ci": 114, - //"utf16_spanish2_ci": 115, - //"utf16_roman_ci": 116, - //"utf16_persian_ci": 117, - //"utf16_esperanto_ci": 118, - //"utf16_hungarian_ci": 119, - //"utf16_sinhala_ci": 120, - //"utf16_german2_ci": 121, - //"utf16_croatian_ci": 122, - //"utf16_unicode_520_ci": 123, - //"utf16_vietnamese_ci": 124, - //"ucs2_unicode_ci": 128, - //"ucs2_icelandic_ci": 129, - //"ucs2_latvian_ci": 130, - //"ucs2_romanian_ci": 131, - //"ucs2_slovenian_ci": 132, - //"ucs2_polish_ci": 133, - //"ucs2_estonian_ci": 134, - //"ucs2_spanish_ci": 135, - //"ucs2_swedish_ci": 136, - //"ucs2_turkish_ci": 137, - //"ucs2_czech_ci": 138, - //"ucs2_danish_ci": 139, - //"ucs2_lithuanian_ci": 140, - //"ucs2_slovak_ci": 141, - //"ucs2_spanish2_ci": 142, - //"ucs2_roman_ci": 143, - //"ucs2_persian_ci": 144, - //"ucs2_esperanto_ci": 145, - //"ucs2_hungarian_ci": 146, - //"ucs2_sinhala_ci": 147, - //"ucs2_german2_ci": 148, - //"ucs2_croatian_ci": 149, - //"ucs2_unicode_520_ci": 150, - //"ucs2_vietnamese_ci": 151, - //"ucs2_general_mysql500_ci": 159, - //"utf32_unicode_ci": 160, - //"utf32_icelandic_ci": 161, - //"utf32_latvian_ci": 162, - //"utf32_romanian_ci": 163, - //"utf32_slovenian_ci": 164, - //"utf32_polish_ci": 165, - //"utf32_estonian_ci": 166, - //"utf32_spanish_ci": 167, - //"utf32_swedish_ci": 168, - //"utf32_turkish_ci": 169, - //"utf32_czech_ci": 170, - //"utf32_danish_ci": 171, - //"utf32_lithuanian_ci": 172, - //"utf32_slovak_ci": 173, - //"utf32_spanish2_ci": 174, - //"utf32_roman_ci": 175, - //"utf32_persian_ci": 176, - //"utf32_esperanto_ci": 177, - //"utf32_hungarian_ci": 178, - //"utf32_sinhala_ci": 179, - //"utf32_german2_ci": 180, - //"utf32_croatian_ci": 181, - //"utf32_unicode_520_ci": 182, - //"utf32_vietnamese_ci": 183, - "utf8_unicode_ci": 192, - "utf8_icelandic_ci": 193, - "utf8_latvian_ci": 194, - "utf8_romanian_ci": 195, - "utf8_slovenian_ci": 196, - "utf8_polish_ci": 197, - "utf8_estonian_ci": 198, - "utf8_spanish_ci": 199, - "utf8_swedish_ci": 200, - "utf8_turkish_ci": 201, - "utf8_czech_ci": 202, - "utf8_danish_ci": 203, - "utf8_lithuanian_ci": 204, - "utf8_slovak_ci": 205, - "utf8_spanish2_ci": 206, - "utf8_roman_ci": 207, - "utf8_persian_ci": 208, - "utf8_esperanto_ci": 209, - "utf8_hungarian_ci": 210, - "utf8_sinhala_ci": 211, - "utf8_german2_ci": 212, - "utf8_croatian_ci": 213, - "utf8_unicode_520_ci": 214, - "utf8_vietnamese_ci": 215, - "utf8_general_mysql500_ci": 223, - "utf8mb4_unicode_ci": 224, - "utf8mb4_icelandic_ci": 225, - "utf8mb4_latvian_ci": 226, - "utf8mb4_romanian_ci": 227, - "utf8mb4_slovenian_ci": 228, - "utf8mb4_polish_ci": 229, - "utf8mb4_estonian_ci": 230, - "utf8mb4_spanish_ci": 231, - "utf8mb4_swedish_ci": 232, - "utf8mb4_turkish_ci": 233, - "utf8mb4_czech_ci": 234, - "utf8mb4_danish_ci": 235, - "utf8mb4_lithuanian_ci": 236, - "utf8mb4_slovak_ci": 237, - "utf8mb4_spanish2_ci": 238, - "utf8mb4_roman_ci": 239, - "utf8mb4_persian_ci": 240, - "utf8mb4_esperanto_ci": 241, - "utf8mb4_hungarian_ci": 242, - "utf8mb4_sinhala_ci": 243, - "utf8mb4_german2_ci": 244, - "utf8mb4_croatian_ci": 245, - "utf8mb4_unicode_520_ci": 246, - "utf8mb4_vietnamese_ci": 247, - "gb18030_chinese_ci": 248, - "gb18030_bin": 249, - "gb18030_unicode_520_ci": 250, - "utf8mb4_0900_ai_ci": 255, -} - -// A denylist of collations which is unsafe to interpolate parameters. -// These multibyte encodings may contains 0x5c (`\`) in their trailing bytes. -var unsafeCollations = map[string]bool{ - "big5_chinese_ci": true, - "sjis_japanese_ci": true, - "gbk_chinese_ci": true, - "big5_bin": true, - "gb2312_bin": true, - "gbk_bin": true, - "sjis_bin": true, - "cp932_japanese_ci": true, - "cp932_bin": true, - "gb18030_chinese_ci": true, - "gb18030_bin": true, - "gb18030_unicode_520_ci": true, -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck.go deleted file mode 100644 index 024eb285..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck.go +++ /dev/null @@ -1,54 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -// +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos - -package mysql - -import ( - "errors" - "io" - "net" - "syscall" -) - -var errUnexpectedRead = errors.New("unexpected read from socket") - -func connCheck(conn net.Conn) error { - var sysErr error - - sysConn, ok := conn.(syscall.Conn) - if !ok { - return nil - } - rawConn, err := sysConn.SyscallConn() - if err != nil { - return err - } - - err = rawConn.Read(func(fd uintptr) bool { - var buf [1]byte - n, err := syscall.Read(int(fd), buf[:]) - switch { - case n == 0 && err == nil: - sysErr = io.EOF - case n > 0: - sysErr = errUnexpectedRead - case err == syscall.EAGAIN || err == syscall.EWOULDBLOCK: - sysErr = nil - default: - sysErr = err - } - return true - }) - if err != nil { - return err - } - - return sysErr -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck_dummy.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck_dummy.go deleted file mode 100644 index ea7fb607..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck_dummy.go +++ /dev/null @@ -1,17 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -// +build !linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd,!solaris,!illumos - -package mysql - -import "net" - -func connCheck(conn net.Conn) error { - return nil -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/connection.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/connection.go deleted file mode 100644 index 835f8972..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/connection.go +++ /dev/null @@ -1,650 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "context" - "database/sql" - "database/sql/driver" - "encoding/json" - "io" - "net" - "strconv" - "strings" - "time" -) - -type mysqlConn struct { - buf buffer - netConn net.Conn - rawConn net.Conn // underlying connection when netConn is TLS connection. - affectedRows uint64 - insertId uint64 - cfg *Config - maxAllowedPacket int - maxWriteSize int - writeTimeout time.Duration - flags clientFlag - status statusFlag - sequence uint8 - parseTime bool - reset bool // set when the Go SQL package calls ResetSession - - // for context support (Go 1.8+) - watching bool - watcher chan<- context.Context - closech chan struct{} - finished chan<- struct{} - canceled atomicError // set non-nil if conn is canceled - closed atomicBool // set when conn is closed, before closech is closed -} - -// Handles parameters set in DSN after the connection is established -func (mc *mysqlConn) handleParams() (err error) { - var cmdSet strings.Builder - for param, val := range mc.cfg.Params { - switch param { - // Charset: character_set_connection, character_set_client, character_set_results - case "charset": - charsets := strings.Split(val, ",") - for i := range charsets { - // ignore errors here - a charset may not exist - err = mc.exec("SET NAMES " + charsets[i]) - if err == nil { - break - } - } - if err != nil { - return - } - - // Other system vars accumulated in a single SET command - default: - if cmdSet.Len() == 0 { - // Heuristic: 29 chars for each other key=value to reduce reallocations - cmdSet.Grow(4 + len(param) + 1 + len(val) + 30*(len(mc.cfg.Params)-1)) - cmdSet.WriteString("SET ") - } else { - cmdSet.WriteByte(',') - } - cmdSet.WriteString(param) - cmdSet.WriteByte('=') - cmdSet.WriteString(val) - } - } - - if cmdSet.Len() > 0 { - err = mc.exec(cmdSet.String()) - if err != nil { - return - } - } - - return -} - -func (mc *mysqlConn) markBadConn(err error) error { - if mc == nil { - return err - } - if err != errBadConnNoWrite { - return err - } - return driver.ErrBadConn -} - -func (mc *mysqlConn) Begin() (driver.Tx, error) { - return mc.begin(false) -} - -func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - var q string - if readOnly { - q = "START TRANSACTION READ ONLY" - } else { - q = "START TRANSACTION" - } - err := mc.exec(q) - if err == nil { - return &mysqlTx{mc}, err - } - return nil, mc.markBadConn(err) -} - -func (mc *mysqlConn) Close() (err error) { - // Makes Close idempotent - if !mc.closed.IsSet() { - err = mc.writeCommandPacket(comQuit) - } - - mc.cleanup() - - return -} - -// Closes the network connection and unsets internal variables. Do not call this -// function after successfully authentication, call Close instead. This function -// is called before auth or on auth failure because MySQL will have already -// closed the network connection. -func (mc *mysqlConn) cleanup() { - if !mc.closed.TrySet(true) { - return - } - - // Makes cleanup idempotent - close(mc.closech) - if mc.netConn == nil { - return - } - if err := mc.netConn.Close(); err != nil { - errLog.Print(err) - } -} - -func (mc *mysqlConn) error() error { - if mc.closed.IsSet() { - if err := mc.canceled.Value(); err != nil { - return err - } - return ErrInvalidConn - } - return nil -} - -func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := mc.writeCommandPacketStr(comStmtPrepare, query) - if err != nil { - // STMT_PREPARE is safe to retry. So we can return ErrBadConn here. - errLog.Print(err) - return nil, driver.ErrBadConn - } - - stmt := &mysqlStmt{ - mc: mc, - } - - // Read Result - columnCount, err := stmt.readPrepareResultPacket() - if err == nil { - if stmt.paramCount > 0 { - if err = mc.readUntilEOF(); err != nil { - return nil, err - } - } - - if columnCount > 0 { - err = mc.readUntilEOF() - } - } - - return stmt, err -} - -func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) { - // Number of ? should be same to len(args) - if strings.Count(query, "?") != len(args) { - return "", driver.ErrSkip - } - - buf, err := mc.buf.takeCompleteBuffer() - if err != nil { - // can not take the buffer. Something must be wrong with the connection - errLog.Print(err) - return "", ErrInvalidConn - } - buf = buf[:0] - argPos := 0 - - for i := 0; i < len(query); i++ { - q := strings.IndexByte(query[i:], '?') - if q == -1 { - buf = append(buf, query[i:]...) - break - } - buf = append(buf, query[i:i+q]...) - i += q - - arg := args[argPos] - argPos++ - - if arg == nil { - buf = append(buf, "NULL"...) - continue - } - - switch v := arg.(type) { - case int64: - buf = strconv.AppendInt(buf, v, 10) - case uint64: - // Handle uint64 explicitly because our custom ConvertValue emits unsigned values - buf = strconv.AppendUint(buf, v, 10) - case float64: - buf = strconv.AppendFloat(buf, v, 'g', -1, 64) - case bool: - if v { - buf = append(buf, '1') - } else { - buf = append(buf, '0') - } - case time.Time: - if v.IsZero() { - buf = append(buf, "'0000-00-00'"...) - } else { - buf = append(buf, '\'') - buf, err = appendDateTime(buf, v.In(mc.cfg.Loc)) - if err != nil { - return "", err - } - buf = append(buf, '\'') - } - case json.RawMessage: - buf = append(buf, '\'') - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeBytesBackslash(buf, v) - } else { - buf = escapeBytesQuotes(buf, v) - } - buf = append(buf, '\'') - case []byte: - if v == nil { - buf = append(buf, "NULL"...) - } else { - buf = append(buf, "_binary'"...) - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeBytesBackslash(buf, v) - } else { - buf = escapeBytesQuotes(buf, v) - } - buf = append(buf, '\'') - } - case string: - buf = append(buf, '\'') - if mc.status&statusNoBackslashEscapes == 0 { - buf = escapeStringBackslash(buf, v) - } else { - buf = escapeStringQuotes(buf, v) - } - buf = append(buf, '\'') - default: - return "", driver.ErrSkip - } - - if len(buf)+4 > mc.maxAllowedPacket { - return "", driver.ErrSkip - } - } - if argPos != len(args) { - return "", driver.ErrSkip - } - return string(buf), nil -} - -func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - if len(args) != 0 { - if !mc.cfg.InterpolateParams { - return nil, driver.ErrSkip - } - // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement - prepared, err := mc.interpolateParams(query, args) - if err != nil { - return nil, err - } - query = prepared - } - mc.affectedRows = 0 - mc.insertId = 0 - - err := mc.exec(query) - if err == nil { - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, err - } - return nil, mc.markBadConn(err) -} - -// Internal function to execute commands -func (mc *mysqlConn) exec(query string) error { - // Send command - if err := mc.writeCommandPacketStr(comQuery, query); err != nil { - return mc.markBadConn(err) - } - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return err - } - - if resLen > 0 { - // columns - if err := mc.readUntilEOF(); err != nil { - return err - } - - // rows - if err := mc.readUntilEOF(); err != nil { - return err - } - } - - return mc.discardResults() -} - -func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) { - return mc.query(query, args) -} - -func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - if len(args) != 0 { - if !mc.cfg.InterpolateParams { - return nil, driver.ErrSkip - } - // try client-side prepare to reduce roundtrip - prepared, err := mc.interpolateParams(query, args) - if err != nil { - return nil, err - } - query = prepared - } - // Send command - err := mc.writeCommandPacketStr(comQuery, query) - if err == nil { - // Read Result - var resLen int - resLen, err = mc.readResultSetHeaderPacket() - if err == nil { - rows := new(textRows) - rows.mc = mc - - if resLen == 0 { - rows.rs.done = true - - switch err := rows.NextResultSet(); err { - case nil, io.EOF: - return rows, nil - default: - return nil, err - } - } - - // Columns - rows.rs.columns, err = mc.readColumns(resLen) - return rows, err - } - } - return nil, mc.markBadConn(err) -} - -// Gets the value of the given MySQL System Variable -// The returned byte slice is only valid until the next read -func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) { - // Send command - if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil { - return nil, err - } - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err == nil { - rows := new(textRows) - rows.mc = mc - rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}} - - if resLen > 0 { - // Columns - if err := mc.readUntilEOF(); err != nil { - return nil, err - } - } - - dest := make([]driver.Value, resLen) - if err = rows.readRow(dest); err == nil { - return dest[0].([]byte), mc.readUntilEOF() - } - } - return nil, err -} - -// finish is called when the query has canceled. -func (mc *mysqlConn) cancel(err error) { - mc.canceled.Set(err) - mc.cleanup() -} - -// finish is called when the query has succeeded. -func (mc *mysqlConn) finish() { - if !mc.watching || mc.finished == nil { - return - } - select { - case mc.finished <- struct{}{}: - mc.watching = false - case <-mc.closech: - } -} - -// Ping implements driver.Pinger interface -func (mc *mysqlConn) Ping(ctx context.Context) (err error) { - if mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return driver.ErrBadConn - } - - if err = mc.watchCancel(ctx); err != nil { - return - } - defer mc.finish() - - if err = mc.writeCommandPacket(comPing); err != nil { - return mc.markBadConn(err) - } - - return mc.readResultOK() -} - -// BeginTx implements driver.ConnBeginTx interface -func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - if mc.closed.IsSet() { - return nil, driver.ErrBadConn - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - defer mc.finish() - - if sql.IsolationLevel(opts.Isolation) != sql.LevelDefault { - level, err := mapIsolationLevel(opts.Isolation) - if err != nil { - return nil, err - } - err = mc.exec("SET TRANSACTION ISOLATION LEVEL " + level) - if err != nil { - return nil, err - } - } - - return mc.begin(opts.ReadOnly) -} - -func (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - - rows, err := mc.query(query, dargs) - if err != nil { - mc.finish() - return nil, err - } - rows.finish = mc.finish - return rows, err -} - -func (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - defer mc.finish() - - return mc.Exec(query, dargs) -} - -func (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - if err := mc.watchCancel(ctx); err != nil { - return nil, err - } - - stmt, err := mc.Prepare(query) - mc.finish() - if err != nil { - return nil, err - } - - select { - default: - case <-ctx.Done(): - stmt.Close() - return nil, ctx.Err() - } - return stmt, nil -} - -func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := stmt.mc.watchCancel(ctx); err != nil { - return nil, err - } - - rows, err := stmt.query(dargs) - if err != nil { - stmt.mc.finish() - return nil, err - } - rows.finish = stmt.mc.finish - return rows, err -} - -func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { - dargs, err := namedValueToValue(args) - if err != nil { - return nil, err - } - - if err := stmt.mc.watchCancel(ctx); err != nil { - return nil, err - } - defer stmt.mc.finish() - - return stmt.Exec(dargs) -} - -func (mc *mysqlConn) watchCancel(ctx context.Context) error { - if mc.watching { - // Reach here if canceled, - // so the connection is already invalid - mc.cleanup() - return nil - } - // When ctx is already cancelled, don't watch it. - if err := ctx.Err(); err != nil { - return err - } - // When ctx is not cancellable, don't watch it. - if ctx.Done() == nil { - return nil - } - // When watcher is not alive, can't watch it. - if mc.watcher == nil { - return nil - } - - mc.watching = true - mc.watcher <- ctx - return nil -} - -func (mc *mysqlConn) startWatcher() { - watcher := make(chan context.Context, 1) - mc.watcher = watcher - finished := make(chan struct{}) - mc.finished = finished - go func() { - for { - var ctx context.Context - select { - case ctx = <-watcher: - case <-mc.closech: - return - } - - select { - case <-ctx.Done(): - mc.cancel(ctx.Err()) - case <-finished: - case <-mc.closech: - return - } - } - }() -} - -func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) { - nv.Value, err = converter{}.ConvertValue(nv.Value) - return -} - -// ResetSession implements driver.SessionResetter. -// (From Go 1.10) -func (mc *mysqlConn) ResetSession(ctx context.Context) error { - if mc.closed.IsSet() { - return driver.ErrBadConn - } - mc.reset = true - return nil -} - -// IsValid implements driver.Validator interface -// (From Go 1.15) -func (mc *mysqlConn) IsValid() bool { - return !mc.closed.IsSet() -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/connector.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/connector.go deleted file mode 100644 index d567b4e4..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/connector.go +++ /dev/null @@ -1,146 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "context" - "database/sql/driver" - "net" -) - -type connector struct { - cfg *Config // immutable private copy. -} - -// Connect implements driver.Connector interface. -// Connect returns a connection to the database. -func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { - var err error - - // New mysqlConn - mc := &mysqlConn{ - maxAllowedPacket: maxPacketSize, - maxWriteSize: maxPacketSize - 1, - closech: make(chan struct{}), - cfg: c.cfg, - } - mc.parseTime = mc.cfg.ParseTime - - // Connect to Server - dialsLock.RLock() - dial, ok := dials[mc.cfg.Net] - dialsLock.RUnlock() - if ok { - dctx := ctx - if mc.cfg.Timeout > 0 { - var cancel context.CancelFunc - dctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout) - defer cancel() - } - mc.netConn, err = dial(dctx, mc.cfg.Addr) - } else { - nd := net.Dialer{Timeout: mc.cfg.Timeout} - mc.netConn, err = nd.DialContext(ctx, mc.cfg.Net, mc.cfg.Addr) - } - - if err != nil { - return nil, err - } - - // Enable TCP Keepalives on TCP connections - if tc, ok := mc.netConn.(*net.TCPConn); ok { - if err := tc.SetKeepAlive(true); err != nil { - // Don't send COM_QUIT before handshake. - mc.netConn.Close() - mc.netConn = nil - return nil, err - } - } - - // Call startWatcher for context support (From Go 1.8) - mc.startWatcher() - if err := mc.watchCancel(ctx); err != nil { - mc.cleanup() - return nil, err - } - defer mc.finish() - - mc.buf = newBuffer(mc.netConn) - - // Set I/O timeouts - mc.buf.timeout = mc.cfg.ReadTimeout - mc.writeTimeout = mc.cfg.WriteTimeout - - // Reading Handshake Initialization Packet - authData, plugin, err := mc.readHandshakePacket() - if err != nil { - mc.cleanup() - return nil, err - } - - if plugin == "" { - plugin = defaultAuthPlugin - } - - // Send Client Authentication Packet - authResp, err := mc.auth(authData, plugin) - if err != nil { - // try the default auth plugin, if using the requested plugin failed - errLog.Print("could not use requested auth plugin '"+plugin+"': ", err.Error()) - plugin = defaultAuthPlugin - authResp, err = mc.auth(authData, plugin) - if err != nil { - mc.cleanup() - return nil, err - } - } - if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil { - mc.cleanup() - return nil, err - } - - // Handle response to auth packet, switch methods if possible - if err = mc.handleAuthResult(authData, plugin); err != nil { - // Authentication failed and MySQL has already closed the connection - // (https://dev.mysql.com/doc/internals/en/authentication-fails.html). - // Do not send COM_QUIT, just cleanup and return the error. - mc.cleanup() - return nil, err - } - - if mc.cfg.MaxAllowedPacket > 0 { - mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket - } else { - // Get max allowed packet size - maxap, err := mc.getSystemVar("max_allowed_packet") - if err != nil { - mc.Close() - return nil, err - } - mc.maxAllowedPacket = stringToInt(maxap) - 1 - } - if mc.maxAllowedPacket < maxPacketSize { - mc.maxWriteSize = mc.maxAllowedPacket - } - - // Handle DSN Params - err = mc.handleParams() - if err != nil { - mc.Close() - return nil, err - } - - return mc, nil -} - -// Driver implements driver.Connector interface. -// Driver returns &MySQLDriver{}. -func (c *connector) Driver() driver.Driver { - return &MySQLDriver{} -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/const.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/const.go deleted file mode 100644 index b1e6b85e..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/const.go +++ /dev/null @@ -1,174 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -const ( - defaultAuthPlugin = "mysql_native_password" - defaultMaxAllowedPacket = 4 << 20 // 4 MiB - minProtocolVersion = 10 - maxPacketSize = 1<<24 - 1 - timeFormat = "2006-01-02 15:04:05.999999" -) - -// MySQL constants documentation: -// http://dev.mysql.com/doc/internals/en/client-server-protocol.html - -const ( - iOK byte = 0x00 - iAuthMoreData byte = 0x01 - iLocalInFile byte = 0xfb - iEOF byte = 0xfe - iERR byte = 0xff -) - -// https://dev.mysql.com/doc/internals/en/capability-flags.html#packet-Protocol::CapabilityFlags -type clientFlag uint32 - -const ( - clientLongPassword clientFlag = 1 << iota - clientFoundRows - clientLongFlag - clientConnectWithDB - clientNoSchema - clientCompress - clientODBC - clientLocalFiles - clientIgnoreSpace - clientProtocol41 - clientInteractive - clientSSL - clientIgnoreSIGPIPE - clientTransactions - clientReserved - clientSecureConn - clientMultiStatements - clientMultiResults - clientPSMultiResults - clientPluginAuth - clientConnectAttrs - clientPluginAuthLenEncClientData - clientCanHandleExpiredPasswords - clientSessionTrack - clientDeprecateEOF -) - -const ( - comQuit byte = iota + 1 - comInitDB - comQuery - comFieldList - comCreateDB - comDropDB - comRefresh - comShutdown - comStatistics - comProcessInfo - comConnect - comProcessKill - comDebug - comPing - comTime - comDelayedInsert - comChangeUser - comBinlogDump - comTableDump - comConnectOut - comRegisterSlave - comStmtPrepare - comStmtExecute - comStmtSendLongData - comStmtClose - comStmtReset - comSetOption - comStmtFetch -) - -// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType -type fieldType byte - -const ( - fieldTypeDecimal fieldType = iota - fieldTypeTiny - fieldTypeShort - fieldTypeLong - fieldTypeFloat - fieldTypeDouble - fieldTypeNULL - fieldTypeTimestamp - fieldTypeLongLong - fieldTypeInt24 - fieldTypeDate - fieldTypeTime - fieldTypeDateTime - fieldTypeYear - fieldTypeNewDate - fieldTypeVarChar - fieldTypeBit -) -const ( - fieldTypeJSON fieldType = iota + 0xf5 - fieldTypeNewDecimal - fieldTypeEnum - fieldTypeSet - fieldTypeTinyBLOB - fieldTypeMediumBLOB - fieldTypeLongBLOB - fieldTypeBLOB - fieldTypeVarString - fieldTypeString - fieldTypeGeometry -) - -type fieldFlag uint16 - -const ( - flagNotNULL fieldFlag = 1 << iota - flagPriKey - flagUniqueKey - flagMultipleKey - flagBLOB - flagUnsigned - flagZeroFill - flagBinary - flagEnum - flagAutoIncrement - flagTimestamp - flagSet - flagUnknown1 - flagUnknown2 - flagUnknown3 - flagUnknown4 -) - -// http://dev.mysql.com/doc/internals/en/status-flags.html -type statusFlag uint16 - -const ( - statusInTrans statusFlag = 1 << iota - statusInAutocommit - statusReserved // Not in documentation - statusMoreResultsExists - statusNoGoodIndexUsed - statusNoIndexUsed - statusCursorExists - statusLastRowSent - statusDbDropped - statusNoBackslashEscapes - statusMetadataChanged - statusQueryWasSlow - statusPsOutParams - statusInTransReadonly - statusSessionStateChanged -) - -const ( - cachingSha2PasswordRequestPublicKey = 2 - cachingSha2PasswordFastAuthSuccess = 3 - cachingSha2PasswordPerformFullAuthentication = 4 -) diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/driver.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/driver.go deleted file mode 100644 index c1bdf119..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/driver.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -// Package mysql provides a MySQL driver for Go's database/sql package. -// -// The driver should be used via the database/sql package: -// -// import "database/sql" -// import _ "github.com/go-sql-driver/mysql" -// -// db, err := sql.Open("mysql", "user:password@/dbname") -// -// See https://github.com/go-sql-driver/mysql#usage for details -package mysql - -import ( - "context" - "database/sql" - "database/sql/driver" - "net" - "sync" -) - -// MySQLDriver is exported to make the driver directly accessible. -// In general the driver is used via the database/sql package. -type MySQLDriver struct{} - -// DialFunc is a function which can be used to establish the network connection. -// Custom dial functions must be registered with RegisterDial -// -// Deprecated: users should register a DialContextFunc instead -type DialFunc func(addr string) (net.Conn, error) - -// DialContextFunc is a function which can be used to establish the network connection. -// Custom dial functions must be registered with RegisterDialContext -type DialContextFunc func(ctx context.Context, addr string) (net.Conn, error) - -var ( - dialsLock sync.RWMutex - dials map[string]DialContextFunc -) - -// RegisterDialContext registers a custom dial function. It can then be used by the -// network address mynet(addr), where mynet is the registered new network. -// The current context for the connection and its address is passed to the dial function. -func RegisterDialContext(net string, dial DialContextFunc) { - dialsLock.Lock() - defer dialsLock.Unlock() - if dials == nil { - dials = make(map[string]DialContextFunc) - } - dials[net] = dial -} - -// RegisterDial registers a custom dial function. It can then be used by the -// network address mynet(addr), where mynet is the registered new network. -// addr is passed as a parameter to the dial function. -// -// Deprecated: users should call RegisterDialContext instead -func RegisterDial(network string, dial DialFunc) { - RegisterDialContext(network, func(_ context.Context, addr string) (net.Conn, error) { - return dial(addr) - }) -} - -// Open new Connection. -// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how -// the DSN string is formatted -func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { - cfg, err := ParseDSN(dsn) - if err != nil { - return nil, err - } - c := &connector{ - cfg: cfg, - } - return c.Connect(context.Background()) -} - -func init() { - sql.Register("mysql", &MySQLDriver{}) -} - -// NewConnector returns new driver.Connector. -func NewConnector(cfg *Config) (driver.Connector, error) { - cfg = cfg.Clone() - // normalize the contents of cfg so calls to NewConnector have the same - // behavior as MySQLDriver.OpenConnector - if err := cfg.normalize(); err != nil { - return nil, err - } - return &connector{cfg: cfg}, nil -} - -// OpenConnector implements driver.DriverContext. -func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error) { - cfg, err := ParseDSN(dsn) - if err != nil { - return nil, err - } - return &connector{ - cfg: cfg, - }, nil -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/dsn.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/dsn.go deleted file mode 100644 index 93f3548c..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/dsn.go +++ /dev/null @@ -1,560 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "bytes" - "crypto/rsa" - "crypto/tls" - "errors" - "fmt" - "math/big" - "net" - "net/url" - "sort" - "strconv" - "strings" - "time" -) - -var ( - errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?") - errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)") - errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name") - errInvalidDSNUnsafeCollation = errors.New("invalid DSN: interpolateParams can not be used with unsafe collations") -) - -// Config is a configuration parsed from a DSN string. -// If a new Config is created instead of being parsed from a DSN string, -// the NewConfig function should be used, which sets default values. -type Config struct { - User string // Username - Passwd string // Password (requires User) - Net string // Network type - Addr string // Network address (requires Net) - DBName string // Database name - Params map[string]string // Connection parameters - Collation string // Connection collation - Loc *time.Location // Location for time.Time values - MaxAllowedPacket int // Max packet size allowed - ServerPubKey string // Server public key name - pubKey *rsa.PublicKey // Server public key - TLSConfig string // TLS configuration name - tls *tls.Config // TLS configuration - Timeout time.Duration // Dial timeout - ReadTimeout time.Duration // I/O read timeout - WriteTimeout time.Duration // I/O write timeout - - AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE - AllowCleartextPasswords bool // Allows the cleartext client side plugin - AllowNativePasswords bool // Allows the native password authentication method - AllowOldPasswords bool // Allows the old insecure password method - CheckConnLiveness bool // Check connections for liveness before using them - ClientFoundRows bool // Return number of matching rows instead of rows changed - ColumnsWithAlias bool // Prepend table alias to column names - InterpolateParams bool // Interpolate placeholders into query string - MultiStatements bool // Allow multiple statements in one query - ParseTime bool // Parse time values to time.Time - RejectReadOnly bool // Reject read-only connections -} - -// NewConfig creates a new Config and sets default values. -func NewConfig() *Config { - return &Config{ - Collation: defaultCollation, - Loc: time.UTC, - MaxAllowedPacket: defaultMaxAllowedPacket, - AllowNativePasswords: true, - CheckConnLiveness: true, - } -} - -func (cfg *Config) Clone() *Config { - cp := *cfg - if cp.tls != nil { - cp.tls = cfg.tls.Clone() - } - if len(cp.Params) > 0 { - cp.Params = make(map[string]string, len(cfg.Params)) - for k, v := range cfg.Params { - cp.Params[k] = v - } - } - if cfg.pubKey != nil { - cp.pubKey = &rsa.PublicKey{ - N: new(big.Int).Set(cfg.pubKey.N), - E: cfg.pubKey.E, - } - } - return &cp -} - -func (cfg *Config) normalize() error { - if cfg.InterpolateParams && unsafeCollations[cfg.Collation] { - return errInvalidDSNUnsafeCollation - } - - // Set default network if empty - if cfg.Net == "" { - cfg.Net = "tcp" - } - - // Set default address if empty - if cfg.Addr == "" { - switch cfg.Net { - case "tcp": - cfg.Addr = "127.0.0.1:3306" - case "unix": - cfg.Addr = "/tmp/mysql.sock" - default: - return errors.New("default addr for network '" + cfg.Net + "' unknown") - } - } else if cfg.Net == "tcp" { - cfg.Addr = ensureHavePort(cfg.Addr) - } - - switch cfg.TLSConfig { - case "false", "": - // don't set anything - case "true": - cfg.tls = &tls.Config{} - case "skip-verify", "preferred": - cfg.tls = &tls.Config{InsecureSkipVerify: true} - default: - cfg.tls = getTLSConfigClone(cfg.TLSConfig) - if cfg.tls == nil { - return errors.New("invalid value / unknown config name: " + cfg.TLSConfig) - } - } - - if cfg.tls != nil && cfg.tls.ServerName == "" && !cfg.tls.InsecureSkipVerify { - host, _, err := net.SplitHostPort(cfg.Addr) - if err == nil { - cfg.tls.ServerName = host - } - } - - if cfg.ServerPubKey != "" { - cfg.pubKey = getServerPubKey(cfg.ServerPubKey) - if cfg.pubKey == nil { - return errors.New("invalid value / unknown server pub key name: " + cfg.ServerPubKey) - } - } - - return nil -} - -func writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) { - buf.Grow(1 + len(name) + 1 + len(value)) - if !*hasParam { - *hasParam = true - buf.WriteByte('?') - } else { - buf.WriteByte('&') - } - buf.WriteString(name) - buf.WriteByte('=') - buf.WriteString(value) -} - -// FormatDSN formats the given Config into a DSN string which can be passed to -// the driver. -func (cfg *Config) FormatDSN() string { - var buf bytes.Buffer - - // [username[:password]@] - if len(cfg.User) > 0 { - buf.WriteString(cfg.User) - if len(cfg.Passwd) > 0 { - buf.WriteByte(':') - buf.WriteString(cfg.Passwd) - } - buf.WriteByte('@') - } - - // [protocol[(address)]] - if len(cfg.Net) > 0 { - buf.WriteString(cfg.Net) - if len(cfg.Addr) > 0 { - buf.WriteByte('(') - buf.WriteString(cfg.Addr) - buf.WriteByte(')') - } - } - - // /dbname - buf.WriteByte('/') - buf.WriteString(cfg.DBName) - - // [?param1=value1&...¶mN=valueN] - hasParam := false - - if cfg.AllowAllFiles { - hasParam = true - buf.WriteString("?allowAllFiles=true") - } - - if cfg.AllowCleartextPasswords { - writeDSNParam(&buf, &hasParam, "allowCleartextPasswords", "true") - } - - if !cfg.AllowNativePasswords { - writeDSNParam(&buf, &hasParam, "allowNativePasswords", "false") - } - - if cfg.AllowOldPasswords { - writeDSNParam(&buf, &hasParam, "allowOldPasswords", "true") - } - - if !cfg.CheckConnLiveness { - writeDSNParam(&buf, &hasParam, "checkConnLiveness", "false") - } - - if cfg.ClientFoundRows { - writeDSNParam(&buf, &hasParam, "clientFoundRows", "true") - } - - if col := cfg.Collation; col != defaultCollation && len(col) > 0 { - writeDSNParam(&buf, &hasParam, "collation", col) - } - - if cfg.ColumnsWithAlias { - writeDSNParam(&buf, &hasParam, "columnsWithAlias", "true") - } - - if cfg.InterpolateParams { - writeDSNParam(&buf, &hasParam, "interpolateParams", "true") - } - - if cfg.Loc != time.UTC && cfg.Loc != nil { - writeDSNParam(&buf, &hasParam, "loc", url.QueryEscape(cfg.Loc.String())) - } - - if cfg.MultiStatements { - writeDSNParam(&buf, &hasParam, "multiStatements", "true") - } - - if cfg.ParseTime { - writeDSNParam(&buf, &hasParam, "parseTime", "true") - } - - if cfg.ReadTimeout > 0 { - writeDSNParam(&buf, &hasParam, "readTimeout", cfg.ReadTimeout.String()) - } - - if cfg.RejectReadOnly { - writeDSNParam(&buf, &hasParam, "rejectReadOnly", "true") - } - - if len(cfg.ServerPubKey) > 0 { - writeDSNParam(&buf, &hasParam, "serverPubKey", url.QueryEscape(cfg.ServerPubKey)) - } - - if cfg.Timeout > 0 { - writeDSNParam(&buf, &hasParam, "timeout", cfg.Timeout.String()) - } - - if len(cfg.TLSConfig) > 0 { - writeDSNParam(&buf, &hasParam, "tls", url.QueryEscape(cfg.TLSConfig)) - } - - if cfg.WriteTimeout > 0 { - writeDSNParam(&buf, &hasParam, "writeTimeout", cfg.WriteTimeout.String()) - } - - if cfg.MaxAllowedPacket != defaultMaxAllowedPacket { - writeDSNParam(&buf, &hasParam, "maxAllowedPacket", strconv.Itoa(cfg.MaxAllowedPacket)) - } - - // other params - if cfg.Params != nil { - var params []string - for param := range cfg.Params { - params = append(params, param) - } - sort.Strings(params) - for _, param := range params { - writeDSNParam(&buf, &hasParam, param, url.QueryEscape(cfg.Params[param])) - } - } - - return buf.String() -} - -// ParseDSN parses the DSN string to a Config -func ParseDSN(dsn string) (cfg *Config, err error) { - // New config with some default values - cfg = NewConfig() - - // [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN] - // Find the last '/' (since the password or the net addr might contain a '/') - foundSlash := false - for i := len(dsn) - 1; i >= 0; i-- { - if dsn[i] == '/' { - foundSlash = true - var j, k int - - // left part is empty if i <= 0 - if i > 0 { - // [username[:password]@][protocol[(address)]] - // Find the last '@' in dsn[:i] - for j = i; j >= 0; j-- { - if dsn[j] == '@' { - // username[:password] - // Find the first ':' in dsn[:j] - for k = 0; k < j; k++ { - if dsn[k] == ':' { - cfg.Passwd = dsn[k+1 : j] - break - } - } - cfg.User = dsn[:k] - - break - } - } - - // [protocol[(address)]] - // Find the first '(' in dsn[j+1:i] - for k = j + 1; k < i; k++ { - if dsn[k] == '(' { - // dsn[i-1] must be == ')' if an address is specified - if dsn[i-1] != ')' { - if strings.ContainsRune(dsn[k+1:i], ')') { - return nil, errInvalidDSNUnescaped - } - return nil, errInvalidDSNAddr - } - cfg.Addr = dsn[k+1 : i-1] - break - } - } - cfg.Net = dsn[j+1 : k] - } - - // dbname[?param1=value1&...¶mN=valueN] - // Find the first '?' in dsn[i+1:] - for j = i + 1; j < len(dsn); j++ { - if dsn[j] == '?' { - if err = parseDSNParams(cfg, dsn[j+1:]); err != nil { - return - } - break - } - } - cfg.DBName = dsn[i+1 : j] - - break - } - } - - if !foundSlash && len(dsn) > 0 { - return nil, errInvalidDSNNoSlash - } - - if err = cfg.normalize(); err != nil { - return nil, err - } - return -} - -// parseDSNParams parses the DSN "query string" -// Values must be url.QueryEscape'ed -func parseDSNParams(cfg *Config, params string) (err error) { - for _, v := range strings.Split(params, "&") { - param := strings.SplitN(v, "=", 2) - if len(param) != 2 { - continue - } - - // cfg params - switch value := param[1]; param[0] { - // Disable INFILE allowlist / enable all files - case "allowAllFiles": - var isBool bool - cfg.AllowAllFiles, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use cleartext authentication mode (MySQL 5.5.10+) - case "allowCleartextPasswords": - var isBool bool - cfg.AllowCleartextPasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use native password authentication - case "allowNativePasswords": - var isBool bool - cfg.AllowNativePasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Use old authentication mode (pre MySQL 4.1) - case "allowOldPasswords": - var isBool bool - cfg.AllowOldPasswords, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Check connections for Liveness before using them - case "checkConnLiveness": - var isBool bool - cfg.CheckConnLiveness, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Switch "rowsAffected" mode - case "clientFoundRows": - var isBool bool - cfg.ClientFoundRows, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Collation - case "collation": - cfg.Collation = value - break - - case "columnsWithAlias": - var isBool bool - cfg.ColumnsWithAlias, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Compression - case "compress": - return errors.New("compression not implemented yet") - - // Enable client side placeholder substitution - case "interpolateParams": - var isBool bool - cfg.InterpolateParams, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Time Location - case "loc": - if value, err = url.QueryUnescape(value); err != nil { - return - } - cfg.Loc, err = time.LoadLocation(value) - if err != nil { - return - } - - // multiple statements in one query - case "multiStatements": - var isBool bool - cfg.MultiStatements, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // time.Time parsing - case "parseTime": - var isBool bool - cfg.ParseTime, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // I/O read Timeout - case "readTimeout": - cfg.ReadTimeout, err = time.ParseDuration(value) - if err != nil { - return - } - - // Reject read-only connections - case "rejectReadOnly": - var isBool bool - cfg.RejectReadOnly, isBool = readBool(value) - if !isBool { - return errors.New("invalid bool value: " + value) - } - - // Server public key - case "serverPubKey": - name, err := url.QueryUnescape(value) - if err != nil { - return fmt.Errorf("invalid value for server pub key name: %v", err) - } - cfg.ServerPubKey = name - - // Strict mode - case "strict": - panic("strict mode has been removed. See https://github.com/go-sql-driver/mysql/wiki/strict-mode") - - // Dial Timeout - case "timeout": - cfg.Timeout, err = time.ParseDuration(value) - if err != nil { - return - } - - // TLS-Encryption - case "tls": - boolValue, isBool := readBool(value) - if isBool { - if boolValue { - cfg.TLSConfig = "true" - } else { - cfg.TLSConfig = "false" - } - } else if vl := strings.ToLower(value); vl == "skip-verify" || vl == "preferred" { - cfg.TLSConfig = vl - } else { - name, err := url.QueryUnescape(value) - if err != nil { - return fmt.Errorf("invalid value for TLS config name: %v", err) - } - cfg.TLSConfig = name - } - - // I/O write Timeout - case "writeTimeout": - cfg.WriteTimeout, err = time.ParseDuration(value) - if err != nil { - return - } - case "maxAllowedPacket": - cfg.MaxAllowedPacket, err = strconv.Atoi(value) - if err != nil { - return - } - default: - // lazy init - if cfg.Params == nil { - cfg.Params = make(map[string]string) - } - - if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil { - return - } - } - } - - return -} - -func ensureHavePort(addr string) string { - if _, _, err := net.SplitHostPort(addr); err != nil { - return net.JoinHostPort(addr, "3306") - } - return addr -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/errors.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/errors.go deleted file mode 100644 index 760782ff..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/errors.go +++ /dev/null @@ -1,65 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "errors" - "fmt" - "log" - "os" -) - -// Various errors the driver might return. Can change between driver versions. -var ( - ErrInvalidConn = errors.New("invalid connection") - ErrMalformPkt = errors.New("malformed packet") - ErrNoTLS = errors.New("TLS requested but server does not support TLS") - ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") - ErrNativePassword = errors.New("this user requires mysql native password authentication.") - ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") - ErrUnknownPlugin = errors.New("this authentication plugin is not supported") - ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") - ErrPktSync = errors.New("commands out of sync. You can't run this command now") - ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") - ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") - ErrBusyBuffer = errors.New("busy buffer") - - // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. - // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn - // to trigger a resend. - // See https://github.com/go-sql-driver/mysql/pull/302 - errBadConnNoWrite = errors.New("bad connection") -) - -var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) - -// Logger is used to log critical error messages. -type Logger interface { - Print(v ...interface{}) -} - -// SetLogger is used to set the logger for critical errors. -// The initial logger is os.Stderr. -func SetLogger(logger Logger) error { - if logger == nil { - return errors.New("logger is nil") - } - errLog = logger - return nil -} - -// MySQLError is an error type which represents a single MySQL error -type MySQLError struct { - Number uint16 - Message string -} - -func (me *MySQLError) Error() string { - return fmt.Sprintf("Error %d: %s", me.Number, me.Message) -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/fields.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/fields.go deleted file mode 100644 index ed6c7a37..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/fields.go +++ /dev/null @@ -1,194 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "database/sql" - "reflect" -) - -func (mf *mysqlField) typeDatabaseName() string { - switch mf.fieldType { - case fieldTypeBit: - return "BIT" - case fieldTypeBLOB: - if mf.charSet != collations[binaryCollation] { - return "TEXT" - } - return "BLOB" - case fieldTypeDate: - return "DATE" - case fieldTypeDateTime: - return "DATETIME" - case fieldTypeDecimal: - return "DECIMAL" - case fieldTypeDouble: - return "DOUBLE" - case fieldTypeEnum: - return "ENUM" - case fieldTypeFloat: - return "FLOAT" - case fieldTypeGeometry: - return "GEOMETRY" - case fieldTypeInt24: - return "MEDIUMINT" - case fieldTypeJSON: - return "JSON" - case fieldTypeLong: - return "INT" - case fieldTypeLongBLOB: - if mf.charSet != collations[binaryCollation] { - return "LONGTEXT" - } - return "LONGBLOB" - case fieldTypeLongLong: - return "BIGINT" - case fieldTypeMediumBLOB: - if mf.charSet != collations[binaryCollation] { - return "MEDIUMTEXT" - } - return "MEDIUMBLOB" - case fieldTypeNewDate: - return "DATE" - case fieldTypeNewDecimal: - return "DECIMAL" - case fieldTypeNULL: - return "NULL" - case fieldTypeSet: - return "SET" - case fieldTypeShort: - return "SMALLINT" - case fieldTypeString: - if mf.charSet == collations[binaryCollation] { - return "BINARY" - } - return "CHAR" - case fieldTypeTime: - return "TIME" - case fieldTypeTimestamp: - return "TIMESTAMP" - case fieldTypeTiny: - return "TINYINT" - case fieldTypeTinyBLOB: - if mf.charSet != collations[binaryCollation] { - return "TINYTEXT" - } - return "TINYBLOB" - case fieldTypeVarChar: - if mf.charSet == collations[binaryCollation] { - return "VARBINARY" - } - return "VARCHAR" - case fieldTypeVarString: - if mf.charSet == collations[binaryCollation] { - return "VARBINARY" - } - return "VARCHAR" - case fieldTypeYear: - return "YEAR" - default: - return "" - } -} - -var ( - scanTypeFloat32 = reflect.TypeOf(float32(0)) - scanTypeFloat64 = reflect.TypeOf(float64(0)) - scanTypeInt8 = reflect.TypeOf(int8(0)) - scanTypeInt16 = reflect.TypeOf(int16(0)) - scanTypeInt32 = reflect.TypeOf(int32(0)) - scanTypeInt64 = reflect.TypeOf(int64(0)) - scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) - scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) - scanTypeNullTime = reflect.TypeOf(nullTime{}) - scanTypeUint8 = reflect.TypeOf(uint8(0)) - scanTypeUint16 = reflect.TypeOf(uint16(0)) - scanTypeUint32 = reflect.TypeOf(uint32(0)) - scanTypeUint64 = reflect.TypeOf(uint64(0)) - scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{}) - scanTypeUnknown = reflect.TypeOf(new(interface{})) -) - -type mysqlField struct { - tableName string - name string - length uint32 - flags fieldFlag - fieldType fieldType - decimals byte - charSet uint8 -} - -func (mf *mysqlField) scanType() reflect.Type { - switch mf.fieldType { - case fieldTypeTiny: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint8 - } - return scanTypeInt8 - } - return scanTypeNullInt - - case fieldTypeShort, fieldTypeYear: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint16 - } - return scanTypeInt16 - } - return scanTypeNullInt - - case fieldTypeInt24, fieldTypeLong: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint32 - } - return scanTypeInt32 - } - return scanTypeNullInt - - case fieldTypeLongLong: - if mf.flags&flagNotNULL != 0 { - if mf.flags&flagUnsigned != 0 { - return scanTypeUint64 - } - return scanTypeInt64 - } - return scanTypeNullInt - - case fieldTypeFloat: - if mf.flags&flagNotNULL != 0 { - return scanTypeFloat32 - } - return scanTypeNullFloat - - case fieldTypeDouble: - if mf.flags&flagNotNULL != 0 { - return scanTypeFloat64 - } - return scanTypeNullFloat - - case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, - fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, - fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, - fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON, - fieldTypeTime: - return scanTypeRawBytes - - case fieldTypeDate, fieldTypeNewDate, - fieldTypeTimestamp, fieldTypeDateTime: - // NullTime is always returned for more consistent behavior as it can - // handle both cases of parseTime regardless if the field is nullable. - return scanTypeNullTime - - default: - return scanTypeUnknown - } -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/fuzz.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/fuzz.go deleted file mode 100644 index fa75adf6..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/fuzz.go +++ /dev/null @@ -1,24 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package. -// -// Copyright 2020 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -// +build gofuzz - -package mysql - -import ( - "database/sql" -) - -func Fuzz(data []byte) int { - db, err := sql.Open("mysql", string(data)) - if err != nil { - return 0 - } - db.Close() - return 1 -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/go.mod b/taskman-server/vendor/github.com/go-sql-driver/mysql/go.mod deleted file mode 100644 index fffbf6a9..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/go-sql-driver/mysql - -go 1.10 diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/infile.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/infile.go deleted file mode 100644 index 60effdfc..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/infile.go +++ /dev/null @@ -1,182 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "fmt" - "io" - "os" - "strings" - "sync" -) - -var ( - fileRegister map[string]bool - fileRegisterLock sync.RWMutex - readerRegister map[string]func() io.Reader - readerRegisterLock sync.RWMutex -) - -// RegisterLocalFile adds the given file to the file allowlist, -// so that it can be used by "LOAD DATA LOCAL INFILE ". -// Alternatively you can allow the use of all local files with -// the DSN parameter 'allowAllFiles=true' -// -// filePath := "/home/gopher/data.csv" -// mysql.RegisterLocalFile(filePath) -// err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") -// if err != nil { -// ... -// -func RegisterLocalFile(filePath string) { - fileRegisterLock.Lock() - // lazy map init - if fileRegister == nil { - fileRegister = make(map[string]bool) - } - - fileRegister[strings.Trim(filePath, `"`)] = true - fileRegisterLock.Unlock() -} - -// DeregisterLocalFile removes the given filepath from the allowlist. -func DeregisterLocalFile(filePath string) { - fileRegisterLock.Lock() - delete(fileRegister, strings.Trim(filePath, `"`)) - fileRegisterLock.Unlock() -} - -// RegisterReaderHandler registers a handler function which is used -// to receive a io.Reader. -// The Reader can be used by "LOAD DATA LOCAL INFILE Reader::". -// If the handler returns a io.ReadCloser Close() is called when the -// request is finished. -// -// mysql.RegisterReaderHandler("data", func() io.Reader { -// var csvReader io.Reader // Some Reader that returns CSV data -// ... // Open Reader here -// return csvReader -// }) -// err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo") -// if err != nil { -// ... -// -func RegisterReaderHandler(name string, handler func() io.Reader) { - readerRegisterLock.Lock() - // lazy map init - if readerRegister == nil { - readerRegister = make(map[string]func() io.Reader) - } - - readerRegister[name] = handler - readerRegisterLock.Unlock() -} - -// DeregisterReaderHandler removes the ReaderHandler function with -// the given name from the registry. -func DeregisterReaderHandler(name string) { - readerRegisterLock.Lock() - delete(readerRegister, name) - readerRegisterLock.Unlock() -} - -func deferredClose(err *error, closer io.Closer) { - closeErr := closer.Close() - if *err == nil { - *err = closeErr - } -} - -func (mc *mysqlConn) handleInFileRequest(name string) (err error) { - var rdr io.Reader - var data []byte - packetSize := 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP - if mc.maxWriteSize < packetSize { - packetSize = mc.maxWriteSize - } - - if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader - // The server might return an an absolute path. See issue #355. - name = name[idx+8:] - - readerRegisterLock.RLock() - handler, inMap := readerRegister[name] - readerRegisterLock.RUnlock() - - if inMap { - rdr = handler() - if rdr != nil { - if cl, ok := rdr.(io.Closer); ok { - defer deferredClose(&err, cl) - } - } else { - err = fmt.Errorf("Reader '%s' is ", name) - } - } else { - err = fmt.Errorf("Reader '%s' is not registered", name) - } - } else { // File - name = strings.Trim(name, `"`) - fileRegisterLock.RLock() - fr := fileRegister[name] - fileRegisterLock.RUnlock() - if mc.cfg.AllowAllFiles || fr { - var file *os.File - var fi os.FileInfo - - if file, err = os.Open(name); err == nil { - defer deferredClose(&err, file) - - // get file size - if fi, err = file.Stat(); err == nil { - rdr = file - if fileSize := int(fi.Size()); fileSize < packetSize { - packetSize = fileSize - } - } - } - } else { - err = fmt.Errorf("local file '%s' is not registered", name) - } - } - - // send content packets - // if packetSize == 0, the Reader contains no data - if err == nil && packetSize > 0 { - data := make([]byte, 4+packetSize) - var n int - for err == nil { - n, err = rdr.Read(data[4:]) - if n > 0 { - if ioErr := mc.writePacket(data[:4+n]); ioErr != nil { - return ioErr - } - } - } - if err == io.EOF { - err = nil - } - } - - // send empty packet (termination) - if data == nil { - data = make([]byte, 4) - } - if ioErr := mc.writePacket(data[:4]); ioErr != nil { - return ioErr - } - - // read OK packet - if err == nil { - return mc.readResultOK() - } - - mc.readPacket() - return err -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime.go deleted file mode 100644 index 651723a9..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime.go +++ /dev/null @@ -1,50 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "database/sql/driver" - "fmt" - "time" -) - -// Scan implements the Scanner interface. -// The value type must be time.Time or string / []byte (formatted time-string), -// otherwise Scan fails. -func (nt *NullTime) Scan(value interface{}) (err error) { - if value == nil { - nt.Time, nt.Valid = time.Time{}, false - return - } - - switch v := value.(type) { - case time.Time: - nt.Time, nt.Valid = v, true - return - case []byte: - nt.Time, err = parseDateTime(v, time.UTC) - nt.Valid = (err == nil) - return - case string: - nt.Time, err = parseDateTime([]byte(v), time.UTC) - nt.Valid = (err == nil) - return - } - - nt.Valid = false - return fmt.Errorf("Can't convert %T to time.Time", value) -} - -// Value implements the driver Valuer interface. -func (nt NullTime) Value() (driver.Value, error) { - if !nt.Valid { - return nil, nil - } - return nt.Time, nil -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_go113.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_go113.go deleted file mode 100644 index 453b4b39..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_go113.go +++ /dev/null @@ -1,40 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -// +build go1.13 - -package mysql - -import ( - "database/sql" -) - -// NullTime represents a time.Time that may be NULL. -// NullTime implements the Scanner interface so -// it can be used as a scan destination: -// -// var nt NullTime -// err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt) -// ... -// if nt.Valid { -// // use nt.Time -// } else { -// // NULL value -// } -// -// This NullTime implementation is not driver-specific -// -// Deprecated: NullTime doesn't honor the loc DSN parameter. -// NullTime.Scan interprets a time as UTC, not the loc DSN parameter. -// Use sql.NullTime instead. -type NullTime sql.NullTime - -// for internal use. -// the mysql package uses sql.NullTime if it is available. -// if not, the package uses mysql.NullTime. -type nullTime = sql.NullTime // sql.NullTime is available diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_legacy.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_legacy.go deleted file mode 100644 index 9f7ae27a..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime_legacy.go +++ /dev/null @@ -1,39 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -// +build !go1.13 - -package mysql - -import ( - "time" -) - -// NullTime represents a time.Time that may be NULL. -// NullTime implements the Scanner interface so -// it can be used as a scan destination: -// -// var nt NullTime -// err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt) -// ... -// if nt.Valid { -// // use nt.Time -// } else { -// // NULL value -// } -// -// This NullTime implementation is not driver-specific -type NullTime struct { - Time time.Time - Valid bool // Valid is true if Time is not NULL -} - -// for internal use. -// the mysql package uses sql.NullTime if it is available. -// if not, the package uses mysql.NullTime. -type nullTime = NullTime // sql.NullTime is not available diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/packets.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/packets.go deleted file mode 100644 index 6664e5ae..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/packets.go +++ /dev/null @@ -1,1349 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "bytes" - "crypto/tls" - "database/sql/driver" - "encoding/binary" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "time" -) - -// Packets documentation: -// http://dev.mysql.com/doc/internals/en/client-server-protocol.html - -// Read packet to buffer 'data' -func (mc *mysqlConn) readPacket() ([]byte, error) { - var prevData []byte - for { - // read packet header - data, err := mc.buf.readNext(4) - if err != nil { - if cerr := mc.canceled.Value(); cerr != nil { - return nil, cerr - } - errLog.Print(err) - mc.Close() - return nil, ErrInvalidConn - } - - // packet length [24 bit] - pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16) - - // check packet sync [8 bit] - if data[3] != mc.sequence { - if data[3] > mc.sequence { - return nil, ErrPktSyncMul - } - return nil, ErrPktSync - } - mc.sequence++ - - // packets with length 0 terminate a previous packet which is a - // multiple of (2^24)-1 bytes long - if pktLen == 0 { - // there was no previous packet - if prevData == nil { - errLog.Print(ErrMalformPkt) - mc.Close() - return nil, ErrInvalidConn - } - - return prevData, nil - } - - // read packet body [pktLen bytes] - data, err = mc.buf.readNext(pktLen) - if err != nil { - if cerr := mc.canceled.Value(); cerr != nil { - return nil, cerr - } - errLog.Print(err) - mc.Close() - return nil, ErrInvalidConn - } - - // return data if this was the last packet - if pktLen < maxPacketSize { - // zero allocations for non-split packets - if prevData == nil { - return data, nil - } - - return append(prevData, data...), nil - } - - prevData = append(prevData, data...) - } -} - -// Write packet buffer 'data' -func (mc *mysqlConn) writePacket(data []byte) error { - pktLen := len(data) - 4 - - if pktLen > mc.maxAllowedPacket { - return ErrPktTooLarge - } - - // Perform a stale connection check. We only perform this check for - // the first query on a connection that has been checked out of the - // connection pool: a fresh connection from the pool is more likely - // to be stale, and it has not performed any previous writes that - // could cause data corruption, so it's safe to return ErrBadConn - // if the check fails. - if mc.reset { - mc.reset = false - conn := mc.netConn - if mc.rawConn != nil { - conn = mc.rawConn - } - var err error - // If this connection has a ReadTimeout which we've been setting on - // reads, reset it to its default value before we attempt a non-blocking - // read, otherwise the scheduler will just time us out before we can read - if mc.cfg.ReadTimeout != 0 { - err = conn.SetReadDeadline(time.Time{}) - } - if err == nil && mc.cfg.CheckConnLiveness { - err = connCheck(conn) - } - if err != nil { - errLog.Print("closing bad idle connection: ", err) - mc.Close() - return driver.ErrBadConn - } - } - - for { - var size int - if pktLen >= maxPacketSize { - data[0] = 0xff - data[1] = 0xff - data[2] = 0xff - size = maxPacketSize - } else { - data[0] = byte(pktLen) - data[1] = byte(pktLen >> 8) - data[2] = byte(pktLen >> 16) - size = pktLen - } - data[3] = mc.sequence - - // Write packet - if mc.writeTimeout > 0 { - if err := mc.netConn.SetWriteDeadline(time.Now().Add(mc.writeTimeout)); err != nil { - return err - } - } - - n, err := mc.netConn.Write(data[:4+size]) - if err == nil && n == 4+size { - mc.sequence++ - if size != maxPacketSize { - return nil - } - pktLen -= size - data = data[size:] - continue - } - - // Handle error - if err == nil { // n != len(data) - mc.cleanup() - errLog.Print(ErrMalformPkt) - } else { - if cerr := mc.canceled.Value(); cerr != nil { - return cerr - } - if n == 0 && pktLen == len(data)-4 { - // only for the first loop iteration when nothing was written yet - return errBadConnNoWrite - } - mc.cleanup() - errLog.Print(err) - } - return ErrInvalidConn - } -} - -/****************************************************************************** -* Initialization Process * -******************************************************************************/ - -// Handshake Initialization Packet -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake -func (mc *mysqlConn) readHandshakePacket() (data []byte, plugin string, err error) { - data, err = mc.readPacket() - if err != nil { - // for init we can rewrite this to ErrBadConn for sql.Driver to retry, since - // in connection initialization we don't risk retrying non-idempotent actions. - if err == ErrInvalidConn { - return nil, "", driver.ErrBadConn - } - return - } - - if data[0] == iERR { - return nil, "", mc.handleErrorPacket(data) - } - - // protocol version [1 byte] - if data[0] < minProtocolVersion { - return nil, "", fmt.Errorf( - "unsupported protocol version %d. Version %d or higher is required", - data[0], - minProtocolVersion, - ) - } - - // server version [null terminated string] - // connection id [4 bytes] - pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4 - - // first part of the password cipher [8 bytes] - authData := data[pos : pos+8] - - // (filler) always 0x00 [1 byte] - pos += 8 + 1 - - // capability flags (lower 2 bytes) [2 bytes] - mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) - if mc.flags&clientProtocol41 == 0 { - return nil, "", ErrOldProtocol - } - if mc.flags&clientSSL == 0 && mc.cfg.tls != nil { - if mc.cfg.TLSConfig == "preferred" { - mc.cfg.tls = nil - } else { - return nil, "", ErrNoTLS - } - } - pos += 2 - - if len(data) > pos { - // character set [1 byte] - // status flags [2 bytes] - // capability flags (upper 2 bytes) [2 bytes] - // length of auth-plugin-data [1 byte] - // reserved (all [00]) [10 bytes] - pos += 1 + 2 + 2 + 1 + 10 - - // second part of the password cipher [mininum 13 bytes], - // where len=MAX(13, length of auth-plugin-data - 8) - // - // The web documentation is ambiguous about the length. However, - // according to mysql-5.7/sql/auth/sql_authentication.cc line 538, - // the 13th byte is "\0 byte, terminating the second part of - // a scramble". So the second part of the password cipher is - // a NULL terminated string that's at least 13 bytes with the - // last byte being NULL. - // - // The official Python library uses the fixed length 12 - // which seems to work but technically could have a hidden bug. - authData = append(authData, data[pos:pos+12]...) - pos += 13 - - // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2) - // \NUL otherwise - if end := bytes.IndexByte(data[pos:], 0x00); end != -1 { - plugin = string(data[pos : pos+end]) - } else { - plugin = string(data[pos:]) - } - - // make a memory safe copy of the cipher slice - var b [20]byte - copy(b[:], authData) - return b[:], plugin, nil - } - - // make a memory safe copy of the cipher slice - var b [8]byte - copy(b[:], authData) - return b[:], plugin, nil -} - -// Client Authentication Packet -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse -func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string) error { - // Adjust client flags based on server support - clientFlags := clientProtocol41 | - clientSecureConn | - clientLongPassword | - clientTransactions | - clientLocalFiles | - clientPluginAuth | - clientMultiResults | - mc.flags&clientLongFlag - - if mc.cfg.ClientFoundRows { - clientFlags |= clientFoundRows - } - - // To enable TLS / SSL - if mc.cfg.tls != nil { - clientFlags |= clientSSL - } - - if mc.cfg.MultiStatements { - clientFlags |= clientMultiStatements - } - - // encode length of the auth plugin data - var authRespLEIBuf [9]byte - authRespLen := len(authResp) - authRespLEI := appendLengthEncodedInteger(authRespLEIBuf[:0], uint64(authRespLen)) - if len(authRespLEI) > 1 { - // if the length can not be written in 1 byte, it must be written as a - // length encoded integer - clientFlags |= clientPluginAuthLenEncClientData - } - - pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1 + len(authRespLEI) + len(authResp) + 21 + 1 - - // To specify a db name - if n := len(mc.cfg.DBName); n > 0 { - clientFlags |= clientConnectWithDB - pktLen += n + 1 - } - - // Calculate packet length and get buffer with that size - data, err := mc.buf.takeSmallBuffer(pktLen + 4) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // ClientFlags [32 bit] - data[4] = byte(clientFlags) - data[5] = byte(clientFlags >> 8) - data[6] = byte(clientFlags >> 16) - data[7] = byte(clientFlags >> 24) - - // MaxPacketSize [32 bit] (none) - data[8] = 0x00 - data[9] = 0x00 - data[10] = 0x00 - data[11] = 0x00 - - // Charset [1 byte] - var found bool - data[12], found = collations[mc.cfg.Collation] - if !found { - // Note possibility for false negatives: - // could be triggered although the collation is valid if the - // collations map does not contain entries the server supports. - return errors.New("unknown collation") - } - - // Filler [23 bytes] (all 0x00) - pos := 13 - for ; pos < 13+23; pos++ { - data[pos] = 0 - } - - // SSL Connection Request Packet - // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest - if mc.cfg.tls != nil { - // Send TLS / SSL request packet - if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil { - return err - } - - // Switch to TLS - tlsConn := tls.Client(mc.netConn, mc.cfg.tls) - if err := tlsConn.Handshake(); err != nil { - return err - } - mc.rawConn = mc.netConn - mc.netConn = tlsConn - mc.buf.nc = tlsConn - } - - // User [null terminated string] - if len(mc.cfg.User) > 0 { - pos += copy(data[pos:], mc.cfg.User) - } - data[pos] = 0x00 - pos++ - - // Auth Data [length encoded integer] - pos += copy(data[pos:], authRespLEI) - pos += copy(data[pos:], authResp) - - // Databasename [null terminated string] - if len(mc.cfg.DBName) > 0 { - pos += copy(data[pos:], mc.cfg.DBName) - data[pos] = 0x00 - pos++ - } - - pos += copy(data[pos:], plugin) - data[pos] = 0x00 - pos++ - - // Send Auth packet - return mc.writePacket(data[:pos]) -} - -// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse -func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error { - pktLen := 4 + len(authData) - data, err := mc.buf.takeSmallBuffer(pktLen) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add the auth data [EOF] - copy(data[4:], authData) - return mc.writePacket(data) -} - -/****************************************************************************** -* Command Packets * -******************************************************************************/ - -func (mc *mysqlConn) writeCommandPacket(command byte) error { - // Reset Packet Sequence - mc.sequence = 0 - - data, err := mc.buf.takeSmallBuffer(4 + 1) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Send CMD packet - return mc.writePacket(data) -} - -func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { - // Reset Packet Sequence - mc.sequence = 0 - - pktLen := 1 + len(arg) - data, err := mc.buf.takeBuffer(pktLen + 4) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Add arg - copy(data[5:], arg) - - // Send CMD packet - return mc.writePacket(data) -} - -func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error { - // Reset Packet Sequence - mc.sequence = 0 - - data, err := mc.buf.takeSmallBuffer(4 + 1 + 4) - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // Add command byte - data[4] = command - - // Add arg [32 bit] - data[5] = byte(arg) - data[6] = byte(arg >> 8) - data[7] = byte(arg >> 16) - data[8] = byte(arg >> 24) - - // Send CMD packet - return mc.writePacket(data) -} - -/****************************************************************************** -* Result Packets * -******************************************************************************/ - -func (mc *mysqlConn) readAuthResult() ([]byte, string, error) { - data, err := mc.readPacket() - if err != nil { - return nil, "", err - } - - // packet indicator - switch data[0] { - - case iOK: - return nil, "", mc.handleOkPacket(data) - - case iAuthMoreData: - return data[1:], "", err - - case iEOF: - if len(data) == 1 { - // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest - return nil, "mysql_old_password", nil - } - pluginEndIndex := bytes.IndexByte(data, 0x00) - if pluginEndIndex < 0 { - return nil, "", ErrMalformPkt - } - plugin := string(data[1:pluginEndIndex]) - authData := data[pluginEndIndex+1:] - return authData, plugin, nil - - default: // Error otherwise - return nil, "", mc.handleErrorPacket(data) - } -} - -// Returns error if Packet is not an 'Result OK'-Packet -func (mc *mysqlConn) readResultOK() error { - data, err := mc.readPacket() - if err != nil { - return err - } - - if data[0] == iOK { - return mc.handleOkPacket(data) - } - return mc.handleErrorPacket(data) -} - -// Result Set Header Packet -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::Resultset -func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) { - data, err := mc.readPacket() - if err == nil { - switch data[0] { - - case iOK: - return 0, mc.handleOkPacket(data) - - case iERR: - return 0, mc.handleErrorPacket(data) - - case iLocalInFile: - return 0, mc.handleInFileRequest(string(data[1:])) - } - - // column count - num, _, n := readLengthEncodedInteger(data) - if n-len(data) == 0 { - return int(num), nil - } - - return 0, ErrMalformPkt - } - return 0, err -} - -// Error Packet -// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-ERR_Packet -func (mc *mysqlConn) handleErrorPacket(data []byte) error { - if data[0] != iERR { - return ErrMalformPkt - } - - // 0xff [1 byte] - - // Error Number [16 bit uint] - errno := binary.LittleEndian.Uint16(data[1:3]) - - // 1792: ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION - // 1290: ER_OPTION_PREVENTS_STATEMENT (returned by Aurora during failover) - if (errno == 1792 || errno == 1290) && mc.cfg.RejectReadOnly { - // Oops; we are connected to a read-only connection, and won't be able - // to issue any write statements. Since RejectReadOnly is configured, - // we throw away this connection hoping this one would have write - // permission. This is specifically for a possible race condition - // during failover (e.g. on AWS Aurora). See README.md for more. - // - // We explicitly close the connection before returning - // driver.ErrBadConn to ensure that `database/sql` purges this - // connection and initiates a new one for next statement next time. - mc.Close() - return driver.ErrBadConn - } - - pos := 3 - - // SQL State [optional: # + 5bytes string] - if data[3] == 0x23 { - //sqlstate := string(data[4 : 4+5]) - pos = 9 - } - - // Error Message [string] - return &MySQLError{ - Number: errno, - Message: string(data[pos:]), - } -} - -func readStatus(b []byte) statusFlag { - return statusFlag(b[0]) | statusFlag(b[1])<<8 -} - -// Ok Packet -// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-OK_Packet -func (mc *mysqlConn) handleOkPacket(data []byte) error { - var n, m int - - // 0x00 [1 byte] - - // Affected rows [Length Coded Binary] - mc.affectedRows, _, n = readLengthEncodedInteger(data[1:]) - - // Insert id [Length Coded Binary] - mc.insertId, _, m = readLengthEncodedInteger(data[1+n:]) - - // server_status [2 bytes] - mc.status = readStatus(data[1+n+m : 1+n+m+2]) - if mc.status&statusMoreResultsExists != 0 { - return nil - } - - // warning count [2 bytes] - - return nil -} - -// Read Packets as Field Packets until EOF-Packet or an Error appears -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnDefinition41 -func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) { - columns := make([]mysqlField, count) - - for i := 0; ; i++ { - data, err := mc.readPacket() - if err != nil { - return nil, err - } - - // EOF Packet - if data[0] == iEOF && (len(data) == 5 || len(data) == 1) { - if i == count { - return columns, nil - } - return nil, fmt.Errorf("column count mismatch n:%d len:%d", count, len(columns)) - } - - // Catalog - pos, err := skipLengthEncodedString(data) - if err != nil { - return nil, err - } - - // Database [len coded string] - n, err := skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Table [len coded string] - if mc.cfg.ColumnsWithAlias { - tableName, _, n, err := readLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - columns[i].tableName = string(tableName) - } else { - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - } - - // Original table [len coded string] - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Name [len coded string] - name, _, n, err := readLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - columns[i].name = string(name) - pos += n - - // Original name [len coded string] - n, err = skipLengthEncodedString(data[pos:]) - if err != nil { - return nil, err - } - pos += n - - // Filler [uint8] - pos++ - - // Charset [charset, collation uint8] - columns[i].charSet = data[pos] - pos += 2 - - // Length [uint32] - columns[i].length = binary.LittleEndian.Uint32(data[pos : pos+4]) - pos += 4 - - // Field type [uint8] - columns[i].fieldType = fieldType(data[pos]) - pos++ - - // Flags [uint16] - columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) - pos += 2 - - // Decimals [uint8] - columns[i].decimals = data[pos] - //pos++ - - // Default value [len coded binary] - //if pos < len(data) { - // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:]) - //} - } -} - -// Read Packets as Field Packets until EOF-Packet or an Error appears -// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow -func (rows *textRows) readRow(dest []driver.Value) error { - mc := rows.mc - - if rows.rs.done { - return io.EOF - } - - data, err := mc.readPacket() - if err != nil { - return err - } - - // EOF Packet - if data[0] == iEOF && len(data) == 5 { - // server_status [2 bytes] - rows.mc.status = readStatus(data[3:]) - rows.rs.done = true - if !rows.HasNextResultSet() { - rows.mc = nil - } - return io.EOF - } - if data[0] == iERR { - rows.mc = nil - return mc.handleErrorPacket(data) - } - - // RowSet Packet - var n int - var isNull bool - pos := 0 - - for i := range dest { - // Read bytes and convert to string - dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) - pos += n - if err == nil { - if !isNull { - if !mc.parseTime { - continue - } else { - switch rows.rs.columns[i].fieldType { - case fieldTypeTimestamp, fieldTypeDateTime, - fieldTypeDate, fieldTypeNewDate: - dest[i], err = parseDateTime( - dest[i].([]byte), - mc.cfg.Loc, - ) - if err == nil { - continue - } - default: - continue - } - } - - } else { - dest[i] = nil - continue - } - } - return err // err != nil - } - - return nil -} - -// Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read -func (mc *mysqlConn) readUntilEOF() error { - for { - data, err := mc.readPacket() - if err != nil { - return err - } - - switch data[0] { - case iERR: - return mc.handleErrorPacket(data) - case iEOF: - if len(data) == 5 { - mc.status = readStatus(data[3:]) - } - return nil - } - } -} - -/****************************************************************************** -* Prepared Statements * -******************************************************************************/ - -// Prepare Result Packets -// http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html -func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) { - data, err := stmt.mc.readPacket() - if err == nil { - // packet indicator [1 byte] - if data[0] != iOK { - return 0, stmt.mc.handleErrorPacket(data) - } - - // statement id [4 bytes] - stmt.id = binary.LittleEndian.Uint32(data[1:5]) - - // Column count [16 bit uint] - columnCount := binary.LittleEndian.Uint16(data[5:7]) - - // Param count [16 bit uint] - stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9])) - - // Reserved [8 bit] - - // Warning count [16 bit uint] - - return columnCount, nil - } - return 0, err -} - -// http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html -func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error { - maxLen := stmt.mc.maxAllowedPacket - 1 - pktLen := maxLen - - // After the header (bytes 0-3) follows before the data: - // 1 byte command - // 4 bytes stmtID - // 2 bytes paramID - const dataOffset = 1 + 4 + 2 - - // Cannot use the write buffer since - // a) the buffer is too small - // b) it is in use - data := make([]byte, 4+1+4+2+len(arg)) - - copy(data[4+dataOffset:], arg) - - for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset { - if dataOffset+argLen < maxLen { - pktLen = dataOffset + argLen - } - - stmt.mc.sequence = 0 - // Add command byte [1 byte] - data[4] = comStmtSendLongData - - // Add stmtID [32 bit] - data[5] = byte(stmt.id) - data[6] = byte(stmt.id >> 8) - data[7] = byte(stmt.id >> 16) - data[8] = byte(stmt.id >> 24) - - // Add paramID [16 bit] - data[9] = byte(paramID) - data[10] = byte(paramID >> 8) - - // Send CMD packet - err := stmt.mc.writePacket(data[:4+pktLen]) - if err == nil { - data = data[pktLen-dataOffset:] - continue - } - return err - - } - - // Reset Packet Sequence - stmt.mc.sequence = 0 - return nil -} - -// Execute Prepared Statement -// http://dev.mysql.com/doc/internals/en/com-stmt-execute.html -func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { - if len(args) != stmt.paramCount { - return fmt.Errorf( - "argument count mismatch (got: %d; has: %d)", - len(args), - stmt.paramCount, - ) - } - - const minPktLen = 4 + 1 + 4 + 1 + 4 - mc := stmt.mc - - // Determine threshold dynamically to avoid packet size shortage. - longDataSize := mc.maxAllowedPacket / (stmt.paramCount + 1) - if longDataSize < 64 { - longDataSize = 64 - } - - // Reset packet-sequence - mc.sequence = 0 - - var data []byte - var err error - - if len(args) == 0 { - data, err = mc.buf.takeBuffer(minPktLen) - } else { - data, err = mc.buf.takeCompleteBuffer() - // In this case the len(data) == cap(data) which is used to optimise the flow below. - } - if err != nil { - // cannot take the buffer. Something must be wrong with the connection - errLog.Print(err) - return errBadConnNoWrite - } - - // command [1 byte] - data[4] = comStmtExecute - - // statement_id [4 bytes] - data[5] = byte(stmt.id) - data[6] = byte(stmt.id >> 8) - data[7] = byte(stmt.id >> 16) - data[8] = byte(stmt.id >> 24) - - // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte] - data[9] = 0x00 - - // iteration_count (uint32(1)) [4 bytes] - data[10] = 0x01 - data[11] = 0x00 - data[12] = 0x00 - data[13] = 0x00 - - if len(args) > 0 { - pos := minPktLen - - var nullMask []byte - if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= cap(data) { - // buffer has to be extended but we don't know by how much so - // we depend on append after all data with known sizes fit. - // We stop at that because we deal with a lot of columns here - // which makes the required allocation size hard to guess. - tmp := make([]byte, pos+maskLen+typesLen) - copy(tmp[:pos], data[:pos]) - data = tmp - nullMask = data[pos : pos+maskLen] - // No need to clean nullMask as make ensures that. - pos += maskLen - } else { - nullMask = data[pos : pos+maskLen] - for i := range nullMask { - nullMask[i] = 0 - } - pos += maskLen - } - - // newParameterBoundFlag 1 [1 byte] - data[pos] = 0x01 - pos++ - - // type of each parameter [len(args)*2 bytes] - paramTypes := data[pos:] - pos += len(args) * 2 - - // value of each parameter [n bytes] - paramValues := data[pos:pos] - valuesCap := cap(paramValues) - - for i, arg := range args { - // build NULL-bitmap - if arg == nil { - nullMask[i/8] |= 1 << (uint(i) & 7) - paramTypes[i+i] = byte(fieldTypeNULL) - paramTypes[i+i+1] = 0x00 - continue - } - - if v, ok := arg.(json.RawMessage); ok { - arg = []byte(v) - } - // cache types and values - switch v := arg.(type) { - case int64: - paramTypes[i+i] = byte(fieldTypeLongLong) - paramTypes[i+i+1] = 0x00 - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - uint64(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(uint64(v))..., - ) - } - - case uint64: - paramTypes[i+i] = byte(fieldTypeLongLong) - paramTypes[i+i+1] = 0x80 // type is unsigned - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - uint64(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(uint64(v))..., - ) - } - - case float64: - paramTypes[i+i] = byte(fieldTypeDouble) - paramTypes[i+i+1] = 0x00 - - if cap(paramValues)-len(paramValues)-8 >= 0 { - paramValues = paramValues[:len(paramValues)+8] - binary.LittleEndian.PutUint64( - paramValues[len(paramValues)-8:], - math.Float64bits(v), - ) - } else { - paramValues = append(paramValues, - uint64ToBytes(math.Float64bits(v))..., - ) - } - - case bool: - paramTypes[i+i] = byte(fieldTypeTiny) - paramTypes[i+i+1] = 0x00 - - if v { - paramValues = append(paramValues, 0x01) - } else { - paramValues = append(paramValues, 0x00) - } - - case []byte: - // Common case (non-nil value) first - if v != nil { - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - if len(v) < longDataSize { - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(v)), - ) - paramValues = append(paramValues, v...) - } else { - if err := stmt.writeCommandLongData(i, v); err != nil { - return err - } - } - continue - } - - // Handle []byte(nil) as a NULL value - nullMask[i/8] |= 1 << (uint(i) & 7) - paramTypes[i+i] = byte(fieldTypeNULL) - paramTypes[i+i+1] = 0x00 - - case string: - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - if len(v) < longDataSize { - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(v)), - ) - paramValues = append(paramValues, v...) - } else { - if err := stmt.writeCommandLongData(i, []byte(v)); err != nil { - return err - } - } - - case time.Time: - paramTypes[i+i] = byte(fieldTypeString) - paramTypes[i+i+1] = 0x00 - - var a [64]byte - var b = a[:0] - - if v.IsZero() { - b = append(b, "0000-00-00"...) - } else { - b, err = appendDateTime(b, v.In(mc.cfg.Loc)) - if err != nil { - return err - } - } - - paramValues = appendLengthEncodedInteger(paramValues, - uint64(len(b)), - ) - paramValues = append(paramValues, b...) - - default: - return fmt.Errorf("cannot convert type: %T", arg) - } - } - - // Check if param values exceeded the available buffer - // In that case we must build the data packet with the new values buffer - if valuesCap != cap(paramValues) { - data = append(data[:pos], paramValues...) - if err = mc.buf.store(data); err != nil { - errLog.Print(err) - return errBadConnNoWrite - } - } - - pos += len(paramValues) - data = data[:pos] - } - - return mc.writePacket(data) -} - -func (mc *mysqlConn) discardResults() error { - for mc.status&statusMoreResultsExists != 0 { - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return err - } - if resLen > 0 { - // columns - if err := mc.readUntilEOF(); err != nil { - return err - } - // rows - if err := mc.readUntilEOF(); err != nil { - return err - } - } - } - return nil -} - -// http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html -func (rows *binaryRows) readRow(dest []driver.Value) error { - data, err := rows.mc.readPacket() - if err != nil { - return err - } - - // packet indicator [1 byte] - if data[0] != iOK { - // EOF Packet - if data[0] == iEOF && len(data) == 5 { - rows.mc.status = readStatus(data[3:]) - rows.rs.done = true - if !rows.HasNextResultSet() { - rows.mc = nil - } - return io.EOF - } - mc := rows.mc - rows.mc = nil - - // Error otherwise - return mc.handleErrorPacket(data) - } - - // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes] - pos := 1 + (len(dest)+7+2)>>3 - nullMask := data[1:pos] - - for i := range dest { - // Field is NULL - // (byte >> bit-pos) % 2 == 1 - if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 { - dest[i] = nil - continue - } - - // Convert to byte-coded string - switch rows.rs.columns[i].fieldType { - case fieldTypeNULL: - dest[i] = nil - continue - - // Numeric Types - case fieldTypeTiny: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(data[pos]) - } else { - dest[i] = int64(int8(data[pos])) - } - pos++ - continue - - case fieldTypeShort, fieldTypeYear: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2])) - } else { - dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2]))) - } - pos += 2 - continue - - case fieldTypeInt24, fieldTypeLong: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4])) - } else { - dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4]))) - } - pos += 4 - continue - - case fieldTypeLongLong: - if rows.rs.columns[i].flags&flagUnsigned != 0 { - val := binary.LittleEndian.Uint64(data[pos : pos+8]) - if val > math.MaxInt64 { - dest[i] = uint64ToString(val) - } else { - dest[i] = int64(val) - } - } else { - dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8])) - } - pos += 8 - continue - - case fieldTypeFloat: - dest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])) - pos += 4 - continue - - case fieldTypeDouble: - dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8])) - pos += 8 - continue - - // Length coded Binary Strings - case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, - fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, - fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, - fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON: - var isNull bool - var n int - dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) - pos += n - if err == nil { - if !isNull { - continue - } else { - dest[i] = nil - continue - } - } - return err - - case - fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD - fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal] - fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal] - - num, isNull, n := readLengthEncodedInteger(data[pos:]) - pos += n - - switch { - case isNull: - dest[i] = nil - continue - case rows.rs.columns[i].fieldType == fieldTypeTime: - // database/sql does not support an equivalent to TIME, return a string - var dstlen uint8 - switch decimals := rows.rs.columns[i].decimals; decimals { - case 0x00, 0x1f: - dstlen = 8 - case 1, 2, 3, 4, 5, 6: - dstlen = 8 + 1 + decimals - default: - return fmt.Errorf( - "protocol error, illegal decimals value %d", - rows.rs.columns[i].decimals, - ) - } - dest[i], err = formatBinaryTime(data[pos:pos+int(num)], dstlen) - case rows.mc.parseTime: - dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc) - default: - var dstlen uint8 - if rows.rs.columns[i].fieldType == fieldTypeDate { - dstlen = 10 - } else { - switch decimals := rows.rs.columns[i].decimals; decimals { - case 0x00, 0x1f: - dstlen = 19 - case 1, 2, 3, 4, 5, 6: - dstlen = 19 + 1 + decimals - default: - return fmt.Errorf( - "protocol error, illegal decimals value %d", - rows.rs.columns[i].decimals, - ) - } - } - dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen) - } - - if err == nil { - pos += int(num) - continue - } else { - return err - } - - // Please report if this happens! - default: - return fmt.Errorf("unknown field type %d", rows.rs.columns[i].fieldType) - } - } - - return nil -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/result.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/result.go deleted file mode 100644 index c6438d03..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/result.go +++ /dev/null @@ -1,22 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -type mysqlResult struct { - affectedRows int64 - insertId int64 -} - -func (res *mysqlResult) LastInsertId() (int64, error) { - return res.insertId, nil -} - -func (res *mysqlResult) RowsAffected() (int64, error) { - return res.affectedRows, nil -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/rows.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/rows.go deleted file mode 100644 index 888bdb5f..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/rows.go +++ /dev/null @@ -1,223 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "database/sql/driver" - "io" - "math" - "reflect" -) - -type resultSet struct { - columns []mysqlField - columnNames []string - done bool -} - -type mysqlRows struct { - mc *mysqlConn - rs resultSet - finish func() -} - -type binaryRows struct { - mysqlRows -} - -type textRows struct { - mysqlRows -} - -func (rows *mysqlRows) Columns() []string { - if rows.rs.columnNames != nil { - return rows.rs.columnNames - } - - columns := make([]string, len(rows.rs.columns)) - if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias { - for i := range columns { - if tableName := rows.rs.columns[i].tableName; len(tableName) > 0 { - columns[i] = tableName + "." + rows.rs.columns[i].name - } else { - columns[i] = rows.rs.columns[i].name - } - } - } else { - for i := range columns { - columns[i] = rows.rs.columns[i].name - } - } - - rows.rs.columnNames = columns - return columns -} - -func (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string { - return rows.rs.columns[i].typeDatabaseName() -} - -// func (rows *mysqlRows) ColumnTypeLength(i int) (length int64, ok bool) { -// return int64(rows.rs.columns[i].length), true -// } - -func (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) { - return rows.rs.columns[i].flags&flagNotNULL == 0, true -} - -func (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, bool) { - column := rows.rs.columns[i] - decimals := int64(column.decimals) - - switch column.fieldType { - case fieldTypeDecimal, fieldTypeNewDecimal: - if decimals > 0 { - return int64(column.length) - 2, decimals, true - } - return int64(column.length) - 1, decimals, true - case fieldTypeTimestamp, fieldTypeDateTime, fieldTypeTime: - return decimals, decimals, true - case fieldTypeFloat, fieldTypeDouble: - if decimals == 0x1f { - return math.MaxInt64, math.MaxInt64, true - } - return math.MaxInt64, decimals, true - } - - return 0, 0, false -} - -func (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type { - return rows.rs.columns[i].scanType() -} - -func (rows *mysqlRows) Close() (err error) { - if f := rows.finish; f != nil { - f() - rows.finish = nil - } - - mc := rows.mc - if mc == nil { - return nil - } - if err := mc.error(); err != nil { - return err - } - - // flip the buffer for this connection if we need to drain it. - // note that for a successful query (i.e. one where rows.next() - // has been called until it returns false), `rows.mc` will be nil - // by the time the user calls `(*Rows).Close`, so we won't reach this - // see: https://github.com/golang/go/commit/651ddbdb5056ded455f47f9c494c67b389622a47 - mc.buf.flip() - - // Remove unread packets from stream - if !rows.rs.done { - err = mc.readUntilEOF() - } - if err == nil { - if err = mc.discardResults(); err != nil { - return err - } - } - - rows.mc = nil - return err -} - -func (rows *mysqlRows) HasNextResultSet() (b bool) { - if rows.mc == nil { - return false - } - return rows.mc.status&statusMoreResultsExists != 0 -} - -func (rows *mysqlRows) nextResultSet() (int, error) { - if rows.mc == nil { - return 0, io.EOF - } - if err := rows.mc.error(); err != nil { - return 0, err - } - - // Remove unread packets from stream - if !rows.rs.done { - if err := rows.mc.readUntilEOF(); err != nil { - return 0, err - } - rows.rs.done = true - } - - if !rows.HasNextResultSet() { - rows.mc = nil - return 0, io.EOF - } - rows.rs = resultSet{} - return rows.mc.readResultSetHeaderPacket() -} - -func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) { - for { - resLen, err := rows.nextResultSet() - if err != nil { - return 0, err - } - - if resLen > 0 { - return resLen, nil - } - - rows.rs.done = true - } -} - -func (rows *binaryRows) NextResultSet() error { - resLen, err := rows.nextNotEmptyResultSet() - if err != nil { - return err - } - - rows.rs.columns, err = rows.mc.readColumns(resLen) - return err -} - -func (rows *binaryRows) Next(dest []driver.Value) error { - if mc := rows.mc; mc != nil { - if err := mc.error(); err != nil { - return err - } - - // Fetch next row from stream - return rows.readRow(dest) - } - return io.EOF -} - -func (rows *textRows) NextResultSet() (err error) { - resLen, err := rows.nextNotEmptyResultSet() - if err != nil { - return err - } - - rows.rs.columns, err = rows.mc.readColumns(resLen) - return err -} - -func (rows *textRows) Next(dest []driver.Value) error { - if mc := rows.mc; mc != nil { - if err := mc.error(); err != nil { - return err - } - - // Fetch next row from stream - return rows.readRow(dest) - } - return io.EOF -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/statement.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/statement.go deleted file mode 100644 index 18a3ae49..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/statement.go +++ /dev/null @@ -1,220 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "database/sql/driver" - "encoding/json" - "fmt" - "io" - "reflect" -) - -type mysqlStmt struct { - mc *mysqlConn - id uint32 - paramCount int -} - -func (stmt *mysqlStmt) Close() error { - if stmt.mc == nil || stmt.mc.closed.IsSet() { - // driver.Stmt.Close can be called more than once, thus this function - // has to be idempotent. - // See also Issue #450 and golang/go#16019. - //errLog.Print(ErrInvalidConn) - return driver.ErrBadConn - } - - err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id) - stmt.mc = nil - return err -} - -func (stmt *mysqlStmt) NumInput() int { - return stmt.paramCount -} - -func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter { - return converter{} -} - -func (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err error) { - nv.Value, err = converter{}.ConvertValue(nv.Value) - return -} - -func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { - if stmt.mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := stmt.writeExecutePacket(args) - if err != nil { - return nil, stmt.mc.markBadConn(err) - } - - mc := stmt.mc - - mc.affectedRows = 0 - mc.insertId = 0 - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return nil, err - } - - if resLen > 0 { - // Columns - if err = mc.readUntilEOF(); err != nil { - return nil, err - } - - // Rows - if err := mc.readUntilEOF(); err != nil { - return nil, err - } - } - - if err := mc.discardResults(); err != nil { - return nil, err - } - - return &mysqlResult{ - affectedRows: int64(mc.affectedRows), - insertId: int64(mc.insertId), - }, nil -} - -func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { - return stmt.query(args) -} - -func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { - if stmt.mc.closed.IsSet() { - errLog.Print(ErrInvalidConn) - return nil, driver.ErrBadConn - } - // Send command - err := stmt.writeExecutePacket(args) - if err != nil { - return nil, stmt.mc.markBadConn(err) - } - - mc := stmt.mc - - // Read Result - resLen, err := mc.readResultSetHeaderPacket() - if err != nil { - return nil, err - } - - rows := new(binaryRows) - - if resLen > 0 { - rows.mc = mc - rows.rs.columns, err = mc.readColumns(resLen) - } else { - rows.rs.done = true - - switch err := rows.NextResultSet(); err { - case nil, io.EOF: - return rows, nil - default: - return nil, err - } - } - - return rows, err -} - -var jsonType = reflect.TypeOf(json.RawMessage{}) - -type converter struct{} - -// ConvertValue mirrors the reference/default converter in database/sql/driver -// with _one_ exception. We support uint64 with their high bit and the default -// implementation does not. This function should be kept in sync with -// database/sql/driver defaultConverter.ConvertValue() except for that -// deliberate difference. -func (c converter) ConvertValue(v interface{}) (driver.Value, error) { - if driver.IsValue(v) { - return v, nil - } - - if vr, ok := v.(driver.Valuer); ok { - sv, err := callValuerValue(vr) - if err != nil { - return nil, err - } - if driver.IsValue(sv) { - return sv, nil - } - // A value returend from the Valuer interface can be "a type handled by - // a database driver's NamedValueChecker interface" so we should accept - // uint64 here as well. - if u, ok := sv.(uint64); ok { - return u, nil - } - return nil, fmt.Errorf("non-Value type %T returned from Value", sv) - } - rv := reflect.ValueOf(v) - switch rv.Kind() { - case reflect.Ptr: - // indirect pointers - if rv.IsNil() { - return nil, nil - } else { - return c.ConvertValue(rv.Elem().Interface()) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int(), nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return rv.Uint(), nil - case reflect.Float32, reflect.Float64: - return rv.Float(), nil - case reflect.Bool: - return rv.Bool(), nil - case reflect.Slice: - switch t := rv.Type(); { - case t == jsonType: - return v, nil - case t.Elem().Kind() == reflect.Uint8: - return rv.Bytes(), nil - default: - return nil, fmt.Errorf("unsupported type %T, a slice of %s", v, t.Elem().Kind()) - } - case reflect.String: - return rv.String(), nil - } - return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) -} - -var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() - -// callValuerValue returns vr.Value(), with one exception: -// If vr.Value is an auto-generated method on a pointer type and the -// pointer is nil, it would panic at runtime in the panicwrap -// method. Treat it like nil instead. -// -// This is so people can implement driver.Value on value types and -// still use nil pointers to those types to mean nil/NULL, just like -// string/*string. -// -// This is an exact copy of the same-named unexported function from the -// database/sql package. -func callValuerValue(vr driver.Valuer) (v driver.Value, err error) { - if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr && - rv.IsNil() && - rv.Type().Elem().Implements(valuerReflectType) { - return nil, nil - } - return vr.Value() -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/transaction.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/transaction.go deleted file mode 100644 index 417d7279..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/transaction.go +++ /dev/null @@ -1,31 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -type mysqlTx struct { - mc *mysqlConn -} - -func (tx *mysqlTx) Commit() (err error) { - if tx.mc == nil || tx.mc.closed.IsSet() { - return ErrInvalidConn - } - err = tx.mc.exec("COMMIT") - tx.mc = nil - return -} - -func (tx *mysqlTx) Rollback() (err error) { - if tx.mc == nil || tx.mc.closed.IsSet() { - return ErrInvalidConn - } - err = tx.mc.exec("ROLLBACK") - tx.mc = nil - return -} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/utils.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/utils.go deleted file mode 100644 index d6545f5b..00000000 --- a/taskman-server/vendor/github.com/go-sql-driver/mysql/utils.go +++ /dev/null @@ -1,868 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this file, -// You can obtain one at http://mozilla.org/MPL/2.0/. - -package mysql - -import ( - "crypto/tls" - "database/sql" - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "io" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -// Registry for custom tls.Configs -var ( - tlsConfigLock sync.RWMutex - tlsConfigRegistry map[string]*tls.Config -) - -// RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. -// Use the key as a value in the DSN where tls=value. -// -// Note: The provided tls.Config is exclusively owned by the driver after -// registering it. -// -// rootCertPool := x509.NewCertPool() -// pem, err := ioutil.ReadFile("/path/ca-cert.pem") -// if err != nil { -// log.Fatal(err) -// } -// if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { -// log.Fatal("Failed to append PEM.") -// } -// clientCert := make([]tls.Certificate, 0, 1) -// certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem") -// if err != nil { -// log.Fatal(err) -// } -// clientCert = append(clientCert, certs) -// mysql.RegisterTLSConfig("custom", &tls.Config{ -// RootCAs: rootCertPool, -// Certificates: clientCert, -// }) -// db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom") -// -func RegisterTLSConfig(key string, config *tls.Config) error { - if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" || strings.ToLower(key) == "preferred" { - return fmt.Errorf("key '%s' is reserved", key) - } - - tlsConfigLock.Lock() - if tlsConfigRegistry == nil { - tlsConfigRegistry = make(map[string]*tls.Config) - } - - tlsConfigRegistry[key] = config - tlsConfigLock.Unlock() - return nil -} - -// DeregisterTLSConfig removes the tls.Config associated with key. -func DeregisterTLSConfig(key string) { - tlsConfigLock.Lock() - if tlsConfigRegistry != nil { - delete(tlsConfigRegistry, key) - } - tlsConfigLock.Unlock() -} - -func getTLSConfigClone(key string) (config *tls.Config) { - tlsConfigLock.RLock() - if v, ok := tlsConfigRegistry[key]; ok { - config = v.Clone() - } - tlsConfigLock.RUnlock() - return -} - -// Returns the bool value of the input. -// The 2nd return value indicates if the input was a valid bool value -func readBool(input string) (value bool, valid bool) { - switch input { - case "1", "true", "TRUE", "True": - return true, true - case "0", "false", "FALSE", "False": - return false, true - } - - // Not a valid bool value - return -} - -/****************************************************************************** -* Time related utils * -******************************************************************************/ - -func parseDateTime(b []byte, loc *time.Location) (time.Time, error) { - const base = "0000-00-00 00:00:00.000000" - switch len(b) { - case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM" - if string(b) == base[:len(b)] { - return time.Time{}, nil - } - - year, err := parseByteYear(b) - if err != nil { - return time.Time{}, err - } - if year <= 0 { - year = 1 - } - - if b[4] != '-' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[4]) - } - - m, err := parseByte2Digits(b[5], b[6]) - if err != nil { - return time.Time{}, err - } - if m <= 0 { - m = 1 - } - month := time.Month(m) - - if b[7] != '-' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[7]) - } - - day, err := parseByte2Digits(b[8], b[9]) - if err != nil { - return time.Time{}, err - } - if day <= 0 { - day = 1 - } - if len(b) == 10 { - return time.Date(year, month, day, 0, 0, 0, 0, loc), nil - } - - if b[10] != ' ' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[10]) - } - - hour, err := parseByte2Digits(b[11], b[12]) - if err != nil { - return time.Time{}, err - } - if b[13] != ':' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[13]) - } - - min, err := parseByte2Digits(b[14], b[15]) - if err != nil { - return time.Time{}, err - } - if b[16] != ':' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[16]) - } - - sec, err := parseByte2Digits(b[17], b[18]) - if err != nil { - return time.Time{}, err - } - if len(b) == 19 { - return time.Date(year, month, day, hour, min, sec, 0, loc), nil - } - - if b[19] != '.' { - return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[19]) - } - nsec, err := parseByteNanoSec(b[20:]) - if err != nil { - return time.Time{}, err - } - return time.Date(year, month, day, hour, min, sec, nsec, loc), nil - default: - return time.Time{}, fmt.Errorf("invalid time bytes: %s", b) - } -} - -func parseByteYear(b []byte) (int, error) { - year, n := 0, 1000 - for i := 0; i < 4; i++ { - v, err := bToi(b[i]) - if err != nil { - return 0, err - } - year += v * n - n = n / 10 - } - return year, nil -} - -func parseByte2Digits(b1, b2 byte) (int, error) { - d1, err := bToi(b1) - if err != nil { - return 0, err - } - d2, err := bToi(b2) - if err != nil { - return 0, err - } - return d1*10 + d2, nil -} - -func parseByteNanoSec(b []byte) (int, error) { - ns, digit := 0, 100000 // max is 6-digits - for i := 0; i < len(b); i++ { - v, err := bToi(b[i]) - if err != nil { - return 0, err - } - ns += v * digit - digit /= 10 - } - // nanoseconds has 10-digits. (needs to scale digits) - // 10 - 6 = 4, so we have to multiple 1000. - return ns * 1000, nil -} - -func bToi(b byte) (int, error) { - if b < '0' || b > '9' { - return 0, errors.New("not [0-9]") - } - return int(b - '0'), nil -} - -func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) { - switch num { - case 0: - return time.Time{}, nil - case 4: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - 0, 0, 0, 0, - loc, - ), nil - case 7: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds - 0, - loc, - ), nil - case 11: - return time.Date( - int(binary.LittleEndian.Uint16(data[:2])), // year - time.Month(data[2]), // month - int(data[3]), // day - int(data[4]), // hour - int(data[5]), // minutes - int(data[6]), // seconds - int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds - loc, - ), nil - } - return nil, fmt.Errorf("invalid DATETIME packet length %d", num) -} - -func appendDateTime(buf []byte, t time.Time) ([]byte, error) { - year, month, day := t.Date() - hour, min, sec := t.Clock() - nsec := t.Nanosecond() - - if year < 1 || year > 9999 { - return buf, errors.New("year is not in the range [1, 9999]: " + strconv.Itoa(year)) // use errors.New instead of fmt.Errorf to avoid year escape to heap - } - year100 := year / 100 - year1 := year % 100 - - var localBuf [len("2006-01-02T15:04:05.999999999")]byte // does not escape - localBuf[0], localBuf[1], localBuf[2], localBuf[3] = digits10[year100], digits01[year100], digits10[year1], digits01[year1] - localBuf[4] = '-' - localBuf[5], localBuf[6] = digits10[month], digits01[month] - localBuf[7] = '-' - localBuf[8], localBuf[9] = digits10[day], digits01[day] - - if hour == 0 && min == 0 && sec == 0 && nsec == 0 { - return append(buf, localBuf[:10]...), nil - } - - localBuf[10] = ' ' - localBuf[11], localBuf[12] = digits10[hour], digits01[hour] - localBuf[13] = ':' - localBuf[14], localBuf[15] = digits10[min], digits01[min] - localBuf[16] = ':' - localBuf[17], localBuf[18] = digits10[sec], digits01[sec] - - if nsec == 0 { - return append(buf, localBuf[:19]...), nil - } - nsec100000000 := nsec / 100000000 - nsec1000000 := (nsec / 1000000) % 100 - nsec10000 := (nsec / 10000) % 100 - nsec100 := (nsec / 100) % 100 - nsec1 := nsec % 100 - localBuf[19] = '.' - - // milli second - localBuf[20], localBuf[21], localBuf[22] = - digits01[nsec100000000], digits10[nsec1000000], digits01[nsec1000000] - // micro second - localBuf[23], localBuf[24], localBuf[25] = - digits10[nsec10000], digits01[nsec10000], digits10[nsec100] - // nano second - localBuf[26], localBuf[27], localBuf[28] = - digits01[nsec100], digits10[nsec1], digits01[nsec1] - - // trim trailing zeros - n := len(localBuf) - for n > 0 && localBuf[n-1] == '0' { - n-- - } - - return append(buf, localBuf[:n]...), nil -} - -// zeroDateTime is used in formatBinaryDateTime to avoid an allocation -// if the DATE or DATETIME has the zero value. -// It must never be changed. -// The current behavior depends on database/sql copying the result. -var zeroDateTime = []byte("0000-00-00 00:00:00.000000") - -const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" -const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999" - -func appendMicrosecs(dst, src []byte, decimals int) []byte { - if decimals <= 0 { - return dst - } - if len(src) == 0 { - return append(dst, ".000000"[:decimals+1]...) - } - - microsecs := binary.LittleEndian.Uint32(src[:4]) - p1 := byte(microsecs / 10000) - microsecs -= 10000 * uint32(p1) - p2 := byte(microsecs / 100) - microsecs -= 100 * uint32(p2) - p3 := byte(microsecs) - - switch decimals { - default: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - digits10[p3], digits01[p3], - ) - case 1: - return append(dst, '.', - digits10[p1], - ) - case 2: - return append(dst, '.', - digits10[p1], digits01[p1], - ) - case 3: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], - ) - case 4: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - ) - case 5: - return append(dst, '.', - digits10[p1], digits01[p1], - digits10[p2], digits01[p2], - digits10[p3], - ) - } -} - -func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) { - // length expects the deterministic length of the zero value, - // negative time and 100+ hours are automatically added if needed - if len(src) == 0 { - return zeroDateTime[:length], nil - } - var dst []byte // return value - var p1, p2, p3 byte // current digit pair - - switch length { - case 10, 19, 21, 22, 23, 24, 25, 26: - default: - t := "DATE" - if length > 10 { - t += "TIME" - } - return nil, fmt.Errorf("illegal %s length %d", t, length) - } - switch len(src) { - case 4, 7, 11: - default: - t := "DATE" - if length > 10 { - t += "TIME" - } - return nil, fmt.Errorf("illegal %s packet length %d", t, len(src)) - } - dst = make([]byte, 0, length) - // start with the date - year := binary.LittleEndian.Uint16(src[:2]) - pt := year / 100 - p1 = byte(year - 100*uint16(pt)) - p2, p3 = src[2], src[3] - dst = append(dst, - digits10[pt], digits01[pt], - digits10[p1], digits01[p1], '-', - digits10[p2], digits01[p2], '-', - digits10[p3], digits01[p3], - ) - if length == 10 { - return dst, nil - } - if len(src) == 4 { - return append(dst, zeroDateTime[10:length]...), nil - } - dst = append(dst, ' ') - p1 = src[4] // hour - src = src[5:] - - // p1 is 2-digit hour, src is after hour - p2, p3 = src[0], src[1] - dst = append(dst, - digits10[p1], digits01[p1], ':', - digits10[p2], digits01[p2], ':', - digits10[p3], digits01[p3], - ) - return appendMicrosecs(dst, src[2:], int(length)-20), nil -} - -func formatBinaryTime(src []byte, length uint8) (driver.Value, error) { - // length expects the deterministic length of the zero value, - // negative time and 100+ hours are automatically added if needed - if len(src) == 0 { - return zeroDateTime[11 : 11+length], nil - } - var dst []byte // return value - - switch length { - case - 8, // time (can be up to 10 when negative and 100+ hours) - 10, 11, 12, 13, 14, 15: // time with fractional seconds - default: - return nil, fmt.Errorf("illegal TIME length %d", length) - } - switch len(src) { - case 8, 12: - default: - return nil, fmt.Errorf("invalid TIME packet length %d", len(src)) - } - // +2 to enable negative time and 100+ hours - dst = make([]byte, 0, length+2) - if src[0] == 1 { - dst = append(dst, '-') - } - days := binary.LittleEndian.Uint32(src[1:5]) - hours := int64(days)*24 + int64(src[5]) - - if hours >= 100 { - dst = strconv.AppendInt(dst, hours, 10) - } else { - dst = append(dst, digits10[hours], digits01[hours]) - } - - min, sec := src[6], src[7] - dst = append(dst, ':', - digits10[min], digits01[min], ':', - digits10[sec], digits01[sec], - ) - return appendMicrosecs(dst, src[8:], int(length)-9), nil -} - -/****************************************************************************** -* Convert from and to bytes * -******************************************************************************/ - -func uint64ToBytes(n uint64) []byte { - return []byte{ - byte(n), - byte(n >> 8), - byte(n >> 16), - byte(n >> 24), - byte(n >> 32), - byte(n >> 40), - byte(n >> 48), - byte(n >> 56), - } -} - -func uint64ToString(n uint64) []byte { - var a [20]byte - i := 20 - - // U+0030 = 0 - // ... - // U+0039 = 9 - - var q uint64 - for n >= 10 { - i-- - q = n / 10 - a[i] = uint8(n-q*10) + 0x30 - n = q - } - - i-- - a[i] = uint8(n) + 0x30 - - return a[i:] -} - -// treats string value as unsigned integer representation -func stringToInt(b []byte) int { - val := 0 - for i := range b { - val *= 10 - val += int(b[i] - 0x30) - } - return val -} - -// returns the string read as a bytes slice, wheter the value is NULL, -// the number of bytes read and an error, in case the string is longer than -// the input slice -func readLengthEncodedString(b []byte) ([]byte, bool, int, error) { - // Get length - num, isNull, n := readLengthEncodedInteger(b) - if num < 1 { - return b[n:n], isNull, n, nil - } - - n += int(num) - - // Check data length - if len(b) >= n { - return b[n-int(num) : n : n], false, n, nil - } - return nil, false, n, io.EOF -} - -// returns the number of bytes skipped and an error, in case the string is -// longer than the input slice -func skipLengthEncodedString(b []byte) (int, error) { - // Get length - num, _, n := readLengthEncodedInteger(b) - if num < 1 { - return n, nil - } - - n += int(num) - - // Check data length - if len(b) >= n { - return n, nil - } - return n, io.EOF -} - -// returns the number read, whether the value is NULL and the number of bytes read -func readLengthEncodedInteger(b []byte) (uint64, bool, int) { - // See issue #349 - if len(b) == 0 { - return 0, true, 1 - } - - switch b[0] { - // 251: NULL - case 0xfb: - return 0, true, 1 - - // 252: value of following 2 - case 0xfc: - return uint64(b[1]) | uint64(b[2])<<8, false, 3 - - // 253: value of following 3 - case 0xfd: - return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4 - - // 254: value of following 8 - case 0xfe: - return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 | - uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 | - uint64(b[7])<<48 | uint64(b[8])<<56, - false, 9 - } - - // 0-250: value of first byte - return uint64(b[0]), false, 1 -} - -// encodes a uint64 value and appends it to the given bytes slice -func appendLengthEncodedInteger(b []byte, n uint64) []byte { - switch { - case n <= 250: - return append(b, byte(n)) - - case n <= 0xffff: - return append(b, 0xfc, byte(n), byte(n>>8)) - - case n <= 0xffffff: - return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16)) - } - return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24), - byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56)) -} - -// reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize. -// If cap(buf) is not enough, reallocate new buffer. -func reserveBuffer(buf []byte, appendSize int) []byte { - newSize := len(buf) + appendSize - if cap(buf) < newSize { - // Grow buffer exponentially - newBuf := make([]byte, len(buf)*2+appendSize) - copy(newBuf, buf) - buf = newBuf - } - return buf[:newSize] -} - -// escapeBytesBackslash escapes []byte with backslashes (\) -// This escapes the contents of a string (provided as []byte) by adding backslashes before special -// characters, and turning others into specific escape sequences, such as -// turning newlines into \n and null bytes into \0. -// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932 -func escapeBytesBackslash(buf, v []byte) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for _, c := range v { - switch c { - case '\x00': - buf[pos] = '\\' - buf[pos+1] = '0' - pos += 2 - case '\n': - buf[pos] = '\\' - buf[pos+1] = 'n' - pos += 2 - case '\r': - buf[pos] = '\\' - buf[pos+1] = 'r' - pos += 2 - case '\x1a': - buf[pos] = '\\' - buf[pos+1] = 'Z' - pos += 2 - case '\'': - buf[pos] = '\\' - buf[pos+1] = '\'' - pos += 2 - case '"': - buf[pos] = '\\' - buf[pos+1] = '"' - pos += 2 - case '\\': - buf[pos] = '\\' - buf[pos+1] = '\\' - pos += 2 - default: - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeStringBackslash is similar to escapeBytesBackslash but for string. -func escapeStringBackslash(buf []byte, v string) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for i := 0; i < len(v); i++ { - c := v[i] - switch c { - case '\x00': - buf[pos] = '\\' - buf[pos+1] = '0' - pos += 2 - case '\n': - buf[pos] = '\\' - buf[pos+1] = 'n' - pos += 2 - case '\r': - buf[pos] = '\\' - buf[pos+1] = 'r' - pos += 2 - case '\x1a': - buf[pos] = '\\' - buf[pos+1] = 'Z' - pos += 2 - case '\'': - buf[pos] = '\\' - buf[pos+1] = '\'' - pos += 2 - case '"': - buf[pos] = '\\' - buf[pos+1] = '"' - pos += 2 - case '\\': - buf[pos] = '\\' - buf[pos+1] = '\\' - pos += 2 - default: - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeBytesQuotes escapes apostrophes in []byte by doubling them up. -// This escapes the contents of a string by doubling up any apostrophes that -// it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in -// effect on the server. -// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038 -func escapeBytesQuotes(buf, v []byte) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for _, c := range v { - if c == '\'' { - buf[pos] = '\'' - buf[pos+1] = '\'' - pos += 2 - } else { - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -// escapeStringQuotes is similar to escapeBytesQuotes but for string. -func escapeStringQuotes(buf []byte, v string) []byte { - pos := len(buf) - buf = reserveBuffer(buf, len(v)*2) - - for i := 0; i < len(v); i++ { - c := v[i] - if c == '\'' { - buf[pos] = '\'' - buf[pos+1] = '\'' - pos += 2 - } else { - buf[pos] = c - pos++ - } - } - - return buf[:pos] -} - -/****************************************************************************** -* Sync utils * -******************************************************************************/ - -// noCopy may be embedded into structs which must not be copied -// after the first use. -// -// See https://github.com/golang/go/issues/8005#issuecomment-190753527 -// for details. -type noCopy struct{} - -// Lock is a no-op used by -copylocks checker from `go vet`. -func (*noCopy) Lock() {} - -// atomicBool is a wrapper around uint32 for usage as a boolean value with -// atomic access. -type atomicBool struct { - _noCopy noCopy - value uint32 -} - -// IsSet returns whether the current boolean value is true -func (ab *atomicBool) IsSet() bool { - return atomic.LoadUint32(&ab.value) > 0 -} - -// Set sets the value of the bool regardless of the previous value -func (ab *atomicBool) Set(value bool) { - if value { - atomic.StoreUint32(&ab.value, 1) - } else { - atomic.StoreUint32(&ab.value, 0) - } -} - -// TrySet sets the value of the bool and returns whether the value changed -func (ab *atomicBool) TrySet(value bool) bool { - if value { - return atomic.SwapUint32(&ab.value, 1) == 0 - } - return atomic.SwapUint32(&ab.value, 0) > 0 -} - -// atomicError is a wrapper for atomically accessed error values -type atomicError struct { - _noCopy noCopy - value atomic.Value -} - -// Set sets the error value regardless of the previous value. -// The value must not be nil -func (ae *atomicError) Set(value error) { - ae.value.Store(value) -} - -// Value returns the current error value -func (ae *atomicError) Value() error { - if v := ae.value.Load(); v != nil { - // this will panic if the value doesn't implement the error interface - return v.(error) - } - return nil -} - -func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) { - dargs := make([]driver.Value, len(named)) - for n, param := range named { - if len(param.Name) > 0 { - // TODO: support the use of Named Parameters #561 - return nil, errors.New("mysql: driver does not support the use of Named Parameters") - } - dargs[n] = param.Value - } - return dargs, nil -} - -func mapIsolationLevel(level driver.IsolationLevel) (string, error) { - switch sql.IsolationLevel(level) { - case sql.LevelRepeatableRead: - return "REPEATABLE READ", nil - case sql.LevelReadCommitted: - return "READ COMMITTED", nil - case sql.LevelReadUncommitted: - return "READ UNCOMMITTED", nil - case sql.LevelSerializable: - return "SERIALIZABLE", nil - default: - return "", fmt.Errorf("mysql: unsupported isolation level: %v", level) - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/.codecov.yml b/taskman-server/vendor/github.com/goccy/go-json/.codecov.yml deleted file mode 100644 index e9813457..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/.codecov.yml +++ /dev/null @@ -1,32 +0,0 @@ -codecov: - require_ci_to_pass: yes - -coverage: - precision: 2 - round: down - range: "70...100" - - status: - project: - default: - target: 70% - threshold: 2% - patch: off - changes: no - -parsers: - gcov: - branch_detection: - conditional: yes - loop: yes - method: no - macro: no - -comment: - layout: "header,diff" - behavior: default - require_changes: no - -ignore: - - internal/encoder/vm_color - - internal/encoder/vm_color_indent diff --git a/taskman-server/vendor/github.com/goccy/go-json/.gitignore b/taskman-server/vendor/github.com/goccy/go-json/.gitignore deleted file mode 100644 index 37828382..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -cover.html -cover.out diff --git a/taskman-server/vendor/github.com/goccy/go-json/.golangci.yml b/taskman-server/vendor/github.com/goccy/go-json/.golangci.yml deleted file mode 100644 index 44ae40f6..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/.golangci.yml +++ /dev/null @@ -1,75 +0,0 @@ -run: - skip-files: - - encode_optype.go - - ".*_test\\.go$" - -linters-settings: - govet: - enable-all: true - disable: - - shadow - -linters: - enable-all: true - disable: - - dogsled - - dupl - - exhaustive - - exhaustivestruct - - errorlint - - forbidigo - - funlen - - gci - - gochecknoglobals - - gochecknoinits - - gocognit - - gocritic - - gocyclo - - godot - - godox - - goerr113 - - gofumpt - - gomnd - - gosec - - ifshort - - lll - - makezero - - nakedret - - nestif - - nlreturn - - paralleltest - - testpackage - - thelper - - wrapcheck - - interfacer - - lll - - nakedret - - nestif - - nlreturn - - testpackage - - wsl - -issues: - exclude-rules: - # not needed - - path: /*.go - text: "ST1003: should not use underscores in package names" - linters: - - stylecheck - - path: /*.go - text: "don't use an underscore in package name" - linters: - - golint - - path: rtype.go - linters: - - golint - - stylecheck - - path: error.go - linters: - - staticcheck - - # Maximum issues count per one linter. Set to 0 to disable. Default is 50. - max-issues-per-linter: 0 - - # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. - max-same-issues: 0 diff --git a/taskman-server/vendor/github.com/goccy/go-json/CHANGELOG.md b/taskman-server/vendor/github.com/goccy/go-json/CHANGELOG.md deleted file mode 100644 index fd6aa9d6..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/CHANGELOG.md +++ /dev/null @@ -1,236 +0,0 @@ -# v0.7.4 - 2021/07/06 - -* Fix encoding of indirect layout structure ( #264 ) - -# v0.7.3 - 2021/06/29 - -* Fix encoding of pointer type in empty interface ( #262 ) - -# v0.7.2 - 2021/06/26 - -### Fix decoder - -* Add decoder for func type to fix decoding of nil function value ( #257 ) -* Fix stream decoding of []byte type ( #258 ) - -### Performance - -* Improve decoding performance of map[string]interface{} type ( use `mapassign_faststr` ) ( #256 ) -* Improve encoding performance of empty interface type ( remove recursive calling of `vm.Run` ) ( #259 ) - -### Benchmark - -* Add bytedance/sonic as benchmark target ( #254 ) - -# v0.7.1 - 2021/06/18 - -### Fix decoder - -* Fix error when unmarshal empty array ( #253 ) - -# v0.7.0 - 2021/06/12 - -### Support context for MarshalJSON and UnmarshalJSON ( #248 ) - -* json.MarshalContext(context.Context, interface{}, ...json.EncodeOption) ([]byte, error) -* json.NewEncoder(io.Writer).EncodeContext(context.Context, interface{}, ...json.EncodeOption) error -* json.UnmarshalContext(context.Context, []byte, interface{}, ...json.DecodeOption) error -* json.NewDecoder(io.Reader).DecodeContext(context.Context, interface{}) error - -```go -type MarshalerContext interface { - MarshalJSON(context.Context) ([]byte, error) -} - -type UnmarshalerContext interface { - UnmarshalJSON(context.Context, []byte) error -} -``` - -### Add DecodeFieldPriorityFirstWin option ( #242 ) - -In the default behavior, go-json, like encoding/json, will reflect the result of the last evaluation when a field with the same name exists. I've added new options to allow you to change this behavior. `json.DecodeFieldPriorityFirstWin` option reflects the result of the first evaluation if a field with the same name exists. This behavior has a performance advantage as it allows the subsequent strings to be skipped if all fields have been evaluated. - -### Fix encoder - -* Fix indent number contains recursive type ( #249 ) -* Fix encoding of using empty interface as map key ( #244 ) - -### Fix decoder - -* Fix decoding fields containing escaped characters ( #237 ) - -### Refactor - -* Move some tests to subdirectory ( #243 ) -* Refactor package layout for decoder ( #238 ) - -# v0.6.1 - 2021/06/02 - -### Fix encoder - -* Fix value of totalLength for encoding ( #236 ) - -# v0.6.0 - 2021/06/01 - -### Support Colorize option for encoding (#233) - -```go -b, err := json.MarshalWithOption(v, json.Colorize(json.DefaultColorScheme)) -if err != nil { - ... -} -fmt.Println(string(b)) // print colored json -``` - -### Refactor - -* Fix opcode layout - Adjust memory layout of the opcode to 128 bytes in a 64-bit environment ( #230 ) -* Refactor encode option ( #231 ) -* Refactor escape string ( #232 ) - -# v0.5.1 - 2021/5/20 - -### Optimization - -* Add type addrShift to enable bigger encoder/decoder cache ( #213 ) - -### Fix decoder - -* Keep original reference of slice element ( #229 ) - -### Refactor - -* Refactor Debug mode for encoding ( #226 ) -* Generate VM sources for encoding ( #227 ) -* Refactor validator for null/true/false for decoding ( #221 ) - -# v0.5.0 - 2021/5/9 - -### Supports using omitempty and string tags at the same time ( #216 ) - -### Fix decoder - -* Fix stream decoder for unicode char ( #215 ) -* Fix decoding of slice element ( #219 ) -* Fix calculating of buffer length for stream decoder ( #220 ) - -### Refactor - -* replace skipWhiteSpace goto by loop ( #212 ) - -# v0.4.14 - 2021/5/4 - -### Benchmark - -* Add valyala/fastjson to benchmark ( #193 ) -* Add benchmark task for CI ( #211 ) - -### Fix decoder - -* Fix decoding of slice with unmarshal json type ( #198 ) -* Fix decoding of null value for interface type that does not implement Unmarshaler ( #205 ) -* Fix decoding of null value to []byte by json.Unmarshal ( #206 ) -* Fix decoding of backslash char at the end of string ( #207 ) -* Fix stream decoder for null/true/false value ( #208 ) -* Fix stream decoder for slow reader ( #211 ) - -### Performance - -* If cap of slice is enough, reuse slice data for compatibility with encoding/json ( #200 ) - -# v0.4.13 - 2021/4/20 - -### Fix json.Compact and json.Indent - -* Support validation the input buffer for json.Compact and json.Indent ( #189 ) -* Optimize json.Compact and json.Indent ( improve memory footprint ) ( #190 ) - -# v0.4.12 - 2021/4/15 - -### Fix encoder - -* Fix unnecessary indent for empty slice type ( #181 ) -* Fix encoding of omitempty feature for the slice or interface type ( #183 ) -* Fix encoding custom types zero values with omitempty when marshaller exists ( #187 ) - -### Fix decoder - -* Fix decoder for invalid top level value ( #184 ) -* Fix decoder for invalid number value ( #185 ) - -# v0.4.11 - 2021/4/3 - -* Improve decoder performance for interface type - -# v0.4.10 - 2021/4/2 - -### Fix encoder - -* Fixed a bug when encoding slice and map containing recursive structures -* Fixed a logic to determine if indirect reference - -# v0.4.9 - 2021/3/29 - -### Add debug mode - -If you use `json.MarshalWithOption(v, json.Debug())` and `panic` occurred in `go-json`, produces debug information to console. - -### Support a new feature to compatible with encoding/json - -- invalid UTF-8 is coerced to valid UTF-8 ( without performance down ) - -### Fix encoder - -- Fixed handling of MarshalJSON of function type - -### Fix decoding of slice of pointer type - -If there is a pointer value, go-json will use it. (This behavior is necessary to achieve the ability to prioritize pre-filled values). However, since slices are reused internally, there was a bug that referred to the previous pointer value. Therefore, it is not necessary to refer to the pointer value in advance for the slice element, so we explicitly initialize slice element by `nil`. - -# v0.4.8 - 2021/3/21 - -### Reduce memory usage at compile time - -* go-json have used about 2GB of memory at compile time, but now it can compile with about less than 550MB. - -### Fix any encoder's bug - -* Add many test cases for encoder -* Fix composite type ( slice/array/map ) -* Fix pointer types -* Fix encoding of MarshalJSON or MarshalText or json.Number type - -### Refactor encoder - -* Change package layout for reducing memory usage at compile -* Remove anonymous and only operation -* Remove root property from encodeCompileContext and opcode - -### Fix CI - -* Add Go 1.16 -* Remove Go 1.13 -* Fix `make cover` task - -### Number/Delim/Token/RawMessage use the types defined in encoding/json by type alias - -# v0.4.7 - 2021/02/22 - -### Fix decoder - -* Fix decoding of deep recursive structure -* Fix decoding of embedded unexported pointer field -* Fix invalid test case -* Fix decoding of invalid value -* Fix decoding of prefilled value -* Fix not being able to return UnmarshalTypeError when it should be returned -* Fix decoding of null value -* Fix decoding of type of null string -* Use pre allocated pointer if exists it at decoding - -### Reduce memory usage at compile - -* Integrate int/int8/int16/int32/int64 and uint/uint8/uint16/uint32/uint64 operation to reduce memory usage at compile - -### Remove unnecessary optype diff --git a/taskman-server/vendor/github.com/goccy/go-json/LICENSE b/taskman-server/vendor/github.com/goccy/go-json/LICENSE deleted file mode 100644 index 6449c8bf..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Masaaki Goshima - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/taskman-server/vendor/github.com/goccy/go-json/Makefile b/taskman-server/vendor/github.com/goccy/go-json/Makefile deleted file mode 100644 index 363563ab..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/Makefile +++ /dev/null @@ -1,39 +0,0 @@ -PKG := github.com/goccy/go-json - -BIN_DIR := $(CURDIR)/bin -PKGS := $(shell go list ./... | grep -v internal/cmd|grep -v test) -COVER_PKGS := $(foreach pkg,$(PKGS),$(subst $(PKG),.,$(pkg))) - -COMMA := , -EMPTY := -SPACE := $(EMPTY) $(EMPTY) -COVERPKG_OPT := $(subst $(SPACE),$(COMMA),$(COVER_PKGS)) - -$(BIN_DIR): - @mkdir -p $(BIN_DIR) - -.PHONY: cover -cover: - go test -coverpkg=$(COVERPKG_OPT) -coverprofile=cover.out ./... - -.PHONY: cover-html -cover-html: cover - go tool cover -html=cover.out - -.PHONY: lint -lint: golangci-lint - golangci-lint run - -golangci-lint: | $(BIN_DIR) - @{ \ - set -e; \ - GOLANGCI_LINT_TMP_DIR=$$(mktemp -d); \ - cd $$GOLANGCI_LINT_TMP_DIR; \ - go mod init tmp; \ - GOBIN=$(BIN_DIR) go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.36.0; \ - rm -rf $$GOLANGCI_LINT_TMP_DIR; \ - } - -.PHONY: generate -generate: - go generate ./internal/... diff --git a/taskman-server/vendor/github.com/goccy/go-json/README.md b/taskman-server/vendor/github.com/goccy/go-json/README.md deleted file mode 100644 index 418854e5..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/README.md +++ /dev/null @@ -1,529 +0,0 @@ -# go-json - -![Go](https://github.com/goccy/go-json/workflows/Go/badge.svg) -[![GoDoc](https://godoc.org/github.com/goccy/go-json?status.svg)](https://pkg.go.dev/github.com/goccy/go-json?tab=doc) -[![codecov](https://codecov.io/gh/goccy/go-json/branch/master/graph/badge.svg)](https://codecov.io/gh/goccy/go-json) - -Fast JSON encoder/decoder compatible with encoding/json for Go - - - -# Roadmap - -``` -* version ( expected release date ) - -* v0.7.0 - | - | while maintaining compatibility with encoding/json, we will add convenient APIs - | - v -* v1.0.0 -``` - -We are accepting requests for features that will be implemented between v0.7.0 and v.1.0.0. -If you have the API you need, please submit your issue [here](https://github.com/goccy/go-json/issues). -For example, I'm thinking of supporting `context.Context` of `json.Marshaler` and decoding using JSON Path. - -# Features - -- Drop-in replacement of `encoding/json` -- Fast ( See [Benchmark section](https://github.com/goccy/go-json#benchmarks) ) -- Flexible customization with options -- Coloring the encoded string -- Can propagate context.Context to `MarshalJSON` or `UnmarshalJSON` - -# Installation - -``` -go get github.com/goccy/go-json -``` - -# How to use - -Replace import statement from `encoding/json` to `github.com/goccy/go-json` - -``` --import "encoding/json" -+import "github.com/goccy/go-json" -``` - -# JSON library comparison - -| name | encoder | decoder | compatible with `encoding/json` | -| :----: | :------: | :-----: | :-----------------------------: | -| encoding/json | yes | yes | N/A | -| [json-iterator/go](https://github.com/json-iterator/go) | yes | yes | partial | -| [easyjson](https://github.com/mailru/easyjson) | yes | yes | no | -| [gojay](https://github.com/francoispqt/gojay) | yes | yes | no | -| [segmentio/encoding/json](https://github.com/segmentio/encoding/tree/master/json) | yes | yes | partial | -| [jettison](https://github.com/wI2L/jettison) | yes | no | no | -| [simdjson-go](https://github.com/minio/simdjson-go) | no | yes | no | -| goccy/go-json | yes | yes | yes | - -- `json-iterator/go` isn't compatible with `encoding/json` in many ways (e.g. https://github.com/json-iterator/go/issues/229 ), but it hasn't been supported for a long time. -- `segmentio/encoding/json` is well supported for encoders, but some are not supported for decoder APIs such as `Token` ( streaming decode ) - -## Other libraries - -- [jingo](https://github.com/bet365/jingo) - -I tried the benchmark but it didn't work. -Also, it seems to panic when it receives an unexpected value because there is no error handling... - -- [ffjson](https://github.com/pquerna/ffjson) - -Benchmarking gave very slow results. -It seems that it is assumed that the user will use the buffer pool properly. -Also, development seems to have already stopped - -# Benchmarks - -``` -$ cd benchmarks -$ go test -bench . -``` - -## Encode - - - - -## Decode - - - - - - -# Fuzzing - -[go-json-fuzz](https://github.com/goccy/go-json-fuzz) is the repository for fuzzing tests. -If you run the test in this repository and find a bug, please commit to corpus to go-json-fuzz and report the issue to [go-json](https://github.com/goccy/go-json/issues). - -# How it works - -`go-json` is very fast in both encoding and decoding compared to other libraries. -It's easier to implement by using automatic code generation for performance or by using a dedicated interface, but `go-json` dares to stick to compatibility with `encoding/json` and is the simple interface. Despite this, we are developing with the aim of being the fastest library. - -Here, we explain the various speed-up techniques implemented by `go-json`. - -## Basic technique - -The techniques listed here are the ones used by most of the libraries listed above. - -### Buffer reuse - -Since the only value required for the result of `json.Marshal(interface{}) ([]byte, error)` is `[]byte`, the only value that must be allocated during encoding is the return value `[]byte` . - -Also, as the number of allocations increases, the performance will be affected, so the number of allocations should be kept as low as possible when creating `[]byte`. - -Therefore, there is a technique to reduce the number of times a new buffer must be allocated by reusing the buffer used for the previous encoding by using `sync.Pool`. - -Finally, you allocate a buffer that is as long as the resulting buffer and copy the contents into it, you only need to allocate the buffer once in theory. - -```go -type buffer struct { - data []byte -} - -var bufPool = sync.Pool{ - New: func() interface{} { - return &buffer{data: make([]byte, 0, 1024)} - }, -} - -buf := bufPool.Get().(*buffer) -data := encode(buf.data) // reuse buf.data - -newBuf := make([]byte, len(data)) -copy(newBuf, buf) - -buf.data = data -bufPool.Put(buf) -``` - -### Elimination of reflection - -As you know, the reflection operation is very slow. - -Therefore, using the fact that the address position where the type information is stored is fixed for each binary ( we call this `typeptr` ), -we can use the address in the type information to call a pre-built optimized process. - -For example, you can get the address to the type information from `interface{}` as follows and you can use that information to call a process that does not have reflection. - -To process without reflection, pass a pointer (`unsafe.Pointer`) to the value is stored. - -```go - -type emptyInterface struct { - typ unsafe.Pointer - ptr unsafe.Pointer -} - -var typeToEncoder = map[uintptr]func(unsafe.Pointer)([]byte, error){} - -func Marshal(v interface{}) ([]byte, error) { - iface := (*emptyInterface)(unsafe.Pointer(&v) - typeptr := uintptr(iface.typ) - if enc, exists := typeToEncoder[typeptr]; exists { - return enc(iface.ptr) - } - ... -} -``` - -※ In reality, `typeToEncoder` can be referenced by multiple goroutines, so exclusive control is required. - -## Unique speed-up technique - -## Encoder - -### Do not escape arguments of `Marshal` - -`json.Marshal` and `json.Unmarshal` receive `interface{}` value and they perform type determination dynamically to process. -In normal case, you need to use the `reflect` library to determine the type dynamically, but since `reflect.Type` is defined as `interface`, when you call the method of `reflect.Type`, The reflect's argument is escaped. - -Therefore, the arguments for `Marshal` and `Unmarshal` are always escape to the heap. -However, `go-json` can use the feature of `reflect.Type` while avoiding escaping. - -`reflect.Type` is defined as `interface`, but in reality `reflect.Type` is implemented only by the structure `rtype` defined in the `reflect` package. -For this reason, to date `reflect.Type` is the same as `*reflect.rtype`. - -Therefore, by directly handling `*reflect.rtype`, which is an implementation of `reflect.Type`, it is possible to avoid escaping because it changes from `interface` to using `struct`. - -The technique for working with `*reflect.rtype` directly from `go-json` is implemented at [rtype.go](https://github.com/goccy/go-json/blob/master/internal/runtime/rtype.go) - -Also, the same technique is cut out as a library ( https://github.com/goccy/go-reflect ) - -Initially this feature was the default behavior of `go-json`. -But after careful testing, I found that I passed a large value to `json.Marshal()` and if the argument could not be assigned to the stack, it could not be properly escaped to the heap (a bug in the Go compiler). - -Therefore, this feature will be provided as an **optional** until this issue is resolved. - -To use it, add `NoEscape` like `MarshalNoEscape()` - -### Encoding using opcode sequence - -I explained that you can use `typeptr` to call a pre-built process from type information. - -In other libraries, this dedicated process is processed by making it an function calling like anonymous function, but function calls are inherently slow processes and should be avoided as much as possible. - -Therefore, `go-json` adopted the Instruction-based execution processing system, which is also used to implement virtual machines for programming language. - -If it is the first type to encode, create the opcode ( instruction ) sequence required for encoding. -From the second time onward, use `typeptr` to get the cached pre-built opcode sequence and encode it based on it. An example of the opcode sequence is shown below. - -```go -json.Marshal(struct{ - X int `json:"x"` - Y string `json:"y"` -}{X: 1, Y: "hello"}) -``` - -When encoding a structure like the one above, create a sequence of opcodes like this: - -``` -- opStructFieldHead ( `{` ) -- opStructFieldInt ( `"x": 1,` ) -- opStructFieldString ( `"y": "hello"` ) -- opStructEnd ( `}` ) -- opEnd -``` - -※ When processing each operation, write the letters on the right. - -In addition, each opcode is managed by the following structure ( -Pseudo code ). - -```go -type opType int -const ( - opStructFieldHead opType = iota - opStructFieldInt - opStructFieldStirng - opStructEnd - opEnd -) -type opcode struct { - op opType - key []byte - next *opcode -} -``` - -The process of encoding using the opcode sequence is roughly implemented as follows. - -```go -func encode(code *opcode, b []byte, p unsafe.Pointer) ([]byte, error) { - for { - switch code.op { - case opStructFieldHead: - b = append(b, '{') - code = code.next - case opStructFieldInt: - b = append(b, code.key...) - b = appendInt((*int)(unsafe.Pointer(uintptr(p)+code.offset))) - code = code.next - case opStructFieldString: - b = append(b, code.key...) - b = appendString((*string)(unsafe.Pointer(uintptr(p)+code.offset))) - code = code.next - case opStructEnd: - b = append(b, '}') - code = code.next - case opEnd: - goto END - } - } -END: - return b, nil -} -``` - -In this way, the huge `switch-case` is used to encode by manipulating the linked list opcodes to avoid unnecessary function calls. - -### Opcode sequence optimization - -One of the advantages of encoding using the opcode sequence is the ease of optimization. -The opcode sequence mentioned above is actually converted into the following optimized operations and used. - -``` -- opStructFieldHeadInt ( `{"x": 1,` ) -- opStructEndString ( `"y": "hello"}` ) -- opEnd -``` - -It has been reduced from 5 opcodes to 3 opcodes ! -Reducing the number of opcodees means reducing the number of branches with `switch-case`. -In other words, the closer the number of operations is to 1, the faster the processing can be performed. - -In `go-json`, optimization to reduce the number of opcodes itself like the above and it speeds up by preparing opcodes with optimized paths. - -### Change recursive call from CALL to JMP - -Recursive processing is required during encoding if the type is defined recursively as follows: - -```go -type T struct { - X int - U *U -} - -type U struct { - T *T -} - -b, err := json.Marshal(&T{ - X: 1, - U: &U{ - T: &T{ - X: 2, - }, - }, -}) -fmt.Println(string(b)) // {"X":1,"U":{"T":{"X":2,"U":null}}} -``` - -In `go-json`, recursive processing is processed by the operation type of ` opStructFieldRecursive`. - -In this operation, after acquiring the opcode sequence used for recursive processing, the function is **not** called recursively as it is, but the necessary values ​​are saved by itself and implemented by moving to the next operation. - -The technique of implementing recursive processing with the `JMP` operation while avoiding the `CALL` operation is a famous technique for implementing a high-speed virtual machine. - -For more details, please refer to [the article](https://engineering.mercari.com/blog/entry/1599563768-081104c850) ( but Japanese only ). - -### Dispatch by typeptr from map to slice - -When retrieving the data cached from the type information by `typeptr`, we usually use map. -Map requires exclusive control, so use `sync.Map` for a naive implementation. - -However, this is slow, so it's a good idea to use the `atomic` package for exclusive control as implemented by `segmentio/encoding/json` ( https://github.com/segmentio/encoding/blob/master/json/codec.go#L41-L55 ). - -This implementation slows down the set instead of speeding up the get, but it works well because of the nature of the library, it encodes much more for the same type. - -However, as a result of profiling, I noticed that `runtime.mapaccess2` accounts for a significant percentage of the execution time. So I thought if I could change the lookup from map to slice. - -There is an API named `typelinks` defined in the `runtime` package that the `reflect` package uses internally. -This allows you to get all the type information defined in the binary at runtime. - -The fact that all type information can be acquired means that by constructing slices in advance with the acquired total number of type information, it is possible to look up with the value of `typeptr` without worrying about out-of-range access. - -However, if there is too much type information, it will use a lot of memory, so by default we will only use this optimization if the slice size fits within **2Mib** . - -If this approach is not available, it will fall back to the `atomic` based process described above. - -If you want to know more, please refer to the implementation [here](https://github.com/goccy/go-json/blob/master/internal/runtime/type.go#L36-L100) - -## Decoder - -### Dispatch by typeptr from map to slice - -Like the encoder, the decoder also uses typeptr to call the dedicated process. - -### Faster termination character inspection using NUL character - -In order to decode, you have to traverse the input buffer character by position. -At that time, if you check whether the buffer has reached the end, it will be very slow. - -`buf` : `[]byte` type variable. holds the string passed to the decoder -`cursor` : `int64` type variable. holds the current read position - -```go -buflen := len(buf) -for ; cursor < buflen; cursor++ { // compare cursor and buflen at all times, it is so slow. - switch buf[cursor] { - case ' ', '\n', '\r', '\t': - } -} -``` - -Therefore, by adding the `NUL` (`\000`) character to the end of the read buffer as shown below, it is possible to check the termination character at the same time as other characters. - -```go -for { - switch buf[cursor] { - case ' ', '\n', '\r', '\t': - case '\000': - return nil - } - cursor++ -} -``` - -### Use Boundary Check Elimination - -Due to the `NUL` character optimization, the Go compiler does a boundary check every time, even though `buf[cursor]` does not cause out-of-range access. - -Therefore, `go-json` eliminates boundary check by fetching characters for hotspot by pointer operation. For example, the following code. - -```go -func char(ptr unsafe.Pointer, offset int64) byte { - return *(*byte)(unsafe.Pointer(uintptr(ptr) + uintptr(offset))) -} - -p := (*sliceHeader)(&unsafe.Pointer(buf)).data -for { - switch char(p, cursor) { - case ' ', '\n', '\r', '\t': - case '\000': - return nil - } - cursor++ -} -``` - -### Checking the existence of fields of struct using Bitmaps - -I found by the profiling result, in the struct decode, lookup process for field was taking a long time. - -For example, consider decoding a string like `{"a":1,"b":2,"c":3}` into the following structure: - -```go -type T struct { - A int `json:"a"` - B int `json:"b"` - C int `json:"c"` -} -``` - -At this time, it was found that it takes a lot of time to acquire the decoding process corresponding to the field from the field name as shown below during the decoding process. - -```go -fieldName := decodeKey(buf, cursor) // "a" or "b" or "c" -decoder, exists := fieldToDecoderMap[fieldName] // so slow -if exists { - decoder(buf, cursor) -} else { - skipValue(buf, cursor) -} -``` - -To improve this process, `json-iterator/go` is optimized so that it can be branched by switch-case when the number of fields in the structure is 10 or less (switch-case is faster than map). However, there is a risk of hash collision because the value hashed by the FNV algorithm is used for conditional branching. Also, `gojay` processes this part at high speed by letting the library user yourself write `switch-case`. - - -`go-json` considers and implements a new approach that is different from these. I call this **bitmap field optimization**. - -The range of values ​​per character can be represented by `[256]byte`. Also, if the number of fields in the structure is 8 or less, `int8` type can represent the state of each field. -In other words, it has the following structure. - -- Base ( 8bit ): `00000000` -- Key "a": `00000001` ( assign key "a" to the first bit ) -- Key "b": `00000010` ( assign key "b" to the second bit ) -- Key "c": `00000100` ( assign key "c" to the third bit ) - -Bitmap structure is the following - -``` - | key index(0) | ------------------------- - 0 | 00000000 | - 1 | 00000000 | -~~ | | -97 (a) | 00000001 | -98 (b) | 00000010 | -99 (c) | 00000100 | -~~ | | -255 | 00000000 | -``` - -You can think of this as a Bitmap with a height of `256` and a width of the maximum string length in the field name. -In other words, it can be represented by the following type . - -```go -[maxFieldKeyLength][256]int8 -``` - -When decoding a field character, check whether the corresponding character exists by referring to the pre-built bitmap like the following. - -```go -var curBit int8 = math.MaxInt8 // 11111111 - -c := char(buf, cursor) -bit := bitmap[keyIdx][c] -curBit &= bit -if curBit == 0 { - // not found field -} -``` - -If `curBit` is not `0` until the end of the field string, then the string is -You may have hit one of the fields. -But the possibility is that if the decoded string is shorter than the field string, you will get a false hit. - -- input: `{"a":1}` -```go -type T struct { - X int `json:"abc"` -} -``` -※ Since `a` is shorter than `abc`, it can decode to the end of the field character without `curBit` being 0. - -Rest assured. In this case, it doesn't matter because you can tell if you hit by comparing the string length of `a` with the string length of `abc`. - -Finally, calculate the position of the bit where `1` is set and get the corresponding value, and you're done. - -Using this technique, field lookups are possible with only bitwise operations and access to slices. - -`go-json` uses a similar technique for fields with 9 or more and 16 or less fields. At this time, Bitmap is constructed as `[maxKeyLen][256]int16` type. - -Currently, this optimization is not performed when the maximum length of the field name is long (specifically, 64 bytes or more) in addition to the limitation of the number of fields from the viewpoint of saving memory usage. - -### Others - -I have done a lot of other optimizations. I will find time to write about them. If you have any questions about what's written here or other optimizations, please visit the `#go-json` channel on `gophers.slack.com` . - -## Reference - -Regarding the story of go-json, there are the following articles in Japanese only. - -- https://speakerdeck.com/goccy/zui-su-falsejsonraiburariwoqiu-mete -- https://engineering.mercari.com/blog/entry/1599563768-081104c850/ - -# Looking for Sponsors - -I'm looking for sponsors this library. This library is being developed as a personal project in my spare time. If you want a quick response or problem resolution when using this library in your project, please register as a [sponsor](https://github.com/sponsors/goccy). I will cooperate as much as possible. Of course, this library is developed as an MIT license, so you can use it freely for free. - -# License - -MIT diff --git a/taskman-server/vendor/github.com/goccy/go-json/color.go b/taskman-server/vendor/github.com/goccy/go-json/color.go deleted file mode 100644 index e80b22b4..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/color.go +++ /dev/null @@ -1,68 +0,0 @@ -package json - -import ( - "fmt" - - "github.com/goccy/go-json/internal/encoder" -) - -type ( - ColorFormat = encoder.ColorFormat - ColorScheme = encoder.ColorScheme -) - -const escape = "\x1b" - -type colorAttr int - -//nolint:deadcode,varcheck -const ( - fgBlackColor colorAttr = iota + 30 - fgRedColor - fgGreenColor - fgYellowColor - fgBlueColor - fgMagentaColor - fgCyanColor - fgWhiteColor -) - -//nolint:deadcode,varcheck -const ( - fgHiBlackColor colorAttr = iota + 90 - fgHiRedColor - fgHiGreenColor - fgHiYellowColor - fgHiBlueColor - fgHiMagentaColor - fgHiCyanColor - fgHiWhiteColor -) - -func createColorFormat(attr colorAttr) ColorFormat { - return ColorFormat{ - Header: wrapColor(attr), - Footer: resetColor(), - } -} - -func wrapColor(attr colorAttr) string { - return fmt.Sprintf("%s[%dm", escape, attr) -} - -func resetColor() string { - return wrapColor(colorAttr(0)) -} - -var ( - DefaultColorScheme = &ColorScheme{ - Int: createColorFormat(fgHiMagentaColor), - Uint: createColorFormat(fgHiMagentaColor), - Float: createColorFormat(fgHiMagentaColor), - Bool: createColorFormat(fgHiYellowColor), - String: createColorFormat(fgHiGreenColor), - Binary: createColorFormat(fgHiRedColor), - ObjectKey: createColorFormat(fgHiCyanColor), - Null: createColorFormat(fgBlueColor), - } -) diff --git a/taskman-server/vendor/github.com/goccy/go-json/decode.go b/taskman-server/vendor/github.com/goccy/go-json/decode.go deleted file mode 100644 index d99749d0..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/decode.go +++ /dev/null @@ -1,232 +0,0 @@ -package json - -import ( - "context" - "fmt" - "io" - "reflect" - "unsafe" - - "github.com/goccy/go-json/internal/decoder" - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type Decoder struct { - s *decoder.Stream -} - -const ( - nul = '\000' -) - -type emptyInterface struct { - typ *runtime.Type - ptr unsafe.Pointer -} - -func unmarshal(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { - src := make([]byte, len(data)+1) // append nul byte to the end - copy(src, data) - - header := (*emptyInterface)(unsafe.Pointer(&v)) - - if err := validateType(header.typ, uintptr(header.ptr)); err != nil { - return err - } - dec, err := decoder.CompileToGetDecoder(header.typ) - if err != nil { - return err - } - ctx := decoder.TakeRuntimeContext() - ctx.Buf = src - ctx.Option.Flags = 0 - for _, optFunc := range optFuncs { - optFunc(ctx.Option) - } - cursor, err := dec.Decode(ctx, 0, 0, header.ptr) - if err != nil { - decoder.ReleaseRuntimeContext(ctx) - return err - } - decoder.ReleaseRuntimeContext(ctx) - return validateEndBuf(src, cursor) -} - -func unmarshalContext(ctx context.Context, data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { - src := make([]byte, len(data)+1) // append nul byte to the end - copy(src, data) - - header := (*emptyInterface)(unsafe.Pointer(&v)) - - if err := validateType(header.typ, uintptr(header.ptr)); err != nil { - return err - } - dec, err := decoder.CompileToGetDecoder(header.typ) - if err != nil { - return err - } - rctx := decoder.TakeRuntimeContext() - rctx.Buf = src - rctx.Option.Flags = 0 - rctx.Option.Flags |= decoder.ContextOption - rctx.Option.Context = ctx - for _, optFunc := range optFuncs { - optFunc(rctx.Option) - } - cursor, err := dec.Decode(rctx, 0, 0, header.ptr) - if err != nil { - decoder.ReleaseRuntimeContext(rctx) - return err - } - decoder.ReleaseRuntimeContext(rctx) - return validateEndBuf(src, cursor) -} - -func unmarshalNoEscape(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { - src := make([]byte, len(data)+1) // append nul byte to the end - copy(src, data) - - header := (*emptyInterface)(unsafe.Pointer(&v)) - - if err := validateType(header.typ, uintptr(header.ptr)); err != nil { - return err - } - dec, err := decoder.CompileToGetDecoder(header.typ) - if err != nil { - return err - } - - ctx := decoder.TakeRuntimeContext() - ctx.Buf = src - ctx.Option.Flags = 0 - for _, optFunc := range optFuncs { - optFunc(ctx.Option) - } - cursor, err := dec.Decode(ctx, 0, 0, noescape(header.ptr)) - if err != nil { - decoder.ReleaseRuntimeContext(ctx) - return err - } - decoder.ReleaseRuntimeContext(ctx) - return validateEndBuf(src, cursor) -} - -func validateEndBuf(src []byte, cursor int64) error { - for { - switch src[cursor] { - case ' ', '\t', '\n', '\r': - cursor++ - continue - case nul: - return nil - } - return errors.ErrSyntax( - fmt.Sprintf("invalid character '%c' after top-level value", src[cursor]), - cursor+1, - ) - } -} - -//nolint:staticcheck -//go:nosplit -func noescape(p unsafe.Pointer) unsafe.Pointer { - x := uintptr(p) - return unsafe.Pointer(x ^ 0) -} - -func validateType(typ *runtime.Type, p uintptr) error { - if typ == nil || typ.Kind() != reflect.Ptr || p == 0 { - return &InvalidUnmarshalError{Type: runtime.RType2Type(typ)} - } - return nil -} - -// NewDecoder returns a new decoder that reads from r. -// -// The decoder introduces its own buffering and may -// read data from r beyond the JSON values requested. -func NewDecoder(r io.Reader) *Decoder { - s := decoder.NewStream(r) - return &Decoder{ - s: s, - } -} - -// Buffered returns a reader of the data remaining in the Decoder's -// buffer. The reader is valid until the next call to Decode. -func (d *Decoder) Buffered() io.Reader { - return d.s.Buffered() -} - -// Decode reads the next JSON-encoded value from its -// input and stores it in the value pointed to by v. -// -// See the documentation for Unmarshal for details about -// the conversion of JSON into a Go value. -func (d *Decoder) Decode(v interface{}) error { - return d.DecodeWithOption(v) -} - -// DecodeContext reads the next JSON-encoded value from its -// input and stores it in the value pointed to by v with context.Context. -func (d *Decoder) DecodeContext(ctx context.Context, v interface{}) error { - d.s.Option.Flags |= decoder.ContextOption - d.s.Option.Context = ctx - return d.DecodeWithOption(v) -} - -func (d *Decoder) DecodeWithOption(v interface{}, optFuncs ...DecodeOptionFunc) error { - header := (*emptyInterface)(unsafe.Pointer(&v)) - typ := header.typ - ptr := uintptr(header.ptr) - typeptr := uintptr(unsafe.Pointer(typ)) - // noescape trick for header.typ ( reflect.*rtype ) - copiedType := *(**runtime.Type)(unsafe.Pointer(&typeptr)) - - if err := validateType(copiedType, ptr); err != nil { - return err - } - - dec, err := decoder.CompileToGetDecoder(typ) - if err != nil { - return err - } - if err := d.s.PrepareForDecode(); err != nil { - return err - } - s := d.s - for _, optFunc := range optFuncs { - optFunc(s.Option) - } - if err := dec.DecodeStream(s, 0, header.ptr); err != nil { - return err - } - s.Reset() - return nil -} - -func (d *Decoder) More() bool { - return d.s.More() -} - -func (d *Decoder) Token() (Token, error) { - return d.s.Token() -} - -// DisallowUnknownFields causes the Decoder to return an error when the destination -// is a struct and the input contains object keys which do not match any -// non-ignored, exported fields in the destination. -func (d *Decoder) DisallowUnknownFields() { - d.s.DisallowUnknownFields = true -} - -func (d *Decoder) InputOffset() int64 { - return d.s.TotalOffset() -} - -// UseNumber causes the Decoder to unmarshal a number into an interface{} as a -// Number instead of as a float64. -func (d *Decoder) UseNumber() { - d.s.UseNumber = true -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/docker-compose.yml b/taskman-server/vendor/github.com/goccy/go-json/docker-compose.yml deleted file mode 100644 index e5106662..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: '2' -services: - go-json: - image: golang:1.16 - volumes: - - '.:/go/src/go-json' - deploy: - resources: - limits: - memory: 620M - working_dir: /go/src/go-json - command: | - sh -c "go test -c . && ls go-json.test" diff --git a/taskman-server/vendor/github.com/goccy/go-json/encode.go b/taskman-server/vendor/github.com/goccy/go-json/encode.go deleted file mode 100644 index 7f198bdc..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/encode.go +++ /dev/null @@ -1,323 +0,0 @@ -package json - -import ( - "context" - "io" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" - "github.com/goccy/go-json/internal/encoder/vm" - "github.com/goccy/go-json/internal/encoder/vm_color" - "github.com/goccy/go-json/internal/encoder/vm_color_indent" - "github.com/goccy/go-json/internal/encoder/vm_indent" -) - -// An Encoder writes JSON values to an output stream. -type Encoder struct { - w io.Writer - enabledIndent bool - enabledHTMLEscape bool - prefix string - indentStr string -} - -// NewEncoder returns a new encoder that writes to w. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{w: w, enabledHTMLEscape: true} -} - -// Encode writes the JSON encoding of v to the stream, followed by a newline character. -// -// See the documentation for Marshal for details about the conversion of Go values to JSON. -func (e *Encoder) Encode(v interface{}) error { - return e.EncodeWithOption(v) -} - -// EncodeWithOption call Encode with EncodeOption. -func (e *Encoder) EncodeWithOption(v interface{}, optFuncs ...EncodeOptionFunc) error { - ctx := encoder.TakeRuntimeContext() - ctx.Option.Flag = 0 - - err := e.encodeWithOption(ctx, v, optFuncs...) - - encoder.ReleaseRuntimeContext(ctx) - return err -} - -// EncodeContext call Encode with context.Context and EncodeOption. -func (e *Encoder) EncodeContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) error { - rctx := encoder.TakeRuntimeContext() - rctx.Option.Flag = 0 - rctx.Option.Flag |= encoder.ContextOption - rctx.Option.Context = ctx - - err := e.encodeWithOption(rctx, v, optFuncs...) - - encoder.ReleaseRuntimeContext(rctx) - return err -} - -func (e *Encoder) encodeWithOption(ctx *encoder.RuntimeContext, v interface{}, optFuncs ...EncodeOptionFunc) error { - if e.enabledHTMLEscape { - ctx.Option.Flag |= encoder.HTMLEscapeOption - } - for _, optFunc := range optFuncs { - optFunc(ctx.Option) - } - var ( - buf []byte - err error - ) - if e.enabledIndent { - buf, err = encodeIndent(ctx, v, e.prefix, e.indentStr) - } else { - buf, err = encode(ctx, v) - } - if err != nil { - return err - } - if e.enabledIndent { - buf = buf[:len(buf)-2] - } else { - buf = buf[:len(buf)-1] - } - buf = append(buf, '\n') - if _, err := e.w.Write(buf); err != nil { - return err - } - return nil -} - -// SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. -// The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML. -// -// In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior. -func (e *Encoder) SetEscapeHTML(on bool) { - e.enabledHTMLEscape = on -} - -// SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). -// Calling SetIndent("", "") disables indentation. -func (e *Encoder) SetIndent(prefix, indent string) { - if prefix == "" && indent == "" { - e.enabledIndent = false - return - } - e.prefix = prefix - e.indentStr = indent - e.enabledIndent = true -} - -func marshalContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { - rctx := encoder.TakeRuntimeContext() - rctx.Option.Flag = 0 - rctx.Option.Flag = encoder.HTMLEscapeOption | encoder.ContextOption - rctx.Option.Context = ctx - for _, optFunc := range optFuncs { - optFunc(rctx.Option) - } - - buf, err := encode(rctx, v) - if err != nil { - encoder.ReleaseRuntimeContext(rctx) - return nil, err - } - - // this line exists to escape call of `runtime.makeslicecopy` . - // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`, - // dst buffer size and src buffer size are differrent. - // in this case, compiler uses `runtime.makeslicecopy`, but it is slow. - buf = buf[:len(buf)-1] - copied := make([]byte, len(buf)) - copy(copied, buf) - - encoder.ReleaseRuntimeContext(rctx) - return copied, nil -} - -func marshal(v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { - ctx := encoder.TakeRuntimeContext() - - ctx.Option.Flag = 0 - ctx.Option.Flag |= encoder.HTMLEscapeOption - for _, optFunc := range optFuncs { - optFunc(ctx.Option) - } - - buf, err := encode(ctx, v) - if err != nil { - encoder.ReleaseRuntimeContext(ctx) - return nil, err - } - - // this line exists to escape call of `runtime.makeslicecopy` . - // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`, - // dst buffer size and src buffer size are differrent. - // in this case, compiler uses `runtime.makeslicecopy`, but it is slow. - buf = buf[:len(buf)-1] - copied := make([]byte, len(buf)) - copy(copied, buf) - - encoder.ReleaseRuntimeContext(ctx) - return copied, nil -} - -func marshalNoEscape(v interface{}) ([]byte, error) { - ctx := encoder.TakeRuntimeContext() - - ctx.Option.Flag = 0 - ctx.Option.Flag |= encoder.HTMLEscapeOption - - buf, err := encodeNoEscape(ctx, v) - if err != nil { - encoder.ReleaseRuntimeContext(ctx) - return nil, err - } - - // this line exists to escape call of `runtime.makeslicecopy` . - // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`, - // dst buffer size and src buffer size are differrent. - // in this case, compiler uses `runtime.makeslicecopy`, but it is slow. - buf = buf[:len(buf)-1] - copied := make([]byte, len(buf)) - copy(copied, buf) - - encoder.ReleaseRuntimeContext(ctx) - return copied, nil -} - -func marshalIndent(v interface{}, prefix, indent string, optFuncs ...EncodeOptionFunc) ([]byte, error) { - ctx := encoder.TakeRuntimeContext() - - ctx.Option.Flag = 0 - ctx.Option.Flag |= (encoder.HTMLEscapeOption | encoder.IndentOption) - for _, optFunc := range optFuncs { - optFunc(ctx.Option) - } - - buf, err := encodeIndent(ctx, v, prefix, indent) - if err != nil { - encoder.ReleaseRuntimeContext(ctx) - return nil, err - } - - buf = buf[:len(buf)-2] - copied := make([]byte, len(buf)) - copy(copied, buf) - - encoder.ReleaseRuntimeContext(ctx) - return copied, nil -} - -func encode(ctx *encoder.RuntimeContext, v interface{}) ([]byte, error) { - b := ctx.Buf[:0] - if v == nil { - b = encoder.AppendNull(ctx, b) - b = encoder.AppendComma(ctx, b) - return b, nil - } - header := (*emptyInterface)(unsafe.Pointer(&v)) - typ := header.typ - - typeptr := uintptr(unsafe.Pointer(typ)) - codeSet, err := encoder.CompileToGetCodeSet(typeptr) - if err != nil { - return nil, err - } - - p := uintptr(header.ptr) - ctx.Init(p, codeSet.CodeLength) - ctx.KeepRefs = append(ctx.KeepRefs, header.ptr) - - buf, err := encodeRunCode(ctx, b, codeSet) - if err != nil { - return nil, err - } - ctx.Buf = buf - return buf, nil -} - -func encodeNoEscape(ctx *encoder.RuntimeContext, v interface{}) ([]byte, error) { - b := ctx.Buf[:0] - if v == nil { - b = encoder.AppendNull(ctx, b) - b = encoder.AppendComma(ctx, b) - return b, nil - } - header := (*emptyInterface)(unsafe.Pointer(&v)) - typ := header.typ - - typeptr := uintptr(unsafe.Pointer(typ)) - codeSet, err := encoder.CompileToGetCodeSet(typeptr) - if err != nil { - return nil, err - } - - p := uintptr(header.ptr) - ctx.Init(p, codeSet.CodeLength) - buf, err := encodeRunCode(ctx, b, codeSet) - if err != nil { - return nil, err - } - - ctx.Buf = buf - return buf, nil -} - -func encodeIndent(ctx *encoder.RuntimeContext, v interface{}, prefix, indent string) ([]byte, error) { - b := ctx.Buf[:0] - if v == nil { - b = encoder.AppendNull(ctx, b) - b = encoder.AppendCommaIndent(ctx, b) - return b, nil - } - header := (*emptyInterface)(unsafe.Pointer(&v)) - typ := header.typ - - typeptr := uintptr(unsafe.Pointer(typ)) - codeSet, err := encoder.CompileToGetCodeSet(typeptr) - if err != nil { - return nil, err - } - - p := uintptr(header.ptr) - ctx.Init(p, codeSet.CodeLength) - buf, err := encodeRunIndentCode(ctx, b, codeSet, prefix, indent) - - ctx.KeepRefs = append(ctx.KeepRefs, header.ptr) - - if err != nil { - return nil, err - } - - ctx.Buf = buf - return buf, nil -} - -func encodeRunCode(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - if (ctx.Option.Flag & encoder.DebugOption) != 0 { - if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { - return vm_color.DebugRun(ctx, b, codeSet) - } - return vm.DebugRun(ctx, b, codeSet) - } - if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { - return vm_color.Run(ctx, b, codeSet) - } - return vm.Run(ctx, b, codeSet) -} - -func encodeRunIndentCode(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet, prefix, indent string) ([]byte, error) { - ctx.Prefix = []byte(prefix) - ctx.IndentStr = []byte(indent) - if (ctx.Option.Flag & encoder.DebugOption) != 0 { - if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { - return vm_color_indent.DebugRun(ctx, b, codeSet) - } - return vm_indent.DebugRun(ctx, b, codeSet) - } - if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { - return vm_color_indent.Run(ctx, b, codeSet) - } - return vm_indent.Run(ctx, b, codeSet) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/error.go b/taskman-server/vendor/github.com/goccy/go-json/error.go deleted file mode 100644 index 94c1339a..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/error.go +++ /dev/null @@ -1,39 +0,0 @@ -package json - -import ( - "github.com/goccy/go-json/internal/errors" -) - -// Before Go 1.2, an InvalidUTF8Error was returned by Marshal when -// attempting to encode a string value with invalid UTF-8 sequences. -// As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by -// replacing invalid bytes with the Unicode replacement rune U+FFFD. -// -// Deprecated: No longer used; kept for compatibility. -type InvalidUTF8Error = errors.InvalidUTF8Error - -// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. -// (The argument to Unmarshal must be a non-nil pointer.) -type InvalidUnmarshalError = errors.InvalidUnmarshalError - -// A MarshalerError represents an error from calling a MarshalJSON or MarshalText method. -type MarshalerError = errors.MarshalerError - -// A SyntaxError is a description of a JSON syntax error. -type SyntaxError = errors.SyntaxError - -// An UnmarshalFieldError describes a JSON object key that -// led to an unexported (and therefore unwritable) struct field. -// -// Deprecated: No longer used; kept for compatibility. -type UnmarshalFieldError = errors.UnmarshalFieldError - -// An UnmarshalTypeError describes a JSON value that was -// not appropriate for a value of a specific Go type. -type UnmarshalTypeError = errors.UnmarshalTypeError - -// An UnsupportedTypeError is returned by Marshal when attempting -// to encode an unsupported value type. -type UnsupportedTypeError = errors.UnsupportedTypeError - -type UnsupportedValueError = errors.UnsupportedValueError diff --git a/taskman-server/vendor/github.com/goccy/go-json/go.mod b/taskman-server/vendor/github.com/goccy/go-json/go.mod deleted file mode 100644 index 58a14881..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/goccy/go-json - -go 1.12 diff --git a/taskman-server/vendor/github.com/goccy/go-json/go.sum b/taskman-server/vendor/github.com/goccy/go-json/go.sum deleted file mode 100644 index e69de29b..00000000 diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/anonymous_field.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/anonymous_field.go deleted file mode 100644 index 030cb7a9..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/anonymous_field.go +++ /dev/null @@ -1,37 +0,0 @@ -package decoder - -import ( - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -type anonymousFieldDecoder struct { - structType *runtime.Type - offset uintptr - dec Decoder -} - -func newAnonymousFieldDecoder(structType *runtime.Type, offset uintptr, dec Decoder) *anonymousFieldDecoder { - return &anonymousFieldDecoder{ - structType: structType, - offset: offset, - dec: dec, - } -} - -func (d *anonymousFieldDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - if *(*unsafe.Pointer)(p) == nil { - *(*unsafe.Pointer)(p) = unsafe_New(d.structType) - } - p = *(*unsafe.Pointer)(p) - return d.dec.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+d.offset)) -} - -func (d *anonymousFieldDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - if *(*unsafe.Pointer)(p) == nil { - *(*unsafe.Pointer)(p) = unsafe_New(d.structType) - } - p = *(*unsafe.Pointer)(p) - return d.dec.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+d.offset)) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/array.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/array.go deleted file mode 100644 index 21f1fd58..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/array.go +++ /dev/null @@ -1,169 +0,0 @@ -package decoder - -import ( - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type arrayDecoder struct { - elemType *runtime.Type - size uintptr - valueDecoder Decoder - alen int - structName string - fieldName string - zeroValue unsafe.Pointer -} - -func newArrayDecoder(dec Decoder, elemType *runtime.Type, alen int, structName, fieldName string) *arrayDecoder { - zeroValue := *(*unsafe.Pointer)(unsafe_New(elemType)) - return &arrayDecoder{ - valueDecoder: dec, - elemType: elemType, - size: elemType.Size(), - alen: alen, - structName: structName, - fieldName: fieldName, - zeroValue: zeroValue, - } -} - -func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - case 'n': - if err := nullBytes(s); err != nil { - return err - } - return nil - case '[': - idx := 0 - s.cursor++ - if s.skipWhiteSpace() == ']' { - for idx < d.alen { - *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue - idx++ - } - s.cursor++ - return nil - } - for { - if idx < d.alen { - if err := d.valueDecoder.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)); err != nil { - return err - } - } else { - if err := s.skipValue(depth); err != nil { - return err - } - } - idx++ - switch s.skipWhiteSpace() { - case ']': - for idx < d.alen { - *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue - idx++ - } - s.cursor++ - return nil - case ',': - s.cursor++ - continue - case nul: - if s.read() { - s.cursor++ - continue - } - goto ERROR - default: - goto ERROR - } - } - case nul: - if s.read() { - continue - } - goto ERROR - default: - goto ERROR - } - s.cursor++ - } -ERROR: - return errors.ErrUnexpectedEndOfJSON("array", s.totalOffset()) -} - -func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - - for { - switch buf[cursor] { - case ' ', '\n', '\t', '\r': - cursor++ - continue - case 'n': - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - return cursor, nil - case '[': - idx := 0 - cursor++ - cursor = skipWhiteSpace(buf, cursor) - if buf[cursor] == ']' { - for idx < d.alen { - *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue - idx++ - } - cursor++ - return cursor, nil - } - for { - if idx < d.alen { - c, err := d.valueDecoder.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)) - if err != nil { - return 0, err - } - cursor = c - } else { - c, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - cursor = c - } - idx++ - cursor = skipWhiteSpace(buf, cursor) - switch buf[cursor] { - case ']': - for idx < d.alen { - *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue - idx++ - } - cursor++ - return cursor, nil - case ',': - cursor++ - continue - default: - return 0, errors.ErrInvalidCharacter(buf[cursor], "array", cursor) - } - } - default: - return 0, errors.ErrUnexpectedEndOfJSON("array", cursor) - } - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bool.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bool.go deleted file mode 100644 index 455042a5..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bool.go +++ /dev/null @@ -1,78 +0,0 @@ -package decoder - -import ( - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -type boolDecoder struct { - structName string - fieldName string -} - -func newBoolDecoder(structName, fieldName string) *boolDecoder { - return &boolDecoder{structName: structName, fieldName: fieldName} -} - -func (d *boolDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - c := s.skipWhiteSpace() - for { - switch c { - case 't': - if err := trueBytes(s); err != nil { - return err - } - **(**bool)(unsafe.Pointer(&p)) = true - return nil - case 'f': - if err := falseBytes(s); err != nil { - return err - } - **(**bool)(unsafe.Pointer(&p)) = false - return nil - case 'n': - if err := nullBytes(s); err != nil { - return err - } - return nil - case nul: - if s.read() { - c = s.char() - continue - } - goto ERROR - } - break - } -ERROR: - return errors.ErrUnexpectedEndOfJSON("bool", s.totalOffset()) -} - -func (d *boolDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - cursor = skipWhiteSpace(buf, cursor) - switch buf[cursor] { - case 't': - if err := validateTrue(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - **(**bool)(unsafe.Pointer(&p)) = true - return cursor, nil - case 'f': - if err := validateFalse(buf, cursor); err != nil { - return 0, err - } - cursor += 5 - **(**bool)(unsafe.Pointer(&p)) = false - return cursor, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - return cursor, nil - } - return 0, errors.ErrUnexpectedEndOfJSON("bool", cursor) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bytes.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bytes.go deleted file mode 100644 index 0c4681a1..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bytes.go +++ /dev/null @@ -1,177 +0,0 @@ -package decoder - -import ( - "encoding/base64" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type bytesDecoder struct { - typ *runtime.Type - sliceDecoder Decoder - structName string - fieldName string -} - -func byteUnmarshalerSliceDecoder(typ *runtime.Type, structName string, fieldName string) Decoder { - var unmarshalDecoder Decoder - switch { - case runtime.PtrTo(typ).Implements(unmarshalJSONType): - unmarshalDecoder = newUnmarshalJSONDecoder(runtime.PtrTo(typ), structName, fieldName) - case runtime.PtrTo(typ).Implements(unmarshalTextType): - unmarshalDecoder = newUnmarshalTextDecoder(runtime.PtrTo(typ), structName, fieldName) - } - if unmarshalDecoder == nil { - return nil - } - return newSliceDecoder(unmarshalDecoder, typ, 1, structName, fieldName) -} - -func newBytesDecoder(typ *runtime.Type, structName string, fieldName string) *bytesDecoder { - return &bytesDecoder{ - typ: typ, - sliceDecoder: byteUnmarshalerSliceDecoder(typ, structName, fieldName), - structName: structName, - fieldName: fieldName, - } -} - -func (d *bytesDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - bytes, err := d.decodeStreamBinary(s, depth, p) - if err != nil { - return err - } - if bytes == nil { - s.reset() - return nil - } - decodedLen := base64.StdEncoding.DecodedLen(len(bytes)) - buf := make([]byte, decodedLen) - n, err := base64.StdEncoding.Decode(buf, bytes) - if err != nil { - return err - } - *(*[]byte)(p) = buf[:n] - s.reset() - return nil -} - -func (d *bytesDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - bytes, c, err := d.decodeBinary(ctx, cursor, depth, p) - if err != nil { - return 0, err - } - if bytes == nil { - return c, nil - } - cursor = c - decodedLen := base64.StdEncoding.DecodedLen(len(bytes)) - b := make([]byte, decodedLen) - n, err := base64.StdEncoding.Decode(b, bytes) - if err != nil { - return 0, err - } - *(*[]byte)(p) = b[:n] - return cursor, nil -} - -func binaryBytes(s *Stream) ([]byte, error) { - s.cursor++ - start := s.cursor - for { - switch s.char() { - case '"': - literal := s.buf[start:s.cursor] - s.cursor++ - return literal, nil - case nul: - if s.read() { - continue - } - goto ERROR - } - s.cursor++ - } -ERROR: - return nil, errors.ErrUnexpectedEndOfJSON("[]byte", s.totalOffset()) -} - -func (d *bytesDecoder) decodeStreamBinary(s *Stream, depth int64, p unsafe.Pointer) ([]byte, error) { - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - s.cursor++ - continue - case '"': - return binaryBytes(s) - case 'n': - if err := nullBytes(s); err != nil { - return nil, err - } - return nil, nil - case '[': - if d.sliceDecoder == nil { - return nil, &errors.UnmarshalTypeError{ - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - } - if err := d.sliceDecoder.DecodeStream(s, depth, p); err != nil { - return nil, err - } - return nil, nil - case nul: - if s.read() { - continue - } - } - break - } - return nil, errors.ErrNotAtBeginningOfValue(s.totalOffset()) -} - -func (d *bytesDecoder) decodeBinary(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) ([]byte, int64, error) { - buf := ctx.Buf - for { - switch buf[cursor] { - case ' ', '\n', '\t', '\r': - cursor++ - case '"': - cursor++ - start := cursor - for { - switch buf[cursor] { - case '"': - literal := buf[start:cursor] - cursor++ - return literal, cursor, nil - case nul: - return nil, 0, errors.ErrUnexpectedEndOfJSON("[]byte", cursor) - } - cursor++ - } - case '[': - if d.sliceDecoder == nil { - return nil, 0, &errors.UnmarshalTypeError{ - Type: runtime.RType2Type(d.typ), - Offset: cursor, - } - } - c, err := d.sliceDecoder.Decode(ctx, cursor, depth, p) - if err != nil { - return nil, 0, err - } - return nil, c, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return nil, 0, err - } - cursor += 4 - return nil, cursor, nil - default: - return nil, 0, errors.ErrNotAtBeginningOfValue(cursor) - } - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile.go deleted file mode 100644 index 08dd044e..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile.go +++ /dev/null @@ -1,510 +0,0 @@ -package decoder - -import ( - "encoding/json" - "fmt" - "reflect" - "strings" - "sync/atomic" - "unicode" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -var ( - jsonNumberType = reflect.TypeOf(json.Number("")) - typeAddr *runtime.TypeAddr - cachedDecoderMap unsafe.Pointer // map[uintptr]decoder - cachedDecoder []Decoder -) - -func init() { - typeAddr = runtime.AnalyzeTypeAddr() - if typeAddr == nil { - typeAddr = &runtime.TypeAddr{} - } - cachedDecoder = make([]Decoder, typeAddr.AddrRange>>typeAddr.AddrShift) -} - -func loadDecoderMap() map[uintptr]Decoder { - p := atomic.LoadPointer(&cachedDecoderMap) - return *(*map[uintptr]Decoder)(unsafe.Pointer(&p)) -} - -func storeDecoder(typ uintptr, dec Decoder, m map[uintptr]Decoder) { - newDecoderMap := make(map[uintptr]Decoder, len(m)+1) - newDecoderMap[typ] = dec - - for k, v := range m { - newDecoderMap[k] = v - } - - atomic.StorePointer(&cachedDecoderMap, *(*unsafe.Pointer)(unsafe.Pointer(&newDecoderMap))) -} - -func compileToGetDecoderSlowPath(typeptr uintptr, typ *runtime.Type) (Decoder, error) { - decoderMap := loadDecoderMap() - if dec, exists := decoderMap[typeptr]; exists { - return dec, nil - } - - dec, err := compileHead(typ, map[uintptr]Decoder{}) - if err != nil { - return nil, err - } - storeDecoder(typeptr, dec, decoderMap) - return dec, nil -} - -func compileHead(typ *runtime.Type, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - switch { - case implementsUnmarshalJSONType(runtime.PtrTo(typ)): - return newUnmarshalJSONDecoder(runtime.PtrTo(typ), "", ""), nil - case runtime.PtrTo(typ).Implements(unmarshalTextType): - return newUnmarshalTextDecoder(runtime.PtrTo(typ), "", ""), nil - } - return compile(typ.Elem(), "", "", structTypeToDecoder) -} - -func compile(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - switch { - case implementsUnmarshalJSONType(runtime.PtrTo(typ)): - return newUnmarshalJSONDecoder(runtime.PtrTo(typ), structName, fieldName), nil - case runtime.PtrTo(typ).Implements(unmarshalTextType): - return newUnmarshalTextDecoder(runtime.PtrTo(typ), structName, fieldName), nil - } - - switch typ.Kind() { - case reflect.Ptr: - return compilePtr(typ, structName, fieldName, structTypeToDecoder) - case reflect.Struct: - return compileStruct(typ, structName, fieldName, structTypeToDecoder) - case reflect.Slice: - elem := typ.Elem() - if elem.Kind() == reflect.Uint8 { - return compileBytes(elem, structName, fieldName) - } - return compileSlice(typ, structName, fieldName, structTypeToDecoder) - case reflect.Array: - return compileArray(typ, structName, fieldName, structTypeToDecoder) - case reflect.Map: - return compileMap(typ, structName, fieldName, structTypeToDecoder) - case reflect.Interface: - return compileInterface(typ, structName, fieldName) - case reflect.Uintptr: - return compileUint(typ, structName, fieldName) - case reflect.Int: - return compileInt(typ, structName, fieldName) - case reflect.Int8: - return compileInt8(typ, structName, fieldName) - case reflect.Int16: - return compileInt16(typ, structName, fieldName) - case reflect.Int32: - return compileInt32(typ, structName, fieldName) - case reflect.Int64: - return compileInt64(typ, structName, fieldName) - case reflect.Uint: - return compileUint(typ, structName, fieldName) - case reflect.Uint8: - return compileUint8(typ, structName, fieldName) - case reflect.Uint16: - return compileUint16(typ, structName, fieldName) - case reflect.Uint32: - return compileUint32(typ, structName, fieldName) - case reflect.Uint64: - return compileUint64(typ, structName, fieldName) - case reflect.String: - return compileString(typ, structName, fieldName) - case reflect.Bool: - return compileBool(structName, fieldName) - case reflect.Float32: - return compileFloat32(structName, fieldName) - case reflect.Float64: - return compileFloat64(structName, fieldName) - case reflect.Func: - return compileFunc(typ, structName, fieldName) - } - return nil, &errors.UnmarshalTypeError{ - Value: "object", - Type: runtime.RType2Type(typ), - Offset: 0, - Struct: structName, - Field: fieldName, - } -} - -func isStringTagSupportedType(typ *runtime.Type) bool { - switch { - case implementsUnmarshalJSONType(runtime.PtrTo(typ)): - return false - case runtime.PtrTo(typ).Implements(unmarshalTextType): - return false - } - switch typ.Kind() { - case reflect.Map: - return false - case reflect.Slice: - return false - case reflect.Array: - return false - case reflect.Struct: - return false - case reflect.Interface: - return false - } - return true -} - -func compileMapKey(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - if runtime.PtrTo(typ).Implements(unmarshalTextType) { - return newUnmarshalTextDecoder(runtime.PtrTo(typ), structName, fieldName), nil - } - dec, err := compile(typ, structName, fieldName, structTypeToDecoder) - if err != nil { - return nil, err - } - for { - switch t := dec.(type) { - case *stringDecoder, *interfaceDecoder: - return dec, nil - case *boolDecoder, *intDecoder, *uintDecoder, *numberDecoder: - return newWrappedStringDecoder(typ, dec, structName, fieldName), nil - case *ptrDecoder: - dec = t.dec - default: - goto ERROR - } - } -ERROR: - return nil, &errors.UnmarshalTypeError{ - Value: "object", - Type: runtime.RType2Type(typ), - Offset: 0, - Struct: structName, - Field: fieldName, - } -} - -func compilePtr(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - dec, err := compile(typ.Elem(), structName, fieldName, structTypeToDecoder) - if err != nil { - return nil, err - } - return newPtrDecoder(dec, typ.Elem(), structName, fieldName), nil -} - -func compileInt(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { - *(*int)(p) = int(v) - }), nil -} - -func compileInt8(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { - *(*int8)(p) = int8(v) - }), nil -} - -func compileInt16(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { - *(*int16)(p) = int16(v) - }), nil -} - -func compileInt32(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { - *(*int32)(p) = int32(v) - }), nil -} - -func compileInt64(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { - *(*int64)(p) = v - }), nil -} - -func compileUint(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { - *(*uint)(p) = uint(v) - }), nil -} - -func compileUint8(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { - *(*uint8)(p) = uint8(v) - }), nil -} - -func compileUint16(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { - *(*uint16)(p) = uint16(v) - }), nil -} - -func compileUint32(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { - *(*uint32)(p) = uint32(v) - }), nil -} - -func compileUint64(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { - *(*uint64)(p) = v - }), nil -} - -func compileFloat32(structName, fieldName string) (Decoder, error) { - return newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { - *(*float32)(p) = float32(v) - }), nil -} - -func compileFloat64(structName, fieldName string) (Decoder, error) { - return newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { - *(*float64)(p) = v - }), nil -} - -func compileString(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - if typ == runtime.Type2RType(jsonNumberType) { - return newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) { - *(*json.Number)(p) = v - }), nil - } - return newStringDecoder(structName, fieldName), nil -} - -func compileBool(structName, fieldName string) (Decoder, error) { - return newBoolDecoder(structName, fieldName), nil -} - -func compileBytes(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newBytesDecoder(typ, structName, fieldName), nil -} - -func compileSlice(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - elem := typ.Elem() - decoder, err := compile(elem, structName, fieldName, structTypeToDecoder) - if err != nil { - return nil, err - } - return newSliceDecoder(decoder, elem, elem.Size(), structName, fieldName), nil -} - -func compileArray(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - elem := typ.Elem() - decoder, err := compile(elem, structName, fieldName, structTypeToDecoder) - if err != nil { - return nil, err - } - return newArrayDecoder(decoder, elem, typ.Len(), structName, fieldName), nil -} - -func compileMap(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - keyDec, err := compileMapKey(typ.Key(), structName, fieldName, structTypeToDecoder) - if err != nil { - return nil, err - } - valueDec, err := compile(typ.Elem(), structName, fieldName, structTypeToDecoder) - if err != nil { - return nil, err - } - return newMapDecoder(typ, typ.Key(), keyDec, typ.Elem(), valueDec, structName, fieldName), nil -} - -func compileInterface(typ *runtime.Type, structName, fieldName string) (Decoder, error) { - return newInterfaceDecoder(typ, structName, fieldName), nil -} - -func compileFunc(typ *runtime.Type, strutName, fieldName string) (Decoder, error) { - return newFuncDecoder(typ, strutName, fieldName), nil -} - -func removeConflictFields(fieldMap map[string]*structFieldSet, conflictedMap map[string]struct{}, dec *structDecoder, field reflect.StructField) { - for k, v := range dec.fieldMap { - if _, exists := conflictedMap[k]; exists { - // already conflicted key - continue - } - set, exists := fieldMap[k] - if !exists { - fieldSet := &structFieldSet{ - dec: v.dec, - offset: field.Offset + v.offset, - isTaggedKey: v.isTaggedKey, - key: k, - keyLen: int64(len(k)), - } - fieldMap[k] = fieldSet - lower := strings.ToLower(k) - if _, exists := fieldMap[lower]; !exists { - fieldMap[lower] = fieldSet - } - continue - } - if set.isTaggedKey { - if v.isTaggedKey { - // conflict tag key - delete(fieldMap, k) - delete(fieldMap, strings.ToLower(k)) - conflictedMap[k] = struct{}{} - conflictedMap[strings.ToLower(k)] = struct{}{} - } - } else { - if v.isTaggedKey { - fieldSet := &structFieldSet{ - dec: v.dec, - offset: field.Offset + v.offset, - isTaggedKey: v.isTaggedKey, - key: k, - keyLen: int64(len(k)), - } - fieldMap[k] = fieldSet - lower := strings.ToLower(k) - if _, exists := fieldMap[lower]; !exists { - fieldMap[lower] = fieldSet - } - } else { - // conflict tag key - delete(fieldMap, k) - delete(fieldMap, strings.ToLower(k)) - conflictedMap[k] = struct{}{} - conflictedMap[strings.ToLower(k)] = struct{}{} - } - } - } -} - -func compileStruct(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { - fieldNum := typ.NumField() - conflictedMap := map[string]struct{}{} - fieldMap := map[string]*structFieldSet{} - typeptr := uintptr(unsafe.Pointer(typ)) - if dec, exists := structTypeToDecoder[typeptr]; exists { - return dec, nil - } - structDec := newStructDecoder(structName, fieldName, fieldMap) - structTypeToDecoder[typeptr] = structDec - structName = typ.Name() - for i := 0; i < fieldNum; i++ { - field := typ.Field(i) - if runtime.IsIgnoredStructField(field) { - continue - } - isUnexportedField := unicode.IsLower([]rune(field.Name)[0]) - tag := runtime.StructTagFromField(field) - dec, err := compile(runtime.Type2RType(field.Type), structName, field.Name, structTypeToDecoder) - if err != nil { - return nil, err - } - if field.Anonymous && !tag.IsTaggedKey { - if stDec, ok := dec.(*structDecoder); ok { - if runtime.Type2RType(field.Type) == typ { - // recursive definition - continue - } - removeConflictFields(fieldMap, conflictedMap, stDec, field) - } else if pdec, ok := dec.(*ptrDecoder); ok { - contentDec := pdec.contentDecoder() - if pdec.typ == typ { - // recursive definition - continue - } - var fieldSetErr error - if isUnexportedField { - fieldSetErr = fmt.Errorf( - "json: cannot set embedded pointer to unexported struct: %v", - field.Type.Elem(), - ) - } - if dec, ok := contentDec.(*structDecoder); ok { - for k, v := range dec.fieldMap { - if _, exists := conflictedMap[k]; exists { - // already conflicted key - continue - } - set, exists := fieldMap[k] - if !exists { - fieldSet := &structFieldSet{ - dec: newAnonymousFieldDecoder(pdec.typ, v.offset, v.dec), - offset: field.Offset, - isTaggedKey: v.isTaggedKey, - key: k, - keyLen: int64(len(k)), - err: fieldSetErr, - } - fieldMap[k] = fieldSet - lower := strings.ToLower(k) - if _, exists := fieldMap[lower]; !exists { - fieldMap[lower] = fieldSet - } - continue - } - if set.isTaggedKey { - if v.isTaggedKey { - // conflict tag key - delete(fieldMap, k) - delete(fieldMap, strings.ToLower(k)) - conflictedMap[k] = struct{}{} - conflictedMap[strings.ToLower(k)] = struct{}{} - } - } else { - if v.isTaggedKey { - fieldSet := &structFieldSet{ - dec: newAnonymousFieldDecoder(pdec.typ, v.offset, v.dec), - offset: field.Offset, - isTaggedKey: v.isTaggedKey, - key: k, - keyLen: int64(len(k)), - err: fieldSetErr, - } - fieldMap[k] = fieldSet - lower := strings.ToLower(k) - if _, exists := fieldMap[lower]; !exists { - fieldMap[lower] = fieldSet - } - } else { - // conflict tag key - delete(fieldMap, k) - delete(fieldMap, strings.ToLower(k)) - conflictedMap[k] = struct{}{} - conflictedMap[strings.ToLower(k)] = struct{}{} - } - } - } - } - } - } else { - if tag.IsString && isStringTagSupportedType(runtime.Type2RType(field.Type)) { - dec = newWrappedStringDecoder(runtime.Type2RType(field.Type), dec, structName, field.Name) - } - var key string - if tag.Key != "" { - key = tag.Key - } else { - key = field.Name - } - fieldSet := &structFieldSet{ - dec: dec, - offset: field.Offset, - isTaggedKey: tag.IsTaggedKey, - key: key, - keyLen: int64(len(key)), - } - fieldMap[key] = fieldSet - lower := strings.ToLower(key) - if _, exists := fieldMap[lower]; !exists { - fieldMap[lower] = fieldSet - } - } - } - delete(structTypeToDecoder, typeptr) - structDec.tryOptimize() - return structDec, nil -} - -func implementsUnmarshalJSONType(typ *runtime.Type) bool { - return typ.Implements(unmarshalJSONType) || typ.Implements(unmarshalJSONContextType) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_norace.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_norace.go deleted file mode 100644 index 592f6373..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_norace.go +++ /dev/null @@ -1,28 +0,0 @@ -// +build !race - -package decoder - -import ( - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -func CompileToGetDecoder(typ *runtime.Type) (Decoder, error) { - typeptr := uintptr(unsafe.Pointer(typ)) - if typeptr > typeAddr.MaxTypeAddr { - return compileToGetDecoderSlowPath(typeptr, typ) - } - - index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift - if dec := cachedDecoder[index]; dec != nil { - return dec, nil - } - - dec, err := compileHead(typ, map[uintptr]Decoder{}) - if err != nil { - return nil, err - } - cachedDecoder[index] = dec - return dec, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_race.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_race.go deleted file mode 100644 index b691bc94..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_race.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build race - -package decoder - -import ( - "sync" - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -var decMu sync.RWMutex - -func CompileToGetDecoder(typ *runtime.Type) (Decoder, error) { - typeptr := uintptr(unsafe.Pointer(typ)) - if typeptr > typeAddr.MaxTypeAddr { - return compileToGetDecoderSlowPath(typeptr, typ) - } - - index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift - decMu.RLock() - if dec := cachedDecoder[index]; dec != nil { - decMu.RUnlock() - return dec, nil - } - decMu.RUnlock() - - dec, err := compileHead(typ, map[uintptr]Decoder{}) - if err != nil { - return nil, err - } - decMu.Lock() - cachedDecoder[index] = dec - decMu.Unlock() - return dec, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/context.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/context.go deleted file mode 100644 index cb2ffdaf..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/context.go +++ /dev/null @@ -1,254 +0,0 @@ -package decoder - -import ( - "sync" - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -type RuntimeContext struct { - Buf []byte - Option *Option -} - -var ( - runtimeContextPool = sync.Pool{ - New: func() interface{} { - return &RuntimeContext{ - Option: &Option{}, - } - }, - } -) - -func TakeRuntimeContext() *RuntimeContext { - return runtimeContextPool.Get().(*RuntimeContext) -} - -func ReleaseRuntimeContext(ctx *RuntimeContext) { - runtimeContextPool.Put(ctx) -} - -var ( - isWhiteSpace = [256]bool{} -) - -func init() { - isWhiteSpace[' '] = true - isWhiteSpace['\n'] = true - isWhiteSpace['\t'] = true - isWhiteSpace['\r'] = true -} - -func char(ptr unsafe.Pointer, offset int64) byte { - return *(*byte)(unsafe.Pointer(uintptr(ptr) + uintptr(offset))) -} - -func skipWhiteSpace(buf []byte, cursor int64) int64 { - for isWhiteSpace[buf[cursor]] { - cursor++ - } - return cursor -} - -func skipObject(buf []byte, cursor, depth int64) (int64, error) { - braceCount := 1 - for { - switch buf[cursor] { - case '{': - braceCount++ - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - case '}': - depth-- - braceCount-- - if braceCount == 0 { - return cursor + 1, nil - } - case '[': - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - case ']': - depth-- - case '"': - for { - cursor++ - switch buf[cursor] { - case '\\': - cursor++ - if buf[cursor] == nul { - return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - case '"': - goto SWITCH_OUT - case nul: - return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - } - case nul: - return 0, errors.ErrUnexpectedEndOfJSON("object of object", cursor) - } - SWITCH_OUT: - cursor++ - } -} - -func skipArray(buf []byte, cursor, depth int64) (int64, error) { - bracketCount := 1 - for { - switch buf[cursor] { - case '[': - bracketCount++ - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - case ']': - bracketCount-- - depth-- - if bracketCount == 0 { - return cursor + 1, nil - } - case '{': - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - case '}': - depth-- - case '"': - for { - cursor++ - switch buf[cursor] { - case '\\': - cursor++ - if buf[cursor] == nul { - return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - case '"': - goto SWITCH_OUT - case nul: - return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - } - case nul: - return 0, errors.ErrUnexpectedEndOfJSON("array of object", cursor) - } - SWITCH_OUT: - cursor++ - } -} - -func skipValue(buf []byte, cursor, depth int64) (int64, error) { - for { - switch buf[cursor] { - case ' ', '\t', '\n', '\r': - cursor++ - continue - case '{': - return skipObject(buf, cursor+1, depth+1) - case '[': - return skipArray(buf, cursor+1, depth+1) - case '"': - for { - cursor++ - switch buf[cursor] { - case '\\': - cursor++ - if buf[cursor] == nul { - return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - case '"': - return cursor + 1, nil - case nul: - return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - for { - cursor++ - if floatTable[buf[cursor]] { - continue - } - break - } - return cursor, nil - case 't': - if err := validateTrue(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - return cursor, nil - case 'f': - if err := validateFalse(buf, cursor); err != nil { - return 0, err - } - cursor += 5 - return cursor, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - return cursor, nil - default: - return cursor, errors.ErrUnexpectedEndOfJSON("null", cursor) - } - } -} - -func validateTrue(buf []byte, cursor int64) error { - if cursor+3 >= int64(len(buf)) { - return errors.ErrUnexpectedEndOfJSON("true", cursor) - } - if buf[cursor+1] != 'r' { - return errors.ErrInvalidCharacter(buf[cursor+1], "true", cursor) - } - if buf[cursor+2] != 'u' { - return errors.ErrInvalidCharacter(buf[cursor+2], "true", cursor) - } - if buf[cursor+3] != 'e' { - return errors.ErrInvalidCharacter(buf[cursor+3], "true", cursor) - } - return nil -} - -func validateFalse(buf []byte, cursor int64) error { - if cursor+4 >= int64(len(buf)) { - return errors.ErrUnexpectedEndOfJSON("false", cursor) - } - if buf[cursor+1] != 'a' { - return errors.ErrInvalidCharacter(buf[cursor+1], "false", cursor) - } - if buf[cursor+2] != 'l' { - return errors.ErrInvalidCharacter(buf[cursor+2], "false", cursor) - } - if buf[cursor+3] != 's' { - return errors.ErrInvalidCharacter(buf[cursor+3], "false", cursor) - } - if buf[cursor+4] != 'e' { - return errors.ErrInvalidCharacter(buf[cursor+4], "false", cursor) - } - return nil -} - -func validateNull(buf []byte, cursor int64) error { - if cursor+3 >= int64(len(buf)) { - return errors.ErrUnexpectedEndOfJSON("null", cursor) - } - if buf[cursor+1] != 'u' { - return errors.ErrInvalidCharacter(buf[cursor+1], "null", cursor) - } - if buf[cursor+2] != 'l' { - return errors.ErrInvalidCharacter(buf[cursor+2], "null", cursor) - } - if buf[cursor+3] != 'l' { - return errors.ErrInvalidCharacter(buf[cursor+3], "null", cursor) - } - return nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/float.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/float.go deleted file mode 100644 index dfb7168d..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/float.go +++ /dev/null @@ -1,158 +0,0 @@ -package decoder - -import ( - "strconv" - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -type floatDecoder struct { - op func(unsafe.Pointer, float64) - structName string - fieldName string -} - -func newFloatDecoder(structName, fieldName string, op func(unsafe.Pointer, float64)) *floatDecoder { - return &floatDecoder{op: op, structName: structName, fieldName: fieldName} -} - -var ( - floatTable = [256]bool{ - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - '.': true, - 'e': true, - 'E': true, - '+': true, - '-': true, - } - - validEndNumberChar = [256]bool{ - nul: true, - ' ': true, - '\t': true, - '\r': true, - '\n': true, - ',': true, - ':': true, - '}': true, - ']': true, - } -) - -func floatBytes(s *Stream) []byte { - start := s.cursor - for { - s.cursor++ - if floatTable[s.char()] { - continue - } else if s.char() == nul { - if s.read() { - s.cursor-- // for retry current character - continue - } - } - break - } - return s.buf[start:s.cursor] -} - -func (d *floatDecoder) decodeStreamByte(s *Stream) ([]byte, error) { - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - s.cursor++ - continue - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return floatBytes(s), nil - case 'n': - if err := nullBytes(s); err != nil { - return nil, err - } - return nil, nil - case nul: - if s.read() { - continue - } - goto ERROR - default: - goto ERROR - } - } -ERROR: - return nil, errors.ErrUnexpectedEndOfJSON("float", s.totalOffset()) -} - -func (d *floatDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { - for { - switch buf[cursor] { - case ' ', '\n', '\t', '\r': - cursor++ - continue - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - start := cursor - cursor++ - for floatTable[buf[cursor]] { - cursor++ - } - num := buf[start:cursor] - return num, cursor, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return nil, 0, err - } - cursor += 4 - return nil, cursor, nil - default: - return nil, 0, errors.ErrUnexpectedEndOfJSON("float", cursor) - } - } -} - -func (d *floatDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - bytes, err := d.decodeStreamByte(s) - if err != nil { - return err - } - if bytes == nil { - return nil - } - str := *(*string)(unsafe.Pointer(&bytes)) - f64, err := strconv.ParseFloat(str, 64) - if err != nil { - return errors.ErrSyntax(err.Error(), s.totalOffset()) - } - d.op(p, f64) - return nil -} - -func (d *floatDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - bytes, c, err := d.decodeByte(buf, cursor) - if err != nil { - return 0, err - } - if bytes == nil { - return c, nil - } - cursor = c - if !validEndNumberChar[buf[cursor]] { - return 0, errors.ErrUnexpectedEndOfJSON("float", cursor) - } - s := *(*string)(unsafe.Pointer(&bytes)) - f64, err := strconv.ParseFloat(s, 64) - if err != nil { - return 0, errors.ErrSyntax(err.Error(), cursor) - } - d.op(p, f64) - return cursor, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/func.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/func.go deleted file mode 100644 index 75afe75c..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/func.go +++ /dev/null @@ -1,141 +0,0 @@ -package decoder - -import ( - "bytes" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type funcDecoder struct { - typ *runtime.Type - structName string - fieldName string -} - -func newFuncDecoder(typ *runtime.Type, structName, fieldName string) *funcDecoder { - fnDecoder := &funcDecoder{typ, structName, fieldName} - return fnDecoder -} - -func (d *funcDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - s.skipWhiteSpace() - start := s.cursor - if err := s.skipValue(depth); err != nil { - return err - } - src := s.buf[start:s.cursor] - if len(src) > 0 { - switch src[0] { - case '"': - return &errors.UnmarshalTypeError{ - Value: "string", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - case '[': - return &errors.UnmarshalTypeError{ - Value: "array", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - case '{': - return &errors.UnmarshalTypeError{ - Value: "object", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return &errors.UnmarshalTypeError{ - Value: "number", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - case 'n': - if err := nullBytes(s); err != nil { - return err - } - *(*unsafe.Pointer)(p) = nil - return nil - case 't': - if err := trueBytes(s); err == nil { - return &errors.UnmarshalTypeError{ - Value: "boolean", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - } - case 'f': - if err := falseBytes(s); err == nil { - return &errors.UnmarshalTypeError{ - Value: "boolean", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - } - } - } - return errors.ErrNotAtBeginningOfValue(start) -} - -func (d *funcDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - cursor = skipWhiteSpace(buf, cursor) - start := cursor - end, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - src := buf[start:end] - if len(src) > 0 { - switch src[0] { - case '"': - return 0, &errors.UnmarshalTypeError{ - Value: "string", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - case '[': - return 0, &errors.UnmarshalTypeError{ - Value: "array", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - case '{': - return 0, &errors.UnmarshalTypeError{ - Value: "object", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return 0, &errors.UnmarshalTypeError{ - Value: "number", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - case 'n': - if bytes.Equal(src, nullbytes) { - *(*unsafe.Pointer)(p) = nil - return end, nil - } - case 't': - if err := validateTrue(buf, start); err == nil { - return 0, &errors.UnmarshalTypeError{ - Value: "boolean", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - } - case 'f': - if err := validateFalse(buf, start); err == nil { - return 0, &errors.UnmarshalTypeError{ - Value: "boolean", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - } - } - } - return 0, errors.ErrNotAtBeginningOfValue(start) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/int.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/int.go deleted file mode 100644 index 7edfb041..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/int.go +++ /dev/null @@ -1,242 +0,0 @@ -package decoder - -import ( - "fmt" - "reflect" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type intDecoder struct { - typ *runtime.Type - kind reflect.Kind - op func(unsafe.Pointer, int64) - structName string - fieldName string -} - -func newIntDecoder(typ *runtime.Type, structName, fieldName string, op func(unsafe.Pointer, int64)) *intDecoder { - return &intDecoder{ - typ: typ, - kind: typ.Kind(), - op: op, - structName: structName, - fieldName: fieldName, - } -} - -func (d *intDecoder) typeError(buf []byte, offset int64) *errors.UnmarshalTypeError { - return &errors.UnmarshalTypeError{ - Value: fmt.Sprintf("number %s", string(buf)), - Type: runtime.RType2Type(d.typ), - Struct: d.structName, - Field: d.fieldName, - Offset: offset, - } -} - -var ( - pow10i64 = [...]int64{ - 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, - 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, - } - pow10i64Len = len(pow10i64) -) - -func (d *intDecoder) parseInt(b []byte) (int64, error) { - isNegative := false - if b[0] == '-' { - b = b[1:] - isNegative = true - } - maxDigit := len(b) - if maxDigit > pow10i64Len { - return 0, fmt.Errorf("invalid length of number") - } - sum := int64(0) - for i := 0; i < maxDigit; i++ { - c := int64(b[i]) - 48 - digitValue := pow10i64[maxDigit-i-1] - sum += c * digitValue - } - if isNegative { - return -1 * sum, nil - } - return sum, nil -} - -var ( - numTable = [256]bool{ - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - } -) - -var ( - numZeroBuf = []byte{'0'} -) - -func (d *intDecoder) decodeStreamByte(s *Stream) ([]byte, error) { - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - s.cursor++ - continue - case '-': - start := s.cursor - for { - s.cursor++ - if numTable[s.char()] { - continue - } else if s.char() == nul { - if s.read() { - s.cursor-- // for retry current character - continue - } - } - break - } - num := s.buf[start:s.cursor] - if len(num) < 2 { - goto ERROR - } - return num, nil - case '0': - s.cursor++ - return numZeroBuf, nil - case '1', '2', '3', '4', '5', '6', '7', '8', '9': - start := s.cursor - for { - s.cursor++ - if numTable[s.char()] { - continue - } else if s.char() == nul { - if s.read() { - s.cursor-- // for retry current character - continue - } - } - break - } - num := s.buf[start:s.cursor] - return num, nil - case 'n': - if err := nullBytes(s); err != nil { - return nil, err - } - return nil, nil - case nul: - if s.read() { - continue - } - goto ERROR - default: - return nil, d.typeError([]byte{s.char()}, s.totalOffset()) - } - } -ERROR: - return nil, errors.ErrUnexpectedEndOfJSON("number(integer)", s.totalOffset()) -} - -func (d *intDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { - b := (*sliceHeader)(unsafe.Pointer(&buf)).data - for { - switch char(b, cursor) { - case ' ', '\n', '\t', '\r': - cursor++ - continue - case '0': - cursor++ - return numZeroBuf, cursor, nil - case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': - start := cursor - cursor++ - for numTable[char(b, cursor)] { - cursor++ - } - num := buf[start:cursor] - return num, cursor, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return nil, 0, err - } - cursor += 4 - return nil, cursor, nil - default: - return nil, 0, d.typeError([]byte{char(b, cursor)}, cursor) - } - } -} - -func (d *intDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - bytes, err := d.decodeStreamByte(s) - if err != nil { - return err - } - if bytes == nil { - return nil - } - i64, err := d.parseInt(bytes) - if err != nil { - return d.typeError(bytes, s.totalOffset()) - } - switch d.kind { - case reflect.Int8: - if i64 <= -1*(1<<7) || (1<<7) <= i64 { - return d.typeError(bytes, s.totalOffset()) - } - case reflect.Int16: - if i64 <= -1*(1<<15) || (1<<15) <= i64 { - return d.typeError(bytes, s.totalOffset()) - } - case reflect.Int32: - if i64 <= -1*(1<<31) || (1<<31) <= i64 { - return d.typeError(bytes, s.totalOffset()) - } - } - d.op(p, i64) - s.reset() - return nil -} - -func (d *intDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - bytes, c, err := d.decodeByte(ctx.Buf, cursor) - if err != nil { - return 0, err - } - if bytes == nil { - return c, nil - } - cursor = c - - i64, err := d.parseInt(bytes) - if err != nil { - return 0, d.typeError(bytes, cursor) - } - switch d.kind { - case reflect.Int8: - if i64 <= -1*(1<<7) || (1<<7) <= i64 { - return 0, d.typeError(bytes, cursor) - } - case reflect.Int16: - if i64 <= -1*(1<<15) || (1<<15) <= i64 { - return 0, d.typeError(bytes, cursor) - } - case reflect.Int32: - if i64 <= -1*(1<<31) || (1<<31) <= i64 { - return 0, d.typeError(bytes, cursor) - } - } - d.op(p, i64) - return cursor, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/interface.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/interface.go deleted file mode 100644 index ea1b4aa5..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/interface.go +++ /dev/null @@ -1,458 +0,0 @@ -package decoder - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type interfaceDecoder struct { - typ *runtime.Type - structName string - fieldName string - sliceDecoder *sliceDecoder - mapDecoder *mapDecoder - floatDecoder *floatDecoder - numberDecoder *numberDecoder - stringDecoder *stringDecoder -} - -func newEmptyInterfaceDecoder(structName, fieldName string) *interfaceDecoder { - ifaceDecoder := &interfaceDecoder{ - typ: emptyInterfaceType, - structName: structName, - fieldName: fieldName, - floatDecoder: newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { - *(*interface{})(p) = v - }), - numberDecoder: newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) { - *(*interface{})(p) = v - }), - stringDecoder: newStringDecoder(structName, fieldName), - } - ifaceDecoder.sliceDecoder = newSliceDecoder( - ifaceDecoder, - emptyInterfaceType, - emptyInterfaceType.Size(), - structName, fieldName, - ) - ifaceDecoder.mapDecoder = newMapDecoder( - interfaceMapType, - stringType, - ifaceDecoder.stringDecoder, - interfaceMapType.Elem(), - ifaceDecoder, - structName, - fieldName, - ) - return ifaceDecoder -} - -func newInterfaceDecoder(typ *runtime.Type, structName, fieldName string) *interfaceDecoder { - emptyIfaceDecoder := newEmptyInterfaceDecoder(structName, fieldName) - stringDecoder := newStringDecoder(structName, fieldName) - return &interfaceDecoder{ - typ: typ, - structName: structName, - fieldName: fieldName, - sliceDecoder: newSliceDecoder( - emptyIfaceDecoder, - emptyInterfaceType, - emptyInterfaceType.Size(), - structName, fieldName, - ), - mapDecoder: newMapDecoder( - interfaceMapType, - stringType, - stringDecoder, - interfaceMapType.Elem(), - emptyIfaceDecoder, - structName, - fieldName, - ), - floatDecoder: newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { - *(*interface{})(p) = v - }), - numberDecoder: newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) { - *(*interface{})(p) = v - }), - stringDecoder: stringDecoder, - } -} - -func (d *interfaceDecoder) numDecoder(s *Stream) Decoder { - if s.UseNumber { - return d.numberDecoder - } - return d.floatDecoder -} - -var ( - emptyInterfaceType = runtime.Type2RType(reflect.TypeOf((*interface{})(nil)).Elem()) - interfaceMapType = runtime.Type2RType( - reflect.TypeOf((*map[string]interface{})(nil)).Elem(), - ) - stringType = runtime.Type2RType( - reflect.TypeOf(""), - ) -) - -func decodeStreamUnmarshaler(s *Stream, depth int64, unmarshaler json.Unmarshaler) error { - start := s.cursor - if err := s.skipValue(depth); err != nil { - return err - } - src := s.buf[start:s.cursor] - dst := make([]byte, len(src)) - copy(dst, src) - - if err := unmarshaler.UnmarshalJSON(dst); err != nil { - return err - } - return nil -} - -func decodeStreamUnmarshalerContext(s *Stream, depth int64, unmarshaler unmarshalerContext) error { - start := s.cursor - if err := s.skipValue(depth); err != nil { - return err - } - src := s.buf[start:s.cursor] - dst := make([]byte, len(src)) - copy(dst, src) - - if err := unmarshaler.UnmarshalJSON(s.Option.Context, dst); err != nil { - return err - } - return nil -} - -func decodeUnmarshaler(buf []byte, cursor, depth int64, unmarshaler json.Unmarshaler) (int64, error) { - cursor = skipWhiteSpace(buf, cursor) - start := cursor - end, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - src := buf[start:end] - dst := make([]byte, len(src)) - copy(dst, src) - - if err := unmarshaler.UnmarshalJSON(dst); err != nil { - return 0, err - } - return end, nil -} - -func decodeUnmarshalerContext(ctx *RuntimeContext, buf []byte, cursor, depth int64, unmarshaler unmarshalerContext) (int64, error) { - cursor = skipWhiteSpace(buf, cursor) - start := cursor - end, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - src := buf[start:end] - dst := make([]byte, len(src)) - copy(dst, src) - - if err := unmarshaler.UnmarshalJSON(ctx.Option.Context, dst); err != nil { - return 0, err - } - return end, nil -} - -func decodeStreamTextUnmarshaler(s *Stream, depth int64, unmarshaler encoding.TextUnmarshaler, p unsafe.Pointer) error { - start := s.cursor - if err := s.skipValue(depth); err != nil { - return err - } - src := s.buf[start:s.cursor] - if bytes.Equal(src, nullbytes) { - *(*unsafe.Pointer)(p) = nil - return nil - } - - dst := make([]byte, len(src)) - copy(dst, src) - - if err := unmarshaler.UnmarshalText(dst); err != nil { - return err - } - return nil -} - -func decodeTextUnmarshaler(buf []byte, cursor, depth int64, unmarshaler encoding.TextUnmarshaler, p unsafe.Pointer) (int64, error) { - cursor = skipWhiteSpace(buf, cursor) - start := cursor - end, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - src := buf[start:end] - if bytes.Equal(src, nullbytes) { - *(*unsafe.Pointer)(p) = nil - return end, nil - } - if s, ok := unquoteBytes(src); ok { - src = s - } - if err := unmarshaler.UnmarshalText(src); err != nil { - return 0, err - } - return end, nil -} - -func (d *interfaceDecoder) decodeStreamEmptyInterface(s *Stream, depth int64, p unsafe.Pointer) error { - c := s.skipWhiteSpace() - for { - switch c { - case '{': - var v map[string]interface{} - ptr := unsafe.Pointer(&v) - if err := d.mapDecoder.DecodeStream(s, depth, ptr); err != nil { - return err - } - *(*interface{})(p) = v - return nil - case '[': - var v []interface{} - ptr := unsafe.Pointer(&v) - if err := d.sliceDecoder.DecodeStream(s, depth, ptr); err != nil { - return err - } - *(*interface{})(p) = v - return nil - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return d.numDecoder(s).DecodeStream(s, depth, p) - case '"': - s.cursor++ - start := s.cursor - for { - switch s.char() { - case '\\': - if _, err := decodeEscapeString(s, nil); err != nil { - return err - } - case '"': - literal := s.buf[start:s.cursor] - s.cursor++ - *(*interface{})(p) = string(literal) - return nil - case nul: - if s.read() { - continue - } - return errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - } - s.cursor++ - } - case 't': - if err := trueBytes(s); err != nil { - return err - } - **(**interface{})(unsafe.Pointer(&p)) = true - return nil - case 'f': - if err := falseBytes(s); err != nil { - return err - } - **(**interface{})(unsafe.Pointer(&p)) = false - return nil - case 'n': - if err := nullBytes(s); err != nil { - return err - } - *(*interface{})(p) = nil - return nil - case nul: - if s.read() { - c = s.char() - continue - } - } - break - } - return errors.ErrNotAtBeginningOfValue(s.totalOffset()) -} - -type emptyInterface struct { - typ *runtime.Type - ptr unsafe.Pointer -} - -func (d *interfaceDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - runtimeInterfaceValue := *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: d.typ, - ptr: p, - })) - rv := reflect.ValueOf(runtimeInterfaceValue) - if rv.NumMethod() > 0 && rv.CanInterface() { - if u, ok := rv.Interface().(unmarshalerContext); ok { - return decodeStreamUnmarshalerContext(s, depth, u) - } - if u, ok := rv.Interface().(json.Unmarshaler); ok { - return decodeStreamUnmarshaler(s, depth, u) - } - if u, ok := rv.Interface().(encoding.TextUnmarshaler); ok { - return decodeStreamTextUnmarshaler(s, depth, u, p) - } - if s.skipWhiteSpace() == 'n' { - if err := nullBytes(s); err != nil { - return err - } - *(*interface{})(p) = nil - return nil - } - return d.errUnmarshalType(rv.Type(), s.totalOffset()) - } - iface := rv.Interface() - ifaceHeader := (*emptyInterface)(unsafe.Pointer(&iface)) - typ := ifaceHeader.typ - if ifaceHeader.ptr == nil || d.typ == typ || typ == nil { - // concrete type is empty interface - return d.decodeStreamEmptyInterface(s, depth, p) - } - if typ.Kind() == reflect.Ptr && typ.Elem() == d.typ || typ.Kind() != reflect.Ptr { - return d.decodeStreamEmptyInterface(s, depth, p) - } - if s.skipWhiteSpace() == 'n' { - if err := nullBytes(s); err != nil { - return err - } - *(*interface{})(p) = nil - return nil - } - decoder, err := CompileToGetDecoder(typ) - if err != nil { - return err - } - return decoder.DecodeStream(s, depth, ifaceHeader.ptr) -} - -func (d *interfaceDecoder) errUnmarshalType(typ reflect.Type, offset int64) *errors.UnmarshalTypeError { - return &errors.UnmarshalTypeError{ - Value: typ.String(), - Type: typ, - Offset: offset, - Struct: d.structName, - Field: d.fieldName, - } -} - -func (d *interfaceDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - runtimeInterfaceValue := *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: d.typ, - ptr: p, - })) - rv := reflect.ValueOf(runtimeInterfaceValue) - if rv.NumMethod() > 0 && rv.CanInterface() { - if u, ok := rv.Interface().(unmarshalerContext); ok { - return decodeUnmarshalerContext(ctx, buf, cursor, depth, u) - } - if u, ok := rv.Interface().(json.Unmarshaler); ok { - return decodeUnmarshaler(buf, cursor, depth, u) - } - if u, ok := rv.Interface().(encoding.TextUnmarshaler); ok { - return decodeTextUnmarshaler(buf, cursor, depth, u, p) - } - cursor = skipWhiteSpace(buf, cursor) - if buf[cursor] == 'n' { - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - **(**interface{})(unsafe.Pointer(&p)) = nil - return cursor, nil - } - return 0, d.errUnmarshalType(rv.Type(), cursor) - } - - iface := rv.Interface() - ifaceHeader := (*emptyInterface)(unsafe.Pointer(&iface)) - typ := ifaceHeader.typ - if ifaceHeader.ptr == nil || d.typ == typ || typ == nil { - // concrete type is empty interface - return d.decodeEmptyInterface(ctx, cursor, depth, p) - } - if typ.Kind() == reflect.Ptr && typ.Elem() == d.typ || typ.Kind() != reflect.Ptr { - return d.decodeEmptyInterface(ctx, cursor, depth, p) - } - cursor = skipWhiteSpace(buf, cursor) - if buf[cursor] == 'n' { - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - **(**interface{})(unsafe.Pointer(&p)) = nil - return cursor, nil - } - decoder, err := CompileToGetDecoder(typ) - if err != nil { - return 0, err - } - return decoder.Decode(ctx, cursor, depth, ifaceHeader.ptr) -} - -func (d *interfaceDecoder) decodeEmptyInterface(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - cursor = skipWhiteSpace(buf, cursor) - switch buf[cursor] { - case '{': - var v map[string]interface{} - ptr := unsafe.Pointer(&v) - cursor, err := d.mapDecoder.Decode(ctx, cursor, depth, ptr) - if err != nil { - return 0, err - } - **(**interface{})(unsafe.Pointer(&p)) = v - return cursor, nil - case '[': - var v []interface{} - ptr := unsafe.Pointer(&v) - cursor, err := d.sliceDecoder.Decode(ctx, cursor, depth, ptr) - if err != nil { - return 0, err - } - **(**interface{})(unsafe.Pointer(&p)) = v - return cursor, nil - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return d.floatDecoder.Decode(ctx, cursor, depth, p) - case '"': - var v string - ptr := unsafe.Pointer(&v) - cursor, err := d.stringDecoder.Decode(ctx, cursor, depth, ptr) - if err != nil { - return 0, err - } - **(**interface{})(unsafe.Pointer(&p)) = v - return cursor, nil - case 't': - if err := validateTrue(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - **(**interface{})(unsafe.Pointer(&p)) = true - return cursor, nil - case 'f': - if err := validateFalse(buf, cursor); err != nil { - return 0, err - } - cursor += 5 - **(**interface{})(unsafe.Pointer(&p)) = false - return cursor, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - **(**interface{})(unsafe.Pointer(&p)) = nil - return cursor, nil - } - return cursor, errors.ErrNotAtBeginningOfValue(cursor) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/map.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/map.go deleted file mode 100644 index dd480e16..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/map.go +++ /dev/null @@ -1,173 +0,0 @@ -package decoder - -import ( - "reflect" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type mapDecoder struct { - mapType *runtime.Type - keyType *runtime.Type - valueType *runtime.Type - stringKeyType bool - keyDecoder Decoder - valueDecoder Decoder - structName string - fieldName string -} - -func newMapDecoder(mapType *runtime.Type, keyType *runtime.Type, keyDec Decoder, valueType *runtime.Type, valueDec Decoder, structName, fieldName string) *mapDecoder { - return &mapDecoder{ - mapType: mapType, - keyDecoder: keyDec, - keyType: keyType, - stringKeyType: keyType.Kind() == reflect.String, - valueType: valueType, - valueDecoder: valueDec, - structName: structName, - fieldName: fieldName, - } -} - -//go:linkname makemap reflect.makemap -func makemap(*runtime.Type, int) unsafe.Pointer - -//nolint:golint -//go:linkname mapassign_faststr runtime.mapassign_faststr -//go:noescape -func mapassign_faststr(t *runtime.Type, m unsafe.Pointer, s string) unsafe.Pointer - -//go:linkname mapassign reflect.mapassign -//go:noescape -func mapassign(t *runtime.Type, m unsafe.Pointer, k, v unsafe.Pointer) - -func (d *mapDecoder) mapassign(t *runtime.Type, m, k, v unsafe.Pointer) { - if d.stringKeyType { - mapV := mapassign_faststr(d.mapType, m, *(*string)(k)) - typedmemmove(d.valueType, mapV, v) - } else { - mapassign(t, m, k, v) - } -} - -func (d *mapDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - - switch s.skipWhiteSpace() { - case 'n': - if err := nullBytes(s); err != nil { - return err - } - **(**unsafe.Pointer)(unsafe.Pointer(&p)) = nil - return nil - case '{': - default: - return errors.ErrExpected("{ character for map value", s.totalOffset()) - } - mapValue := *(*unsafe.Pointer)(p) - if mapValue == nil { - mapValue = makemap(d.mapType, 0) - } - if s.buf[s.cursor+1] == '}' { - *(*unsafe.Pointer)(p) = mapValue - s.cursor += 2 - return nil - } - for { - s.cursor++ - k := unsafe_New(d.keyType) - if err := d.keyDecoder.DecodeStream(s, depth, k); err != nil { - return err - } - s.skipWhiteSpace() - if !s.equalChar(':') { - return errors.ErrExpected("colon after object key", s.totalOffset()) - } - s.cursor++ - v := unsafe_New(d.valueType) - if err := d.valueDecoder.DecodeStream(s, depth, v); err != nil { - return err - } - d.mapassign(d.mapType, mapValue, k, v) - s.skipWhiteSpace() - if s.equalChar('}') { - **(**unsafe.Pointer)(unsafe.Pointer(&p)) = mapValue - s.cursor++ - return nil - } - if !s.equalChar(',') { - return errors.ErrExpected("comma after object value", s.totalOffset()) - } - } -} - -func (d *mapDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - - cursor = skipWhiteSpace(buf, cursor) - buflen := int64(len(buf)) - if buflen < 2 { - return 0, errors.ErrExpected("{} for map", cursor) - } - switch buf[cursor] { - case 'n': - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - **(**unsafe.Pointer)(unsafe.Pointer(&p)) = nil - return cursor, nil - case '{': - default: - return 0, errors.ErrExpected("{ character for map value", cursor) - } - cursor++ - cursor = skipWhiteSpace(buf, cursor) - mapValue := *(*unsafe.Pointer)(p) - if mapValue == nil { - mapValue = makemap(d.mapType, 0) - } - if buf[cursor] == '}' { - **(**unsafe.Pointer)(unsafe.Pointer(&p)) = mapValue - cursor++ - return cursor, nil - } - for { - k := unsafe_New(d.keyType) - keyCursor, err := d.keyDecoder.Decode(ctx, cursor, depth, k) - if err != nil { - return 0, err - } - cursor = skipWhiteSpace(buf, keyCursor) - if buf[cursor] != ':' { - return 0, errors.ErrExpected("colon after object key", cursor) - } - cursor++ - v := unsafe_New(d.valueType) - valueCursor, err := d.valueDecoder.Decode(ctx, cursor, depth, v) - if err != nil { - return 0, err - } - d.mapassign(d.mapType, mapValue, k, v) - cursor = skipWhiteSpace(buf, valueCursor) - if buf[cursor] == '}' { - **(**unsafe.Pointer)(unsafe.Pointer(&p)) = mapValue - cursor++ - return cursor, nil - } - if buf[cursor] != ',' { - return 0, errors.ErrExpected("comma after object value", cursor) - } - cursor++ - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/number.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/number.go deleted file mode 100644 index c50d62b9..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/number.go +++ /dev/null @@ -1,108 +0,0 @@ -package decoder - -import ( - "encoding/json" - "strconv" - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -type numberDecoder struct { - stringDecoder *stringDecoder - op func(unsafe.Pointer, json.Number) - structName string - fieldName string -} - -func newNumberDecoder(structName, fieldName string, op func(unsafe.Pointer, json.Number)) *numberDecoder { - return &numberDecoder{ - stringDecoder: newStringDecoder(structName, fieldName), - op: op, - structName: structName, - fieldName: fieldName, - } -} - -func (d *numberDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - bytes, err := d.decodeStreamByte(s) - if err != nil { - return err - } - if _, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&bytes)), 64); err != nil { - return errors.ErrSyntax(err.Error(), s.totalOffset()) - } - d.op(p, json.Number(string(bytes))) - s.reset() - return nil -} - -func (d *numberDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - bytes, c, err := d.decodeByte(ctx.Buf, cursor) - if err != nil { - return 0, err - } - if _, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&bytes)), 64); err != nil { - return 0, errors.ErrSyntax(err.Error(), c) - } - cursor = c - s := *(*string)(unsafe.Pointer(&bytes)) - d.op(p, json.Number(s)) - return cursor, nil -} - -func (d *numberDecoder) decodeStreamByte(s *Stream) ([]byte, error) { - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - s.cursor++ - continue - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return floatBytes(s), nil - case 'n': - if err := nullBytes(s); err != nil { - return nil, err - } - return nil, nil - case '"': - return d.stringDecoder.decodeStreamByte(s) - case nul: - if s.read() { - continue - } - goto ERROR - default: - goto ERROR - } - } -ERROR: - return nil, errors.ErrUnexpectedEndOfJSON("json.Number", s.totalOffset()) -} - -func (d *numberDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { - for { - switch buf[cursor] { - case ' ', '\n', '\t', '\r': - cursor++ - continue - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - start := cursor - cursor++ - for floatTable[buf[cursor]] { - cursor++ - } - num := buf[start:cursor] - return num, cursor, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return nil, 0, err - } - cursor += 4 - return nil, cursor, nil - case '"': - return d.stringDecoder.decodeByte(buf, cursor) - default: - return nil, 0, errors.ErrUnexpectedEndOfJSON("json.Number", cursor) - } - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/option.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/option.go deleted file mode 100644 index e41f876b..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/option.go +++ /dev/null @@ -1,15 +0,0 @@ -package decoder - -import "context" - -type OptionFlags uint8 - -const ( - FirstWinOption OptionFlags = 1 << iota - ContextOption -) - -type Option struct { - Flags OptionFlags - Context context.Context -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/ptr.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/ptr.go deleted file mode 100644 index 2c83b9c4..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/ptr.go +++ /dev/null @@ -1,87 +0,0 @@ -package decoder - -import ( - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -type ptrDecoder struct { - dec Decoder - typ *runtime.Type - structName string - fieldName string -} - -func newPtrDecoder(dec Decoder, typ *runtime.Type, structName, fieldName string) *ptrDecoder { - return &ptrDecoder{ - dec: dec, - typ: typ, - structName: structName, - fieldName: fieldName, - } -} - -func (d *ptrDecoder) contentDecoder() Decoder { - dec, ok := d.dec.(*ptrDecoder) - if !ok { - return d.dec - } - return dec.contentDecoder() -} - -//nolint:golint -//go:linkname unsafe_New reflect.unsafe_New -func unsafe_New(*runtime.Type) unsafe.Pointer - -func (d *ptrDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - if s.skipWhiteSpace() == nul { - s.read() - } - if s.char() == 'n' { - if err := nullBytes(s); err != nil { - return err - } - *(*unsafe.Pointer)(p) = nil - return nil - } - var newptr unsafe.Pointer - if *(*unsafe.Pointer)(p) == nil { - newptr = unsafe_New(d.typ) - *(*unsafe.Pointer)(p) = newptr - } else { - newptr = *(*unsafe.Pointer)(p) - } - if err := d.dec.DecodeStream(s, depth, newptr); err != nil { - return err - } - return nil -} - -func (d *ptrDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - cursor = skipWhiteSpace(buf, cursor) - if buf[cursor] == 'n' { - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - if p != nil { - *(*unsafe.Pointer)(p) = nil - } - cursor += 4 - return cursor, nil - } - var newptr unsafe.Pointer - if *(*unsafe.Pointer)(p) == nil { - newptr = unsafe_New(d.typ) - *(*unsafe.Pointer)(p) = newptr - } else { - newptr = *(*unsafe.Pointer)(p) - } - c, err := d.dec.Decode(ctx, cursor, depth, newptr) - if err != nil { - return 0, err - } - cursor = c - return cursor, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/slice.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/slice.go deleted file mode 100644 index 853a555e..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/slice.go +++ /dev/null @@ -1,294 +0,0 @@ -package decoder - -import ( - "reflect" - "sync" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type sliceDecoder struct { - elemType *runtime.Type - isElemPointerType bool - valueDecoder Decoder - size uintptr - arrayPool sync.Pool - structName string - fieldName string -} - -// If use reflect.SliceHeader, data type is uintptr. -// In this case, Go compiler cannot trace reference created by newArray(). -// So, define using unsafe.Pointer as data type -type sliceHeader struct { - data unsafe.Pointer - len int - cap int -} - -const ( - defaultSliceCapacity = 2 -) - -func newSliceDecoder(dec Decoder, elemType *runtime.Type, size uintptr, structName, fieldName string) *sliceDecoder { - return &sliceDecoder{ - valueDecoder: dec, - elemType: elemType, - isElemPointerType: elemType.Kind() == reflect.Ptr || elemType.Kind() == reflect.Map, - size: size, - arrayPool: sync.Pool{ - New: func() interface{} { - return &sliceHeader{ - data: newArray(elemType, defaultSliceCapacity), - len: 0, - cap: defaultSliceCapacity, - } - }, - }, - structName: structName, - fieldName: fieldName, - } -} - -func (d *sliceDecoder) newSlice(src *sliceHeader) *sliceHeader { - slice := d.arrayPool.Get().(*sliceHeader) - if src.len > 0 { - // copy original elem - if slice.cap < src.cap { - data := newArray(d.elemType, src.cap) - slice = &sliceHeader{data: data, len: src.len, cap: src.cap} - } else { - slice.len = src.len - } - copySlice(d.elemType, *slice, *src) - } else { - slice.len = 0 - } - return slice -} - -func (d *sliceDecoder) releaseSlice(p *sliceHeader) { - d.arrayPool.Put(p) -} - -//go:linkname copySlice reflect.typedslicecopy -func copySlice(elemType *runtime.Type, dst, src sliceHeader) int - -//go:linkname newArray reflect.unsafe_NewArray -func newArray(*runtime.Type, int) unsafe.Pointer - -//go:linkname typedmemmove reflect.typedmemmove -func typedmemmove(t *runtime.Type, dst, src unsafe.Pointer) - -func (d *sliceDecoder) errNumber(offset int64) *errors.UnmarshalTypeError { - return &errors.UnmarshalTypeError{ - Value: "number", - Type: reflect.SliceOf(runtime.RType2Type(d.elemType)), - Struct: d.structName, - Field: d.fieldName, - Offset: offset, - } -} - -func (d *sliceDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - s.cursor++ - continue - case 'n': - if err := nullBytes(s); err != nil { - return err - } - *(*unsafe.Pointer)(p) = nil - return nil - case '[': - s.cursor++ - if s.skipWhiteSpace() == ']' { - dst := (*sliceHeader)(p) - if dst.data == nil { - dst.data = newArray(d.elemType, 0) - } else { - dst.len = 0 - } - s.cursor++ - return nil - } - idx := 0 - slice := d.newSlice((*sliceHeader)(p)) - srcLen := slice.len - capacity := slice.cap - data := slice.data - for { - if capacity <= idx { - src := sliceHeader{data: data, len: idx, cap: capacity} - capacity *= 2 - data = newArray(d.elemType, capacity) - dst := sliceHeader{data: data, len: idx, cap: capacity} - copySlice(d.elemType, dst, src) - } - ep := unsafe.Pointer(uintptr(data) + uintptr(idx)*d.size) - - // if srcLen is greater than idx, keep the original reference - if srcLen <= idx { - if d.isElemPointerType { - **(**unsafe.Pointer)(unsafe.Pointer(&ep)) = nil // initialize elem pointer - } else { - // assign new element to the slice - typedmemmove(d.elemType, ep, unsafe_New(d.elemType)) - } - } - - if err := d.valueDecoder.DecodeStream(s, depth, ep); err != nil { - return err - } - s.skipWhiteSpace() - RETRY: - switch s.char() { - case ']': - slice.cap = capacity - slice.len = idx + 1 - slice.data = data - dst := (*sliceHeader)(p) - dst.len = idx + 1 - if dst.len > dst.cap { - dst.data = newArray(d.elemType, dst.len) - dst.cap = dst.len - } - copySlice(d.elemType, *dst, *slice) - d.releaseSlice(slice) - s.cursor++ - return nil - case ',': - idx++ - case nul: - if s.read() { - goto RETRY - } - slice.cap = capacity - slice.data = data - d.releaseSlice(slice) - goto ERROR - default: - slice.cap = capacity - slice.data = data - d.releaseSlice(slice) - goto ERROR - } - s.cursor++ - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return d.errNumber(s.totalOffset()) - case nul: - if s.read() { - continue - } - goto ERROR - default: - goto ERROR - } - } -ERROR: - return errors.ErrUnexpectedEndOfJSON("slice", s.totalOffset()) -} - -func (d *sliceDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - - for { - switch buf[cursor] { - case ' ', '\n', '\t', '\r': - cursor++ - continue - case 'n': - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - *(*unsafe.Pointer)(p) = nil - return cursor, nil - case '[': - cursor++ - cursor = skipWhiteSpace(buf, cursor) - if buf[cursor] == ']' { - dst := (*sliceHeader)(p) - if dst.data == nil { - dst.data = newArray(d.elemType, 0) - } else { - dst.len = 0 - } - cursor++ - return cursor, nil - } - idx := 0 - slice := d.newSlice((*sliceHeader)(p)) - srcLen := slice.len - capacity := slice.cap - data := slice.data - for { - if capacity <= idx { - src := sliceHeader{data: data, len: idx, cap: capacity} - capacity *= 2 - data = newArray(d.elemType, capacity) - dst := sliceHeader{data: data, len: idx, cap: capacity} - copySlice(d.elemType, dst, src) - } - ep := unsafe.Pointer(uintptr(data) + uintptr(idx)*d.size) - // if srcLen is greater than idx, keep the original reference - if srcLen <= idx { - if d.isElemPointerType { - **(**unsafe.Pointer)(unsafe.Pointer(&ep)) = nil // initialize elem pointer - } else { - // assign new element to the slice - typedmemmove(d.elemType, ep, unsafe_New(d.elemType)) - } - } - c, err := d.valueDecoder.Decode(ctx, cursor, depth, ep) - if err != nil { - return 0, err - } - cursor = c - cursor = skipWhiteSpace(buf, cursor) - switch buf[cursor] { - case ']': - slice.cap = capacity - slice.len = idx + 1 - slice.data = data - dst := (*sliceHeader)(p) - dst.len = idx + 1 - if dst.len > dst.cap { - dst.data = newArray(d.elemType, dst.len) - dst.cap = dst.len - } - copySlice(d.elemType, *dst, *slice) - d.releaseSlice(slice) - cursor++ - return cursor, nil - case ',': - idx++ - default: - slice.cap = capacity - slice.data = data - d.releaseSlice(slice) - return 0, errors.ErrInvalidCharacter(buf[cursor], "slice", cursor) - } - cursor++ - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return 0, d.errNumber(cursor) - default: - return 0, errors.ErrUnexpectedEndOfJSON("slice", cursor) - } - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/stream.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/stream.go deleted file mode 100644 index c2746834..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/stream.go +++ /dev/null @@ -1,554 +0,0 @@ -package decoder - -import ( - "bytes" - "encoding/json" - "io" - "strconv" - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -const ( - initBufSize = 512 -) - -type Stream struct { - buf []byte - bufSize int64 - length int64 - r io.Reader - offset int64 - cursor int64 - filledBuffer bool - allRead bool - UseNumber bool - DisallowUnknownFields bool - Option *Option -} - -func NewStream(r io.Reader) *Stream { - return &Stream{ - r: r, - bufSize: initBufSize, - buf: make([]byte, initBufSize), - Option: &Option{}, - } -} - -func (s *Stream) TotalOffset() int64 { - return s.totalOffset() -} - -func (s *Stream) Buffered() io.Reader { - buflen := int64(len(s.buf)) - for i := s.cursor; i < buflen; i++ { - if s.buf[i] == nul { - return bytes.NewReader(s.buf[s.cursor:i]) - } - } - return bytes.NewReader(s.buf[s.cursor:]) -} - -func (s *Stream) PrepareForDecode() error { - for { - switch s.char() { - case ' ', '\t', '\r', '\n': - s.cursor++ - continue - case ',', ':': - s.cursor++ - return nil - case nul: - if s.read() { - continue - } - return io.EOF - } - break - } - return nil -} - -func (s *Stream) totalOffset() int64 { - return s.offset + s.cursor -} - -func (s *Stream) char() byte { - return s.buf[s.cursor] -} - -func (s *Stream) equalChar(c byte) bool { - cur := s.buf[s.cursor] - if cur == nul { - s.read() - cur = s.buf[s.cursor] - } - return cur == c -} - -func (s *Stream) stat() ([]byte, int64, unsafe.Pointer) { - return s.buf, s.cursor, (*sliceHeader)(unsafe.Pointer(&s.buf)).data -} - -func (s *Stream) bufptr() unsafe.Pointer { - return (*sliceHeader)(unsafe.Pointer(&s.buf)).data -} - -func (s *Stream) statForRetry() ([]byte, int64, unsafe.Pointer) { - s.cursor-- // for retry ( because caller progress cursor position in each loop ) - return s.buf, s.cursor, (*sliceHeader)(unsafe.Pointer(&s.buf)).data -} - -func (s *Stream) Reset() { - s.reset() - s.bufSize = initBufSize -} - -func (s *Stream) More() bool { - for { - switch s.char() { - case ' ', '\n', '\r', '\t': - s.cursor++ - continue - case '}', ']': - return false - case nul: - if s.read() { - continue - } - return false - } - break - } - return true -} - -func (s *Stream) Token() (interface{}, error) { - for { - c := s.char() - switch c { - case ' ', '\n', '\r', '\t': - s.cursor++ - case '{', '[', ']', '}': - s.cursor++ - return json.Delim(c), nil - case ',', ':': - s.cursor++ - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - bytes := floatBytes(s) - s := *(*string)(unsafe.Pointer(&bytes)) - f64, err := strconv.ParseFloat(s, 64) - if err != nil { - return nil, err - } - return f64, nil - case '"': - bytes, err := stringBytes(s) - if err != nil { - return nil, err - } - return string(bytes), nil - case 't': - if err := trueBytes(s); err != nil { - return nil, err - } - return true, nil - case 'f': - if err := falseBytes(s); err != nil { - return nil, err - } - return false, nil - case 'n': - if err := nullBytes(s); err != nil { - return nil, err - } - return nil, nil - case nul: - if s.read() { - continue - } - goto END - default: - return nil, errors.ErrInvalidCharacter(s.char(), "token", s.totalOffset()) - } - } -END: - return nil, io.EOF -} - -func (s *Stream) reset() { - s.offset += s.cursor - s.buf = s.buf[s.cursor:] - s.length -= s.cursor - s.cursor = 0 -} - -func (s *Stream) readBuf() []byte { - if s.filledBuffer { - s.bufSize *= 2 - remainBuf := s.buf - s.buf = make([]byte, s.bufSize) - copy(s.buf, remainBuf) - } - remainLen := s.length - s.cursor - remainNotNulCharNum := int64(0) - for i := int64(0); i < remainLen; i++ { - if s.buf[s.cursor+i] == nul { - break - } - remainNotNulCharNum++ - } - s.length = s.cursor + remainNotNulCharNum - return s.buf[s.cursor+remainNotNulCharNum:] -} - -func (s *Stream) read() bool { - if s.allRead { - return false - } - buf := s.readBuf() - last := len(buf) - 1 - buf[last] = nul - n, err := s.r.Read(buf[:last]) - s.length += int64(n) - if n == last { - s.filledBuffer = true - } else { - s.filledBuffer = false - } - if err == io.EOF { - s.allRead = true - } else if err != nil { - return false - } - return true -} - -func (s *Stream) skipWhiteSpace() byte { - p := s.bufptr() -LOOP: - c := char(p, s.cursor) - switch c { - case ' ', '\n', '\t', '\r': - s.cursor++ - goto LOOP - case nul: - if s.read() { - p = s.bufptr() - goto LOOP - } - } - return c -} - -func (s *Stream) skipObject(depth int64) error { - braceCount := 1 - _, cursor, p := s.stat() - for { - switch char(p, cursor) { - case '{': - braceCount++ - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - case '}': - braceCount-- - depth-- - if braceCount == 0 { - s.cursor = cursor + 1 - return nil - } - case '[': - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - case ']': - depth-- - case '"': - for { - cursor++ - switch char(p, cursor) { - case '\\': - cursor++ - if char(p, cursor) == nul { - s.cursor = cursor - if s.read() { - _, cursor, p = s.statForRetry() - continue - } - return errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - case '"': - goto SWITCH_OUT - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.statForRetry() - continue - } - return errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - } - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - return errors.ErrUnexpectedEndOfJSON("object of object", cursor) - } - SWITCH_OUT: - cursor++ - } -} - -func (s *Stream) skipArray(depth int64) error { - bracketCount := 1 - _, cursor, p := s.stat() - for { - switch char(p, cursor) { - case '[': - bracketCount++ - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - case ']': - bracketCount-- - depth-- - if bracketCount == 0 { - s.cursor = cursor + 1 - return nil - } - case '{': - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - case '}': - depth-- - case '"': - for { - cursor++ - switch char(p, cursor) { - case '\\': - cursor++ - if char(p, cursor) == nul { - s.cursor = cursor - if s.read() { - _, cursor, p = s.statForRetry() - continue - } - return errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - case '"': - goto SWITCH_OUT - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.statForRetry() - continue - } - return errors.ErrUnexpectedEndOfJSON("string of object", cursor) - } - } - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - return errors.ErrUnexpectedEndOfJSON("array of object", cursor) - } - SWITCH_OUT: - cursor++ - } -} - -func (s *Stream) skipValue(depth int64) error { - _, cursor, p := s.stat() - for { - switch char(p, cursor) { - case ' ', '\n', '\t', '\r': - cursor++ - continue - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - return errors.ErrUnexpectedEndOfJSON("value of object", s.totalOffset()) - case '{': - s.cursor = cursor + 1 - return s.skipObject(depth + 1) - case '[': - s.cursor = cursor + 1 - return s.skipArray(depth + 1) - case '"': - for { - cursor++ - switch char(p, cursor) { - case '\\': - cursor++ - if char(p, cursor) == nul { - s.cursor = cursor - if s.read() { - _, cursor, p = s.statForRetry() - continue - } - return errors.ErrUnexpectedEndOfJSON("value of string", s.totalOffset()) - } - case '"': - s.cursor = cursor + 1 - return nil - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.statForRetry() - continue - } - return errors.ErrUnexpectedEndOfJSON("value of string", s.totalOffset()) - } - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - for { - cursor++ - c := char(p, cursor) - if floatTable[c] { - continue - } else if c == nul { - if s.read() { - s.cursor-- // for retry current character - _, cursor, p = s.stat() - continue - } - } - s.cursor = cursor - return nil - } - case 't': - s.cursor = cursor - if err := trueBytes(s); err != nil { - return err - } - return nil - case 'f': - s.cursor = cursor - if err := falseBytes(s); err != nil { - return err - } - return nil - case 'n': - s.cursor = cursor - if err := nullBytes(s); err != nil { - return err - } - return nil - } - cursor++ - } -} - -func nullBytes(s *Stream) error { - // current cursor's character is 'n' - s.cursor++ - if s.char() != 'u' { - if err := retryReadNull(s); err != nil { - return err - } - } - s.cursor++ - if s.char() != 'l' { - if err := retryReadNull(s); err != nil { - return err - } - } - s.cursor++ - if s.char() != 'l' { - if err := retryReadNull(s); err != nil { - return err - } - } - s.cursor++ - return nil -} - -func retryReadNull(s *Stream) error { - if s.char() == nul && s.read() { - return nil - } - return errors.ErrInvalidCharacter(s.char(), "null", s.totalOffset()) -} - -func trueBytes(s *Stream) error { - // current cursor's character is 't' - s.cursor++ - if s.char() != 'r' { - if err := retryReadTrue(s); err != nil { - return err - } - } - s.cursor++ - if s.char() != 'u' { - if err := retryReadTrue(s); err != nil { - return err - } - } - s.cursor++ - if s.char() != 'e' { - if err := retryReadTrue(s); err != nil { - return err - } - } - s.cursor++ - return nil -} - -func retryReadTrue(s *Stream) error { - if s.char() == nul && s.read() { - return nil - } - return errors.ErrInvalidCharacter(s.char(), "bool(true)", s.totalOffset()) -} - -func falseBytes(s *Stream) error { - // current cursor's character is 'f' - s.cursor++ - if s.char() != 'a' { - if err := retryReadFalse(s); err != nil { - return err - } - } - s.cursor++ - if s.char() != 'l' { - if err := retryReadFalse(s); err != nil { - return err - } - } - s.cursor++ - if s.char() != 's' { - if err := retryReadFalse(s); err != nil { - return err - } - } - s.cursor++ - if s.char() != 'e' { - if err := retryReadFalse(s); err != nil { - return err - } - } - s.cursor++ - return nil -} - -func retryReadFalse(s *Stream) error { - if s.char() == nul && s.read() { - return nil - } - return errors.ErrInvalidCharacter(s.char(), "bool(false)", s.totalOffset()) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/string.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/string.go deleted file mode 100644 index 1e1ce157..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/string.go +++ /dev/null @@ -1,361 +0,0 @@ -package decoder - -import ( - "reflect" - "unicode" - "unicode/utf16" - "unicode/utf8" - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -type stringDecoder struct { - structName string - fieldName string -} - -func newStringDecoder(structName, fieldName string) *stringDecoder { - return &stringDecoder{ - structName: structName, - fieldName: fieldName, - } -} - -func (d *stringDecoder) errUnmarshalType(typeName string, offset int64) *errors.UnmarshalTypeError { - return &errors.UnmarshalTypeError{ - Value: typeName, - Type: reflect.TypeOf(""), - Offset: offset, - Struct: d.structName, - Field: d.fieldName, - } -} - -func (d *stringDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - bytes, err := d.decodeStreamByte(s) - if err != nil { - return err - } - if bytes == nil { - return nil - } - **(**string)(unsafe.Pointer(&p)) = *(*string)(unsafe.Pointer(&bytes)) - s.reset() - return nil -} - -func (d *stringDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - bytes, c, err := d.decodeByte(ctx.Buf, cursor) - if err != nil { - return 0, err - } - if bytes == nil { - return c, nil - } - cursor = c - **(**string)(unsafe.Pointer(&p)) = *(*string)(unsafe.Pointer(&bytes)) - return cursor, nil -} - -var ( - hexToInt = [256]int{ - '0': 0, - '1': 1, - '2': 2, - '3': 3, - '4': 4, - '5': 5, - '6': 6, - '7': 7, - '8': 8, - '9': 9, - 'A': 10, - 'B': 11, - 'C': 12, - 'D': 13, - 'E': 14, - 'F': 15, - 'a': 10, - 'b': 11, - 'c': 12, - 'd': 13, - 'e': 14, - 'f': 15, - } -) - -func unicodeToRune(code []byte) rune { - var r rune - for i := 0; i < len(code); i++ { - r = r*16 + rune(hexToInt[code[i]]) - } - return r -} - -func decodeUnicodeRune(s *Stream, p unsafe.Pointer) (rune, int64, unsafe.Pointer, error) { - const defaultOffset = 5 - const surrogateOffset = 11 - - if s.cursor+defaultOffset >= s.length { - if !s.read() { - return rune(0), 0, nil, errors.ErrInvalidCharacter(s.char(), "escaped string", s.totalOffset()) - } - p = s.bufptr() - } - - r := unicodeToRune(s.buf[s.cursor+1 : s.cursor+defaultOffset]) - if utf16.IsSurrogate(r) { - if s.cursor+surrogateOffset >= s.length { - s.read() - p = s.bufptr() - } - if s.cursor+surrogateOffset >= s.length || s.buf[s.cursor+defaultOffset] != '\\' || s.buf[s.cursor+defaultOffset+1] != 'u' { - return unicode.ReplacementChar, defaultOffset, p, nil - } - r2 := unicodeToRune(s.buf[s.cursor+defaultOffset+2 : s.cursor+surrogateOffset]) - if r := utf16.DecodeRune(r, r2); r != unicode.ReplacementChar { - return r, surrogateOffset, p, nil - } - } - return r, defaultOffset, p, nil -} - -func decodeUnicode(s *Stream, p unsafe.Pointer) (unsafe.Pointer, error) { - const backSlashAndULen = 2 // length of \u - - r, offset, pp, err := decodeUnicodeRune(s, p) - if err != nil { - return nil, err - } - unicode := []byte(string(r)) - unicodeLen := int64(len(unicode)) - s.buf = append(append(s.buf[:s.cursor-1], unicode...), s.buf[s.cursor+offset:]...) - unicodeOrgLen := offset - 1 - s.length = s.length - (backSlashAndULen + (unicodeOrgLen - unicodeLen)) - s.cursor = s.cursor - backSlashAndULen + unicodeLen - return pp, nil -} - -func decodeEscapeString(s *Stream, p unsafe.Pointer) (unsafe.Pointer, error) { - s.cursor++ -RETRY: - switch s.buf[s.cursor] { - case '"': - s.buf[s.cursor] = '"' - case '\\': - s.buf[s.cursor] = '\\' - case '/': - s.buf[s.cursor] = '/' - case 'b': - s.buf[s.cursor] = '\b' - case 'f': - s.buf[s.cursor] = '\f' - case 'n': - s.buf[s.cursor] = '\n' - case 'r': - s.buf[s.cursor] = '\r' - case 't': - s.buf[s.cursor] = '\t' - case 'u': - return decodeUnicode(s, p) - case nul: - if !s.read() { - return nil, errors.ErrInvalidCharacter(s.char(), "escaped string", s.totalOffset()) - } - goto RETRY - default: - return nil, errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - } - s.buf = append(s.buf[:s.cursor-1], s.buf[s.cursor:]...) - s.length-- - s.cursor-- - return p, nil -} - -var ( - runeErrBytes = []byte(string(utf8.RuneError)) - runeErrBytesLen = int64(len(runeErrBytes)) -) - -func stringBytes(s *Stream) ([]byte, error) { - _, cursor, p := s.stat() - cursor++ // skip double quote char - start := cursor - for { - switch char(p, cursor) { - case '\\': - s.cursor = cursor - pp, err := decodeEscapeString(s, p) - if err != nil { - return nil, err - } - p = pp - cursor = s.cursor - case '"': - literal := s.buf[start:cursor] - cursor++ - s.cursor = cursor - return literal, nil - case - // 0x00 is nul, 0x5c is '\\', 0x22 is '"' . - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // 0x00-0x0F - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // 0x10-0x1F - 0x20, 0x21 /*0x22,*/, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // 0x20-0x2F - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, // 0x30-0x3F - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, // 0x40-0x4F - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B /*0x5C,*/, 0x5D, 0x5E, 0x5F, // 0x50-0x5F - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, // 0x60-0x6F - 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F: // 0x70-0x7F - // character is ASCII. skip to next char - case - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, // 0x80-0x8F - 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, // 0x90-0x9F - 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, // 0xA0-0xAF - 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, // 0xB0-0xBF - 0xC0, 0xC1, // 0xC0-0xC1 - 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF: // 0xF5-0xFE - // character is invalid - s.buf = append(append(append([]byte{}, s.buf[:cursor]...), runeErrBytes...), s.buf[cursor+1:]...) - _, _, p = s.stat() - cursor += runeErrBytesLen - s.length += runeErrBytesLen - continue - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - goto ERROR - case 0xEF: - // RuneError is {0xEF, 0xBF, 0xBD} - if s.buf[cursor+1] == 0xBF && s.buf[cursor+2] == 0xBD { - // found RuneError: skip - cursor += 2 - break - } - fallthrough - default: - // multi bytes character - r, _ := utf8.DecodeRune(s.buf[cursor:]) - b := []byte(string(r)) - if r == utf8.RuneError { - s.buf = append(append(append([]byte{}, s.buf[:cursor]...), b...), s.buf[cursor+1:]...) - _, _, p = s.stat() - } - cursor += int64(len(b)) - s.length += int64(len(b)) - continue - } - cursor++ - } -ERROR: - return nil, errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) -} - -func (d *stringDecoder) decodeStreamByte(s *Stream) ([]byte, error) { - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - s.cursor++ - continue - case '[': - return nil, d.errUnmarshalType("array", s.totalOffset()) - case '{': - return nil, d.errUnmarshalType("object", s.totalOffset()) - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return nil, d.errUnmarshalType("number", s.totalOffset()) - case '"': - return stringBytes(s) - case 'n': - if err := nullBytes(s); err != nil { - return nil, err - } - return nil, nil - case nul: - if s.read() { - continue - } - } - break - } - return nil, errors.ErrNotAtBeginningOfValue(s.totalOffset()) -} - -func (d *stringDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { - for { - switch buf[cursor] { - case ' ', '\n', '\t', '\r': - cursor++ - case '[': - return nil, 0, d.errUnmarshalType("array", cursor) - case '{': - return nil, 0, d.errUnmarshalType("object", cursor) - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return nil, 0, d.errUnmarshalType("number", cursor) - case '"': - cursor++ - start := cursor - b := (*sliceHeader)(unsafe.Pointer(&buf)).data - for { - switch char(b, cursor) { - case '\\': - cursor++ - switch char(b, cursor) { - case '"': - buf[cursor] = '"' - buf = append(buf[:cursor-1], buf[cursor:]...) - case '\\': - buf[cursor] = '\\' - buf = append(buf[:cursor-1], buf[cursor:]...) - case '/': - buf[cursor] = '/' - buf = append(buf[:cursor-1], buf[cursor:]...) - case 'b': - buf[cursor] = '\b' - buf = append(buf[:cursor-1], buf[cursor:]...) - case 'f': - buf[cursor] = '\f' - buf = append(buf[:cursor-1], buf[cursor:]...) - case 'n': - buf[cursor] = '\n' - buf = append(buf[:cursor-1], buf[cursor:]...) - case 'r': - buf[cursor] = '\r' - buf = append(buf[:cursor-1], buf[cursor:]...) - case 't': - buf[cursor] = '\t' - buf = append(buf[:cursor-1], buf[cursor:]...) - case 'u': - buflen := int64(len(buf)) - if cursor+5 >= buflen { - return nil, 0, errors.ErrUnexpectedEndOfJSON("escaped string", cursor) - } - code := unicodeToRune(buf[cursor+1 : cursor+5]) - unicode := []byte(string(code)) - buf = append(append(buf[:cursor-1], unicode...), buf[cursor+5:]...) - default: - return nil, 0, errors.ErrUnexpectedEndOfJSON("escaped string", cursor) - } - continue - case '"': - literal := buf[start:cursor] - cursor++ - return literal, cursor, nil - case nul: - return nil, 0, errors.ErrUnexpectedEndOfJSON("string", cursor) - } - cursor++ - } - case 'n': - if err := validateNull(buf, cursor); err != nil { - return nil, 0, err - } - cursor += 4 - return nil, cursor, nil - default: - return nil, 0, errors.ErrNotAtBeginningOfValue(cursor) - } - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/struct.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/struct.go deleted file mode 100644 index d467b0d2..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/struct.go +++ /dev/null @@ -1,819 +0,0 @@ -package decoder - -import ( - "fmt" - "math" - "math/bits" - "sort" - "strings" - "unicode" - "unicode/utf16" - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -type structFieldSet struct { - dec Decoder - offset uintptr - isTaggedKey bool - fieldIdx int - key string - keyLen int64 - err error -} - -type structDecoder struct { - fieldMap map[string]*structFieldSet - fieldUniqueNameNum int - stringDecoder *stringDecoder - structName string - fieldName string - isTriedOptimize bool - keyBitmapUint8 [][256]uint8 - keyBitmapUint16 [][256]uint16 - sortedFieldSets []*structFieldSet - keyDecoder func(*structDecoder, []byte, int64) (int64, *structFieldSet, error) - keyStreamDecoder func(*structDecoder, *Stream) (*structFieldSet, string, error) -} - -var ( - largeToSmallTable [256]byte -) - -func init() { - for i := 0; i < 256; i++ { - c := i - if 'A' <= c && c <= 'Z' { - c += 'a' - 'A' - } - largeToSmallTable[i] = byte(c) - } -} - -func newStructDecoder(structName, fieldName string, fieldMap map[string]*structFieldSet) *structDecoder { - return &structDecoder{ - fieldMap: fieldMap, - stringDecoder: newStringDecoder(structName, fieldName), - structName: structName, - fieldName: fieldName, - keyDecoder: decodeKey, - keyStreamDecoder: decodeKeyStream, - } -} - -const ( - allowOptimizeMaxKeyLen = 64 - allowOptimizeMaxFieldLen = 16 -) - -func (d *structDecoder) tryOptimize() { - fieldUniqueNameMap := map[string]int{} - fieldIdx := -1 - for k, v := range d.fieldMap { - lower := strings.ToLower(k) - idx, exists := fieldUniqueNameMap[lower] - if exists { - v.fieldIdx = idx - } else { - fieldIdx++ - v.fieldIdx = fieldIdx - } - fieldUniqueNameMap[lower] = fieldIdx - } - d.fieldUniqueNameNum = len(fieldUniqueNameMap) - - if d.isTriedOptimize { - return - } - fieldMap := map[string]*structFieldSet{} - conflicted := map[string]struct{}{} - for k, v := range d.fieldMap { - key := strings.ToLower(k) - if key != k { - // already exists same key (e.g. Hello and HELLO has same lower case key - if _, exists := conflicted[key]; exists { - d.isTriedOptimize = true - return - } - conflicted[key] = struct{}{} - } - if field, exists := fieldMap[key]; exists { - if field != v { - d.isTriedOptimize = true - return - } - } - fieldMap[key] = v - } - - if len(fieldMap) > allowOptimizeMaxFieldLen { - d.isTriedOptimize = true - return - } - - var maxKeyLen int - sortedKeys := []string{} - for key := range fieldMap { - keyLen := len(key) - if keyLen > allowOptimizeMaxKeyLen { - d.isTriedOptimize = true - return - } - if maxKeyLen < keyLen { - maxKeyLen = keyLen - } - sortedKeys = append(sortedKeys, key) - } - sort.Strings(sortedKeys) - - // By allocating one extra capacity than `maxKeyLen`, - // it is possible to avoid the process of comparing the index of the key with the length of the bitmap each time. - bitmapLen := maxKeyLen + 1 - if len(sortedKeys) <= 8 { - keyBitmap := make([][256]uint8, bitmapLen) - for i, key := range sortedKeys { - for j := 0; j < len(key); j++ { - c := key[j] - keyBitmap[j][c] |= (1 << uint(i)) - } - d.sortedFieldSets = append(d.sortedFieldSets, fieldMap[key]) - } - d.keyBitmapUint8 = keyBitmap - d.keyDecoder = decodeKeyByBitmapUint8 - d.keyStreamDecoder = decodeKeyByBitmapUint8Stream - } else { - keyBitmap := make([][256]uint16, bitmapLen) - for i, key := range sortedKeys { - for j := 0; j < len(key); j++ { - c := key[j] - keyBitmap[j][c] |= (1 << uint(i)) - } - d.sortedFieldSets = append(d.sortedFieldSets, fieldMap[key]) - } - d.keyBitmapUint16 = keyBitmap - d.keyDecoder = decodeKeyByBitmapUint16 - d.keyStreamDecoder = decodeKeyByBitmapUint16Stream - } -} - -// decode from '\uXXXX' -func decodeKeyCharByUnicodeRune(buf []byte, cursor int64) ([]byte, int64) { - const defaultOffset = 4 - const surrogateOffset = 6 - - r := unicodeToRune(buf[cursor : cursor+defaultOffset]) - if utf16.IsSurrogate(r) { - cursor += defaultOffset - if cursor+surrogateOffset >= int64(len(buf)) || buf[cursor] != '\\' || buf[cursor+1] != 'u' { - return []byte(string(unicode.ReplacementChar)), cursor + defaultOffset - 1 - } - cursor += 2 - r2 := unicodeToRune(buf[cursor : cursor+defaultOffset]) - if r := utf16.DecodeRune(r, r2); r != unicode.ReplacementChar { - return []byte(string(r)), cursor + defaultOffset - 1 - } - } - return []byte(string(r)), cursor + defaultOffset - 1 -} - -func decodeKeyCharByEscapedChar(buf []byte, cursor int64) ([]byte, int64) { - c := buf[cursor] - cursor++ - switch c { - case '"': - return []byte{'"'}, cursor - case '\\': - return []byte{'\\'}, cursor - case '/': - return []byte{'/'}, cursor - case 'b': - return []byte{'\b'}, cursor - case 'f': - return []byte{'\f'}, cursor - case 'n': - return []byte{'\n'}, cursor - case 'r': - return []byte{'\r'}, cursor - case 't': - return []byte{'\t'}, cursor - case 'u': - return decodeKeyCharByUnicodeRune(buf, cursor) - } - return nil, cursor -} - -func decodeKeyByBitmapUint8(d *structDecoder, buf []byte, cursor int64) (int64, *structFieldSet, error) { - var ( - curBit uint8 = math.MaxUint8 - ) - b := (*sliceHeader)(unsafe.Pointer(&buf)).data - for { - switch char(b, cursor) { - case ' ', '\n', '\t', '\r': - cursor++ - case '"': - cursor++ - c := char(b, cursor) - switch c { - case '"': - cursor++ - return cursor, nil, nil - case nul: - return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) - } - keyIdx := 0 - bitmap := d.keyBitmapUint8 - start := cursor - for { - c := char(b, cursor) - switch c { - case '"': - fieldSetIndex := bits.TrailingZeros8(curBit) - field := d.sortedFieldSets[fieldSetIndex] - keyLen := cursor - start - cursor++ - if keyLen < field.keyLen { - // early match - return cursor, nil, nil - } - return cursor, field, nil - case nul: - return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) - case '\\': - cursor++ - chars, nextCursor := decodeKeyCharByEscapedChar(buf, cursor) - for _, c := range chars { - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - return decodeKeyNotFound(b, cursor) - } - keyIdx++ - } - cursor = nextCursor - default: - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - return decodeKeyNotFound(b, cursor) - } - keyIdx++ - } - cursor++ - } - default: - return cursor, nil, errors.ErrNotAtBeginningOfValue(cursor) - } - } -} - -func decodeKeyByBitmapUint16(d *structDecoder, buf []byte, cursor int64) (int64, *structFieldSet, error) { - var ( - curBit uint16 = math.MaxUint16 - ) - b := (*sliceHeader)(unsafe.Pointer(&buf)).data - for { - switch char(b, cursor) { - case ' ', '\n', '\t', '\r': - cursor++ - case '"': - cursor++ - c := char(b, cursor) - switch c { - case '"': - cursor++ - return cursor, nil, nil - case nul: - return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) - } - keyIdx := 0 - bitmap := d.keyBitmapUint16 - start := cursor - for { - c := char(b, cursor) - switch c { - case '"': - fieldSetIndex := bits.TrailingZeros16(curBit) - field := d.sortedFieldSets[fieldSetIndex] - keyLen := cursor - start - cursor++ - if keyLen < field.keyLen { - // early match - return cursor, nil, nil - } - return cursor, field, nil - case nul: - return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) - case '\\': - cursor++ - chars, nextCursor := decodeKeyCharByEscapedChar(buf, cursor) - for _, c := range chars { - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - return decodeKeyNotFound(b, cursor) - } - keyIdx++ - } - cursor = nextCursor - default: - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - return decodeKeyNotFound(b, cursor) - } - keyIdx++ - } - cursor++ - } - default: - return cursor, nil, errors.ErrNotAtBeginningOfValue(cursor) - } - } -} - -func decodeKeyNotFound(b unsafe.Pointer, cursor int64) (int64, *structFieldSet, error) { - for { - cursor++ - switch char(b, cursor) { - case '"': - cursor++ - return cursor, nil, nil - case '\\': - cursor++ - if char(b, cursor) == nul { - return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) - } - case nul: - return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) - } - } -} - -func decodeKey(d *structDecoder, buf []byte, cursor int64) (int64, *structFieldSet, error) { - key, c, err := d.stringDecoder.decodeByte(buf, cursor) - if err != nil { - return 0, nil, err - } - cursor = c - k := *(*string)(unsafe.Pointer(&key)) - field, exists := d.fieldMap[k] - if !exists { - return cursor, nil, nil - } - return cursor, field, nil -} - -func decodeKeyByBitmapUint8Stream(d *structDecoder, s *Stream) (*structFieldSet, string, error) { - var ( - curBit uint8 = math.MaxUint8 - ) - _, cursor, p := s.stat() - for { - switch char(p, cursor) { - case ' ', '\n', '\t', '\r': - cursor++ - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - return nil, "", errors.ErrNotAtBeginningOfValue(s.totalOffset()) - case '"': - cursor++ - FIRST_CHAR: - start := cursor - switch char(p, cursor) { - case '"': - cursor++ - s.cursor = cursor - return nil, "", nil - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - goto FIRST_CHAR - } - return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - } - keyIdx := 0 - bitmap := d.keyBitmapUint8 - for { - c := char(p, cursor) - switch c { - case '"': - fieldSetIndex := bits.TrailingZeros8(curBit) - field := d.sortedFieldSets[fieldSetIndex] - keyLen := cursor - start - cursor++ - s.cursor = cursor - if keyLen < field.keyLen { - // early match - return nil, field.key, nil - } - return field, field.key, nil - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - case '\\': - s.cursor = cursor + 1 // skip '\' char - chars, err := decodeKeyCharByEscapeCharStream(s) - if err != nil { - return nil, "", err - } - cursor = s.cursor - for _, c := range chars { - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - s.cursor = cursor - return decodeKeyNotFoundStream(s, start) - } - keyIdx++ - } - default: - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - s.cursor = cursor - return decodeKeyNotFoundStream(s, start) - } - keyIdx++ - } - cursor++ - } - default: - return nil, "", errors.ErrNotAtBeginningOfValue(s.totalOffset()) - } - } -} - -func decodeKeyByBitmapUint16Stream(d *structDecoder, s *Stream) (*structFieldSet, string, error) { - var ( - curBit uint16 = math.MaxUint16 - ) - _, cursor, p := s.stat() - for { - switch char(p, cursor) { - case ' ', '\n', '\t', '\r': - cursor++ - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - return nil, "", errors.ErrNotAtBeginningOfValue(s.totalOffset()) - case '"': - cursor++ - FIRST_CHAR: - start := cursor - switch char(p, cursor) { - case '"': - cursor++ - s.cursor = cursor - return nil, "", nil - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - goto FIRST_CHAR - } - return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - } - keyIdx := 0 - bitmap := d.keyBitmapUint16 - for { - c := char(p, cursor) - switch c { - case '"': - fieldSetIndex := bits.TrailingZeros16(curBit) - field := d.sortedFieldSets[fieldSetIndex] - keyLen := cursor - start - cursor++ - s.cursor = cursor - if keyLen < field.keyLen { - // early match - return nil, field.key, nil - } - return field, field.key, nil - case nul: - s.cursor = cursor - if s.read() { - _, cursor, p = s.stat() - continue - } - return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - case '\\': - s.cursor = cursor + 1 // skip '\' char - chars, err := decodeKeyCharByEscapeCharStream(s) - if err != nil { - return nil, "", err - } - cursor = s.cursor - for _, c := range chars { - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - s.cursor = cursor - return decodeKeyNotFoundStream(s, start) - } - keyIdx++ - } - default: - curBit &= bitmap[keyIdx][largeToSmallTable[c]] - if curBit == 0 { - s.cursor = cursor - return decodeKeyNotFoundStream(s, start) - } - keyIdx++ - } - cursor++ - } - default: - return nil, "", errors.ErrNotAtBeginningOfValue(s.totalOffset()) - } - } -} - -// decode from '\uXXXX' -func decodeKeyCharByUnicodeRuneStream(s *Stream) ([]byte, error) { - const defaultOffset = 4 - const surrogateOffset = 6 - - if s.cursor+defaultOffset >= s.length { - if !s.read() { - return nil, errors.ErrInvalidCharacter(s.char(), "escaped unicode char", s.totalOffset()) - } - } - - r := unicodeToRune(s.buf[s.cursor : s.cursor+defaultOffset]) - if utf16.IsSurrogate(r) { - s.cursor += defaultOffset - if s.cursor+surrogateOffset >= s.length { - s.read() - } - if s.cursor+surrogateOffset >= s.length || s.buf[s.cursor] != '\\' || s.buf[s.cursor+1] != 'u' { - s.cursor += defaultOffset - 1 - return []byte(string(unicode.ReplacementChar)), nil - } - r2 := unicodeToRune(s.buf[s.cursor+defaultOffset+2 : s.cursor+surrogateOffset]) - if r := utf16.DecodeRune(r, r2); r != unicode.ReplacementChar { - s.cursor += defaultOffset - 1 - return []byte(string(r)), nil - } - } - s.cursor += defaultOffset - 1 - return []byte(string(r)), nil -} - -func decodeKeyCharByEscapeCharStream(s *Stream) ([]byte, error) { - c := s.buf[s.cursor] - s.cursor++ -RETRY: - switch c { - case '"': - return []byte{'"'}, nil - case '\\': - return []byte{'\\'}, nil - case '/': - return []byte{'/'}, nil - case 'b': - return []byte{'\b'}, nil - case 'f': - return []byte{'\f'}, nil - case 'n': - return []byte{'\n'}, nil - case 'r': - return []byte{'\r'}, nil - case 't': - return []byte{'\t'}, nil - case 'u': - return decodeKeyCharByUnicodeRuneStream(s) - case nul: - if !s.read() { - return nil, errors.ErrInvalidCharacter(s.char(), "escaped char", s.totalOffset()) - } - goto RETRY - default: - return nil, errors.ErrUnexpectedEndOfJSON("struct field", s.totalOffset()) - } -} - -func decodeKeyNotFoundStream(s *Stream, start int64) (*structFieldSet, string, error) { - buf, cursor, p := s.stat() - for { - cursor++ - switch char(p, cursor) { - case '"': - b := buf[start:cursor] - key := *(*string)(unsafe.Pointer(&b)) - cursor++ - s.cursor = cursor - return nil, key, nil - case '\\': - cursor++ - if char(p, cursor) == nul { - s.cursor = cursor - if !s.read() { - return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - } - buf, cursor, p = s.statForRetry() - } - case nul: - s.cursor = cursor - if !s.read() { - return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) - } - buf, cursor, p = s.statForRetry() - } - } -} - -func decodeKeyStream(d *structDecoder, s *Stream) (*structFieldSet, string, error) { - key, err := d.stringDecoder.decodeStreamByte(s) - if err != nil { - return nil, "", err - } - k := *(*string)(unsafe.Pointer(&key)) - return d.fieldMap[k], k, nil -} - -func (d *structDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - depth++ - if depth > maxDecodeNestingDepth { - return errors.ErrExceededMaxDepth(s.char(), s.cursor) - } - - c := s.skipWhiteSpace() - switch c { - case 'n': - if err := nullBytes(s); err != nil { - return err - } - return nil - default: - if s.char() != '{' { - return errors.ErrNotAtBeginningOfValue(s.totalOffset()) - } - } - s.cursor++ - if s.skipWhiteSpace() == '}' { - s.cursor++ - return nil - } - var ( - seenFields map[int]struct{} - seenFieldNum int - ) - firstWin := (s.Option.Flags & FirstWinOption) != 0 - if firstWin { - seenFields = make(map[int]struct{}, d.fieldUniqueNameNum) - } - for { - s.reset() - field, key, err := d.keyStreamDecoder(d, s) - if err != nil { - return err - } - if s.skipWhiteSpace() != ':' { - return errors.ErrExpected("colon after object key", s.totalOffset()) - } - s.cursor++ - if field != nil { - if field.err != nil { - return field.err - } - if firstWin { - if _, exists := seenFields[field.fieldIdx]; exists { - if err := s.skipValue(depth); err != nil { - return err - } - } else { - if err := field.dec.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+field.offset)); err != nil { - return err - } - seenFieldNum++ - if d.fieldUniqueNameNum <= seenFieldNum { - return s.skipObject(depth) - } - seenFields[field.fieldIdx] = struct{}{} - } - } else { - if err := field.dec.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+field.offset)); err != nil { - return err - } - } - } else if s.DisallowUnknownFields { - return fmt.Errorf("json: unknown field %q", key) - } else { - if err := s.skipValue(depth); err != nil { - return err - } - } - c := s.skipWhiteSpace() - if c == '}' { - s.cursor++ - return nil - } - if c != ',' { - return errors.ErrExpected("comma after object element", s.totalOffset()) - } - s.cursor++ - } -} - -func (d *structDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - depth++ - if depth > maxDecodeNestingDepth { - return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) - } - buflen := int64(len(buf)) - cursor = skipWhiteSpace(buf, cursor) - b := (*sliceHeader)(unsafe.Pointer(&buf)).data - switch char(b, cursor) { - case 'n': - if err := validateNull(buf, cursor); err != nil { - return 0, err - } - cursor += 4 - return cursor, nil - case '{': - default: - return 0, errors.ErrNotAtBeginningOfValue(cursor) - } - cursor++ - cursor = skipWhiteSpace(buf, cursor) - if buf[cursor] == '}' { - cursor++ - return cursor, nil - } - var ( - seenFields map[int]struct{} - seenFieldNum int - ) - firstWin := (ctx.Option.Flags & FirstWinOption) != 0 - if firstWin { - seenFields = make(map[int]struct{}, d.fieldUniqueNameNum) - } - for { - c, field, err := d.keyDecoder(d, buf, cursor) - if err != nil { - return 0, err - } - cursor = skipWhiteSpace(buf, c) - if char(b, cursor) != ':' { - return 0, errors.ErrExpected("colon after object key", cursor) - } - cursor++ - if cursor >= buflen { - return 0, errors.ErrExpected("object value after colon", cursor) - } - if field != nil { - if field.err != nil { - return 0, field.err - } - if firstWin { - if _, exists := seenFields[field.fieldIdx]; exists { - c, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - cursor = c - } else { - c, err := field.dec.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+field.offset)) - if err != nil { - return 0, err - } - cursor = c - seenFieldNum++ - if d.fieldUniqueNameNum <= seenFieldNum { - return skipObject(buf, cursor, depth) - } - seenFields[field.fieldIdx] = struct{}{} - } - } else { - c, err := field.dec.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+field.offset)) - if err != nil { - return 0, err - } - cursor = c - } - } else { - c, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - cursor = c - } - cursor = skipWhiteSpace(buf, cursor) - if char(b, cursor) == '}' { - cursor++ - return cursor, nil - } - if char(b, cursor) != ',' { - return 0, errors.ErrExpected("comma after object element", cursor) - } - cursor++ - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/type.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/type.go deleted file mode 100644 index 70e9907c..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/type.go +++ /dev/null @@ -1,29 +0,0 @@ -package decoder - -import ( - "context" - "encoding" - "encoding/json" - "reflect" - "unsafe" -) - -type Decoder interface { - Decode(*RuntimeContext, int64, int64, unsafe.Pointer) (int64, error) - DecodeStream(*Stream, int64, unsafe.Pointer) error -} - -const ( - nul = '\000' - maxDecodeNestingDepth = 10000 -) - -type unmarshalerContext interface { - UnmarshalJSON(context.Context, []byte) error -} - -var ( - unmarshalJSONType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() - unmarshalJSONContextType = reflect.TypeOf((*unmarshalerContext)(nil)).Elem() - unmarshalTextType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() -) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/uint.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/uint.go deleted file mode 100644 index a62c5149..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/uint.go +++ /dev/null @@ -1,190 +0,0 @@ -package decoder - -import ( - "fmt" - "reflect" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type uintDecoder struct { - typ *runtime.Type - kind reflect.Kind - op func(unsafe.Pointer, uint64) - structName string - fieldName string -} - -func newUintDecoder(typ *runtime.Type, structName, fieldName string, op func(unsafe.Pointer, uint64)) *uintDecoder { - return &uintDecoder{ - typ: typ, - kind: typ.Kind(), - op: op, - structName: structName, - fieldName: fieldName, - } -} - -func (d *uintDecoder) typeError(buf []byte, offset int64) *errors.UnmarshalTypeError { - return &errors.UnmarshalTypeError{ - Value: fmt.Sprintf("number %s", string(buf)), - Type: runtime.RType2Type(d.typ), - Offset: offset, - } -} - -var ( - pow10u64 = [...]uint64{ - 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, - 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, - } - pow10u64Len = len(pow10u64) -) - -func (d *uintDecoder) parseUint(b []byte) (uint64, error) { - maxDigit := len(b) - if maxDigit > pow10u64Len { - return 0, fmt.Errorf("invalid length of number") - } - sum := uint64(0) - for i := 0; i < maxDigit; i++ { - c := uint64(b[i]) - 48 - digitValue := pow10u64[maxDigit-i-1] - sum += c * digitValue - } - return sum, nil -} - -func (d *uintDecoder) decodeStreamByte(s *Stream) ([]byte, error) { - for { - switch s.char() { - case ' ', '\n', '\t', '\r': - s.cursor++ - continue - case '0': - s.cursor++ - return numZeroBuf, nil - case '1', '2', '3', '4', '5', '6', '7', '8', '9': - start := s.cursor - for { - s.cursor++ - if numTable[s.char()] { - continue - } else if s.char() == nul { - if s.read() { - s.cursor-- // for retry current character - continue - } - } - break - } - num := s.buf[start:s.cursor] - return num, nil - case 'n': - if err := nullBytes(s); err != nil { - return nil, err - } - return nil, nil - case nul: - if s.read() { - continue - } - default: - return nil, d.typeError([]byte{s.char()}, s.totalOffset()) - } - break - } - return nil, errors.ErrUnexpectedEndOfJSON("number(unsigned integer)", s.totalOffset()) -} - -func (d *uintDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { - for { - switch buf[cursor] { - case ' ', '\n', '\t', '\r': - cursor++ - continue - case '0': - cursor++ - return numZeroBuf, cursor, nil - case '1', '2', '3', '4', '5', '6', '7', '8', '9': - start := cursor - cursor++ - for numTable[buf[cursor]] { - cursor++ - } - num := buf[start:cursor] - return num, cursor, nil - case 'n': - if err := validateNull(buf, cursor); err != nil { - return nil, 0, err - } - cursor += 4 - return nil, cursor, nil - default: - return nil, 0, d.typeError([]byte{buf[cursor]}, cursor) - } - } -} - -func (d *uintDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - bytes, err := d.decodeStreamByte(s) - if err != nil { - return err - } - if bytes == nil { - return nil - } - u64, err := d.parseUint(bytes) - if err != nil { - return d.typeError(bytes, s.totalOffset()) - } - switch d.kind { - case reflect.Uint8: - if (1 << 8) <= u64 { - return d.typeError(bytes, s.totalOffset()) - } - case reflect.Uint16: - if (1 << 16) <= u64 { - return d.typeError(bytes, s.totalOffset()) - } - case reflect.Uint32: - if (1 << 32) <= u64 { - return d.typeError(bytes, s.totalOffset()) - } - } - d.op(p, u64) - return nil -} - -func (d *uintDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - bytes, c, err := d.decodeByte(ctx.Buf, cursor) - if err != nil { - return 0, err - } - if bytes == nil { - return c, nil - } - cursor = c - u64, err := d.parseUint(bytes) - if err != nil { - return 0, d.typeError(bytes, cursor) - } - switch d.kind { - case reflect.Uint8: - if (1 << 8) <= u64 { - return 0, d.typeError(bytes, cursor) - } - case reflect.Uint16: - if (1 << 16) <= u64 { - return 0, d.typeError(bytes, cursor) - } - case reflect.Uint32: - if (1 << 32) <= u64 { - return 0, d.typeError(bytes, cursor) - } - } - d.op(p, u64) - return cursor, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_json.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_json.go deleted file mode 100644 index d90f39cc..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_json.go +++ /dev/null @@ -1,91 +0,0 @@ -package decoder - -import ( - "encoding/json" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type unmarshalJSONDecoder struct { - typ *runtime.Type - structName string - fieldName string -} - -func newUnmarshalJSONDecoder(typ *runtime.Type, structName, fieldName string) *unmarshalJSONDecoder { - return &unmarshalJSONDecoder{ - typ: typ, - structName: structName, - fieldName: fieldName, - } -} - -func (d *unmarshalJSONDecoder) annotateError(cursor int64, err error) { - switch e := err.(type) { - case *errors.UnmarshalTypeError: - e.Struct = d.structName - e.Field = d.fieldName - case *errors.SyntaxError: - e.Offset = cursor - } -} - -func (d *unmarshalJSONDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - s.skipWhiteSpace() - start := s.cursor - if err := s.skipValue(depth); err != nil { - return err - } - src := s.buf[start:s.cursor] - dst := make([]byte, len(src)) - copy(dst, src) - - v := *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: d.typ, - ptr: p, - })) - if (s.Option.Flags & ContextOption) != 0 { - if err := v.(unmarshalerContext).UnmarshalJSON(s.Option.Context, dst); err != nil { - d.annotateError(s.cursor, err) - return err - } - } else { - if err := v.(json.Unmarshaler).UnmarshalJSON(dst); err != nil { - d.annotateError(s.cursor, err) - return err - } - } - return nil -} - -func (d *unmarshalJSONDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - cursor = skipWhiteSpace(buf, cursor) - start := cursor - end, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - src := buf[start:end] - dst := make([]byte, len(src)) - copy(dst, src) - - v := *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: d.typ, - ptr: p, - })) - if (ctx.Option.Flags & ContextOption) != 0 { - if err := v.(unmarshalerContext).UnmarshalJSON(ctx.Option.Context, dst); err != nil { - d.annotateError(cursor, err) - return 0, err - } - } else { - if err := v.(json.Unmarshaler).UnmarshalJSON(dst); err != nil { - d.annotateError(cursor, err) - return 0, err - } - } - return end, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_text.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_text.go deleted file mode 100644 index 1ef28778..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_text.go +++ /dev/null @@ -1,280 +0,0 @@ -package decoder - -import ( - "bytes" - "encoding" - "unicode" - "unicode/utf16" - "unicode/utf8" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type unmarshalTextDecoder struct { - typ *runtime.Type - structName string - fieldName string -} - -func newUnmarshalTextDecoder(typ *runtime.Type, structName, fieldName string) *unmarshalTextDecoder { - return &unmarshalTextDecoder{ - typ: typ, - structName: structName, - fieldName: fieldName, - } -} - -func (d *unmarshalTextDecoder) annotateError(cursor int64, err error) { - switch e := err.(type) { - case *errors.UnmarshalTypeError: - e.Struct = d.structName - e.Field = d.fieldName - case *errors.SyntaxError: - e.Offset = cursor - } -} - -var ( - nullbytes = []byte(`null`) -) - -func (d *unmarshalTextDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - s.skipWhiteSpace() - start := s.cursor - if err := s.skipValue(depth); err != nil { - return err - } - src := s.buf[start:s.cursor] - if len(src) > 0 { - switch src[0] { - case '[': - return &errors.UnmarshalTypeError{ - Value: "array", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - case '{': - return &errors.UnmarshalTypeError{ - Value: "object", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return &errors.UnmarshalTypeError{ - Value: "number", - Type: runtime.RType2Type(d.typ), - Offset: s.totalOffset(), - } - case 'n': - if bytes.Equal(src, nullbytes) { - *(*unsafe.Pointer)(p) = nil - return nil - } - } - } - dst := make([]byte, len(src)) - copy(dst, src) - - if b, ok := unquoteBytes(dst); ok { - dst = b - } - v := *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: d.typ, - ptr: p, - })) - if err := v.(encoding.TextUnmarshaler).UnmarshalText(dst); err != nil { - d.annotateError(s.cursor, err) - return err - } - return nil -} - -func (d *unmarshalTextDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - buf := ctx.Buf - cursor = skipWhiteSpace(buf, cursor) - start := cursor - end, err := skipValue(buf, cursor, depth) - if err != nil { - return 0, err - } - src := buf[start:end] - if len(src) > 0 { - switch src[0] { - case '[': - return 0, &errors.UnmarshalTypeError{ - Value: "array", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - case '{': - return 0, &errors.UnmarshalTypeError{ - Value: "object", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return 0, &errors.UnmarshalTypeError{ - Value: "number", - Type: runtime.RType2Type(d.typ), - Offset: start, - } - case 'n': - if bytes.Equal(src, nullbytes) { - *(*unsafe.Pointer)(p) = nil - return end, nil - } - } - } - - if s, ok := unquoteBytes(src); ok { - src = s - } - v := *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: d.typ, - ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), - })) - if err := v.(encoding.TextUnmarshaler).UnmarshalText(src); err != nil { - d.annotateError(cursor, err) - return 0, err - } - return end, nil -} - -func unquoteBytes(s []byte) (t []byte, ok bool) { - length := len(s) - if length < 2 || s[0] != '"' || s[length-1] != '"' { - return - } - s = s[1 : length-1] - length -= 2 - - // Check for unusual characters. If there are none, - // then no unquoting is needed, so return a slice of the - // original bytes. - r := 0 - for r < length { - c := s[r] - if c == '\\' || c == '"' || c < ' ' { - break - } - if c < utf8.RuneSelf { - r++ - continue - } - rr, size := utf8.DecodeRune(s[r:]) - if rr == utf8.RuneError && size == 1 { - break - } - r += size - } - if r == length { - return s, true - } - - b := make([]byte, length+2*utf8.UTFMax) - w := copy(b, s[0:r]) - for r < length { - // Out of room? Can only happen if s is full of - // malformed UTF-8 and we're replacing each - // byte with RuneError. - if w >= len(b)-2*utf8.UTFMax { - nb := make([]byte, (len(b)+utf8.UTFMax)*2) - copy(nb, b[0:w]) - b = nb - } - switch c := s[r]; { - case c == '\\': - r++ - if r >= length { - return - } - switch s[r] { - default: - return - case '"', '\\', '/', '\'': - b[w] = s[r] - r++ - w++ - case 'b': - b[w] = '\b' - r++ - w++ - case 'f': - b[w] = '\f' - r++ - w++ - case 'n': - b[w] = '\n' - r++ - w++ - case 'r': - b[w] = '\r' - r++ - w++ - case 't': - b[w] = '\t' - r++ - w++ - case 'u': - r-- - rr := getu4(s[r:]) - if rr < 0 { - return - } - r += 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(s[r:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - // A valid pair; consume. - r += 6 - w += utf8.EncodeRune(b[w:], dec) - break - } - // Invalid surrogate; fall back to replacement rune. - rr = unicode.ReplacementChar - } - w += utf8.EncodeRune(b[w:], rr) - } - - // Quote, control characters are invalid. - case c == '"', c < ' ': - return - - // ASCII - case c < utf8.RuneSelf: - b[w] = c - r++ - w++ - - // Coerce to well-formed UTF-8. - default: - rr, size := utf8.DecodeRune(s[r:]) - r += size - w += utf8.EncodeRune(b[w:], rr) - } - } - return b[0:w], true -} - -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - var r rune - for _, c := range s[2:6] { - switch { - case '0' <= c && c <= '9': - c = c - '0' - case 'a' <= c && c <= 'f': - c = c - 'a' + 10 - case 'A' <= c && c <= 'F': - c = c - 'A' + 10 - default: - return -1 - } - r = r*16 + rune(c) - } - return r -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/wrapped_string.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/wrapped_string.go deleted file mode 100644 index 66227ae0..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/wrapped_string.go +++ /dev/null @@ -1,68 +0,0 @@ -package decoder - -import ( - "reflect" - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -type wrappedStringDecoder struct { - typ *runtime.Type - dec Decoder - stringDecoder *stringDecoder - structName string - fieldName string - isPtrType bool -} - -func newWrappedStringDecoder(typ *runtime.Type, dec Decoder, structName, fieldName string) *wrappedStringDecoder { - return &wrappedStringDecoder{ - typ: typ, - dec: dec, - stringDecoder: newStringDecoder(structName, fieldName), - structName: structName, - fieldName: fieldName, - isPtrType: typ.Kind() == reflect.Ptr, - } -} - -func (d *wrappedStringDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { - bytes, err := d.stringDecoder.decodeStreamByte(s) - if err != nil { - return err - } - if bytes == nil { - if d.isPtrType { - *(*unsafe.Pointer)(p) = nil - } - return nil - } - b := make([]byte, len(bytes)+1) - copy(b, bytes) - if _, err := d.dec.Decode(&RuntimeContext{Buf: b}, 0, depth, p); err != nil { - return err - } - return nil -} - -func (d *wrappedStringDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { - bytes, c, err := d.stringDecoder.decodeByte(ctx.Buf, cursor) - if err != nil { - return 0, err - } - if bytes == nil { - if d.isPtrType { - *(*unsafe.Pointer)(p) = nil - } - return c, nil - } - bytes = append(bytes, nul) - oldBuf := ctx.Buf - ctx.Buf = bytes - if _, err := d.dec.Decode(ctx, 0, depth, p); err != nil { - return 0, err - } - ctx.Buf = oldBuf - return c, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compact.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compact.go deleted file mode 100644 index 0eb9545d..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compact.go +++ /dev/null @@ -1,286 +0,0 @@ -package encoder - -import ( - "bytes" - "fmt" - "strconv" - "unsafe" - - "github.com/goccy/go-json/internal/errors" -) - -var ( - isWhiteSpace = [256]bool{ - ' ': true, - '\n': true, - '\t': true, - '\r': true, - } - isHTMLEscapeChar = [256]bool{ - '<': true, - '>': true, - '&': true, - } - nul = byte('\000') -) - -func Compact(buf *bytes.Buffer, src []byte, escape bool) error { - if len(src) == 0 { - return errors.ErrUnexpectedEndOfJSON("", 0) - } - buf.Grow(len(src)) - dst := buf.Bytes() - - ctx := TakeRuntimeContext() - ctxBuf := ctx.Buf[:0] - ctxBuf = append(append(ctxBuf, src...), nul) - ctx.Buf = ctxBuf - - if err := compactAndWrite(buf, dst, ctxBuf, escape); err != nil { - ReleaseRuntimeContext(ctx) - return err - } - ReleaseRuntimeContext(ctx) - return nil -} - -func compactAndWrite(buf *bytes.Buffer, dst []byte, src []byte, escape bool) error { - dst, err := compact(dst, src, escape) - if err != nil { - return err - } - if _, err := buf.Write(dst); err != nil { - return err - } - return nil -} - -func compact(dst, src []byte, escape bool) ([]byte, error) { - buf, cursor, err := compactValue(dst, src, 0, escape) - if err != nil { - return nil, err - } - if err := validateEndBuf(src, cursor); err != nil { - return nil, err - } - return buf, nil -} - -func validateEndBuf(src []byte, cursor int64) error { - for { - switch src[cursor] { - case ' ', '\t', '\n', '\r': - cursor++ - continue - case nul: - return nil - } - return errors.ErrSyntax( - fmt.Sprintf("invalid character '%c' after top-level value", src[cursor]), - cursor+1, - ) - } -} - -func skipWhiteSpace(buf []byte, cursor int64) int64 { -LOOP: - if isWhiteSpace[buf[cursor]] { - cursor++ - goto LOOP - } - return cursor -} - -func compactValue(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { - for { - switch src[cursor] { - case ' ', '\t', '\n', '\r': - cursor++ - continue - case '{': - return compactObject(dst, src, cursor, escape) - case '}': - return nil, 0, errors.ErrSyntax("unexpected character '}'", cursor) - case '[': - return compactArray(dst, src, cursor, escape) - case ']': - return nil, 0, errors.ErrSyntax("unexpected character ']'", cursor) - case '"': - return compactString(dst, src, cursor, escape) - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return compactNumber(dst, src, cursor) - case 't': - return compactTrue(dst, src, cursor) - case 'f': - return compactFalse(dst, src, cursor) - case 'n': - return compactNull(dst, src, cursor) - default: - return nil, 0, errors.ErrSyntax(fmt.Sprintf("unexpected character '%c'", src[cursor]), cursor) - } - } -} - -func compactObject(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { - if src[cursor] == '{' { - dst = append(dst, '{') - } else { - return nil, 0, errors.ErrExpected("expected { character for object value", cursor) - } - cursor = skipWhiteSpace(src, cursor+1) - if src[cursor] == '}' { - dst = append(dst, '}') - return dst, cursor + 1, nil - } - var err error - for { - cursor = skipWhiteSpace(src, cursor) - dst, cursor, err = compactString(dst, src, cursor, escape) - if err != nil { - return nil, 0, err - } - cursor = skipWhiteSpace(src, cursor) - if src[cursor] != ':' { - return nil, 0, errors.ErrExpected("colon after object key", cursor) - } - dst = append(dst, ':') - dst, cursor, err = compactValue(dst, src, cursor+1, escape) - if err != nil { - return nil, 0, err - } - cursor = skipWhiteSpace(src, cursor) - switch src[cursor] { - case '}': - dst = append(dst, '}') - cursor++ - return dst, cursor, nil - case ',': - dst = append(dst, ',') - default: - return nil, 0, errors.ErrExpected("comma after object value", cursor) - } - cursor++ - } -} - -func compactArray(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { - if src[cursor] == '[' { - dst = append(dst, '[') - } else { - return nil, 0, errors.ErrExpected("expected [ character for array value", cursor) - } - cursor = skipWhiteSpace(src, cursor+1) - if src[cursor] == ']' { - dst = append(dst, ']') - return dst, cursor + 1, nil - } - var err error - for { - dst, cursor, err = compactValue(dst, src, cursor, escape) - if err != nil { - return nil, 0, err - } - cursor = skipWhiteSpace(src, cursor) - switch src[cursor] { - case ']': - dst = append(dst, ']') - cursor++ - return dst, cursor, nil - case ',': - dst = append(dst, ',') - default: - return nil, 0, errors.ErrExpected("comma after array value", cursor) - } - cursor++ - } -} - -func compactString(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { - if src[cursor] != '"' { - return nil, 0, errors.ErrInvalidCharacter(src[cursor], "string", cursor) - } - start := cursor - for { - cursor++ - c := src[cursor] - if escape { - if isHTMLEscapeChar[c] { - dst = append(dst, src[start:cursor]...) - dst = append(dst, `\u00`...) - dst = append(dst, hex[c>>4], hex[c&0xF]) - start = cursor + 1 - } else if c == 0xE2 && cursor+2 < int64(len(src)) && src[cursor+1] == 0x80 && src[cursor+2]&^1 == 0xA8 { - dst = append(dst, src[start:cursor]...) - dst = append(dst, `\u202`...) - dst = append(dst, hex[src[cursor+2]&0xF]) - cursor += 2 - start = cursor + 3 - } - } - switch c { - case '\\': - cursor++ - if src[cursor] == nul { - return nil, 0, errors.ErrUnexpectedEndOfJSON("string", int64(len(src))) - } - case '"': - cursor++ - return append(dst, src[start:cursor]...), cursor, nil - case nul: - return nil, 0, errors.ErrUnexpectedEndOfJSON("string", int64(len(src))) - } - } -} - -func compactNumber(dst, src []byte, cursor int64) ([]byte, int64, error) { - start := cursor - for { - cursor++ - if floatTable[src[cursor]] { - continue - } - break - } - num := src[start:cursor] - if _, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&num)), 64); err != nil { - return nil, 0, err - } - dst = append(dst, num...) - return dst, cursor, nil -} - -func compactTrue(dst, src []byte, cursor int64) ([]byte, int64, error) { - if cursor+3 >= int64(len(src)) { - return nil, 0, errors.ErrUnexpectedEndOfJSON("true", cursor) - } - if !bytes.Equal(src[cursor:cursor+4], []byte(`true`)) { - return nil, 0, errors.ErrInvalidCharacter(src[cursor], "true", cursor) - } - dst = append(dst, "true"...) - cursor += 4 - return dst, cursor, nil -} - -func compactFalse(dst, src []byte, cursor int64) ([]byte, int64, error) { - if cursor+4 >= int64(len(src)) { - return nil, 0, errors.ErrUnexpectedEndOfJSON("false", cursor) - } - if !bytes.Equal(src[cursor:cursor+5], []byte(`false`)) { - return nil, 0, errors.ErrInvalidCharacter(src[cursor], "false", cursor) - } - dst = append(dst, "false"...) - cursor += 5 - return dst, cursor, nil -} - -func compactNull(dst, src []byte, cursor int64) ([]byte, int64, error) { - if cursor+3 >= int64(len(src)) { - return nil, 0, errors.ErrUnexpectedEndOfJSON("null", cursor) - } - if !bytes.Equal(src[cursor:cursor+4], []byte(`null`)) { - return nil, 0, errors.ErrInvalidCharacter(src[cursor], "null", cursor) - } - dst = append(dst, "null"...) - cursor += 4 - return dst, cursor, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler.go deleted file mode 100644 index 01a5d4b2..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler.go +++ /dev/null @@ -1,1569 +0,0 @@ -package encoder - -import ( - "context" - "encoding" - "encoding/json" - "fmt" - "reflect" - "strings" - "sync/atomic" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -type marshalerContext interface { - MarshalJSON(context.Context) ([]byte, error) -} - -var ( - marshalJSONType = reflect.TypeOf((*json.Marshaler)(nil)).Elem() - marshalJSONContextType = reflect.TypeOf((*marshalerContext)(nil)).Elem() - marshalTextType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - jsonNumberType = reflect.TypeOf(json.Number("")) - cachedOpcodeSets []*OpcodeSet - cachedOpcodeMap unsafe.Pointer // map[uintptr]*OpcodeSet - typeAddr *runtime.TypeAddr -) - -func init() { - typeAddr = runtime.AnalyzeTypeAddr() - if typeAddr == nil { - typeAddr = &runtime.TypeAddr{} - } - cachedOpcodeSets = make([]*OpcodeSet, typeAddr.AddrRange>>typeAddr.AddrShift) -} - -func loadOpcodeMap() map[uintptr]*OpcodeSet { - p := atomic.LoadPointer(&cachedOpcodeMap) - return *(*map[uintptr]*OpcodeSet)(unsafe.Pointer(&p)) -} - -func storeOpcodeSet(typ uintptr, set *OpcodeSet, m map[uintptr]*OpcodeSet) { - newOpcodeMap := make(map[uintptr]*OpcodeSet, len(m)+1) - newOpcodeMap[typ] = set - - for k, v := range m { - newOpcodeMap[k] = v - } - - atomic.StorePointer(&cachedOpcodeMap, *(*unsafe.Pointer)(unsafe.Pointer(&newOpcodeMap))) -} - -func compileToGetCodeSetSlowPath(typeptr uintptr) (*OpcodeSet, error) { - opcodeMap := loadOpcodeMap() - if codeSet, exists := opcodeMap[typeptr]; exists { - return codeSet, nil - } - - // noescape trick for header.typ ( reflect.*rtype ) - copiedType := *(**runtime.Type)(unsafe.Pointer(&typeptr)) - - noescapeKeyCode, err := compileHead(&compileContext{ - typ: copiedType, - structTypeToCompiledCode: map[uintptr]*CompiledCode{}, - }) - if err != nil { - return nil, err - } - escapeKeyCode, err := compileHead(&compileContext{ - typ: copiedType, - structTypeToCompiledCode: map[uintptr]*CompiledCode{}, - escapeKey: true, - }) - if err != nil { - return nil, err - } - noescapeKeyCode = copyOpcode(noescapeKeyCode) - escapeKeyCode = copyOpcode(escapeKeyCode) - setTotalLengthToInterfaceOp(noescapeKeyCode) - setTotalLengthToInterfaceOp(escapeKeyCode) - interfaceNoescapeKeyCode := copyToInterfaceOpcode(noescapeKeyCode) - interfaceEscapeKeyCode := copyToInterfaceOpcode(escapeKeyCode) - codeLength := noescapeKeyCode.TotalLength() - codeSet := &OpcodeSet{ - Type: copiedType, - NoescapeKeyCode: noescapeKeyCode, - EscapeKeyCode: escapeKeyCode, - InterfaceNoescapeKeyCode: interfaceNoescapeKeyCode, - InterfaceEscapeKeyCode: interfaceEscapeKeyCode, - CodeLength: codeLength, - EndCode: ToEndCode(interfaceNoescapeKeyCode), - } - storeOpcodeSet(typeptr, codeSet, opcodeMap) - return codeSet, nil -} - -func compileHead(ctx *compileContext) (*Opcode, error) { - typ := ctx.typ - switch { - case implementsMarshalJSON(typ): - return compileMarshalJSON(ctx) - case implementsMarshalText(typ): - return compileMarshalText(ctx) - } - - isPtr := false - orgType := typ - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - isPtr = true - } - switch { - case implementsMarshalJSON(typ): - return compileMarshalJSON(ctx) - case implementsMarshalText(typ): - return compileMarshalText(ctx) - } - switch typ.Kind() { - case reflect.Slice: - ctx := ctx.withType(typ) - elem := typ.Elem() - if elem.Kind() == reflect.Uint8 { - p := runtime.PtrTo(elem) - if !implementsMarshalJSONType(p) && !p.Implements(marshalTextType) { - if isPtr { - return compileBytesPtr(ctx) - } - return compileBytes(ctx) - } - } - code, err := compileSlice(ctx) - if err != nil { - return nil, err - } - optimizeStructEnd(code) - linkRecursiveCode(code) - return code, nil - case reflect.Map: - if isPtr { - return compilePtr(ctx.withType(runtime.PtrTo(typ))) - } - code, err := compileMap(ctx.withType(typ)) - if err != nil { - return nil, err - } - optimizeStructEnd(code) - linkRecursiveCode(code) - return code, nil - case reflect.Struct: - code, err := compileStruct(ctx.withType(typ), isPtr) - if err != nil { - return nil, err - } - optimizeStructEnd(code) - linkRecursiveCode(code) - return code, nil - case reflect.Int: - ctx := ctx.withType(typ) - if isPtr { - return compileIntPtr(ctx) - } - return compileInt(ctx) - case reflect.Int8: - ctx := ctx.withType(typ) - if isPtr { - return compileInt8Ptr(ctx) - } - return compileInt8(ctx) - case reflect.Int16: - ctx := ctx.withType(typ) - if isPtr { - return compileInt16Ptr(ctx) - } - return compileInt16(ctx) - case reflect.Int32: - ctx := ctx.withType(typ) - if isPtr { - return compileInt32Ptr(ctx) - } - return compileInt32(ctx) - case reflect.Int64: - ctx := ctx.withType(typ) - if isPtr { - return compileInt64Ptr(ctx) - } - return compileInt64(ctx) - case reflect.Uint, reflect.Uintptr: - ctx := ctx.withType(typ) - if isPtr { - return compileUintPtr(ctx) - } - return compileUint(ctx) - case reflect.Uint8: - ctx := ctx.withType(typ) - if isPtr { - return compileUint8Ptr(ctx) - } - return compileUint8(ctx) - case reflect.Uint16: - ctx := ctx.withType(typ) - if isPtr { - return compileUint16Ptr(ctx) - } - return compileUint16(ctx) - case reflect.Uint32: - ctx := ctx.withType(typ) - if isPtr { - return compileUint32Ptr(ctx) - } - return compileUint32(ctx) - case reflect.Uint64: - ctx := ctx.withType(typ) - if isPtr { - return compileUint64Ptr(ctx) - } - return compileUint64(ctx) - case reflect.Float32: - ctx := ctx.withType(typ) - if isPtr { - return compileFloat32Ptr(ctx) - } - return compileFloat32(ctx) - case reflect.Float64: - ctx := ctx.withType(typ) - if isPtr { - return compileFloat64Ptr(ctx) - } - return compileFloat64(ctx) - case reflect.String: - ctx := ctx.withType(typ) - if isPtr { - return compileStringPtr(ctx) - } - return compileString(ctx) - case reflect.Bool: - ctx := ctx.withType(typ) - if isPtr { - return compileBoolPtr(ctx) - } - return compileBool(ctx) - case reflect.Interface: - ctx := ctx.withType(typ) - if isPtr { - return compileInterfacePtr(ctx) - } - return compileInterface(ctx) - default: - if isPtr && typ.Implements(marshalTextType) { - typ = orgType - } - code, err := compile(ctx.withType(typ), isPtr) - if err != nil { - return nil, err - } - optimizeStructEnd(code) - linkRecursiveCode(code) - return code, nil - } -} - -func linkRecursiveCode(c *Opcode) { - for code := c; code.Op != OpEnd && code.Op != OpRecursiveEnd; { - switch code.Op { - case OpRecursive, OpRecursivePtr: - if code.Jmp.Linked { - code = code.Next - continue - } - code.Jmp.Code = copyOpcode(code.Jmp.Code) - - c := code.Jmp.Code - c.End.Next = newEndOp(&compileContext{}) - c.Op = c.Op.PtrHeadToHead() - - beforeLastCode := c.End - lastCode := beforeLastCode.Next - - lastCode.Idx = beforeLastCode.Idx + uintptrSize - lastCode.ElemIdx = lastCode.Idx + uintptrSize - lastCode.Length = lastCode.Idx + 2*uintptrSize - - // extend length to alloc slot for elemIdx + length - totalLength := uintptr(code.TotalLength() + 3) - nextTotalLength := uintptr(c.TotalLength() + 3) - - c.End.Next.Op = OpRecursiveEnd - - code.Jmp.CurLen = totalLength - code.Jmp.NextLen = nextTotalLength - code.Jmp.Linked = true - - linkRecursiveCode(code.Jmp.Code) - - code = code.Next - continue - } - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - code = code.End - default: - code = code.Next - } - } -} - -func optimizeStructEnd(c *Opcode) { - for code := c; code.Op != OpEnd; { - if code.Op == OpRecursive || code.Op == OpRecursivePtr { - // ignore if exists recursive operation - return - } - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - code = code.End - default: - code = code.Next - } - } - - for code := c; code.Op != OpEnd; { - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - code = code.End - case CodeStructEnd: - switch code.Op { - case OpStructEnd: - prev := code.PrevField - prevOp := prev.Op.String() - if strings.Contains(prevOp, "Head") || - strings.Contains(prevOp, "Slice") || - strings.Contains(prevOp, "Array") || - strings.Contains(prevOp, "Map") || - strings.Contains(prevOp, "MarshalJSON") || - strings.Contains(prevOp, "MarshalText") { - // not exists field - code = code.Next - break - } - if prev.Op != prev.Op.FieldToEnd() { - prev.Op = prev.Op.FieldToEnd() - prev.Next = code.Next - } - code = code.Next - default: - code = code.Next - } - default: - code = code.Next - } - } -} - -func implementsMarshalJSON(typ *runtime.Type) bool { - if !implementsMarshalJSONType(typ) { - return false - } - if typ.Kind() != reflect.Ptr { - return true - } - // type kind is reflect.Ptr - if !implementsMarshalJSONType(typ.Elem()) { - return true - } - // needs to dereference - return false -} - -func implementsMarshalText(typ *runtime.Type) bool { - if !typ.Implements(marshalTextType) { - return false - } - if typ.Kind() != reflect.Ptr { - return true - } - // type kind is reflect.Ptr - if !typ.Elem().Implements(marshalTextType) { - return true - } - // needs to dereference - return false -} - -func compile(ctx *compileContext, isPtr bool) (*Opcode, error) { - typ := ctx.typ - switch { - case implementsMarshalJSON(typ): - return compileMarshalJSON(ctx) - case implementsMarshalText(typ): - return compileMarshalText(ctx) - } - switch typ.Kind() { - case reflect.Ptr: - return compilePtr(ctx) - case reflect.Slice: - elem := typ.Elem() - if elem.Kind() == reflect.Uint8 { - p := runtime.PtrTo(elem) - if !implementsMarshalJSONType(p) && !p.Implements(marshalTextType) { - return compileBytes(ctx) - } - } - return compileSlice(ctx) - case reflect.Array: - return compileArray(ctx) - case reflect.Map: - return compileMap(ctx) - case reflect.Struct: - return compileStruct(ctx, isPtr) - case reflect.Interface: - return compileInterface(ctx) - case reflect.Int: - return compileInt(ctx) - case reflect.Int8: - return compileInt8(ctx) - case reflect.Int16: - return compileInt16(ctx) - case reflect.Int32: - return compileInt32(ctx) - case reflect.Int64: - return compileInt64(ctx) - case reflect.Uint: - return compileUint(ctx) - case reflect.Uint8: - return compileUint8(ctx) - case reflect.Uint16: - return compileUint16(ctx) - case reflect.Uint32: - return compileUint32(ctx) - case reflect.Uint64: - return compileUint64(ctx) - case reflect.Uintptr: - return compileUint(ctx) - case reflect.Float32: - return compileFloat32(ctx) - case reflect.Float64: - return compileFloat64(ctx) - case reflect.String: - return compileString(ctx) - case reflect.Bool: - return compileBool(ctx) - } - return nil, &errors.UnsupportedTypeError{Type: runtime.RType2Type(typ)} -} - -func convertPtrOp(code *Opcode) OpType { - ptrHeadOp := code.Op.HeadToPtrHead() - if code.Op != ptrHeadOp { - if code.PtrNum > 0 { - // ptr field and ptr head - code.PtrNum-- - } - return ptrHeadOp - } - switch code.Op { - case OpInt: - return OpIntPtr - case OpUint: - return OpUintPtr - case OpFloat32: - return OpFloat32Ptr - case OpFloat64: - return OpFloat64Ptr - case OpString: - return OpStringPtr - case OpBool: - return OpBoolPtr - case OpBytes: - return OpBytesPtr - case OpNumber: - return OpNumberPtr - case OpArray: - return OpArrayPtr - case OpSlice: - return OpSlicePtr - case OpMap: - return OpMapPtr - case OpMarshalJSON: - return OpMarshalJSONPtr - case OpMarshalText: - return OpMarshalTextPtr - case OpInterface: - return OpInterfacePtr - case OpRecursive: - return OpRecursivePtr - } - return code.Op -} - -func compileKey(ctx *compileContext) (*Opcode, error) { - typ := ctx.typ - switch { - case implementsMarshalJSON(typ): - return compileMarshalJSON(ctx) - case implementsMarshalText(typ): - return compileMarshalText(ctx) - } - switch typ.Kind() { - case reflect.Ptr: - return compilePtr(ctx) - case reflect.String: - return compileString(ctx) - case reflect.Int: - return compileIntString(ctx) - case reflect.Int8: - return compileInt8String(ctx) - case reflect.Int16: - return compileInt16String(ctx) - case reflect.Int32: - return compileInt32String(ctx) - case reflect.Int64: - return compileInt64String(ctx) - case reflect.Uint: - return compileUintString(ctx) - case reflect.Uint8: - return compileUint8String(ctx) - case reflect.Uint16: - return compileUint16String(ctx) - case reflect.Uint32: - return compileUint32String(ctx) - case reflect.Uint64: - return compileUint64String(ctx) - case reflect.Uintptr: - return compileUintString(ctx) - } - return nil, &errors.UnsupportedTypeError{Type: runtime.RType2Type(typ)} -} - -func compilePtr(ctx *compileContext) (*Opcode, error) { - code, err := compile(ctx.withType(ctx.typ.Elem()), true) - if err != nil { - return nil, err - } - code.Op = convertPtrOp(code) - code.PtrNum++ - return code, nil -} - -func compileMarshalJSON(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpMarshalJSON) - typ := ctx.typ - if isPtrMarshalJSONType(typ) { - code.Flags |= AddrForMarshalerFlags - } - if typ.Implements(marshalJSONContextType) || runtime.PtrTo(typ).Implements(marshalJSONContextType) { - code.Flags |= MarshalerContextFlags - } - if isNilableType(typ) { - code.Flags |= IsNilableTypeFlags - } else { - code.Flags &= ^IsNilableTypeFlags - } - ctx.incIndex() - return code, nil -} - -func compileMarshalText(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpMarshalText) - typ := ctx.typ - if !typ.Implements(marshalTextType) && runtime.PtrTo(typ).Implements(marshalTextType) { - code.Flags |= AddrForMarshalerFlags - } - if isNilableType(typ) { - code.Flags |= IsNilableTypeFlags - } else { - code.Flags &= ^IsNilableTypeFlags - } - ctx.incIndex() - return code, nil -} - -const intSize = 32 << (^uint(0) >> 63) - -func compileInt(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpInt) - code.NumBitSize = intSize - ctx.incIndex() - return code, nil -} - -func compileIntPtr(ctx *compileContext) (*Opcode, error) { - code, err := compileInt(ctx) - if err != nil { - return nil, err - } - code.Op = OpIntPtr - return code, nil -} - -func compileInt8(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpInt) - code.NumBitSize = 8 - ctx.incIndex() - return code, nil -} - -func compileInt8Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileInt8(ctx) - if err != nil { - return nil, err - } - code.Op = OpIntPtr - return code, nil -} - -func compileInt16(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpInt) - code.NumBitSize = 16 - ctx.incIndex() - return code, nil -} - -func compileInt16Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileInt16(ctx) - if err != nil { - return nil, err - } - code.Op = OpIntPtr - return code, nil -} - -func compileInt32(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpInt) - code.NumBitSize = 32 - ctx.incIndex() - return code, nil -} - -func compileInt32Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileInt32(ctx) - if err != nil { - return nil, err - } - code.Op = OpIntPtr - return code, nil -} - -func compileInt64(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpInt) - code.NumBitSize = 64 - ctx.incIndex() - return code, nil -} - -func compileInt64Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileInt64(ctx) - if err != nil { - return nil, err - } - code.Op = OpIntPtr - return code, nil -} - -func compileUint(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUint) - code.NumBitSize = intSize - ctx.incIndex() - return code, nil -} - -func compileUintPtr(ctx *compileContext) (*Opcode, error) { - code, err := compileUint(ctx) - if err != nil { - return nil, err - } - code.Op = OpUintPtr - return code, nil -} - -func compileUint8(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUint) - code.NumBitSize = 8 - ctx.incIndex() - return code, nil -} - -func compileUint8Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileUint8(ctx) - if err != nil { - return nil, err - } - code.Op = OpUintPtr - return code, nil -} - -func compileUint16(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUint) - code.NumBitSize = 16 - ctx.incIndex() - return code, nil -} - -func compileUint16Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileUint16(ctx) - if err != nil { - return nil, err - } - code.Op = OpUintPtr - return code, nil -} - -func compileUint32(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUint) - code.NumBitSize = 32 - ctx.incIndex() - return code, nil -} - -func compileUint32Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileUint32(ctx) - if err != nil { - return nil, err - } - code.Op = OpUintPtr - return code, nil -} - -func compileUint64(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUint) - code.NumBitSize = 64 - ctx.incIndex() - return code, nil -} - -func compileUint64Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileUint64(ctx) - if err != nil { - return nil, err - } - code.Op = OpUintPtr - return code, nil -} - -func compileIntString(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpIntString) - code.NumBitSize = intSize - ctx.incIndex() - return code, nil -} - -func compileInt8String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpIntString) - code.NumBitSize = 8 - ctx.incIndex() - return code, nil -} - -func compileInt16String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpIntString) - code.NumBitSize = 16 - ctx.incIndex() - return code, nil -} - -func compileInt32String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpIntString) - code.NumBitSize = 32 - ctx.incIndex() - return code, nil -} - -func compileInt64String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpIntString) - code.NumBitSize = 64 - ctx.incIndex() - return code, nil -} - -func compileUintString(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUintString) - code.NumBitSize = intSize - ctx.incIndex() - return code, nil -} - -func compileUint8String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUintString) - code.NumBitSize = 8 - ctx.incIndex() - return code, nil -} - -func compileUint16String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUintString) - code.NumBitSize = 16 - ctx.incIndex() - return code, nil -} - -func compileUint32String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUintString) - code.NumBitSize = 32 - ctx.incIndex() - return code, nil -} - -func compileUint64String(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpUintString) - code.NumBitSize = 64 - ctx.incIndex() - return code, nil -} - -func compileFloat32(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpFloat32) - ctx.incIndex() - return code, nil -} - -func compileFloat32Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileFloat32(ctx) - if err != nil { - return nil, err - } - code.Op = OpFloat32Ptr - return code, nil -} - -func compileFloat64(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpFloat64) - ctx.incIndex() - return code, nil -} - -func compileFloat64Ptr(ctx *compileContext) (*Opcode, error) { - code, err := compileFloat64(ctx) - if err != nil { - return nil, err - } - code.Op = OpFloat64Ptr - return code, nil -} - -func compileString(ctx *compileContext) (*Opcode, error) { - var op OpType - if ctx.typ == runtime.Type2RType(jsonNumberType) { - op = OpNumber - } else { - op = OpString - } - code := newOpCode(ctx, op) - ctx.incIndex() - return code, nil -} - -func compileStringPtr(ctx *compileContext) (*Opcode, error) { - code, err := compileString(ctx) - if err != nil { - return nil, err - } - if code.Op == OpNumber { - code.Op = OpNumberPtr - } else { - code.Op = OpStringPtr - } - return code, nil -} - -func compileBool(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpBool) - ctx.incIndex() - return code, nil -} - -func compileBoolPtr(ctx *compileContext) (*Opcode, error) { - code, err := compileBool(ctx) - if err != nil { - return nil, err - } - code.Op = OpBoolPtr - return code, nil -} - -func compileBytes(ctx *compileContext) (*Opcode, error) { - code := newOpCode(ctx, OpBytes) - ctx.incIndex() - return code, nil -} - -func compileBytesPtr(ctx *compileContext) (*Opcode, error) { - code, err := compileBytes(ctx) - if err != nil { - return nil, err - } - code.Op = OpBytesPtr - return code, nil -} - -func compileInterface(ctx *compileContext) (*Opcode, error) { - code := newInterfaceCode(ctx) - ctx.incIndex() - return code, nil -} - -func compileInterfacePtr(ctx *compileContext) (*Opcode, error) { - code, err := compileInterface(ctx) - if err != nil { - return nil, err - } - code.Op = OpInterfacePtr - return code, nil -} - -func compileSlice(ctx *compileContext) (*Opcode, error) { - elem := ctx.typ.Elem() - size := elem.Size() - - header := newSliceHeaderCode(ctx) - ctx.incIndex() - - code, err := compileListElem(ctx.withType(elem).incIndent()) - if err != nil { - return nil, err - } - code.Flags |= IndirectFlags - - // header => opcode => elem => end - // ^ | - // |________| - - elemCode := newSliceElemCode(ctx, header, size) - ctx.incIndex() - - end := newOpCode(ctx, OpSliceEnd) - ctx.incIndex() - - header.End = end - header.Next = code - code.BeforeLastCode().Next = (*Opcode)(unsafe.Pointer(elemCode)) - elemCode.Next = code - elemCode.End = end - return (*Opcode)(unsafe.Pointer(header)), nil -} - -func compileListElem(ctx *compileContext) (*Opcode, error) { - typ := ctx.typ - switch { - case isPtrMarshalJSONType(typ): - return compileMarshalJSON(ctx) - case !typ.Implements(marshalTextType) && runtime.PtrTo(typ).Implements(marshalTextType): - return compileMarshalText(ctx) - case typ.Kind() == reflect.Map: - return compilePtr(ctx.withType(runtime.PtrTo(typ))) - default: - code, err := compile(ctx, false) - if err != nil { - return nil, err - } - if code.Op == OpMapPtr { - code.PtrNum++ - } - return code, nil - } -} - -func compileArray(ctx *compileContext) (*Opcode, error) { - typ := ctx.typ - elem := typ.Elem() - alen := typ.Len() - size := elem.Size() - - header := newArrayHeaderCode(ctx, alen) - ctx.incIndex() - - code, err := compileListElem(ctx.withType(elem).incIndent()) - if err != nil { - return nil, err - } - code.Flags |= IndirectFlags - // header => opcode => elem => end - // ^ | - // |________| - - elemCode := newArrayElemCode(ctx, header, alen, size) - ctx.incIndex() - - end := newOpCode(ctx, OpArrayEnd) - ctx.incIndex() - - header.End = end - header.Next = code - code.BeforeLastCode().Next = (*Opcode)(unsafe.Pointer(elemCode)) - elemCode.Next = code - elemCode.End = end - return (*Opcode)(unsafe.Pointer(header)), nil -} - -func compileMap(ctx *compileContext) (*Opcode, error) { - // header => code => value => code => key => code => value => code => end - // ^ | - // |_______________________| - ctx = ctx.incIndent() - header := newMapHeaderCode(ctx) - ctx.incIndex() - - typ := ctx.typ - keyType := ctx.typ.Key() - keyCode, err := compileKey(ctx.withType(keyType)) - if err != nil { - return nil, err - } - - value := newMapValueCode(ctx, header) - ctx.incIndex() - - valueCode, err := compileMapValue(ctx.withType(typ.Elem())) - if err != nil { - return nil, err - } - valueCode.Flags |= IndirectFlags - - key := newMapKeyCode(ctx, header) - ctx.incIndex() - - ctx = ctx.decIndent() - - end := newMapEndCode(ctx, header) - ctx.incIndex() - - header.Next = keyCode - keyCode.BeforeLastCode().Next = (*Opcode)(unsafe.Pointer(value)) - value.Next = valueCode - valueCode.BeforeLastCode().Next = (*Opcode)(unsafe.Pointer(key)) - key.Next = keyCode - - header.End = end - key.End = end - value.End = end - - return (*Opcode)(unsafe.Pointer(header)), nil -} - -func compileMapValue(ctx *compileContext) (*Opcode, error) { - switch ctx.typ.Kind() { - case reflect.Map: - return compilePtr(ctx.withType(runtime.PtrTo(ctx.typ))) - default: - code, err := compile(ctx, false) - if err != nil { - return nil, err - } - if code.Op == OpMapPtr { - code.PtrNum++ - } - return code, nil - } -} - -func optimizeStructHeader(code *Opcode, tag *runtime.StructTag) OpType { - headType := code.ToHeaderType(tag.IsString) - if tag.IsOmitEmpty { - headType = headType.HeadToOmitEmptyHead() - } - return headType -} - -func optimizeStructField(code *Opcode, tag *runtime.StructTag) OpType { - fieldType := code.ToFieldType(tag.IsString) - if tag.IsOmitEmpty { - fieldType = fieldType.FieldToOmitEmptyField() - } - return fieldType -} - -func recursiveCode(ctx *compileContext, jmp *CompiledCode) *Opcode { - code := newRecursiveCode(ctx, jmp) - ctx.incIndex() - return code -} - -func compiledCode(ctx *compileContext) *Opcode { - typ := ctx.typ - typeptr := uintptr(unsafe.Pointer(typ)) - if cc, exists := ctx.structTypeToCompiledCode[typeptr]; exists { - return recursiveCode(ctx, cc) - } - return nil -} - -func structHeader(ctx *compileContext, fieldCode *Opcode, valueCode *Opcode, tag *runtime.StructTag) *Opcode { - op := optimizeStructHeader(valueCode, tag) - fieldCode.Op = op - fieldCode.NumBitSize = valueCode.NumBitSize - fieldCode.PtrNum = valueCode.PtrNum - if op.IsMultipleOpHead() { - return valueCode.BeforeLastCode() - } - ctx.decOpcodeIndex() - return fieldCode -} - -func structField(ctx *compileContext, fieldCode *Opcode, valueCode *Opcode, tag *runtime.StructTag) *Opcode { - op := optimizeStructField(valueCode, tag) - fieldCode.Op = op - fieldCode.NumBitSize = valueCode.NumBitSize - fieldCode.PtrNum = valueCode.PtrNum - if op.IsMultipleOpField() { - return valueCode.BeforeLastCode() - } - ctx.decIndex() - return fieldCode -} - -func isNotExistsField(head *Opcode) bool { - if head == nil { - return false - } - if head.Op != OpStructHead { - return false - } - if (head.Flags & AnonymousHeadFlags) == 0 { - return false - } - if head.Next == nil { - return false - } - if head.NextField == nil { - return false - } - if head.NextField.Op != OpStructAnonymousEnd { - return false - } - if head.Next.Op == OpStructAnonymousEnd { - return true - } - if head.Next.Op.CodeType() != CodeStructField { - return false - } - return isNotExistsField(head.Next) -} - -func optimizeAnonymousFields(head *Opcode) { - code := head - var prev *Opcode - removedFields := map[*Opcode]struct{}{} - for { - if code.Op == OpStructEnd { - break - } - if code.Op == OpStructField { - codeType := code.Next.Op.CodeType() - if codeType == CodeStructField { - if isNotExistsField(code.Next) { - code.Next = code.NextField - diff := code.Next.DisplayIdx - code.DisplayIdx - for i := uint32(0); i < diff; i++ { - code.Next.decOpcodeIndex() - } - linkPrevToNextField(code, removedFields) - code = prev - } - } - } - prev = code - code = code.NextField - } -} - -type structFieldPair struct { - prevField *Opcode - curField *Opcode - isTaggedKey bool - linked bool -} - -func anonymousStructFieldPairMap(tags runtime.StructTags, named string, valueCode *Opcode) map[string][]structFieldPair { - anonymousFields := map[string][]structFieldPair{} - f := valueCode - var prevAnonymousField *Opcode - removedFields := map[*Opcode]struct{}{} - for { - existsKey := tags.ExistsKey(f.DisplayKey) - isHeadOp := strings.Contains(f.Op.String(), "Head") - if existsKey && f.Next != nil && strings.Contains(f.Next.Op.String(), "Recursive") { - // through - } else if isHeadOp && (f.Flags&AnonymousHeadFlags) == 0 { - if existsKey { - // TODO: need to remove this head - f.Op = OpStructHead - f.Flags |= AnonymousKeyFlags - f.Flags |= AnonymousHeadFlags - } else if named == "" { - f.Flags |= AnonymousHeadFlags - } - } else if named == "" && f.Op == OpStructEnd { - f.Op = OpStructAnonymousEnd - } else if existsKey { - diff := f.NextField.DisplayIdx - f.DisplayIdx - for i := uint32(0); i < diff; i++ { - f.NextField.decOpcodeIndex() - } - linkPrevToNextField(f, removedFields) - } - - if f.DisplayKey == "" { - if f.NextField == nil { - break - } - prevAnonymousField = f - f = f.NextField - continue - } - - key := fmt.Sprintf("%s.%s", named, f.DisplayKey) - anonymousFields[key] = append(anonymousFields[key], structFieldPair{ - prevField: prevAnonymousField, - curField: f, - isTaggedKey: (f.Flags & IsTaggedKeyFlags) != 0, - }) - if f.Next != nil && f.NextField != f.Next && f.Next.Op.CodeType() == CodeStructField { - for k, v := range anonymousFieldPairRecursively(named, f.Next) { - anonymousFields[k] = append(anonymousFields[k], v...) - } - } - if f.NextField == nil { - break - } - prevAnonymousField = f - f = f.NextField - } - return anonymousFields -} - -func anonymousFieldPairRecursively(named string, valueCode *Opcode) map[string][]structFieldPair { - anonymousFields := map[string][]structFieldPair{} - f := valueCode - var prevAnonymousField *Opcode - for { - if f.DisplayKey != "" && (f.Flags&AnonymousHeadFlags) != 0 { - key := fmt.Sprintf("%s.%s", named, f.DisplayKey) - anonymousFields[key] = append(anonymousFields[key], structFieldPair{ - prevField: prevAnonymousField, - curField: f, - isTaggedKey: (f.Flags & IsTaggedKeyFlags) != 0, - }) - if f.Next != nil && f.NextField != f.Next && f.Next.Op.CodeType() == CodeStructField { - for k, v := range anonymousFieldPairRecursively(named, f.Next) { - anonymousFields[k] = append(anonymousFields[k], v...) - } - } - } - if f.NextField == nil { - break - } - prevAnonymousField = f - f = f.NextField - } - return anonymousFields -} - -func optimizeConflictAnonymousFields(anonymousFields map[string][]structFieldPair) { - removedFields := map[*Opcode]struct{}{} - for _, fieldPairs := range anonymousFields { - if len(fieldPairs) == 1 { - continue - } - // conflict anonymous fields - taggedPairs := []structFieldPair{} - for _, fieldPair := range fieldPairs { - if fieldPair.isTaggedKey { - taggedPairs = append(taggedPairs, fieldPair) - } else { - if !fieldPair.linked { - if fieldPair.prevField == nil { - // head operation - fieldPair.curField.Op = OpStructHead - fieldPair.curField.Flags |= AnonymousHeadFlags - fieldPair.curField.Flags |= AnonymousKeyFlags - } else { - diff := fieldPair.curField.NextField.DisplayIdx - fieldPair.curField.DisplayIdx - for i := uint32(0); i < diff; i++ { - fieldPair.curField.NextField.decOpcodeIndex() - } - removedFields[fieldPair.curField] = struct{}{} - linkPrevToNextField(fieldPair.curField, removedFields) - } - fieldPair.linked = true - } - } - } - if len(taggedPairs) > 1 { - for _, fieldPair := range taggedPairs { - if !fieldPair.linked { - if fieldPair.prevField == nil { - // head operation - fieldPair.curField.Op = OpStructHead - fieldPair.curField.Flags |= AnonymousHeadFlags - fieldPair.curField.Flags |= AnonymousKeyFlags - } else { - diff := fieldPair.curField.NextField.DisplayIdx - fieldPair.curField.DisplayIdx - removedFields[fieldPair.curField] = struct{}{} - for i := uint32(0); i < diff; i++ { - fieldPair.curField.NextField.decOpcodeIndex() - } - linkPrevToNextField(fieldPair.curField, removedFields) - } - fieldPair.linked = true - } - } - } else { - for _, fieldPair := range taggedPairs { - fieldPair.curField.Flags &= ^IsTaggedKeyFlags - } - } - } -} - -func isNilableType(typ *runtime.Type) bool { - switch typ.Kind() { - case reflect.Ptr: - return true - case reflect.Map: - return true - case reflect.Func: - return true - default: - return false - } -} - -func compileStruct(ctx *compileContext, isPtr bool) (*Opcode, error) { - if code := compiledCode(ctx); code != nil { - return code, nil - } - typ := ctx.typ - typeptr := uintptr(unsafe.Pointer(typ)) - compiled := &CompiledCode{} - ctx.structTypeToCompiledCode[typeptr] = compiled - // header => code => structField => code => end - // ^ | - // |__________| - fieldNum := typ.NumField() - indirect := runtime.IfaceIndir(typ) - fieldIdx := 0 - disableIndirectConversion := false - var ( - head *Opcode - code *Opcode - prevField *Opcode - ) - ctx = ctx.incIndent() - tags := runtime.StructTags{} - anonymousFields := map[string][]structFieldPair{} - for i := 0; i < fieldNum; i++ { - field := typ.Field(i) - if runtime.IsIgnoredStructField(field) { - continue - } - tags = append(tags, runtime.StructTagFromField(field)) - } - for i, tag := range tags { - field := tag.Field - fieldType := runtime.Type2RType(field.Type) - fieldOpcodeIndex := ctx.opcodeIndex - fieldPtrIndex := ctx.ptrIndex - ctx.incIndex() - - nilcheck := true - addrForMarshaler := false - isIndirectSpecialCase := isPtr && i == 0 && fieldNum == 1 - isNilableType := isNilableType(fieldType) - - var valueCode *Opcode - switch { - case isIndirectSpecialCase && !isNilableType && isPtrMarshalJSONType(fieldType): - // *struct{ field T } => struct { field *T } - // func (*T) MarshalJSON() ([]byte, error) - // move pointer position from head to first field - code, err := compileMarshalJSON(ctx.withType(fieldType)) - if err != nil { - return nil, err - } - addrForMarshaler = true - valueCode = code - nilcheck = false - indirect = false - disableIndirectConversion = true - case isIndirectSpecialCase && !isNilableType && isPtrMarshalTextType(fieldType): - // *struct{ field T } => struct { field *T } - // func (*T) MarshalText() ([]byte, error) - // move pointer position from head to first field - code, err := compileMarshalText(ctx.withType(fieldType)) - if err != nil { - return nil, err - } - addrForMarshaler = true - valueCode = code - nilcheck = false - indirect = false - disableIndirectConversion = true - case isPtr && isPtrMarshalJSONType(fieldType): - // *struct{ field T } - // func (*T) MarshalJSON() ([]byte, error) - code, err := compileMarshalJSON(ctx.withType(fieldType)) - if err != nil { - return nil, err - } - addrForMarshaler = true - nilcheck = false - valueCode = code - case isPtr && isPtrMarshalTextType(fieldType): - // *struct{ field T } - // func (*T) MarshalText() ([]byte, error) - code, err := compileMarshalText(ctx.withType(fieldType)) - if err != nil { - return nil, err - } - addrForMarshaler = true - nilcheck = false - valueCode = code - default: - code, err := compile(ctx.withType(fieldType), isPtr) - if err != nil { - return nil, err - } - valueCode = code - } - - if field.Anonymous { - tagKey := "" - if tag.IsTaggedKey { - tagKey = tag.Key - } - for k, v := range anonymousStructFieldPairMap(tags, tagKey, valueCode) { - anonymousFields[k] = append(anonymousFields[k], v...) - } - valueCode.decIndent() - - // fix issue144 - if !(isPtr && strings.Contains(valueCode.Op.String(), "Marshal")) { - if indirect { - valueCode.Flags |= IndirectFlags - } else { - valueCode.Flags &= ^IndirectFlags - } - } - } else { - if indirect { - // if parent is indirect type, set child indirect property to true - valueCode.Flags |= IndirectFlags - } else { - // if parent is not indirect type, set child indirect property to false. - // but if parent's indirect is false and isPtr is true, then indirect must be true. - // Do this only if indirectConversion is enabled at the end of compileStruct. - if i == 0 { - valueCode.Flags &= ^IndirectFlags - } - } - } - var flags OpFlags - if indirect { - flags |= IndirectFlags - } - if field.Anonymous { - flags |= AnonymousKeyFlags - } - if tag.IsTaggedKey { - flags |= IsTaggedKeyFlags - } - if nilcheck { - flags |= NilCheckFlags - } - if addrForMarshaler { - flags |= AddrForMarshalerFlags - } - if strings.Contains(valueCode.Op.String(), "Ptr") || valueCode.Op == OpInterface { - flags |= IsNextOpPtrTypeFlags - } - if isNilableType { - flags |= IsNilableTypeFlags - } - var key string - if ctx.escapeKey { - rctx := &RuntimeContext{Option: &Option{Flag: HTMLEscapeOption}} - key = fmt.Sprintf(`%s:`, string(AppendString(rctx, []byte{}, tag.Key))) - } else { - key = fmt.Sprintf(`"%s":`, tag.Key) - } - fieldCode := &Opcode{ - Idx: opcodeOffset(fieldPtrIndex), - Next: valueCode, - Flags: flags, - Key: key, - Offset: uint32(field.Offset), - Type: valueCode.Type, - DisplayIdx: fieldOpcodeIndex, - Indent: ctx.indent, - DisplayKey: tag.Key, - } - if fieldIdx == 0 { - code = structHeader(ctx, fieldCode, valueCode, tag) - head = fieldCode - prevField = fieldCode - } else { - fieldCode.Idx = head.Idx - code.Next = fieldCode - code = structField(ctx, fieldCode, valueCode, tag) - prevField.NextField = fieldCode - fieldCode.PrevField = prevField - prevField = fieldCode - } - fieldIdx++ - } - - structEndCode := &Opcode{ - Op: OpStructEnd, - Next: newEndOp(ctx), - Type: nil, - Indent: ctx.indent, - } - - ctx = ctx.decIndent() - - // no struct field - if head == nil { - head = &Opcode{ - Op: OpStructHead, - Idx: opcodeOffset(ctx.ptrIndex), - NextField: structEndCode, - Type: typ, - DisplayIdx: ctx.opcodeIndex, - Indent: ctx.indent, - } - structEndCode.PrevField = head - ctx.incIndex() - code = head - } - - structEndCode.DisplayIdx = ctx.opcodeIndex - structEndCode.Idx = opcodeOffset(ctx.ptrIndex) - ctx.incIndex() - - if prevField != nil && prevField.NextField == nil { - prevField.NextField = structEndCode - structEndCode.PrevField = prevField - } - - head.End = structEndCode - code.Next = structEndCode - optimizeConflictAnonymousFields(anonymousFields) - optimizeAnonymousFields(head) - ret := (*Opcode)(unsafe.Pointer(head)) - compiled.Code = ret - - delete(ctx.structTypeToCompiledCode, typeptr) - - if !disableIndirectConversion && (head.Flags&IndirectFlags == 0) && isPtr { - headCode := head - for strings.Contains(headCode.Op.String(), "Head") { - headCode.Flags |= IndirectFlags - headCode = headCode.Next - } - } - - return ret, nil -} - -func implementsMarshalJSONType(typ *runtime.Type) bool { - return typ.Implements(marshalJSONType) || typ.Implements(marshalJSONContextType) -} - -func isPtrMarshalJSONType(typ *runtime.Type) bool { - return !implementsMarshalJSONType(typ) && implementsMarshalJSONType(runtime.PtrTo(typ)) -} - -func isPtrMarshalTextType(typ *runtime.Type) bool { - return !typ.Implements(marshalTextType) && runtime.PtrTo(typ).Implements(marshalTextType) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_norace.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_norace.go deleted file mode 100644 index 9d337f12..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_norace.go +++ /dev/null @@ -1,56 +0,0 @@ -// +build !race - -package encoder - -import ( - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -func CompileToGetCodeSet(typeptr uintptr) (*OpcodeSet, error) { - if typeptr > typeAddr.MaxTypeAddr { - return compileToGetCodeSetSlowPath(typeptr) - } - index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift - if codeSet := cachedOpcodeSets[index]; codeSet != nil { - return codeSet, nil - } - - // noescape trick for header.typ ( reflect.*rtype ) - copiedType := *(**runtime.Type)(unsafe.Pointer(&typeptr)) - - noescapeKeyCode, err := compileHead(&compileContext{ - typ: copiedType, - structTypeToCompiledCode: map[uintptr]*CompiledCode{}, - }) - if err != nil { - return nil, err - } - escapeKeyCode, err := compileHead(&compileContext{ - typ: copiedType, - structTypeToCompiledCode: map[uintptr]*CompiledCode{}, - escapeKey: true, - }) - if err != nil { - return nil, err - } - noescapeKeyCode = copyOpcode(noescapeKeyCode) - escapeKeyCode = copyOpcode(escapeKeyCode) - setTotalLengthToInterfaceOp(noescapeKeyCode) - setTotalLengthToInterfaceOp(escapeKeyCode) - interfaceNoescapeKeyCode := copyToInterfaceOpcode(noescapeKeyCode) - interfaceEscapeKeyCode := copyToInterfaceOpcode(escapeKeyCode) - codeLength := noescapeKeyCode.TotalLength() - codeSet := &OpcodeSet{ - Type: copiedType, - NoescapeKeyCode: noescapeKeyCode, - EscapeKeyCode: escapeKeyCode, - InterfaceNoescapeKeyCode: interfaceNoescapeKeyCode, - InterfaceEscapeKeyCode: interfaceEscapeKeyCode, - CodeLength: codeLength, - EndCode: ToEndCode(interfaceNoescapeKeyCode), - } - cachedOpcodeSets[index] = codeSet - return codeSet, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_race.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_race.go deleted file mode 100644 index 3a239e9d..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_race.go +++ /dev/null @@ -1,65 +0,0 @@ -// +build race - -package encoder - -import ( - "sync" - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -var setsMu sync.RWMutex - -func CompileToGetCodeSet(typeptr uintptr) (*OpcodeSet, error) { - if typeptr > typeAddr.MaxTypeAddr { - return compileToGetCodeSetSlowPath(typeptr) - } - index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift - setsMu.RLock() - if codeSet := cachedOpcodeSets[index]; codeSet != nil { - setsMu.RUnlock() - return codeSet, nil - } - setsMu.RUnlock() - - // noescape trick for header.typ ( reflect.*rtype ) - copiedType := *(**runtime.Type)(unsafe.Pointer(&typeptr)) - - noescapeKeyCode, err := compileHead(&compileContext{ - typ: copiedType, - structTypeToCompiledCode: map[uintptr]*CompiledCode{}, - }) - if err != nil { - return nil, err - } - escapeKeyCode, err := compileHead(&compileContext{ - typ: copiedType, - structTypeToCompiledCode: map[uintptr]*CompiledCode{}, - escapeKey: true, - }) - if err != nil { - return nil, err - } - - noescapeKeyCode = copyOpcode(noescapeKeyCode) - escapeKeyCode = copyOpcode(escapeKeyCode) - setTotalLengthToInterfaceOp(noescapeKeyCode) - setTotalLengthToInterfaceOp(escapeKeyCode) - interfaceNoescapeKeyCode := copyToInterfaceOpcode(noescapeKeyCode) - interfaceEscapeKeyCode := copyToInterfaceOpcode(escapeKeyCode) - codeLength := noescapeKeyCode.TotalLength() - codeSet := &OpcodeSet{ - Type: copiedType, - NoescapeKeyCode: noescapeKeyCode, - EscapeKeyCode: escapeKeyCode, - InterfaceNoescapeKeyCode: interfaceNoescapeKeyCode, - InterfaceEscapeKeyCode: interfaceEscapeKeyCode, - CodeLength: codeLength, - EndCode: ToEndCode(interfaceNoescapeKeyCode), - } - setsMu.Lock() - cachedOpcodeSets[index] = codeSet - setsMu.Unlock() - return codeSet, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/context.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/context.go deleted file mode 100644 index 61b89080..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/context.go +++ /dev/null @@ -1,141 +0,0 @@ -package encoder - -import ( - "context" - "sync" - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -type compileContext struct { - typ *runtime.Type - opcodeIndex uint32 - ptrIndex int - indent uint32 - escapeKey bool - structTypeToCompiledCode map[uintptr]*CompiledCode - - parent *compileContext -} - -func (c *compileContext) context() *compileContext { - return &compileContext{ - typ: c.typ, - opcodeIndex: c.opcodeIndex, - ptrIndex: c.ptrIndex, - indent: c.indent, - escapeKey: c.escapeKey, - structTypeToCompiledCode: c.structTypeToCompiledCode, - parent: c, - } -} - -func (c *compileContext) withType(typ *runtime.Type) *compileContext { - ctx := c.context() - ctx.typ = typ - return ctx -} - -func (c *compileContext) incIndent() *compileContext { - ctx := c.context() - ctx.indent++ - return ctx -} - -func (c *compileContext) decIndent() *compileContext { - ctx := c.context() - ctx.indent-- - return ctx -} - -func (c *compileContext) incIndex() { - c.incOpcodeIndex() - c.incPtrIndex() -} - -func (c *compileContext) decIndex() { - c.decOpcodeIndex() - c.decPtrIndex() -} - -func (c *compileContext) incOpcodeIndex() { - c.opcodeIndex++ - if c.parent != nil { - c.parent.incOpcodeIndex() - } -} - -func (c *compileContext) decOpcodeIndex() { - c.opcodeIndex-- - if c.parent != nil { - c.parent.decOpcodeIndex() - } -} - -func (c *compileContext) incPtrIndex() { - c.ptrIndex++ - if c.parent != nil { - c.parent.incPtrIndex() - } -} - -func (c *compileContext) decPtrIndex() { - c.ptrIndex-- - if c.parent != nil { - c.parent.decPtrIndex() - } -} - -const ( - bufSize = 1024 -) - -var ( - runtimeContextPool = sync.Pool{ - New: func() interface{} { - return &RuntimeContext{ - Buf: make([]byte, 0, bufSize), - Ptrs: make([]uintptr, 128), - KeepRefs: make([]unsafe.Pointer, 0, 8), - Option: &Option{}, - } - }, - } -) - -type RuntimeContext struct { - Context context.Context - Buf []byte - MarshalBuf []byte - Ptrs []uintptr - KeepRefs []unsafe.Pointer - SeenPtr []uintptr - BaseIndent uint32 - Prefix []byte - IndentStr []byte - Option *Option -} - -func (c *RuntimeContext) Init(p uintptr, codelen int) { - if len(c.Ptrs) < codelen { - c.Ptrs = make([]uintptr, codelen) - } - c.Ptrs[0] = p - c.KeepRefs = c.KeepRefs[:0] - c.SeenPtr = c.SeenPtr[:0] - c.BaseIndent = 0 -} - -func (c *RuntimeContext) Ptr() uintptr { - header := (*runtime.SliceHeader)(unsafe.Pointer(&c.Ptrs)) - return uintptr(header.Data) -} - -func TakeRuntimeContext() *RuntimeContext { - return runtimeContextPool.Get().(*RuntimeContext) -} - -func ReleaseRuntimeContext(ctx *RuntimeContext) { - runtimeContextPool.Put(ctx) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/encoder.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/encoder.go deleted file mode 100644 index b7fa99a9..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/encoder.go +++ /dev/null @@ -1,551 +0,0 @@ -package encoder - -import ( - "bytes" - "encoding" - "encoding/base64" - "encoding/json" - "fmt" - "math" - "reflect" - "strconv" - "strings" - "sync" - "unsafe" - - "github.com/goccy/go-json/internal/errors" - "github.com/goccy/go-json/internal/runtime" -) - -func (t OpType) IsMultipleOpHead() bool { - switch t { - case OpStructHead: - return true - case OpStructHeadSlice: - return true - case OpStructHeadArray: - return true - case OpStructHeadMap: - return true - case OpStructHeadStruct: - return true - case OpStructHeadOmitEmpty: - return true - case OpStructHeadOmitEmptySlice: - return true - case OpStructHeadOmitEmptyArray: - return true - case OpStructHeadOmitEmptyMap: - return true - case OpStructHeadOmitEmptyStruct: - return true - case OpStructHeadSlicePtr: - return true - case OpStructHeadOmitEmptySlicePtr: - return true - case OpStructHeadArrayPtr: - return true - case OpStructHeadOmitEmptyArrayPtr: - return true - case OpStructHeadMapPtr: - return true - case OpStructHeadOmitEmptyMapPtr: - return true - } - return false -} - -func (t OpType) IsMultipleOpField() bool { - switch t { - case OpStructField: - return true - case OpStructFieldSlice: - return true - case OpStructFieldArray: - return true - case OpStructFieldMap: - return true - case OpStructFieldStruct: - return true - case OpStructFieldOmitEmpty: - return true - case OpStructFieldOmitEmptySlice: - return true - case OpStructFieldOmitEmptyArray: - return true - case OpStructFieldOmitEmptyMap: - return true - case OpStructFieldOmitEmptyStruct: - return true - case OpStructFieldSlicePtr: - return true - case OpStructFieldOmitEmptySlicePtr: - return true - case OpStructFieldArrayPtr: - return true - case OpStructFieldOmitEmptyArrayPtr: - return true - case OpStructFieldMapPtr: - return true - case OpStructFieldOmitEmptyMapPtr: - return true - } - return false -} - -type OpcodeSet struct { - Type *runtime.Type - NoescapeKeyCode *Opcode - EscapeKeyCode *Opcode - InterfaceNoescapeKeyCode *Opcode - InterfaceEscapeKeyCode *Opcode - CodeLength int - EndCode *Opcode -} - -type CompiledCode struct { - Code *Opcode - Linked bool // whether recursive code already have linked - CurLen uintptr - NextLen uintptr -} - -const StartDetectingCyclesAfter = 1000 - -func Load(base uintptr, idx uintptr) uintptr { - addr := base + idx - return **(**uintptr)(unsafe.Pointer(&addr)) -} - -func Store(base uintptr, idx uintptr, p uintptr) { - addr := base + idx - **(**uintptr)(unsafe.Pointer(&addr)) = p -} - -func LoadNPtr(base uintptr, idx uintptr, ptrNum int) uintptr { - addr := base + idx - p := **(**uintptr)(unsafe.Pointer(&addr)) - if p == 0 { - return 0 - } - return PtrToPtr(p) - /* - for i := 0; i < ptrNum; i++ { - if p == 0 { - return p - } - p = PtrToPtr(p) - } - return p - */ -} - -func PtrToUint64(p uintptr) uint64 { return **(**uint64)(unsafe.Pointer(&p)) } -func PtrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } -func PtrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } -func PtrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } -func PtrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } -func PtrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } -func PtrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } -func PtrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } -func PtrToPtr(p uintptr) uintptr { - return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) -} -func PtrToNPtr(p uintptr, ptrNum int) uintptr { - for i := 0; i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = PtrToPtr(p) - } - return p -} - -func PtrToUnsafePtr(p uintptr) unsafe.Pointer { - return *(*unsafe.Pointer)(unsafe.Pointer(&p)) -} -func PtrToInterface(code *Opcode, p uintptr) interface{} { - return *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: code.Type, - ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), - })) -} - -func ErrUnsupportedValue(code *Opcode, ptr uintptr) *errors.UnsupportedValueError { - v := *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: code.Type, - ptr: *(*unsafe.Pointer)(unsafe.Pointer(&ptr)), - })) - return &errors.UnsupportedValueError{ - Value: reflect.ValueOf(v), - Str: fmt.Sprintf("encountered a cycle via %s", code.Type), - } -} - -func ErrUnsupportedFloat(v float64) *errors.UnsupportedValueError { - return &errors.UnsupportedValueError{ - Value: reflect.ValueOf(v), - Str: strconv.FormatFloat(v, 'g', -1, 64), - } -} - -func ErrMarshalerWithCode(code *Opcode, err error) *errors.MarshalerError { - return &errors.MarshalerError{ - Type: runtime.RType2Type(code.Type), - Err: err, - } -} - -type emptyInterface struct { - typ *runtime.Type - ptr unsafe.Pointer -} - -type MapItem struct { - Key []byte - Value []byte -} - -type Mapslice struct { - Items []MapItem -} - -func (m *Mapslice) Len() int { - return len(m.Items) -} - -func (m *Mapslice) Less(i, j int) bool { - return bytes.Compare(m.Items[i].Key, m.Items[j].Key) < 0 -} - -func (m *Mapslice) Swap(i, j int) { - m.Items[i], m.Items[j] = m.Items[j], m.Items[i] -} - -type MapContext struct { - Pos []int - Slice *Mapslice - Buf []byte -} - -var mapContextPool = sync.Pool{ - New: func() interface{} { - return &MapContext{} - }, -} - -func NewMapContext(mapLen int) *MapContext { - ctx := mapContextPool.Get().(*MapContext) - if ctx.Slice == nil { - ctx.Slice = &Mapslice{ - Items: make([]MapItem, 0, mapLen), - } - } - if cap(ctx.Pos) < (mapLen*2 + 1) { - ctx.Pos = make([]int, 0, mapLen*2+1) - ctx.Slice.Items = make([]MapItem, 0, mapLen) - } else { - ctx.Pos = ctx.Pos[:0] - ctx.Slice.Items = ctx.Slice.Items[:0] - } - ctx.Buf = ctx.Buf[:0] - return ctx -} - -func ReleaseMapContext(c *MapContext) { - mapContextPool.Put(c) -} - -//go:linkname MapIterInit reflect.mapiterinit -//go:noescape -func MapIterInit(mapType *runtime.Type, m unsafe.Pointer) unsafe.Pointer - -//go:linkname MapIterKey reflect.mapiterkey -//go:noescape -func MapIterKey(it unsafe.Pointer) unsafe.Pointer - -//go:linkname MapIterNext reflect.mapiternext -//go:noescape -func MapIterNext(it unsafe.Pointer) - -//go:linkname MapLen reflect.maplen -//go:noescape -func MapLen(m unsafe.Pointer) int - -func AppendByteSlice(_ *RuntimeContext, b []byte, src []byte) []byte { - if src == nil { - return append(b, `null`...) - } - encodedLen := base64.StdEncoding.EncodedLen(len(src)) - b = append(b, '"') - pos := len(b) - remainLen := cap(b[pos:]) - var buf []byte - if remainLen > encodedLen { - buf = b[pos : pos+encodedLen] - } else { - buf = make([]byte, encodedLen) - } - base64.StdEncoding.Encode(buf, src) - return append(append(b, buf...), '"') -} - -func AppendFloat32(_ *RuntimeContext, b []byte, v float32) []byte { - f64 := float64(v) - abs := math.Abs(f64) - fmt := byte('f') - // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. - if abs != 0 { - f32 := float32(abs) - if f32 < 1e-6 || f32 >= 1e21 { - fmt = 'e' - } - } - return strconv.AppendFloat(b, f64, fmt, -1, 32) -} - -func AppendFloat64(_ *RuntimeContext, b []byte, v float64) []byte { - abs := math.Abs(v) - fmt := byte('f') - // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. - if abs != 0 { - if abs < 1e-6 || abs >= 1e21 { - fmt = 'e' - } - } - return strconv.AppendFloat(b, v, fmt, -1, 64) -} - -func AppendBool(_ *RuntimeContext, b []byte, v bool) []byte { - if v { - return append(b, "true"...) - } - return append(b, "false"...) -} - -var ( - floatTable = [256]bool{ - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - '.': true, - 'e': true, - 'E': true, - '+': true, - '-': true, - } -) - -func AppendNumber(_ *RuntimeContext, b []byte, n json.Number) ([]byte, error) { - if len(n) == 0 { - return append(b, '0'), nil - } - for i := 0; i < len(n); i++ { - if !floatTable[n[i]] { - return nil, fmt.Errorf("json: invalid number literal %q", n) - } - } - b = append(b, n...) - return b, nil -} - -func AppendMarshalJSON(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { - rv := reflect.ValueOf(v) // convert by dynamic interface type - if (code.Flags & AddrForMarshalerFlags) != 0 { - if rv.CanAddr() { - rv = rv.Addr() - } else { - newV := reflect.New(rv.Type()) - newV.Elem().Set(rv) - rv = newV - } - } - v = rv.Interface() - var bb []byte - if (code.Flags & MarshalerContextFlags) != 0 { - marshaler, ok := v.(marshalerContext) - if !ok { - return AppendNull(ctx, b), nil - } - b, err := marshaler.MarshalJSON(ctx.Option.Context) - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - bb = b - } else { - marshaler, ok := v.(json.Marshaler) - if !ok { - return AppendNull(ctx, b), nil - } - b, err := marshaler.MarshalJSON() - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - bb = b - } - marshalBuf := ctx.MarshalBuf[:0] - marshalBuf = append(append(marshalBuf, bb...), nul) - compactedBuf, err := compact(b, marshalBuf, (ctx.Option.Flag&HTMLEscapeOption) != 0) - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - ctx.MarshalBuf = marshalBuf - return compactedBuf, nil -} - -func AppendMarshalJSONIndent(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { - rv := reflect.ValueOf(v) // convert by dynamic interface type - if (code.Flags & AddrForMarshalerFlags) != 0 { - if rv.CanAddr() { - rv = rv.Addr() - } else { - newV := reflect.New(rv.Type()) - newV.Elem().Set(rv) - rv = newV - } - } - v = rv.Interface() - var bb []byte - if (code.Flags & MarshalerContextFlags) != 0 { - marshaler, ok := v.(marshalerContext) - if !ok { - return AppendNull(ctx, b), nil - } - b, err := marshaler.MarshalJSON(ctx.Option.Context) - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - bb = b - } else { - marshaler, ok := v.(json.Marshaler) - if !ok { - return AppendNull(ctx, b), nil - } - b, err := marshaler.MarshalJSON() - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - bb = b - } - marshalBuf := ctx.MarshalBuf[:0] - marshalBuf = append(append(marshalBuf, bb...), nul) - indentedBuf, err := doIndent( - b, - marshalBuf, - string(ctx.Prefix)+strings.Repeat(string(ctx.IndentStr), int(ctx.BaseIndent+code.Indent)), - string(ctx.IndentStr), - (ctx.Option.Flag&HTMLEscapeOption) != 0, - ) - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - ctx.MarshalBuf = marshalBuf - return indentedBuf, nil -} - -func AppendMarshalText(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { - rv := reflect.ValueOf(v) // convert by dynamic interface type - if (code.Flags & AddrForMarshalerFlags) != 0 { - if rv.CanAddr() { - rv = rv.Addr() - } else { - newV := reflect.New(rv.Type()) - newV.Elem().Set(rv) - rv = newV - } - } - v = rv.Interface() - marshaler, ok := v.(encoding.TextMarshaler) - if !ok { - return AppendNull(ctx, b), nil - } - bytes, err := marshaler.MarshalText() - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - return AppendString(ctx, b, *(*string)(unsafe.Pointer(&bytes))), nil -} - -func AppendMarshalTextIndent(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { - rv := reflect.ValueOf(v) // convert by dynamic interface type - if (code.Flags & AddrForMarshalerFlags) != 0 { - if rv.CanAddr() { - rv = rv.Addr() - } else { - newV := reflect.New(rv.Type()) - newV.Elem().Set(rv) - rv = newV - } - } - v = rv.Interface() - marshaler, ok := v.(encoding.TextMarshaler) - if !ok { - return AppendNull(ctx, b), nil - } - bytes, err := marshaler.MarshalText() - if err != nil { - return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} - } - return AppendString(ctx, b, *(*string)(unsafe.Pointer(&bytes))), nil -} - -func AppendNull(_ *RuntimeContext, b []byte) []byte { - return append(b, "null"...) -} - -func AppendComma(_ *RuntimeContext, b []byte) []byte { - return append(b, ',') -} - -func AppendCommaIndent(_ *RuntimeContext, b []byte) []byte { - return append(b, ',', '\n') -} - -func AppendStructEnd(_ *RuntimeContext, b []byte) []byte { - return append(b, '}', ',') -} - -func AppendStructEndIndent(ctx *RuntimeContext, code *Opcode, b []byte) []byte { - b = append(b, '\n') - b = append(b, ctx.Prefix...) - indentNum := ctx.BaseIndent + code.Indent - 1 - for i := uint32(0); i < indentNum; i++ { - b = append(b, ctx.IndentStr...) - } - return append(b, '}', ',', '\n') -} - -func AppendIndent(ctx *RuntimeContext, b []byte, indent uint32) []byte { - b = append(b, ctx.Prefix...) - indentNum := ctx.BaseIndent + indent - for i := uint32(0); i < indentNum; i++ { - b = append(b, ctx.IndentStr...) - } - return b -} - -func IsNilForMarshaler(v interface{}) bool { - rv := reflect.ValueOf(v) - switch rv.Kind() { - case reflect.Bool: - return !rv.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return rv.Uint() == 0 - case reflect.Float32, reflect.Float64: - return math.Float64bits(rv.Float()) == 0 - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Func: - return rv.IsNil() - case reflect.Slice: - return rv.IsNil() || rv.Len() == 0 - } - return false -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/indent.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/indent.go deleted file mode 100644 index dfe04b5e..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/indent.go +++ /dev/null @@ -1,211 +0,0 @@ -package encoder - -import ( - "bytes" - "fmt" - - "github.com/goccy/go-json/internal/errors" -) - -func takeIndentSrcRuntimeContext(src []byte) (*RuntimeContext, []byte) { - ctx := TakeRuntimeContext() - buf := ctx.Buf[:0] - buf = append(append(buf, src...), nul) - ctx.Buf = buf - return ctx, buf -} - -func Indent(buf *bytes.Buffer, src []byte, prefix, indentStr string) error { - if len(src) == 0 { - return errors.ErrUnexpectedEndOfJSON("", 0) - } - - srcCtx, srcBuf := takeIndentSrcRuntimeContext(src) - dstCtx := TakeRuntimeContext() - dst := dstCtx.Buf[:0] - - dst, err := indentAndWrite(buf, dst, srcBuf, prefix, indentStr) - if err != nil { - ReleaseRuntimeContext(srcCtx) - ReleaseRuntimeContext(dstCtx) - return err - } - dstCtx.Buf = dst - ReleaseRuntimeContext(srcCtx) - ReleaseRuntimeContext(dstCtx) - return nil -} - -func indentAndWrite(buf *bytes.Buffer, dst []byte, src []byte, prefix, indentStr string) ([]byte, error) { - dst, err := doIndent(dst, src, prefix, indentStr, false) - if err != nil { - return nil, err - } - if _, err := buf.Write(dst); err != nil { - return nil, err - } - return dst, nil -} - -func doIndent(dst, src []byte, prefix, indentStr string, escape bool) ([]byte, error) { - buf, cursor, err := indentValue(dst, src, 0, 0, []byte(prefix), []byte(indentStr), escape) - if err != nil { - return nil, err - } - if err := validateEndBuf(src, cursor); err != nil { - return nil, err - } - return buf, nil -} - -func indentValue( - dst []byte, - src []byte, - indentNum int, - cursor int64, - prefix []byte, - indentBytes []byte, - escape bool) ([]byte, int64, error) { - for { - switch src[cursor] { - case ' ', '\t', '\n', '\r': - cursor++ - continue - case '{': - return indentObject(dst, src, indentNum, cursor, prefix, indentBytes, escape) - case '}': - return nil, 0, errors.ErrSyntax("unexpected character '}'", cursor) - case '[': - return indentArray(dst, src, indentNum, cursor, prefix, indentBytes, escape) - case ']': - return nil, 0, errors.ErrSyntax("unexpected character ']'", cursor) - case '"': - return compactString(dst, src, cursor, escape) - case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return compactNumber(dst, src, cursor) - case 't': - return compactTrue(dst, src, cursor) - case 'f': - return compactFalse(dst, src, cursor) - case 'n': - return compactNull(dst, src, cursor) - default: - return nil, 0, errors.ErrSyntax(fmt.Sprintf("unexpected character '%c'", src[cursor]), cursor) - } - } -} - -func indentObject( - dst []byte, - src []byte, - indentNum int, - cursor int64, - prefix []byte, - indentBytes []byte, - escape bool) ([]byte, int64, error) { - if src[cursor] == '{' { - dst = append(dst, '{') - } else { - return nil, 0, errors.ErrExpected("expected { character for object value", cursor) - } - cursor = skipWhiteSpace(src, cursor+1) - if src[cursor] == '}' { - dst = append(dst, '}') - return dst, cursor + 1, nil - } - indentNum++ - var err error - for { - dst = append(append(dst, '\n'), prefix...) - for i := 0; i < indentNum; i++ { - dst = append(dst, indentBytes...) - } - cursor = skipWhiteSpace(src, cursor) - dst, cursor, err = compactString(dst, src, cursor, escape) - if err != nil { - return nil, 0, err - } - cursor = skipWhiteSpace(src, cursor) - if src[cursor] != ':' { - return nil, 0, errors.ErrSyntax( - fmt.Sprintf("invalid character '%c' after object key", src[cursor]), - cursor+1, - ) - } - dst = append(dst, ':', ' ') - dst, cursor, err = indentValue(dst, src, indentNum, cursor+1, prefix, indentBytes, escape) - if err != nil { - return nil, 0, err - } - cursor = skipWhiteSpace(src, cursor) - switch src[cursor] { - case '}': - dst = append(append(dst, '\n'), prefix...) - for i := 0; i < indentNum-1; i++ { - dst = append(dst, indentBytes...) - } - dst = append(dst, '}') - cursor++ - return dst, cursor, nil - case ',': - dst = append(dst, ',') - default: - return nil, 0, errors.ErrSyntax( - fmt.Sprintf("invalid character '%c' after object key:value pair", src[cursor]), - cursor+1, - ) - } - cursor++ - } -} - -func indentArray( - dst []byte, - src []byte, - indentNum int, - cursor int64, - prefix []byte, - indentBytes []byte, - escape bool) ([]byte, int64, error) { - if src[cursor] == '[' { - dst = append(dst, '[') - } else { - return nil, 0, errors.ErrExpected("expected [ character for array value", cursor) - } - cursor = skipWhiteSpace(src, cursor+1) - if src[cursor] == ']' { - dst = append(dst, ']') - return dst, cursor + 1, nil - } - indentNum++ - var err error - for { - dst = append(append(dst, '\n'), prefix...) - for i := 0; i < indentNum; i++ { - dst = append(dst, indentBytes...) - } - dst, cursor, err = indentValue(dst, src, indentNum, cursor, prefix, indentBytes, escape) - if err != nil { - return nil, 0, err - } - cursor = skipWhiteSpace(src, cursor) - switch src[cursor] { - case ']': - dst = append(append(dst, '\n'), prefix...) - for i := 0; i < indentNum-1; i++ { - dst = append(dst, indentBytes...) - } - dst = append(dst, ']') - cursor++ - return dst, cursor, nil - case ',': - dst = append(dst, ',') - default: - return nil, 0, errors.ErrSyntax( - fmt.Sprintf("invalid character '%c' after array value", src[cursor]), - cursor+1, - ) - } - cursor++ - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/int.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/int.go deleted file mode 100644 index 3a3482d5..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/int.go +++ /dev/null @@ -1,130 +0,0 @@ -package encoder - -import ( - "unsafe" -) - -var endianness int - -func init() { - var b [2]byte - *(*uint16)(unsafe.Pointer(&b)) = uint16(0xABCD) - - switch b[0] { - case 0xCD: - endianness = 0 // LE - case 0xAB: - endianness = 1 // BE - default: - panic("could not determine endianness") - } -} - -// "00010203...96979899" cast to []uint16 -var intLELookup = [100]uint16{ - 0x3030, 0x3130, 0x3230, 0x3330, 0x3430, 0x3530, 0x3630, 0x3730, 0x3830, 0x3930, - 0x3031, 0x3131, 0x3231, 0x3331, 0x3431, 0x3531, 0x3631, 0x3731, 0x3831, 0x3931, - 0x3032, 0x3132, 0x3232, 0x3332, 0x3432, 0x3532, 0x3632, 0x3732, 0x3832, 0x3932, - 0x3033, 0x3133, 0x3233, 0x3333, 0x3433, 0x3533, 0x3633, 0x3733, 0x3833, 0x3933, - 0x3034, 0x3134, 0x3234, 0x3334, 0x3434, 0x3534, 0x3634, 0x3734, 0x3834, 0x3934, - 0x3035, 0x3135, 0x3235, 0x3335, 0x3435, 0x3535, 0x3635, 0x3735, 0x3835, 0x3935, - 0x3036, 0x3136, 0x3236, 0x3336, 0x3436, 0x3536, 0x3636, 0x3736, 0x3836, 0x3936, - 0x3037, 0x3137, 0x3237, 0x3337, 0x3437, 0x3537, 0x3637, 0x3737, 0x3837, 0x3937, - 0x3038, 0x3138, 0x3238, 0x3338, 0x3438, 0x3538, 0x3638, 0x3738, 0x3838, 0x3938, - 0x3039, 0x3139, 0x3239, 0x3339, 0x3439, 0x3539, 0x3639, 0x3739, 0x3839, 0x3939, -} - -var intBELookup = [100]uint16{ - 0x3030, 0x3031, 0x3032, 0x3033, 0x3034, 0x3035, 0x3036, 0x3037, 0x3038, 0x3039, - 0x3130, 0x3131, 0x3132, 0x3133, 0x3134, 0x3135, 0x3136, 0x3137, 0x3138, 0x3139, - 0x3230, 0x3231, 0x3232, 0x3233, 0x3234, 0x3235, 0x3236, 0x3237, 0x3238, 0x3239, - 0x3330, 0x3331, 0x3332, 0x3333, 0x3334, 0x3335, 0x3336, 0x3337, 0x3338, 0x3339, - 0x3430, 0x3431, 0x3432, 0x3433, 0x3434, 0x3435, 0x3436, 0x3437, 0x3438, 0x3439, - 0x3530, 0x3531, 0x3532, 0x3533, 0x3534, 0x3535, 0x3536, 0x3537, 0x3538, 0x3539, - 0x3630, 0x3631, 0x3632, 0x3633, 0x3634, 0x3635, 0x3636, 0x3637, 0x3638, 0x3639, - 0x3730, 0x3731, 0x3732, 0x3733, 0x3734, 0x3735, 0x3736, 0x3737, 0x3738, 0x3739, - 0x3830, 0x3831, 0x3832, 0x3833, 0x3834, 0x3835, 0x3836, 0x3837, 0x3838, 0x3839, - 0x3930, 0x3931, 0x3932, 0x3933, 0x3934, 0x3935, 0x3936, 0x3937, 0x3938, 0x3939, -} - -var intLookup = [2]*[100]uint16{&intLELookup, &intBELookup} - -func numMask(numBitSize uint8) uint64 { - return 1<>(code.NumBitSize-1))&1 == 1 - if !negative { - if n < 10 { - return append(out, byte(n+'0')) - } else if n < 100 { - u := intLELookup[n] - return append(out, byte(u), byte(u>>8)) - } - } else { - n = -n & mask - } - - lookup := intLookup[endianness] - - var b [22]byte - u := (*[11]uint16)(unsafe.Pointer(&b)) - i := 11 - - for n >= 100 { - j := n % 100 - n /= 100 - i-- - u[i] = lookup[j] - } - - i-- - u[i] = lookup[n] - - i *= 2 // convert to byte index - if n < 10 { - i++ // remove leading zero - } - if negative { - i-- - b[i] = '-' - } - - return append(out, b[i:]...) -} - -func AppendUint(_ *RuntimeContext, out []byte, u64 uint64, code *Opcode) []byte { - mask := numMask(code.NumBitSize) - n := u64 & mask - if n < 10 { - return append(out, byte(n+'0')) - } else if n < 100 { - u := intLELookup[n] - return append(out, byte(u), byte(u>>8)) - } - - lookup := intLookup[endianness] - - var b [22]byte - u := (*[11]uint16)(unsafe.Pointer(&b)) - i := 11 - - for n >= 100 { - j := n % 100 - n /= 100 - i-- - u[i] = lookup[j] - } - - i-- - u[i] = lookup[n] - - i *= 2 // convert to byte index - if n < 10 { - i++ // remove leading zero - } - return append(out, b[i:]...) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map112.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map112.go deleted file mode 100644 index 31858d00..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map112.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !go1.13 - -package encoder - -import "unsafe" - -//go:linkname MapIterValue reflect.mapitervalue -func MapIterValue(it unsafe.Pointer) unsafe.Pointer diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map113.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map113.go deleted file mode 100644 index f49c27be..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map113.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build go1.13 - -package encoder - -import "unsafe" - -//go:linkname MapIterValue reflect.mapiterelem -func MapIterValue(it unsafe.Pointer) unsafe.Pointer diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/opcode.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/opcode.go deleted file mode 100644 index c23a90b2..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/opcode.go +++ /dev/null @@ -1,766 +0,0 @@ -package encoder - -import ( - "fmt" - "strings" - "unsafe" - - "github.com/goccy/go-json/internal/runtime" -) - -const uintptrSize = 4 << (^uintptr(0) >> 63) - -type OpFlags uint16 - -const ( - AnonymousHeadFlags OpFlags = 1 << 0 - AnonymousKeyFlags OpFlags = 1 << 1 - IndirectFlags OpFlags = 1 << 2 - IsTaggedKeyFlags OpFlags = 1 << 3 - NilCheckFlags OpFlags = 1 << 4 - AddrForMarshalerFlags OpFlags = 1 << 5 - IsNextOpPtrTypeFlags OpFlags = 1 << 6 - IsNilableTypeFlags OpFlags = 1 << 7 - MarshalerContextFlags OpFlags = 1 << 8 -) - -type Opcode struct { - Op OpType // operation type - Idx uint32 // offset to access ptr - Next *Opcode // next opcode - End *Opcode // array/slice/struct/map end - NextField *Opcode // next struct field - Key string // struct field key - Offset uint32 // offset size from struct header - PtrNum uint8 // pointer number: e.g. double pointer is 2. - NumBitSize uint8 - Flags OpFlags - - Type *runtime.Type // go type - PrevField *Opcode // prev struct field - Jmp *CompiledCode // for recursive call - ElemIdx uint32 // offset to access array/slice/map elem - Length uint32 // offset to access slice/map length or array length - MapIter uint32 // offset to access map iterator - MapPos uint32 // offset to access position list for sorted map - Indent uint32 // indent number - Size uint32 // array/slice elem size - DisplayIdx uint32 // opcode index - DisplayKey string // key text to display -} - -func (c *Opcode) MaxIdx() uint32 { - max := uint32(0) - for _, value := range []uint32{ - c.Idx, - c.ElemIdx, - c.Length, - c.MapIter, - c.MapPos, - c.Size, - } { - if max < value { - max = value - } - } - return max -} - -func (c *Opcode) ToHeaderType(isString bool) OpType { - switch c.Op { - case OpInt: - if isString { - return OpStructHeadIntString - } - return OpStructHeadInt - case OpIntPtr: - if isString { - return OpStructHeadIntPtrString - } - return OpStructHeadIntPtr - case OpUint: - if isString { - return OpStructHeadUintString - } - return OpStructHeadUint - case OpUintPtr: - if isString { - return OpStructHeadUintPtrString - } - return OpStructHeadUintPtr - case OpFloat32: - if isString { - return OpStructHeadFloat32String - } - return OpStructHeadFloat32 - case OpFloat32Ptr: - if isString { - return OpStructHeadFloat32PtrString - } - return OpStructHeadFloat32Ptr - case OpFloat64: - if isString { - return OpStructHeadFloat64String - } - return OpStructHeadFloat64 - case OpFloat64Ptr: - if isString { - return OpStructHeadFloat64PtrString - } - return OpStructHeadFloat64Ptr - case OpString: - if isString { - return OpStructHeadStringString - } - return OpStructHeadString - case OpStringPtr: - if isString { - return OpStructHeadStringPtrString - } - return OpStructHeadStringPtr - case OpNumber: - if isString { - return OpStructHeadNumberString - } - return OpStructHeadNumber - case OpNumberPtr: - if isString { - return OpStructHeadNumberPtrString - } - return OpStructHeadNumberPtr - case OpBool: - if isString { - return OpStructHeadBoolString - } - return OpStructHeadBool - case OpBoolPtr: - if isString { - return OpStructHeadBoolPtrString - } - return OpStructHeadBoolPtr - case OpBytes: - return OpStructHeadBytes - case OpBytesPtr: - return OpStructHeadBytesPtr - case OpMap: - return OpStructHeadMap - case OpMapPtr: - c.Op = OpMap - return OpStructHeadMapPtr - case OpArray: - return OpStructHeadArray - case OpArrayPtr: - c.Op = OpArray - return OpStructHeadArrayPtr - case OpSlice: - return OpStructHeadSlice - case OpSlicePtr: - c.Op = OpSlice - return OpStructHeadSlicePtr - case OpMarshalJSON: - return OpStructHeadMarshalJSON - case OpMarshalJSONPtr: - return OpStructHeadMarshalJSONPtr - case OpMarshalText: - return OpStructHeadMarshalText - case OpMarshalTextPtr: - return OpStructHeadMarshalTextPtr - } - return OpStructHead -} - -func (c *Opcode) ToFieldType(isString bool) OpType { - switch c.Op { - case OpInt: - if isString { - return OpStructFieldIntString - } - return OpStructFieldInt - case OpIntPtr: - if isString { - return OpStructFieldIntPtrString - } - return OpStructFieldIntPtr - case OpUint: - if isString { - return OpStructFieldUintString - } - return OpStructFieldUint - case OpUintPtr: - if isString { - return OpStructFieldUintPtrString - } - return OpStructFieldUintPtr - case OpFloat32: - if isString { - return OpStructFieldFloat32String - } - return OpStructFieldFloat32 - case OpFloat32Ptr: - if isString { - return OpStructFieldFloat32PtrString - } - return OpStructFieldFloat32Ptr - case OpFloat64: - if isString { - return OpStructFieldFloat64String - } - return OpStructFieldFloat64 - case OpFloat64Ptr: - if isString { - return OpStructFieldFloat64PtrString - } - return OpStructFieldFloat64Ptr - case OpString: - if isString { - return OpStructFieldStringString - } - return OpStructFieldString - case OpStringPtr: - if isString { - return OpStructFieldStringPtrString - } - return OpStructFieldStringPtr - case OpNumber: - if isString { - return OpStructFieldNumberString - } - return OpStructFieldNumber - case OpNumberPtr: - if isString { - return OpStructFieldNumberPtrString - } - return OpStructFieldNumberPtr - case OpBool: - if isString { - return OpStructFieldBoolString - } - return OpStructFieldBool - case OpBoolPtr: - if isString { - return OpStructFieldBoolPtrString - } - return OpStructFieldBoolPtr - case OpBytes: - return OpStructFieldBytes - case OpBytesPtr: - return OpStructFieldBytesPtr - case OpMap: - return OpStructFieldMap - case OpMapPtr: - c.Op = OpMap - return OpStructFieldMapPtr - case OpArray: - return OpStructFieldArray - case OpArrayPtr: - c.Op = OpArray - return OpStructFieldArrayPtr - case OpSlice: - return OpStructFieldSlice - case OpSlicePtr: - c.Op = OpSlice - return OpStructFieldSlicePtr - case OpMarshalJSON: - return OpStructFieldMarshalJSON - case OpMarshalJSONPtr: - return OpStructFieldMarshalJSONPtr - case OpMarshalText: - return OpStructFieldMarshalText - case OpMarshalTextPtr: - return OpStructFieldMarshalTextPtr - } - return OpStructField -} - -func newOpCode(ctx *compileContext, op OpType) *Opcode { - return newOpCodeWithNext(ctx, op, newEndOp(ctx)) -} - -func opcodeOffset(idx int) uint32 { - return uint32(idx) * uintptrSize -} - -func copyOpcode(code *Opcode) *Opcode { - codeMap := map[uintptr]*Opcode{} - return code.copy(codeMap) -} - -func setTotalLengthToInterfaceOp(code *Opcode) { - c := code - for c.Op != OpEnd && c.Op != OpInterfaceEnd { - if c.Op == OpInterface { - c.Length = uint32(code.TotalLength()) - } - switch c.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - c = c.End - default: - c = c.Next - } - } -} - -func ToEndCode(code *Opcode) *Opcode { - c := code - for c.Op != OpEnd && c.Op != OpInterfaceEnd { - switch c.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - c = c.End - default: - c = c.Next - } - } - return c -} - -func copyToInterfaceOpcode(code *Opcode) *Opcode { - copied := copyOpcode(code) - c := copied - c = ToEndCode(c) - c.Idx += uintptrSize - c.ElemIdx = c.Idx + uintptrSize - c.Length = c.Idx + 2*uintptrSize - c.Op = OpInterfaceEnd - return copied -} - -func newOpCodeWithNext(ctx *compileContext, op OpType, next *Opcode) *Opcode { - return &Opcode{ - Op: op, - Idx: opcodeOffset(ctx.ptrIndex), - Next: next, - Type: ctx.typ, - DisplayIdx: ctx.opcodeIndex, - Indent: ctx.indent, - } -} - -func newEndOp(ctx *compileContext) *Opcode { - return newOpCodeWithNext(ctx, OpEnd, nil) -} - -func (c *Opcode) copy(codeMap map[uintptr]*Opcode) *Opcode { - if c == nil { - return nil - } - addr := uintptr(unsafe.Pointer(c)) - if code, exists := codeMap[addr]; exists { - return code - } - copied := &Opcode{ - Op: c.Op, - Key: c.Key, - PtrNum: c.PtrNum, - NumBitSize: c.NumBitSize, - Flags: c.Flags, - Idx: c.Idx, - Offset: c.Offset, - Type: c.Type, - DisplayIdx: c.DisplayIdx, - DisplayKey: c.DisplayKey, - ElemIdx: c.ElemIdx, - Length: c.Length, - MapIter: c.MapIter, - MapPos: c.MapPos, - Size: c.Size, - Indent: c.Indent, - } - codeMap[addr] = copied - copied.End = c.End.copy(codeMap) - copied.PrevField = c.PrevField.copy(codeMap) - copied.NextField = c.NextField.copy(codeMap) - copied.Next = c.Next.copy(codeMap) - copied.Jmp = c.Jmp - return copied -} - -func (c *Opcode) BeforeLastCode() *Opcode { - code := c - for { - var nextCode *Opcode - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - nextCode = code.End - default: - nextCode = code.Next - } - if nextCode.Op == OpEnd { - return code - } - code = nextCode - } -} - -func (c *Opcode) TotalLength() int { - var idx int - code := c - for code.Op != OpEnd && code.Op != OpInterfaceEnd { - maxIdx := int(code.MaxIdx() / uintptrSize) - if idx < maxIdx { - idx = maxIdx - } - if code.Op == OpRecursiveEnd { - break - } - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - code = code.End - default: - code = code.Next - } - } - maxIdx := int(code.MaxIdx() / uintptrSize) - if idx < maxIdx { - idx = maxIdx - } - return idx + 1 -} - -func (c *Opcode) decOpcodeIndex() { - for code := c; code.Op != OpEnd; { - code.DisplayIdx-- - if code.Idx > 0 { - code.Idx -= uintptrSize - } - if code.ElemIdx > 0 { - code.ElemIdx -= uintptrSize - } - if code.MapIter > 0 { - code.MapIter -= uintptrSize - } - if code.Length > 0 && code.Op.CodeType() != CodeArrayHead && code.Op.CodeType() != CodeArrayElem { - code.Length -= uintptrSize - } - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - code = code.End - default: - code = code.Next - } - } -} - -func (c *Opcode) decIndent() { - for code := c; code.Op != OpEnd; { - code.Indent-- - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - code = code.End - default: - code = code.Next - } - } -} - -func (c *Opcode) dumpHead(code *Opcode) string { - var length uint32 - if code.Op.CodeType() == CodeArrayHead { - length = code.Length - } else { - length = code.Length / uintptrSize - } - return fmt.Sprintf( - `[%d]%s%s ([idx:%d][elemIdx:%d][length:%d])`, - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - code.ElemIdx/uintptrSize, - length, - ) -} - -func (c *Opcode) dumpMapHead(code *Opcode) string { - return fmt.Sprintf( - `[%d]%s%s ([idx:%d][elemIdx:%d][length:%d][mapIter:%d])`, - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - code.ElemIdx/uintptrSize, - code.Length/uintptrSize, - code.MapIter/uintptrSize, - ) -} - -func (c *Opcode) dumpMapEnd(code *Opcode) string { - return fmt.Sprintf( - `[%d]%s%s ([idx:%d][mapPos:%d][length:%d])`, - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - code.MapPos/uintptrSize, - code.Length/uintptrSize, - ) -} - -func (c *Opcode) dumpElem(code *Opcode) string { - var length uint32 - if code.Op.CodeType() == CodeArrayElem { - length = code.Length - } else { - length = code.Length / uintptrSize - } - return fmt.Sprintf( - `[%d]%s%s ([idx:%d][elemIdx:%d][length:%d][size:%d])`, - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - code.ElemIdx/uintptrSize, - length, - code.Size, - ) -} - -func (c *Opcode) dumpField(code *Opcode) string { - return fmt.Sprintf( - `[%d]%s%s ([idx:%d][key:%s][offset:%d])`, - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - code.DisplayKey, - code.Offset, - ) -} - -func (c *Opcode) dumpKey(code *Opcode) string { - return fmt.Sprintf( - `[%d]%s%s ([idx:%d][elemIdx:%d][length:%d][mapIter:%d])`, - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - code.ElemIdx/uintptrSize, - code.Length/uintptrSize, - code.MapIter/uintptrSize, - ) -} - -func (c *Opcode) dumpValue(code *Opcode) string { - return fmt.Sprintf( - `[%d]%s%s ([idx:%d][mapIter:%d])`, - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - code.MapIter/uintptrSize, - ) -} - -func (c *Opcode) Dump() string { - codes := []string{} - for code := c; code.Op != OpEnd && code.Op != OpInterfaceEnd; { - switch code.Op.CodeType() { - case CodeSliceHead: - codes = append(codes, c.dumpHead(code)) - code = code.Next - case CodeMapHead: - codes = append(codes, c.dumpMapHead(code)) - code = code.Next - case CodeArrayElem, CodeSliceElem: - codes = append(codes, c.dumpElem(code)) - code = code.End - case CodeMapKey: - codes = append(codes, c.dumpKey(code)) - code = code.End - case CodeMapValue: - codes = append(codes, c.dumpValue(code)) - code = code.Next - case CodeMapEnd: - codes = append(codes, c.dumpMapEnd(code)) - code = code.Next - case CodeStructField: - codes = append(codes, c.dumpField(code)) - code = code.Next - case CodeStructEnd: - codes = append(codes, c.dumpField(code)) - code = code.Next - default: - codes = append(codes, fmt.Sprintf( - "[%d]%s%s ([idx:%d])", - code.DisplayIdx, - strings.Repeat("-", int(code.Indent)), - code.Op, - code.Idx/uintptrSize, - )) - code = code.Next - } - } - return strings.Join(codes, "\n") -} - -func prevField(code *Opcode, removedFields map[*Opcode]struct{}) *Opcode { - if _, exists := removedFields[code]; exists { - return prevField(code.PrevField, removedFields) - } - return code -} - -func nextField(code *Opcode, removedFields map[*Opcode]struct{}) *Opcode { - if _, exists := removedFields[code]; exists { - return nextField(code.NextField, removedFields) - } - return code -} - -func linkPrevToNextField(cur *Opcode, removedFields map[*Opcode]struct{}) { - prev := prevField(cur.PrevField, removedFields) - prev.NextField = nextField(cur.NextField, removedFields) - code := prev - fcode := cur - for { - var nextCode *Opcode - switch code.Op.CodeType() { - case CodeArrayElem, CodeSliceElem, CodeMapKey: - nextCode = code.End - default: - nextCode = code.Next - } - if nextCode == fcode { - code.Next = fcode.Next - break - } else if nextCode.Op == OpEnd { - break - } - code = nextCode - } -} - -func newSliceHeaderCode(ctx *compileContext) *Opcode { - idx := opcodeOffset(ctx.ptrIndex) - ctx.incPtrIndex() - elemIdx := opcodeOffset(ctx.ptrIndex) - ctx.incPtrIndex() - length := opcodeOffset(ctx.ptrIndex) - return &Opcode{ - Op: OpSlice, - Idx: idx, - DisplayIdx: ctx.opcodeIndex, - ElemIdx: elemIdx, - Length: length, - Indent: ctx.indent, - } -} - -func newSliceElemCode(ctx *compileContext, head *Opcode, size uintptr) *Opcode { - return &Opcode{ - Op: OpSliceElem, - Idx: head.Idx, - DisplayIdx: ctx.opcodeIndex, - ElemIdx: head.ElemIdx, - Length: head.Length, - Indent: ctx.indent, - Size: uint32(size), - } -} - -func newArrayHeaderCode(ctx *compileContext, alen int) *Opcode { - idx := opcodeOffset(ctx.ptrIndex) - ctx.incPtrIndex() - elemIdx := opcodeOffset(ctx.ptrIndex) - return &Opcode{ - Op: OpArray, - Idx: idx, - DisplayIdx: ctx.opcodeIndex, - ElemIdx: elemIdx, - Indent: ctx.indent, - Length: uint32(alen), - } -} - -func newArrayElemCode(ctx *compileContext, head *Opcode, length int, size uintptr) *Opcode { - return &Opcode{ - Op: OpArrayElem, - Idx: head.Idx, - DisplayIdx: ctx.opcodeIndex, - ElemIdx: head.ElemIdx, - Length: uint32(length), - Indent: ctx.indent, - Size: uint32(size), - } -} - -func newMapHeaderCode(ctx *compileContext) *Opcode { - idx := opcodeOffset(ctx.ptrIndex) - ctx.incPtrIndex() - elemIdx := opcodeOffset(ctx.ptrIndex) - ctx.incPtrIndex() - length := opcodeOffset(ctx.ptrIndex) - ctx.incPtrIndex() - mapIter := opcodeOffset(ctx.ptrIndex) - return &Opcode{ - Op: OpMap, - Idx: idx, - Type: ctx.typ, - DisplayIdx: ctx.opcodeIndex, - ElemIdx: elemIdx, - Length: length, - MapIter: mapIter, - Indent: ctx.indent, - } -} - -func newMapKeyCode(ctx *compileContext, head *Opcode) *Opcode { - return &Opcode{ - Op: OpMapKey, - Idx: opcodeOffset(ctx.ptrIndex), - DisplayIdx: ctx.opcodeIndex, - ElemIdx: head.ElemIdx, - Length: head.Length, - MapIter: head.MapIter, - Indent: ctx.indent, - } -} - -func newMapValueCode(ctx *compileContext, head *Opcode) *Opcode { - return &Opcode{ - Op: OpMapValue, - Idx: opcodeOffset(ctx.ptrIndex), - DisplayIdx: ctx.opcodeIndex, - ElemIdx: head.ElemIdx, - Length: head.Length, - MapIter: head.MapIter, - Indent: ctx.indent, - } -} - -func newMapEndCode(ctx *compileContext, head *Opcode) *Opcode { - mapPos := opcodeOffset(ctx.ptrIndex) - ctx.incPtrIndex() - idx := opcodeOffset(ctx.ptrIndex) - return &Opcode{ - Op: OpMapEnd, - Idx: idx, - Next: newEndOp(ctx), - DisplayIdx: ctx.opcodeIndex, - Length: head.Length, - MapPos: mapPos, - Indent: ctx.indent, - } -} - -func newInterfaceCode(ctx *compileContext) *Opcode { - return &Opcode{ - Op: OpInterface, - Idx: opcodeOffset(ctx.ptrIndex), - Next: newEndOp(ctx), - Type: ctx.typ, - DisplayIdx: ctx.opcodeIndex, - Indent: ctx.indent, - } -} - -func newRecursiveCode(ctx *compileContext, jmp *CompiledCode) *Opcode { - return &Opcode{ - Op: OpRecursive, - Idx: opcodeOffset(ctx.ptrIndex), - Next: newEndOp(ctx), - Type: ctx.typ, - DisplayIdx: ctx.opcodeIndex, - Indent: ctx.indent, - Jmp: jmp, - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/option.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/option.go deleted file mode 100644 index f5f1f044..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/option.go +++ /dev/null @@ -1,41 +0,0 @@ -package encoder - -import "context" - -type OptionFlag uint8 - -const ( - HTMLEscapeOption OptionFlag = 1 << iota - IndentOption - UnorderedMapOption - DebugOption - ColorizeOption - ContextOption -) - -type Option struct { - Flag OptionFlag - ColorScheme *ColorScheme - Context context.Context -} - -type EncodeFormat struct { - Header string - Footer string -} - -type EncodeFormatScheme struct { - Int EncodeFormat - Uint EncodeFormat - Float EncodeFormat - Bool EncodeFormat - String EncodeFormat - Binary EncodeFormat - ObjectKey EncodeFormat - Null EncodeFormat -} - -type ( - ColorScheme = EncodeFormatScheme - ColorFormat = EncodeFormat -) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/optype.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/optype.go deleted file mode 100644 index 335fc043..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/optype.go +++ /dev/null @@ -1,934 +0,0 @@ -// Code generated by internal/cmd/generator. DO NOT EDIT! -package encoder - -import ( - "strings" -) - -type CodeType int - -const ( - CodeOp CodeType = 0 - CodeArrayHead CodeType = 1 - CodeArrayElem CodeType = 2 - CodeSliceHead CodeType = 3 - CodeSliceElem CodeType = 4 - CodeMapHead CodeType = 5 - CodeMapKey CodeType = 6 - CodeMapValue CodeType = 7 - CodeMapEnd CodeType = 8 - CodeRecursive CodeType = 9 - CodeStructField CodeType = 10 - CodeStructEnd CodeType = 11 -) - -var opTypeStrings = [401]string{ - "End", - "Interface", - "Ptr", - "SliceElem", - "SliceEnd", - "ArrayElem", - "ArrayEnd", - "MapKey", - "MapValue", - "MapEnd", - "Recursive", - "RecursivePtr", - "RecursiveEnd", - "InterfaceEnd", - "StructAnonymousEnd", - "Int", - "Uint", - "Float32", - "Float64", - "Bool", - "String", - "Bytes", - "Number", - "Array", - "Map", - "Slice", - "Struct", - "MarshalJSON", - "MarshalText", - "IntString", - "UintString", - "Float32String", - "Float64String", - "BoolString", - "StringString", - "NumberString", - "IntPtr", - "UintPtr", - "Float32Ptr", - "Float64Ptr", - "BoolPtr", - "StringPtr", - "BytesPtr", - "NumberPtr", - "ArrayPtr", - "MapPtr", - "SlicePtr", - "MarshalJSONPtr", - "MarshalTextPtr", - "InterfacePtr", - "IntPtrString", - "UintPtrString", - "Float32PtrString", - "Float64PtrString", - "BoolPtrString", - "StringPtrString", - "NumberPtrString", - "StructHeadInt", - "StructHeadOmitEmptyInt", - "StructPtrHeadInt", - "StructPtrHeadOmitEmptyInt", - "StructHeadUint", - "StructHeadOmitEmptyUint", - "StructPtrHeadUint", - "StructPtrHeadOmitEmptyUint", - "StructHeadFloat32", - "StructHeadOmitEmptyFloat32", - "StructPtrHeadFloat32", - "StructPtrHeadOmitEmptyFloat32", - "StructHeadFloat64", - "StructHeadOmitEmptyFloat64", - "StructPtrHeadFloat64", - "StructPtrHeadOmitEmptyFloat64", - "StructHeadBool", - "StructHeadOmitEmptyBool", - "StructPtrHeadBool", - "StructPtrHeadOmitEmptyBool", - "StructHeadString", - "StructHeadOmitEmptyString", - "StructPtrHeadString", - "StructPtrHeadOmitEmptyString", - "StructHeadBytes", - "StructHeadOmitEmptyBytes", - "StructPtrHeadBytes", - "StructPtrHeadOmitEmptyBytes", - "StructHeadNumber", - "StructHeadOmitEmptyNumber", - "StructPtrHeadNumber", - "StructPtrHeadOmitEmptyNumber", - "StructHeadArray", - "StructHeadOmitEmptyArray", - "StructPtrHeadArray", - "StructPtrHeadOmitEmptyArray", - "StructHeadMap", - "StructHeadOmitEmptyMap", - "StructPtrHeadMap", - "StructPtrHeadOmitEmptyMap", - "StructHeadSlice", - "StructHeadOmitEmptySlice", - "StructPtrHeadSlice", - "StructPtrHeadOmitEmptySlice", - "StructHeadStruct", - "StructHeadOmitEmptyStruct", - "StructPtrHeadStruct", - "StructPtrHeadOmitEmptyStruct", - "StructHeadMarshalJSON", - "StructHeadOmitEmptyMarshalJSON", - "StructPtrHeadMarshalJSON", - "StructPtrHeadOmitEmptyMarshalJSON", - "StructHeadMarshalText", - "StructHeadOmitEmptyMarshalText", - "StructPtrHeadMarshalText", - "StructPtrHeadOmitEmptyMarshalText", - "StructHeadIntString", - "StructHeadOmitEmptyIntString", - "StructPtrHeadIntString", - "StructPtrHeadOmitEmptyIntString", - "StructHeadUintString", - "StructHeadOmitEmptyUintString", - "StructPtrHeadUintString", - "StructPtrHeadOmitEmptyUintString", - "StructHeadFloat32String", - "StructHeadOmitEmptyFloat32String", - "StructPtrHeadFloat32String", - "StructPtrHeadOmitEmptyFloat32String", - "StructHeadFloat64String", - "StructHeadOmitEmptyFloat64String", - "StructPtrHeadFloat64String", - "StructPtrHeadOmitEmptyFloat64String", - "StructHeadBoolString", - "StructHeadOmitEmptyBoolString", - "StructPtrHeadBoolString", - "StructPtrHeadOmitEmptyBoolString", - "StructHeadStringString", - "StructHeadOmitEmptyStringString", - "StructPtrHeadStringString", - "StructPtrHeadOmitEmptyStringString", - "StructHeadNumberString", - "StructHeadOmitEmptyNumberString", - "StructPtrHeadNumberString", - "StructPtrHeadOmitEmptyNumberString", - "StructHeadIntPtr", - "StructHeadOmitEmptyIntPtr", - "StructPtrHeadIntPtr", - "StructPtrHeadOmitEmptyIntPtr", - "StructHeadUintPtr", - "StructHeadOmitEmptyUintPtr", - "StructPtrHeadUintPtr", - "StructPtrHeadOmitEmptyUintPtr", - "StructHeadFloat32Ptr", - "StructHeadOmitEmptyFloat32Ptr", - "StructPtrHeadFloat32Ptr", - "StructPtrHeadOmitEmptyFloat32Ptr", - "StructHeadFloat64Ptr", - "StructHeadOmitEmptyFloat64Ptr", - "StructPtrHeadFloat64Ptr", - "StructPtrHeadOmitEmptyFloat64Ptr", - "StructHeadBoolPtr", - "StructHeadOmitEmptyBoolPtr", - "StructPtrHeadBoolPtr", - "StructPtrHeadOmitEmptyBoolPtr", - "StructHeadStringPtr", - "StructHeadOmitEmptyStringPtr", - "StructPtrHeadStringPtr", - "StructPtrHeadOmitEmptyStringPtr", - "StructHeadBytesPtr", - "StructHeadOmitEmptyBytesPtr", - "StructPtrHeadBytesPtr", - "StructPtrHeadOmitEmptyBytesPtr", - "StructHeadNumberPtr", - "StructHeadOmitEmptyNumberPtr", - "StructPtrHeadNumberPtr", - "StructPtrHeadOmitEmptyNumberPtr", - "StructHeadArrayPtr", - "StructHeadOmitEmptyArrayPtr", - "StructPtrHeadArrayPtr", - "StructPtrHeadOmitEmptyArrayPtr", - "StructHeadMapPtr", - "StructHeadOmitEmptyMapPtr", - "StructPtrHeadMapPtr", - "StructPtrHeadOmitEmptyMapPtr", - "StructHeadSlicePtr", - "StructHeadOmitEmptySlicePtr", - "StructPtrHeadSlicePtr", - "StructPtrHeadOmitEmptySlicePtr", - "StructHeadMarshalJSONPtr", - "StructHeadOmitEmptyMarshalJSONPtr", - "StructPtrHeadMarshalJSONPtr", - "StructPtrHeadOmitEmptyMarshalJSONPtr", - "StructHeadMarshalTextPtr", - "StructHeadOmitEmptyMarshalTextPtr", - "StructPtrHeadMarshalTextPtr", - "StructPtrHeadOmitEmptyMarshalTextPtr", - "StructHeadInterfacePtr", - "StructHeadOmitEmptyInterfacePtr", - "StructPtrHeadInterfacePtr", - "StructPtrHeadOmitEmptyInterfacePtr", - "StructHeadIntPtrString", - "StructHeadOmitEmptyIntPtrString", - "StructPtrHeadIntPtrString", - "StructPtrHeadOmitEmptyIntPtrString", - "StructHeadUintPtrString", - "StructHeadOmitEmptyUintPtrString", - "StructPtrHeadUintPtrString", - "StructPtrHeadOmitEmptyUintPtrString", - "StructHeadFloat32PtrString", - "StructHeadOmitEmptyFloat32PtrString", - "StructPtrHeadFloat32PtrString", - "StructPtrHeadOmitEmptyFloat32PtrString", - "StructHeadFloat64PtrString", - "StructHeadOmitEmptyFloat64PtrString", - "StructPtrHeadFloat64PtrString", - "StructPtrHeadOmitEmptyFloat64PtrString", - "StructHeadBoolPtrString", - "StructHeadOmitEmptyBoolPtrString", - "StructPtrHeadBoolPtrString", - "StructPtrHeadOmitEmptyBoolPtrString", - "StructHeadStringPtrString", - "StructHeadOmitEmptyStringPtrString", - "StructPtrHeadStringPtrString", - "StructPtrHeadOmitEmptyStringPtrString", - "StructHeadNumberPtrString", - "StructHeadOmitEmptyNumberPtrString", - "StructPtrHeadNumberPtrString", - "StructPtrHeadOmitEmptyNumberPtrString", - "StructHead", - "StructHeadOmitEmpty", - "StructPtrHead", - "StructPtrHeadOmitEmpty", - "StructFieldInt", - "StructFieldOmitEmptyInt", - "StructEndInt", - "StructEndOmitEmptyInt", - "StructFieldUint", - "StructFieldOmitEmptyUint", - "StructEndUint", - "StructEndOmitEmptyUint", - "StructFieldFloat32", - "StructFieldOmitEmptyFloat32", - "StructEndFloat32", - "StructEndOmitEmptyFloat32", - "StructFieldFloat64", - "StructFieldOmitEmptyFloat64", - "StructEndFloat64", - "StructEndOmitEmptyFloat64", - "StructFieldBool", - "StructFieldOmitEmptyBool", - "StructEndBool", - "StructEndOmitEmptyBool", - "StructFieldString", - "StructFieldOmitEmptyString", - "StructEndString", - "StructEndOmitEmptyString", - "StructFieldBytes", - "StructFieldOmitEmptyBytes", - "StructEndBytes", - "StructEndOmitEmptyBytes", - "StructFieldNumber", - "StructFieldOmitEmptyNumber", - "StructEndNumber", - "StructEndOmitEmptyNumber", - "StructFieldArray", - "StructFieldOmitEmptyArray", - "StructEndArray", - "StructEndOmitEmptyArray", - "StructFieldMap", - "StructFieldOmitEmptyMap", - "StructEndMap", - "StructEndOmitEmptyMap", - "StructFieldSlice", - "StructFieldOmitEmptySlice", - "StructEndSlice", - "StructEndOmitEmptySlice", - "StructFieldStruct", - "StructFieldOmitEmptyStruct", - "StructEndStruct", - "StructEndOmitEmptyStruct", - "StructFieldMarshalJSON", - "StructFieldOmitEmptyMarshalJSON", - "StructEndMarshalJSON", - "StructEndOmitEmptyMarshalJSON", - "StructFieldMarshalText", - "StructFieldOmitEmptyMarshalText", - "StructEndMarshalText", - "StructEndOmitEmptyMarshalText", - "StructFieldIntString", - "StructFieldOmitEmptyIntString", - "StructEndIntString", - "StructEndOmitEmptyIntString", - "StructFieldUintString", - "StructFieldOmitEmptyUintString", - "StructEndUintString", - "StructEndOmitEmptyUintString", - "StructFieldFloat32String", - "StructFieldOmitEmptyFloat32String", - "StructEndFloat32String", - "StructEndOmitEmptyFloat32String", - "StructFieldFloat64String", - "StructFieldOmitEmptyFloat64String", - "StructEndFloat64String", - "StructEndOmitEmptyFloat64String", - "StructFieldBoolString", - "StructFieldOmitEmptyBoolString", - "StructEndBoolString", - "StructEndOmitEmptyBoolString", - "StructFieldStringString", - "StructFieldOmitEmptyStringString", - "StructEndStringString", - "StructEndOmitEmptyStringString", - "StructFieldNumberString", - "StructFieldOmitEmptyNumberString", - "StructEndNumberString", - "StructEndOmitEmptyNumberString", - "StructFieldIntPtr", - "StructFieldOmitEmptyIntPtr", - "StructEndIntPtr", - "StructEndOmitEmptyIntPtr", - "StructFieldUintPtr", - "StructFieldOmitEmptyUintPtr", - "StructEndUintPtr", - "StructEndOmitEmptyUintPtr", - "StructFieldFloat32Ptr", - "StructFieldOmitEmptyFloat32Ptr", - "StructEndFloat32Ptr", - "StructEndOmitEmptyFloat32Ptr", - "StructFieldFloat64Ptr", - "StructFieldOmitEmptyFloat64Ptr", - "StructEndFloat64Ptr", - "StructEndOmitEmptyFloat64Ptr", - "StructFieldBoolPtr", - "StructFieldOmitEmptyBoolPtr", - "StructEndBoolPtr", - "StructEndOmitEmptyBoolPtr", - "StructFieldStringPtr", - "StructFieldOmitEmptyStringPtr", - "StructEndStringPtr", - "StructEndOmitEmptyStringPtr", - "StructFieldBytesPtr", - "StructFieldOmitEmptyBytesPtr", - "StructEndBytesPtr", - "StructEndOmitEmptyBytesPtr", - "StructFieldNumberPtr", - "StructFieldOmitEmptyNumberPtr", - "StructEndNumberPtr", - "StructEndOmitEmptyNumberPtr", - "StructFieldArrayPtr", - "StructFieldOmitEmptyArrayPtr", - "StructEndArrayPtr", - "StructEndOmitEmptyArrayPtr", - "StructFieldMapPtr", - "StructFieldOmitEmptyMapPtr", - "StructEndMapPtr", - "StructEndOmitEmptyMapPtr", - "StructFieldSlicePtr", - "StructFieldOmitEmptySlicePtr", - "StructEndSlicePtr", - "StructEndOmitEmptySlicePtr", - "StructFieldMarshalJSONPtr", - "StructFieldOmitEmptyMarshalJSONPtr", - "StructEndMarshalJSONPtr", - "StructEndOmitEmptyMarshalJSONPtr", - "StructFieldMarshalTextPtr", - "StructFieldOmitEmptyMarshalTextPtr", - "StructEndMarshalTextPtr", - "StructEndOmitEmptyMarshalTextPtr", - "StructFieldInterfacePtr", - "StructFieldOmitEmptyInterfacePtr", - "StructEndInterfacePtr", - "StructEndOmitEmptyInterfacePtr", - "StructFieldIntPtrString", - "StructFieldOmitEmptyIntPtrString", - "StructEndIntPtrString", - "StructEndOmitEmptyIntPtrString", - "StructFieldUintPtrString", - "StructFieldOmitEmptyUintPtrString", - "StructEndUintPtrString", - "StructEndOmitEmptyUintPtrString", - "StructFieldFloat32PtrString", - "StructFieldOmitEmptyFloat32PtrString", - "StructEndFloat32PtrString", - "StructEndOmitEmptyFloat32PtrString", - "StructFieldFloat64PtrString", - "StructFieldOmitEmptyFloat64PtrString", - "StructEndFloat64PtrString", - "StructEndOmitEmptyFloat64PtrString", - "StructFieldBoolPtrString", - "StructFieldOmitEmptyBoolPtrString", - "StructEndBoolPtrString", - "StructEndOmitEmptyBoolPtrString", - "StructFieldStringPtrString", - "StructFieldOmitEmptyStringPtrString", - "StructEndStringPtrString", - "StructEndOmitEmptyStringPtrString", - "StructFieldNumberPtrString", - "StructFieldOmitEmptyNumberPtrString", - "StructEndNumberPtrString", - "StructEndOmitEmptyNumberPtrString", - "StructField", - "StructFieldOmitEmpty", - "StructEnd", - "StructEndOmitEmpty", -} - -type OpType uint16 - -const ( - OpEnd OpType = 0 - OpInterface OpType = 1 - OpPtr OpType = 2 - OpSliceElem OpType = 3 - OpSliceEnd OpType = 4 - OpArrayElem OpType = 5 - OpArrayEnd OpType = 6 - OpMapKey OpType = 7 - OpMapValue OpType = 8 - OpMapEnd OpType = 9 - OpRecursive OpType = 10 - OpRecursivePtr OpType = 11 - OpRecursiveEnd OpType = 12 - OpInterfaceEnd OpType = 13 - OpStructAnonymousEnd OpType = 14 - OpInt OpType = 15 - OpUint OpType = 16 - OpFloat32 OpType = 17 - OpFloat64 OpType = 18 - OpBool OpType = 19 - OpString OpType = 20 - OpBytes OpType = 21 - OpNumber OpType = 22 - OpArray OpType = 23 - OpMap OpType = 24 - OpSlice OpType = 25 - OpStruct OpType = 26 - OpMarshalJSON OpType = 27 - OpMarshalText OpType = 28 - OpIntString OpType = 29 - OpUintString OpType = 30 - OpFloat32String OpType = 31 - OpFloat64String OpType = 32 - OpBoolString OpType = 33 - OpStringString OpType = 34 - OpNumberString OpType = 35 - OpIntPtr OpType = 36 - OpUintPtr OpType = 37 - OpFloat32Ptr OpType = 38 - OpFloat64Ptr OpType = 39 - OpBoolPtr OpType = 40 - OpStringPtr OpType = 41 - OpBytesPtr OpType = 42 - OpNumberPtr OpType = 43 - OpArrayPtr OpType = 44 - OpMapPtr OpType = 45 - OpSlicePtr OpType = 46 - OpMarshalJSONPtr OpType = 47 - OpMarshalTextPtr OpType = 48 - OpInterfacePtr OpType = 49 - OpIntPtrString OpType = 50 - OpUintPtrString OpType = 51 - OpFloat32PtrString OpType = 52 - OpFloat64PtrString OpType = 53 - OpBoolPtrString OpType = 54 - OpStringPtrString OpType = 55 - OpNumberPtrString OpType = 56 - OpStructHeadInt OpType = 57 - OpStructHeadOmitEmptyInt OpType = 58 - OpStructPtrHeadInt OpType = 59 - OpStructPtrHeadOmitEmptyInt OpType = 60 - OpStructHeadUint OpType = 61 - OpStructHeadOmitEmptyUint OpType = 62 - OpStructPtrHeadUint OpType = 63 - OpStructPtrHeadOmitEmptyUint OpType = 64 - OpStructHeadFloat32 OpType = 65 - OpStructHeadOmitEmptyFloat32 OpType = 66 - OpStructPtrHeadFloat32 OpType = 67 - OpStructPtrHeadOmitEmptyFloat32 OpType = 68 - OpStructHeadFloat64 OpType = 69 - OpStructHeadOmitEmptyFloat64 OpType = 70 - OpStructPtrHeadFloat64 OpType = 71 - OpStructPtrHeadOmitEmptyFloat64 OpType = 72 - OpStructHeadBool OpType = 73 - OpStructHeadOmitEmptyBool OpType = 74 - OpStructPtrHeadBool OpType = 75 - OpStructPtrHeadOmitEmptyBool OpType = 76 - OpStructHeadString OpType = 77 - OpStructHeadOmitEmptyString OpType = 78 - OpStructPtrHeadString OpType = 79 - OpStructPtrHeadOmitEmptyString OpType = 80 - OpStructHeadBytes OpType = 81 - OpStructHeadOmitEmptyBytes OpType = 82 - OpStructPtrHeadBytes OpType = 83 - OpStructPtrHeadOmitEmptyBytes OpType = 84 - OpStructHeadNumber OpType = 85 - OpStructHeadOmitEmptyNumber OpType = 86 - OpStructPtrHeadNumber OpType = 87 - OpStructPtrHeadOmitEmptyNumber OpType = 88 - OpStructHeadArray OpType = 89 - OpStructHeadOmitEmptyArray OpType = 90 - OpStructPtrHeadArray OpType = 91 - OpStructPtrHeadOmitEmptyArray OpType = 92 - OpStructHeadMap OpType = 93 - OpStructHeadOmitEmptyMap OpType = 94 - OpStructPtrHeadMap OpType = 95 - OpStructPtrHeadOmitEmptyMap OpType = 96 - OpStructHeadSlice OpType = 97 - OpStructHeadOmitEmptySlice OpType = 98 - OpStructPtrHeadSlice OpType = 99 - OpStructPtrHeadOmitEmptySlice OpType = 100 - OpStructHeadStruct OpType = 101 - OpStructHeadOmitEmptyStruct OpType = 102 - OpStructPtrHeadStruct OpType = 103 - OpStructPtrHeadOmitEmptyStruct OpType = 104 - OpStructHeadMarshalJSON OpType = 105 - OpStructHeadOmitEmptyMarshalJSON OpType = 106 - OpStructPtrHeadMarshalJSON OpType = 107 - OpStructPtrHeadOmitEmptyMarshalJSON OpType = 108 - OpStructHeadMarshalText OpType = 109 - OpStructHeadOmitEmptyMarshalText OpType = 110 - OpStructPtrHeadMarshalText OpType = 111 - OpStructPtrHeadOmitEmptyMarshalText OpType = 112 - OpStructHeadIntString OpType = 113 - OpStructHeadOmitEmptyIntString OpType = 114 - OpStructPtrHeadIntString OpType = 115 - OpStructPtrHeadOmitEmptyIntString OpType = 116 - OpStructHeadUintString OpType = 117 - OpStructHeadOmitEmptyUintString OpType = 118 - OpStructPtrHeadUintString OpType = 119 - OpStructPtrHeadOmitEmptyUintString OpType = 120 - OpStructHeadFloat32String OpType = 121 - OpStructHeadOmitEmptyFloat32String OpType = 122 - OpStructPtrHeadFloat32String OpType = 123 - OpStructPtrHeadOmitEmptyFloat32String OpType = 124 - OpStructHeadFloat64String OpType = 125 - OpStructHeadOmitEmptyFloat64String OpType = 126 - OpStructPtrHeadFloat64String OpType = 127 - OpStructPtrHeadOmitEmptyFloat64String OpType = 128 - OpStructHeadBoolString OpType = 129 - OpStructHeadOmitEmptyBoolString OpType = 130 - OpStructPtrHeadBoolString OpType = 131 - OpStructPtrHeadOmitEmptyBoolString OpType = 132 - OpStructHeadStringString OpType = 133 - OpStructHeadOmitEmptyStringString OpType = 134 - OpStructPtrHeadStringString OpType = 135 - OpStructPtrHeadOmitEmptyStringString OpType = 136 - OpStructHeadNumberString OpType = 137 - OpStructHeadOmitEmptyNumberString OpType = 138 - OpStructPtrHeadNumberString OpType = 139 - OpStructPtrHeadOmitEmptyNumberString OpType = 140 - OpStructHeadIntPtr OpType = 141 - OpStructHeadOmitEmptyIntPtr OpType = 142 - OpStructPtrHeadIntPtr OpType = 143 - OpStructPtrHeadOmitEmptyIntPtr OpType = 144 - OpStructHeadUintPtr OpType = 145 - OpStructHeadOmitEmptyUintPtr OpType = 146 - OpStructPtrHeadUintPtr OpType = 147 - OpStructPtrHeadOmitEmptyUintPtr OpType = 148 - OpStructHeadFloat32Ptr OpType = 149 - OpStructHeadOmitEmptyFloat32Ptr OpType = 150 - OpStructPtrHeadFloat32Ptr OpType = 151 - OpStructPtrHeadOmitEmptyFloat32Ptr OpType = 152 - OpStructHeadFloat64Ptr OpType = 153 - OpStructHeadOmitEmptyFloat64Ptr OpType = 154 - OpStructPtrHeadFloat64Ptr OpType = 155 - OpStructPtrHeadOmitEmptyFloat64Ptr OpType = 156 - OpStructHeadBoolPtr OpType = 157 - OpStructHeadOmitEmptyBoolPtr OpType = 158 - OpStructPtrHeadBoolPtr OpType = 159 - OpStructPtrHeadOmitEmptyBoolPtr OpType = 160 - OpStructHeadStringPtr OpType = 161 - OpStructHeadOmitEmptyStringPtr OpType = 162 - OpStructPtrHeadStringPtr OpType = 163 - OpStructPtrHeadOmitEmptyStringPtr OpType = 164 - OpStructHeadBytesPtr OpType = 165 - OpStructHeadOmitEmptyBytesPtr OpType = 166 - OpStructPtrHeadBytesPtr OpType = 167 - OpStructPtrHeadOmitEmptyBytesPtr OpType = 168 - OpStructHeadNumberPtr OpType = 169 - OpStructHeadOmitEmptyNumberPtr OpType = 170 - OpStructPtrHeadNumberPtr OpType = 171 - OpStructPtrHeadOmitEmptyNumberPtr OpType = 172 - OpStructHeadArrayPtr OpType = 173 - OpStructHeadOmitEmptyArrayPtr OpType = 174 - OpStructPtrHeadArrayPtr OpType = 175 - OpStructPtrHeadOmitEmptyArrayPtr OpType = 176 - OpStructHeadMapPtr OpType = 177 - OpStructHeadOmitEmptyMapPtr OpType = 178 - OpStructPtrHeadMapPtr OpType = 179 - OpStructPtrHeadOmitEmptyMapPtr OpType = 180 - OpStructHeadSlicePtr OpType = 181 - OpStructHeadOmitEmptySlicePtr OpType = 182 - OpStructPtrHeadSlicePtr OpType = 183 - OpStructPtrHeadOmitEmptySlicePtr OpType = 184 - OpStructHeadMarshalJSONPtr OpType = 185 - OpStructHeadOmitEmptyMarshalJSONPtr OpType = 186 - OpStructPtrHeadMarshalJSONPtr OpType = 187 - OpStructPtrHeadOmitEmptyMarshalJSONPtr OpType = 188 - OpStructHeadMarshalTextPtr OpType = 189 - OpStructHeadOmitEmptyMarshalTextPtr OpType = 190 - OpStructPtrHeadMarshalTextPtr OpType = 191 - OpStructPtrHeadOmitEmptyMarshalTextPtr OpType = 192 - OpStructHeadInterfacePtr OpType = 193 - OpStructHeadOmitEmptyInterfacePtr OpType = 194 - OpStructPtrHeadInterfacePtr OpType = 195 - OpStructPtrHeadOmitEmptyInterfacePtr OpType = 196 - OpStructHeadIntPtrString OpType = 197 - OpStructHeadOmitEmptyIntPtrString OpType = 198 - OpStructPtrHeadIntPtrString OpType = 199 - OpStructPtrHeadOmitEmptyIntPtrString OpType = 200 - OpStructHeadUintPtrString OpType = 201 - OpStructHeadOmitEmptyUintPtrString OpType = 202 - OpStructPtrHeadUintPtrString OpType = 203 - OpStructPtrHeadOmitEmptyUintPtrString OpType = 204 - OpStructHeadFloat32PtrString OpType = 205 - OpStructHeadOmitEmptyFloat32PtrString OpType = 206 - OpStructPtrHeadFloat32PtrString OpType = 207 - OpStructPtrHeadOmitEmptyFloat32PtrString OpType = 208 - OpStructHeadFloat64PtrString OpType = 209 - OpStructHeadOmitEmptyFloat64PtrString OpType = 210 - OpStructPtrHeadFloat64PtrString OpType = 211 - OpStructPtrHeadOmitEmptyFloat64PtrString OpType = 212 - OpStructHeadBoolPtrString OpType = 213 - OpStructHeadOmitEmptyBoolPtrString OpType = 214 - OpStructPtrHeadBoolPtrString OpType = 215 - OpStructPtrHeadOmitEmptyBoolPtrString OpType = 216 - OpStructHeadStringPtrString OpType = 217 - OpStructHeadOmitEmptyStringPtrString OpType = 218 - OpStructPtrHeadStringPtrString OpType = 219 - OpStructPtrHeadOmitEmptyStringPtrString OpType = 220 - OpStructHeadNumberPtrString OpType = 221 - OpStructHeadOmitEmptyNumberPtrString OpType = 222 - OpStructPtrHeadNumberPtrString OpType = 223 - OpStructPtrHeadOmitEmptyNumberPtrString OpType = 224 - OpStructHead OpType = 225 - OpStructHeadOmitEmpty OpType = 226 - OpStructPtrHead OpType = 227 - OpStructPtrHeadOmitEmpty OpType = 228 - OpStructFieldInt OpType = 229 - OpStructFieldOmitEmptyInt OpType = 230 - OpStructEndInt OpType = 231 - OpStructEndOmitEmptyInt OpType = 232 - OpStructFieldUint OpType = 233 - OpStructFieldOmitEmptyUint OpType = 234 - OpStructEndUint OpType = 235 - OpStructEndOmitEmptyUint OpType = 236 - OpStructFieldFloat32 OpType = 237 - OpStructFieldOmitEmptyFloat32 OpType = 238 - OpStructEndFloat32 OpType = 239 - OpStructEndOmitEmptyFloat32 OpType = 240 - OpStructFieldFloat64 OpType = 241 - OpStructFieldOmitEmptyFloat64 OpType = 242 - OpStructEndFloat64 OpType = 243 - OpStructEndOmitEmptyFloat64 OpType = 244 - OpStructFieldBool OpType = 245 - OpStructFieldOmitEmptyBool OpType = 246 - OpStructEndBool OpType = 247 - OpStructEndOmitEmptyBool OpType = 248 - OpStructFieldString OpType = 249 - OpStructFieldOmitEmptyString OpType = 250 - OpStructEndString OpType = 251 - OpStructEndOmitEmptyString OpType = 252 - OpStructFieldBytes OpType = 253 - OpStructFieldOmitEmptyBytes OpType = 254 - OpStructEndBytes OpType = 255 - OpStructEndOmitEmptyBytes OpType = 256 - OpStructFieldNumber OpType = 257 - OpStructFieldOmitEmptyNumber OpType = 258 - OpStructEndNumber OpType = 259 - OpStructEndOmitEmptyNumber OpType = 260 - OpStructFieldArray OpType = 261 - OpStructFieldOmitEmptyArray OpType = 262 - OpStructEndArray OpType = 263 - OpStructEndOmitEmptyArray OpType = 264 - OpStructFieldMap OpType = 265 - OpStructFieldOmitEmptyMap OpType = 266 - OpStructEndMap OpType = 267 - OpStructEndOmitEmptyMap OpType = 268 - OpStructFieldSlice OpType = 269 - OpStructFieldOmitEmptySlice OpType = 270 - OpStructEndSlice OpType = 271 - OpStructEndOmitEmptySlice OpType = 272 - OpStructFieldStruct OpType = 273 - OpStructFieldOmitEmptyStruct OpType = 274 - OpStructEndStruct OpType = 275 - OpStructEndOmitEmptyStruct OpType = 276 - OpStructFieldMarshalJSON OpType = 277 - OpStructFieldOmitEmptyMarshalJSON OpType = 278 - OpStructEndMarshalJSON OpType = 279 - OpStructEndOmitEmptyMarshalJSON OpType = 280 - OpStructFieldMarshalText OpType = 281 - OpStructFieldOmitEmptyMarshalText OpType = 282 - OpStructEndMarshalText OpType = 283 - OpStructEndOmitEmptyMarshalText OpType = 284 - OpStructFieldIntString OpType = 285 - OpStructFieldOmitEmptyIntString OpType = 286 - OpStructEndIntString OpType = 287 - OpStructEndOmitEmptyIntString OpType = 288 - OpStructFieldUintString OpType = 289 - OpStructFieldOmitEmptyUintString OpType = 290 - OpStructEndUintString OpType = 291 - OpStructEndOmitEmptyUintString OpType = 292 - OpStructFieldFloat32String OpType = 293 - OpStructFieldOmitEmptyFloat32String OpType = 294 - OpStructEndFloat32String OpType = 295 - OpStructEndOmitEmptyFloat32String OpType = 296 - OpStructFieldFloat64String OpType = 297 - OpStructFieldOmitEmptyFloat64String OpType = 298 - OpStructEndFloat64String OpType = 299 - OpStructEndOmitEmptyFloat64String OpType = 300 - OpStructFieldBoolString OpType = 301 - OpStructFieldOmitEmptyBoolString OpType = 302 - OpStructEndBoolString OpType = 303 - OpStructEndOmitEmptyBoolString OpType = 304 - OpStructFieldStringString OpType = 305 - OpStructFieldOmitEmptyStringString OpType = 306 - OpStructEndStringString OpType = 307 - OpStructEndOmitEmptyStringString OpType = 308 - OpStructFieldNumberString OpType = 309 - OpStructFieldOmitEmptyNumberString OpType = 310 - OpStructEndNumberString OpType = 311 - OpStructEndOmitEmptyNumberString OpType = 312 - OpStructFieldIntPtr OpType = 313 - OpStructFieldOmitEmptyIntPtr OpType = 314 - OpStructEndIntPtr OpType = 315 - OpStructEndOmitEmptyIntPtr OpType = 316 - OpStructFieldUintPtr OpType = 317 - OpStructFieldOmitEmptyUintPtr OpType = 318 - OpStructEndUintPtr OpType = 319 - OpStructEndOmitEmptyUintPtr OpType = 320 - OpStructFieldFloat32Ptr OpType = 321 - OpStructFieldOmitEmptyFloat32Ptr OpType = 322 - OpStructEndFloat32Ptr OpType = 323 - OpStructEndOmitEmptyFloat32Ptr OpType = 324 - OpStructFieldFloat64Ptr OpType = 325 - OpStructFieldOmitEmptyFloat64Ptr OpType = 326 - OpStructEndFloat64Ptr OpType = 327 - OpStructEndOmitEmptyFloat64Ptr OpType = 328 - OpStructFieldBoolPtr OpType = 329 - OpStructFieldOmitEmptyBoolPtr OpType = 330 - OpStructEndBoolPtr OpType = 331 - OpStructEndOmitEmptyBoolPtr OpType = 332 - OpStructFieldStringPtr OpType = 333 - OpStructFieldOmitEmptyStringPtr OpType = 334 - OpStructEndStringPtr OpType = 335 - OpStructEndOmitEmptyStringPtr OpType = 336 - OpStructFieldBytesPtr OpType = 337 - OpStructFieldOmitEmptyBytesPtr OpType = 338 - OpStructEndBytesPtr OpType = 339 - OpStructEndOmitEmptyBytesPtr OpType = 340 - OpStructFieldNumberPtr OpType = 341 - OpStructFieldOmitEmptyNumberPtr OpType = 342 - OpStructEndNumberPtr OpType = 343 - OpStructEndOmitEmptyNumberPtr OpType = 344 - OpStructFieldArrayPtr OpType = 345 - OpStructFieldOmitEmptyArrayPtr OpType = 346 - OpStructEndArrayPtr OpType = 347 - OpStructEndOmitEmptyArrayPtr OpType = 348 - OpStructFieldMapPtr OpType = 349 - OpStructFieldOmitEmptyMapPtr OpType = 350 - OpStructEndMapPtr OpType = 351 - OpStructEndOmitEmptyMapPtr OpType = 352 - OpStructFieldSlicePtr OpType = 353 - OpStructFieldOmitEmptySlicePtr OpType = 354 - OpStructEndSlicePtr OpType = 355 - OpStructEndOmitEmptySlicePtr OpType = 356 - OpStructFieldMarshalJSONPtr OpType = 357 - OpStructFieldOmitEmptyMarshalJSONPtr OpType = 358 - OpStructEndMarshalJSONPtr OpType = 359 - OpStructEndOmitEmptyMarshalJSONPtr OpType = 360 - OpStructFieldMarshalTextPtr OpType = 361 - OpStructFieldOmitEmptyMarshalTextPtr OpType = 362 - OpStructEndMarshalTextPtr OpType = 363 - OpStructEndOmitEmptyMarshalTextPtr OpType = 364 - OpStructFieldInterfacePtr OpType = 365 - OpStructFieldOmitEmptyInterfacePtr OpType = 366 - OpStructEndInterfacePtr OpType = 367 - OpStructEndOmitEmptyInterfacePtr OpType = 368 - OpStructFieldIntPtrString OpType = 369 - OpStructFieldOmitEmptyIntPtrString OpType = 370 - OpStructEndIntPtrString OpType = 371 - OpStructEndOmitEmptyIntPtrString OpType = 372 - OpStructFieldUintPtrString OpType = 373 - OpStructFieldOmitEmptyUintPtrString OpType = 374 - OpStructEndUintPtrString OpType = 375 - OpStructEndOmitEmptyUintPtrString OpType = 376 - OpStructFieldFloat32PtrString OpType = 377 - OpStructFieldOmitEmptyFloat32PtrString OpType = 378 - OpStructEndFloat32PtrString OpType = 379 - OpStructEndOmitEmptyFloat32PtrString OpType = 380 - OpStructFieldFloat64PtrString OpType = 381 - OpStructFieldOmitEmptyFloat64PtrString OpType = 382 - OpStructEndFloat64PtrString OpType = 383 - OpStructEndOmitEmptyFloat64PtrString OpType = 384 - OpStructFieldBoolPtrString OpType = 385 - OpStructFieldOmitEmptyBoolPtrString OpType = 386 - OpStructEndBoolPtrString OpType = 387 - OpStructEndOmitEmptyBoolPtrString OpType = 388 - OpStructFieldStringPtrString OpType = 389 - OpStructFieldOmitEmptyStringPtrString OpType = 390 - OpStructEndStringPtrString OpType = 391 - OpStructEndOmitEmptyStringPtrString OpType = 392 - OpStructFieldNumberPtrString OpType = 393 - OpStructFieldOmitEmptyNumberPtrString OpType = 394 - OpStructEndNumberPtrString OpType = 395 - OpStructEndOmitEmptyNumberPtrString OpType = 396 - OpStructField OpType = 397 - OpStructFieldOmitEmpty OpType = 398 - OpStructEnd OpType = 399 - OpStructEndOmitEmpty OpType = 400 -) - -func (t OpType) String() string { - if int(t) >= 401 { - return "" - } - return opTypeStrings[int(t)] -} - -func (t OpType) CodeType() CodeType { - if strings.Contains(t.String(), "Struct") { - if strings.Contains(t.String(), "End") { - return CodeStructEnd - } - return CodeStructField - } - switch t { - case OpArray, OpArrayPtr: - return CodeArrayHead - case OpArrayElem: - return CodeArrayElem - case OpSlice, OpSlicePtr: - return CodeSliceHead - case OpSliceElem: - return CodeSliceElem - case OpMap, OpMapPtr: - return CodeMapHead - case OpMapKey: - return CodeMapKey - case OpMapValue: - return CodeMapValue - case OpMapEnd: - return CodeMapEnd - } - - return CodeOp -} - -func (t OpType) HeadToPtrHead() OpType { - if strings.Index(t.String(), "PtrHead") > 0 { - return t - } - - idx := strings.Index(t.String(), "Head") - if idx == -1 { - return t - } - suffix := "PtrHead" + t.String()[idx+len("Head"):] - - const toPtrOffset = 2 - if strings.Contains(OpType(int(t)+toPtrOffset).String(), suffix) { - return OpType(int(t) + toPtrOffset) - } - return t -} - -func (t OpType) HeadToOmitEmptyHead() OpType { - const toOmitEmptyOffset = 1 - if strings.Contains(OpType(int(t)+toOmitEmptyOffset).String(), "OmitEmpty") { - return OpType(int(t) + toOmitEmptyOffset) - } - - return t -} - -func (t OpType) PtrHeadToHead() OpType { - idx := strings.Index(t.String(), "Ptr") - if idx == -1 { - return t - } - suffix := t.String()[idx+len("Ptr"):] - - const toPtrOffset = 2 - if strings.Contains(OpType(int(t)-toPtrOffset).String(), suffix) { - return OpType(int(t) - toPtrOffset) - } - return t -} - -func (t OpType) FieldToEnd() OpType { - idx := strings.Index(t.String(), "Field") - if idx == -1 { - return t - } - suffix := t.String()[idx+len("Field"):] - if suffix == "" || suffix == "OmitEmpty" { - return t - } - const toEndOffset = 2 - if strings.Contains(OpType(int(t)+toEndOffset).String(), "End"+suffix) { - return OpType(int(t) + toEndOffset) - } - return t -} - -func (t OpType) FieldToOmitEmptyField() OpType { - const toOmitEmptyOffset = 1 - if strings.Contains(OpType(int(t)+toOmitEmptyOffset).String(), "OmitEmpty") { - return OpType(int(t) + toOmitEmptyOffset) - } - return t -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/string.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/string.go deleted file mode 100644 index a699dba1..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/string.go +++ /dev/null @@ -1,640 +0,0 @@ -package encoder - -import ( - "math/bits" - "reflect" - "unicode/utf8" - "unsafe" -) - -const ( - lsb = 0x0101010101010101 - msb = 0x8080808080808080 -) - -var needEscapeWithHTML = [256]bool{ - '"': true, - '&': true, - '<': true, - '>': true, - '\\': true, - 0x00: true, - 0x01: true, - 0x02: true, - 0x03: true, - 0x04: true, - 0x05: true, - 0x06: true, - 0x07: true, - 0x08: true, - 0x09: true, - 0x0a: true, - 0x0b: true, - 0x0c: true, - 0x0d: true, - 0x0e: true, - 0x0f: true, - 0x10: true, - 0x11: true, - 0x12: true, - 0x13: true, - 0x14: true, - 0x15: true, - 0x16: true, - 0x17: true, - 0x18: true, - 0x19: true, - 0x1a: true, - 0x1b: true, - 0x1c: true, - 0x1d: true, - 0x1e: true, - 0x1f: true, - /* 0x20 - 0x7f */ - 0x80: true, - 0x81: true, - 0x82: true, - 0x83: true, - 0x84: true, - 0x85: true, - 0x86: true, - 0x87: true, - 0x88: true, - 0x89: true, - 0x8a: true, - 0x8b: true, - 0x8c: true, - 0x8d: true, - 0x8e: true, - 0x8f: true, - 0x90: true, - 0x91: true, - 0x92: true, - 0x93: true, - 0x94: true, - 0x95: true, - 0x96: true, - 0x97: true, - 0x98: true, - 0x99: true, - 0x9a: true, - 0x9b: true, - 0x9c: true, - 0x9d: true, - 0x9e: true, - 0x9f: true, - 0xa0: true, - 0xa1: true, - 0xa2: true, - 0xa3: true, - 0xa4: true, - 0xa5: true, - 0xa6: true, - 0xa7: true, - 0xa8: true, - 0xa9: true, - 0xaa: true, - 0xab: true, - 0xac: true, - 0xad: true, - 0xae: true, - 0xaf: true, - 0xb0: true, - 0xb1: true, - 0xb2: true, - 0xb3: true, - 0xb4: true, - 0xb5: true, - 0xb6: true, - 0xb7: true, - 0xb8: true, - 0xb9: true, - 0xba: true, - 0xbb: true, - 0xbc: true, - 0xbd: true, - 0xbe: true, - 0xbf: true, - 0xc0: true, - 0xc1: true, - 0xc2: true, - 0xc3: true, - 0xc4: true, - 0xc5: true, - 0xc6: true, - 0xc7: true, - 0xc8: true, - 0xc9: true, - 0xca: true, - 0xcb: true, - 0xcc: true, - 0xcd: true, - 0xce: true, - 0xcf: true, - 0xd0: true, - 0xd1: true, - 0xd2: true, - 0xd3: true, - 0xd4: true, - 0xd5: true, - 0xd6: true, - 0xd7: true, - 0xd8: true, - 0xd9: true, - 0xda: true, - 0xdb: true, - 0xdc: true, - 0xdd: true, - 0xde: true, - 0xdf: true, - 0xe0: true, - 0xe1: true, - 0xe2: true, - 0xe3: true, - 0xe4: true, - 0xe5: true, - 0xe6: true, - 0xe7: true, - 0xe8: true, - 0xe9: true, - 0xea: true, - 0xeb: true, - 0xec: true, - 0xed: true, - 0xee: true, - 0xef: true, - 0xf0: true, - 0xf1: true, - 0xf2: true, - 0xf3: true, - 0xf4: true, - 0xf5: true, - 0xf6: true, - 0xf7: true, - 0xf8: true, - 0xf9: true, - 0xfa: true, - 0xfb: true, - 0xfc: true, - 0xfd: true, - 0xfe: true, - 0xff: true, -} - -var needEscape = [256]bool{ - '"': true, - '\\': true, - 0x00: true, - 0x01: true, - 0x02: true, - 0x03: true, - 0x04: true, - 0x05: true, - 0x06: true, - 0x07: true, - 0x08: true, - 0x09: true, - 0x0a: true, - 0x0b: true, - 0x0c: true, - 0x0d: true, - 0x0e: true, - 0x0f: true, - 0x10: true, - 0x11: true, - 0x12: true, - 0x13: true, - 0x14: true, - 0x15: true, - 0x16: true, - 0x17: true, - 0x18: true, - 0x19: true, - 0x1a: true, - 0x1b: true, - 0x1c: true, - 0x1d: true, - 0x1e: true, - 0x1f: true, - /* 0x20 - 0x7f */ - 0x80: true, - 0x81: true, - 0x82: true, - 0x83: true, - 0x84: true, - 0x85: true, - 0x86: true, - 0x87: true, - 0x88: true, - 0x89: true, - 0x8a: true, - 0x8b: true, - 0x8c: true, - 0x8d: true, - 0x8e: true, - 0x8f: true, - 0x90: true, - 0x91: true, - 0x92: true, - 0x93: true, - 0x94: true, - 0x95: true, - 0x96: true, - 0x97: true, - 0x98: true, - 0x99: true, - 0x9a: true, - 0x9b: true, - 0x9c: true, - 0x9d: true, - 0x9e: true, - 0x9f: true, - 0xa0: true, - 0xa1: true, - 0xa2: true, - 0xa3: true, - 0xa4: true, - 0xa5: true, - 0xa6: true, - 0xa7: true, - 0xa8: true, - 0xa9: true, - 0xaa: true, - 0xab: true, - 0xac: true, - 0xad: true, - 0xae: true, - 0xaf: true, - 0xb0: true, - 0xb1: true, - 0xb2: true, - 0xb3: true, - 0xb4: true, - 0xb5: true, - 0xb6: true, - 0xb7: true, - 0xb8: true, - 0xb9: true, - 0xba: true, - 0xbb: true, - 0xbc: true, - 0xbd: true, - 0xbe: true, - 0xbf: true, - 0xc0: true, - 0xc1: true, - 0xc2: true, - 0xc3: true, - 0xc4: true, - 0xc5: true, - 0xc6: true, - 0xc7: true, - 0xc8: true, - 0xc9: true, - 0xca: true, - 0xcb: true, - 0xcc: true, - 0xcd: true, - 0xce: true, - 0xcf: true, - 0xd0: true, - 0xd1: true, - 0xd2: true, - 0xd3: true, - 0xd4: true, - 0xd5: true, - 0xd6: true, - 0xd7: true, - 0xd8: true, - 0xd9: true, - 0xda: true, - 0xdb: true, - 0xdc: true, - 0xdd: true, - 0xde: true, - 0xdf: true, - 0xe0: true, - 0xe1: true, - 0xe2: true, - 0xe3: true, - 0xe4: true, - 0xe5: true, - 0xe6: true, - 0xe7: true, - 0xe8: true, - 0xe9: true, - 0xea: true, - 0xeb: true, - 0xec: true, - 0xed: true, - 0xee: true, - 0xef: true, - 0xf0: true, - 0xf1: true, - 0xf2: true, - 0xf3: true, - 0xf4: true, - 0xf5: true, - 0xf6: true, - 0xf7: true, - 0xf8: true, - 0xf9: true, - 0xfa: true, - 0xfb: true, - 0xfc: true, - 0xfd: true, - 0xfe: true, - 0xff: true, -} - -var hex = "0123456789abcdef" - -// escapeIndex finds the index of the first char in `s` that requires escaping. -// A char requires escaping if it's outside of the range of [0x20, 0x7F] or if -// it includes a double quote or backslash. -// If no chars in `s` require escaping, the return value is -1. -func escapeIndex(s string) int { - chunks := stringToUint64Slice(s) - for _, n := range chunks { - // combine masks before checking for the MSB of each byte. We include - // `n` in the mask to check whether any of the *input* byte MSBs were - // set (i.e. the byte was outside the ASCII range). - mask := n | below(n, 0x20) | contains(n, '"') | contains(n, '\\') - if (mask & msb) != 0 { - return bits.TrailingZeros64(mask&msb) / 8 - } - } - - valLen := len(s) - for i := len(chunks) * 8; i < valLen; i++ { - if needEscape[s[i]] { - return i - } - } - - return -1 -} - -// below return a mask that can be used to determine if any of the bytes -// in `n` are below `b`. If a byte's MSB is set in the mask then that byte was -// below `b`. The result is only valid if `b`, and each byte in `n`, is below -// 0x80. -func below(n uint64, b byte) uint64 { - return n - expand(b) -} - -// contains returns a mask that can be used to determine if any of the -// bytes in `n` are equal to `b`. If a byte's MSB is set in the mask then -// that byte is equal to `b`. The result is only valid if `b`, and each -// byte in `n`, is below 0x80. -func contains(n uint64, b byte) uint64 { - return (n ^ expand(b)) - lsb -} - -// expand puts the specified byte into each of the 8 bytes of a uint64. -func expand(b byte) uint64 { - return lsb * uint64(b) -} - -//nolint:govet -func stringToUint64Slice(s string) []uint64 { - return *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{ - Data: ((*reflect.StringHeader)(unsafe.Pointer(&s))).Data, - Len: len(s) / 8, - Cap: len(s) / 8, - })) -} - -func AppendString(ctx *RuntimeContext, buf []byte, s string) []byte { - if ctx.Option.Flag&HTMLEscapeOption == 0 { - return appendString(buf, s) - } - valLen := len(s) - if valLen == 0 { - return append(buf, `""`...) - } - buf = append(buf, '"') - var ( - i, j int - ) - if valLen >= 8 { - chunks := stringToUint64Slice(s) - for _, n := range chunks { - // combine masks before checking for the MSB of each byte. We include - // `n` in the mask to check whether any of the *input* byte MSBs were - // set (i.e. the byte was outside the ASCII range). - mask := n | (n - (lsb * 0x20)) | - ((n ^ (lsb * '"')) - lsb) | - ((n ^ (lsb * '\\')) - lsb) | - ((n ^ (lsb * '<')) - lsb) | - ((n ^ (lsb * '>')) - lsb) | - ((n ^ (lsb * '&')) - lsb) - if (mask & msb) != 0 { - j = bits.TrailingZeros64(mask&msb) / 8 - goto ESCAPE_END - } - } - for i := len(chunks) * 8; i < valLen; i++ { - if needEscapeWithHTML[s[i]] { - j = i - goto ESCAPE_END - } - } - // no found any escape characters. - return append(append(buf, s...), '"') - } -ESCAPE_END: - for j < valLen { - c := s[j] - - if !needEscapeWithHTML[c] { - // fast path: most of the time, printable ascii characters are used - j++ - continue - } - - switch c { - case '\\', '"': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', c) - i = j + 1 - j = j + 1 - continue - - case '\n': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', 'n') - i = j + 1 - j = j + 1 - continue - - case '\r': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', 'r') - i = j + 1 - j = j + 1 - continue - - case '\t': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', 't') - i = j + 1 - j = j + 1 - continue - - case '<', '>', '&': - buf = append(buf, s[i:j]...) - buf = append(buf, `\u00`...) - buf = append(buf, hex[c>>4], hex[c&0xF]) - i = j + 1 - j = j + 1 - continue - } - - // This encodes bytes < 0x20 except for \t, \n and \r. - if c < 0x20 { - buf = append(buf, s[i:j]...) - buf = append(buf, `\u00`...) - buf = append(buf, hex[c>>4], hex[c&0xF]) - i = j + 1 - j = j + 1 - continue - } - - r, size := utf8.DecodeRuneInString(s[j:]) - - if r == utf8.RuneError && size == 1 { - buf = append(buf, s[i:j]...) - buf = append(buf, `\ufffd`...) - i = j + size - j = j + size - continue - } - - switch r { - case '\u2028', '\u2029': - // U+2028 is LINE SEPARATOR. - // U+2029 is PARAGRAPH SEPARATOR. - // They are both technically valid characters in JSON strings, - // but don't work in JSONP, which has to be evaluated as JavaScript, - // and can lead to security holes there. It is valid JSON to - // escape them, so we do so unconditionally. - // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. - buf = append(buf, s[i:j]...) - buf = append(buf, `\u202`...) - buf = append(buf, hex[r&0xF]) - i = j + size - j = j + size - continue - } - - j += size - } - - return append(append(buf, s[i:]...), '"') -} - -func appendString(buf []byte, s string) []byte { - valLen := len(s) - if valLen == 0 { - return append(buf, `""`...) - } - buf = append(buf, '"') - var escapeIdx int - if valLen >= 8 { - if escapeIdx = escapeIndex(s); escapeIdx < 0 { - return append(append(buf, s...), '"') - } - } - - i := 0 - j := escapeIdx - for j < valLen { - c := s[j] - - if c >= 0x20 && c <= 0x7f && c != '\\' && c != '"' { - // fast path: most of the time, printable ascii characters are used - j++ - continue - } - - switch c { - case '\\', '"': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', c) - i = j + 1 - j = j + 1 - continue - - case '\n': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', 'n') - i = j + 1 - j = j + 1 - continue - - case '\r': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', 'r') - i = j + 1 - j = j + 1 - continue - - case '\t': - buf = append(buf, s[i:j]...) - buf = append(buf, '\\', 't') - i = j + 1 - j = j + 1 - continue - - case '<', '>', '&': - buf = append(buf, s[i:j]...) - buf = append(buf, `\u00`...) - buf = append(buf, hex[c>>4], hex[c&0xF]) - i = j + 1 - j = j + 1 - continue - } - - // This encodes bytes < 0x20 except for \t, \n and \r. - if c < 0x20 { - buf = append(buf, s[i:j]...) - buf = append(buf, `\u00`...) - buf = append(buf, hex[c>>4], hex[c&0xF]) - i = j + 1 - j = j + 1 - continue - } - - r, size := utf8.DecodeRuneInString(s[j:]) - - if r == utf8.RuneError && size == 1 { - buf = append(buf, s[i:j]...) - buf = append(buf, `\ufffd`...) - i = j + size - j = j + size - continue - } - - switch r { - case '\u2028', '\u2029': - // U+2028 is LINE SEPARATOR. - // U+2029 is PARAGRAPH SEPARATOR. - // They are both technically valid characters in JSON strings, - // but don't work in JSONP, which has to be evaluated as JavaScript, - // and can lead to security holes there. It is valid JSON to - // escape them, so we do so unconditionally. - // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. - buf = append(buf, s[i:j]...) - buf = append(buf, `\u202`...) - buf = append(buf, hex[r&0xF]) - i = j + size - j = j + size - continue - } - - j += size - } - - return append(append(buf, s[i:]...), '"') -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/debug_vm.go deleted file mode 100644 index 05509fed..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/debug_vm.go +++ /dev/null @@ -1,34 +0,0 @@ -package vm - -import ( - "fmt" - - "github.com/goccy/go-json/internal/encoder" -) - -func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - defer func() { - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - if err := recover(); err != nil { - fmt.Println("=============[DEBUG]===============") - fmt.Println("* [TYPE]") - fmt.Println(codeSet.Type) - fmt.Printf("\n") - fmt.Println("* [ALL OPCODE]") - fmt.Println(code.Dump()) - fmt.Printf("\n") - fmt.Println("* [CONTEXT]") - fmt.Printf("%+v\n", ctx) - fmt.Println("===================================") - panic(err) - } - }() - - return Run(ctx, b, codeSet) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/hack.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/hack.go deleted file mode 100644 index 65252b4a..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/hack.go +++ /dev/null @@ -1,9 +0,0 @@ -package vm - -import ( - // HACK: compile order - // `vm`, `vm_indent`, `vm_color`, `vm_color_indent` packages uses a lot of memory to compile, - // so forcibly make dependencies and avoid compiling in concurrent. - // dependency order: vm => vm_indent => vm_color => vm_color_indent - _ "github.com/goccy/go-json/internal/encoder/vm_indent" -) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/util.go deleted file mode 100644 index c5594479..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/util.go +++ /dev/null @@ -1,182 +0,0 @@ -package vm - -import ( - "encoding/json" - "fmt" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" - "github.com/goccy/go-json/internal/runtime" -) - -const uintptrSize = 4 << (^uintptr(0) >> 63) - -var ( - appendInt = encoder.AppendInt - appendUint = encoder.AppendUint - appendFloat32 = encoder.AppendFloat32 - appendFloat64 = encoder.AppendFloat64 - appendString = encoder.AppendString - appendByteSlice = encoder.AppendByteSlice - appendNumber = encoder.AppendNumber - errUnsupportedValue = encoder.ErrUnsupportedValue - errUnsupportedFloat = encoder.ErrUnsupportedFloat - mapiterinit = encoder.MapIterInit - mapiterkey = encoder.MapIterKey - mapitervalue = encoder.MapIterValue - mapiternext = encoder.MapIterNext - maplen = encoder.MapLen -) - -type emptyInterface struct { - typ *runtime.Type - ptr unsafe.Pointer -} - -func errUnimplementedOp(op encoder.OpType) error { - return fmt.Errorf("encoder: opcode %s has not been implemented", op) -} - -func load(base uintptr, idx uint32) uintptr { - addr := base + uintptr(idx) - return **(**uintptr)(unsafe.Pointer(&addr)) -} - -func store(base uintptr, idx uint32, p uintptr) { - addr := base + uintptr(idx) - **(**uintptr)(unsafe.Pointer(&addr)) = p -} - -func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { - addr := base + uintptr(idx) - p := **(**uintptr)(unsafe.Pointer(&addr)) - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUint64(p uintptr) uint64 { return **(**uint64)(unsafe.Pointer(&p)) } -func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } -func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } -func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } -func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } -func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } -func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } -func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } -func ptrToPtr(p uintptr) uintptr { - return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) -} -func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUnsafePtr(p uintptr) unsafe.Pointer { - return *(*unsafe.Pointer)(unsafe.Pointer(&p)) -} -func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { - return *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: code.Type, - ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), - })) -} - -func appendBool(_ *encoder.RuntimeContext, b []byte, v bool) []byte { - if v { - return append(b, "true"...) - } - return append(b, "false"...) -} - -func appendNull(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, "null"...) -} - -func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, ',') -} - -func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { - last := len(b) - 1 - b[last] = ':' - return b -} - -func appendMapKeyValue(_ *encoder.RuntimeContext, _ *encoder.Opcode, b, key, value []byte) []byte { - b = append(b, key...) - b[len(b)-1] = ':' - return append(b, value...) -} - -func appendMapEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - b[len(b)-1] = '}' - b = append(b, ',') - return b -} - -func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - return encoder.AppendMarshalJSON(ctx, code, b, v) -} - -func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - return encoder.AppendMarshalText(ctx, code, b, v) -} - -func appendArrayHead(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - return append(b, '[') -} - -func appendArrayEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - b[last] = ']' - return append(b, ',') -} - -func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '[', ']', ',') -} - -func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{', '}', ',') -} - -func appendObjectEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - b[last] = '}' - return append(b, ',') -} - -func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{') -} - -func appendStructKey(_ *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - return append(b, code.Key...) -} - -func appendStructEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - return append(b, '}', ',') -} - -func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - if b[last] == ',' { - b[last] = '}' - return appendComma(ctx, b) - } - return appendStructEnd(ctx, code, b) -} - -func restoreIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, _ uintptr) {} -func storeIndent(_ uintptr, _ *encoder.Opcode, _ uintptr) {} -func appendMapKeyIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } -func appendArrayElemIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/vm.go deleted file mode 100644 index 78da5e44..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/vm.go +++ /dev/null @@ -1,5041 +0,0 @@ -// Code generated by internal/cmd/generator. DO NOT EDIT! -package vm - -import ( - "math" - "sort" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" -) - -func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - recursiveLevel := 0 - ptrOffset := uintptr(0) - ctxptr := ctx.Ptr() - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - for { - switch code.Op { - default: - return nil, errUnimplementedOp(code.Op) - case encoder.OpPtr: - p := load(ctxptr, code.Idx) - code = code.Next - store(ctxptr, code.Idx, ptrToPtr(p)) - case encoder.OpIntPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInt: - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpUint: - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpIntString: - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintString: - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat32Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat32: - b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat64Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat64: - v := ptrToFloat64(load(ctxptr, code.Idx)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStringPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpString: - b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBoolPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBool: - b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBytesPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBytes: - b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpNumberPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpNumber: - bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpInterfacePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInterface: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if p == seen { - return nil, errUnsupportedValue(code, p) - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, p) - iface := (*emptyInterface)(ptrToUnsafePtr(p)) - if iface.ptr == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(iface)) - ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(iface.typ))) - if err != nil { - return nil, err - } - - totalLength := uintptr(code.Length) + 3 - nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 - - var c *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - c = ifaceCodeSet.InterfaceEscapeKeyCode - } else { - c = ifaceCodeSet.InterfaceNoescapeKeyCode - } - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += totalLength * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + totalLength + nextTotalLength - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - end := ifaceCodeSet.EndCode - store(ctxptr, c.Idx, uintptr(iface.ptr)) - store(ctxptr, end.Idx, oldOffset) - store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, end, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpInterfaceEnd: - recursiveLevel-- - - // restore ctxptr - offset := load(ctxptr, code.Idx) - restoreIndent(ctx, code, ctxptr) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - b = append(b, `""`...) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpSlicePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpSlice: - p := load(ctxptr, code.Idx) - slice := ptrToSlice(p) - if p == 0 || slice.Data == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(slice.Len)) - store(ctxptr, code.Idx, uintptr(slice.Data)) - if slice.Len > 0 { - b = appendArrayHead(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, uintptr(slice.Data)) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpSliceElem: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if idx < length { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - data := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, data+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpArrayPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpArray: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - if code.Length > 0 { - b = appendArrayHead(ctx, code, b) - store(ctxptr, code.ElemIdx, 0) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpArrayElem: - idx := load(ctxptr, code.ElemIdx) - idx++ - if idx < uintptr(code.Length) { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - p := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, p+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpMapPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpMap: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - uptr := ptrToUnsafePtr(p) - mlen := maplen(uptr) - if mlen <= 0 { - b = appendEmptyObject(ctx, b) - code = code.End.Next - break - } - b = appendStructHead(ctx, b) - iter := mapiterinit(code.Type, uptr) - ctx.KeepRefs = append(ctx.KeepRefs, iter) - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(mlen)) - store(ctxptr, code.MapIter, uintptr(iter)) - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendMapKeyIndent(ctx, code.Next, b) - } else { - mapCtx := encoder.NewMapContext(mlen) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) - store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) - } - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - case encoder.OpMapKey: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - if idx < length { - b = appendMapKeyIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - b = appendObjectEnd(ctx, code, b) - code = code.End.Next - } - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - if idx < length { - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - store(ctxptr, code.ElemIdx, idx) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - code = code.End - } - } - case encoder.OpMapValue: - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendColon(ctx, b) - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - } - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - value := mapitervalue(iter) - store(ctxptr, code.Next.Idx, uintptr(value)) - mapiternext(iter) - code = code.Next - case encoder.OpMapEnd: - // this operation only used by sorted map. - length := int(load(ctxptr, code.Length)) - ptr := load(ctxptr, code.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - pos := mapCtx.Pos - for i := 0; i < length; i++ { - startKey := pos[i*2] - startValue := pos[i*2+1] - var endValue int - if i+1 < length { - endValue = pos[i*2+2] - } else { - endValue = len(b) - } - mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ - Key: b[startKey:startValue], - Value: b[startValue:endValue], - }) - } - sort.Sort(mapCtx.Slice) - buf := mapCtx.Buf - for _, item := range mapCtx.Slice.Items { - buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) - } - buf = appendMapEnd(ctx, code, buf) - b = b[:pos[0]] - b = append(b, buf...) - mapCtx.Buf = buf - encoder.ReleaseMapContext(mapCtx) - code = code.Next - case encoder.OpRecursivePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpRecursive: - ptr := load(ctxptr, code.Idx) - if ptr != 0 { - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if ptr == seen { - return nil, errUnsupportedValue(code, ptr) - } - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, ptr) - c := code.Jmp.Code - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += code.Jmp.CurLen * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - store(ctxptr, c.Idx, ptr) - store(ctxptr, c.End.Next.Idx, oldOffset) - store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpRecursiveEnd: - recursiveLevel-- - - // restore ctxptr - restoreIndent(ctx, code, ctxptr) - offset := load(ctxptr, code.Idx) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpStructPtrHead: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHead: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags&encoder.AnonymousKeyFlags) == 0 && len(code.Key) > 0 { - b = appendStructKey(ctx, code, b) - } - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - } - case encoder.OpStructPtrHeadNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructPtrHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyArray: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyArray: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptySlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptySlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - if maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructField: - if code.Flags&encoder.AnonymousKeyFlags == 0 { - b = appendStructKey(ctx, code, b) - } - p := load(ctxptr, code.Idx) + uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmpty: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringString: - p := load(ctxptr, code.Idx) - s := ptrToString(p + uintptr(code.Offset)) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldMarshalJSON: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalJSONPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldMarshalText: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalTextPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldArrayPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArrayPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldSlice: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlice: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldSlicePtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldMap: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMap: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldMapPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldStruct: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyStruct: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructAnonymousEnd: - code = code.Next - case encoder.OpStructEnd: - b = appendStructEndSkipLast(ctx, code, b) - code = code.Next - case encoder.OpStructEndInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendStructEnd(ctx, code, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - s := ptrToString(p + uintptr(code.Offset)) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytesPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - code = code.Next - case encoder.OpStructEndOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpEnd: - goto END - } - } -END: - return b, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/debug_vm.go deleted file mode 100644 index 6a6a33d2..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/debug_vm.go +++ /dev/null @@ -1,34 +0,0 @@ -package vm_color - -import ( - "fmt" - - "github.com/goccy/go-json/internal/encoder" -) - -func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - defer func() { - if err := recover(); err != nil { - fmt.Println("=============[DEBUG]===============") - fmt.Println("* [TYPE]") - fmt.Println(codeSet.Type) - fmt.Printf("\n") - fmt.Println("* [ALL OPCODE]") - fmt.Println(code.Dump()) - fmt.Printf("\n") - fmt.Println("* [CONTEXT]") - fmt.Printf("%+v\n", ctx) - fmt.Println("===================================") - panic(err) - } - }() - - return Run(ctx, b, codeSet) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/hack.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/hack.go deleted file mode 100644 index 12ec56c5..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/hack.go +++ /dev/null @@ -1,9 +0,0 @@ -package vm_color - -import ( - // HACK: compile order - // `vm`, `vm_indent`, `vm_color`, `vm_color_indent` packages uses a lot of memory to compile, - // so forcibly make dependencies and avoid compiling in concurrent. - // dependency order: vm => vm_indent => vm_color => vm_color_indent - _ "github.com/goccy/go-json/internal/encoder/vm_color_indent" -) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/util.go deleted file mode 100644 index 516536d7..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/util.go +++ /dev/null @@ -1,246 +0,0 @@ -package vm_color - -import ( - "encoding/json" - "fmt" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" - "github.com/goccy/go-json/internal/runtime" -) - -const uintptrSize = 4 << (^uintptr(0) >> 63) - -var ( - errUnsupportedValue = encoder.ErrUnsupportedValue - errUnsupportedFloat = encoder.ErrUnsupportedFloat - mapiterinit = encoder.MapIterInit - mapiterkey = encoder.MapIterKey - mapitervalue = encoder.MapIterValue - mapiternext = encoder.MapIterNext - maplen = encoder.MapLen -) - -type emptyInterface struct { - typ *runtime.Type - ptr unsafe.Pointer -} - -func errUnimplementedOp(op encoder.OpType) error { - return fmt.Errorf("encoder: opcode %s has not been implemented", op) -} - -func load(base uintptr, idx uint32) uintptr { - addr := base + uintptr(idx) - return **(**uintptr)(unsafe.Pointer(&addr)) -} - -func store(base uintptr, idx uint32, p uintptr) { - addr := base + uintptr(idx) - **(**uintptr)(unsafe.Pointer(&addr)) = p -} - -func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { - addr := base + uintptr(idx) - p := **(**uintptr)(unsafe.Pointer(&addr)) - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUint64(p uintptr) uint64 { return **(**uint64)(unsafe.Pointer(&p)) } -func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } -func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } -func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } -func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } -func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } -func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } -func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } -func ptrToPtr(p uintptr) uintptr { - return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) -} -func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUnsafePtr(p uintptr) unsafe.Pointer { - return *(*unsafe.Pointer)(unsafe.Pointer(&p)) -} -func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { - return *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: code.Type, - ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), - })) -} - -func appendInt(ctx *encoder.RuntimeContext, b []byte, v uint64, code *encoder.Opcode) []byte { - format := ctx.Option.ColorScheme.Int - b = append(b, format.Header...) - b = encoder.AppendInt(ctx, b, v, code) - return append(b, format.Footer...) -} - -func appendUint(ctx *encoder.RuntimeContext, b []byte, v uint64, code *encoder.Opcode) []byte { - format := ctx.Option.ColorScheme.Uint - b = append(b, format.Header...) - b = encoder.AppendUint(ctx, b, v, code) - return append(b, format.Footer...) -} - -func appendFloat32(ctx *encoder.RuntimeContext, b []byte, v float32) []byte { - format := ctx.Option.ColorScheme.Float - b = append(b, format.Header...) - b = encoder.AppendFloat32(ctx, b, v) - return append(b, format.Footer...) -} - -func appendFloat64(ctx *encoder.RuntimeContext, b []byte, v float64) []byte { - format := ctx.Option.ColorScheme.Float - b = append(b, format.Header...) - b = encoder.AppendFloat64(ctx, b, v) - return append(b, format.Footer...) -} - -func appendString(ctx *encoder.RuntimeContext, b []byte, v string) []byte { - format := ctx.Option.ColorScheme.String - b = append(b, format.Header...) - b = encoder.AppendString(ctx, b, v) - return append(b, format.Footer...) -} - -func appendByteSlice(ctx *encoder.RuntimeContext, b []byte, src []byte) []byte { - format := ctx.Option.ColorScheme.Binary - b = append(b, format.Header...) - b = encoder.AppendByteSlice(ctx, b, src) - return append(b, format.Footer...) -} - -func appendNumber(ctx *encoder.RuntimeContext, b []byte, n json.Number) ([]byte, error) { - format := ctx.Option.ColorScheme.Int - b = append(b, format.Header...) - bb, err := encoder.AppendNumber(ctx, b, n) - if err != nil { - return nil, err - } - return append(bb, format.Footer...), nil -} - -func appendBool(ctx *encoder.RuntimeContext, b []byte, v bool) []byte { - format := ctx.Option.ColorScheme.Bool - b = append(b, format.Header...) - if v { - b = append(b, "true"...) - } else { - b = append(b, "false"...) - } - return append(b, format.Footer...) -} - -func appendNull(ctx *encoder.RuntimeContext, b []byte) []byte { - format := ctx.Option.ColorScheme.Null - b = append(b, format.Header...) - b = append(b, "null"...) - return append(b, format.Footer...) -} - -func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, ',') -} - -func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { - last := len(b) - 1 - b[last] = ':' - return b -} - -func appendMapKeyValue(_ *encoder.RuntimeContext, _ *encoder.Opcode, b, key, value []byte) []byte { - b = append(b, key[:len(key)-1]...) - b = append(b, ':') - return append(b, value...) -} - -func appendMapEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - b[last] = '}' - b = append(b, ',') - return b -} - -func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - return encoder.AppendMarshalJSON(ctx, code, b, v) -} - -func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - format := ctx.Option.ColorScheme.String - b = append(b, format.Header...) - bb, err := encoder.AppendMarshalText(ctx, code, b, v) - if err != nil { - return nil, err - } - return append(bb, format.Footer...), nil -} - -func appendArrayHead(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - return append(b, '[') -} - -func appendArrayEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - b[last] = ']' - return append(b, ',') -} - -func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '[', ']', ',') -} - -func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{', '}', ',') -} - -func appendObjectEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - b[last] = '}' - return append(b, ',') -} - -func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{') -} - -func appendStructKey(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - format := ctx.Option.ColorScheme.ObjectKey - b = append(b, format.Header...) - b = append(b, code.Key[:len(code.Key)-1]...) - b = append(b, format.Footer...) - - return append(b, ':') -} - -func appendStructEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { - return append(b, '}', ',') -} - -func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - if b[last] == ',' { - b[last] = '}' - return appendComma(ctx, b) - } - return appendStructEnd(ctx, code, b) -} - -func restoreIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, _ uintptr) {} -func storeIndent(_ uintptr, _ *encoder.Opcode, _ uintptr) {} -func appendMapKeyIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } -func appendArrayElemIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/vm.go deleted file mode 100644 index 0d4c472a..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/vm.go +++ /dev/null @@ -1,5041 +0,0 @@ -// Code generated by internal/cmd/generator. DO NOT EDIT! -package vm_color - -import ( - "math" - "sort" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" -) - -func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - recursiveLevel := 0 - ptrOffset := uintptr(0) - ctxptr := ctx.Ptr() - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - for { - switch code.Op { - default: - return nil, errUnimplementedOp(code.Op) - case encoder.OpPtr: - p := load(ctxptr, code.Idx) - code = code.Next - store(ctxptr, code.Idx, ptrToPtr(p)) - case encoder.OpIntPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInt: - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpUint: - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpIntString: - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintString: - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat32Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat32: - b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat64Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat64: - v := ptrToFloat64(load(ctxptr, code.Idx)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStringPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpString: - b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBoolPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBool: - b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBytesPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBytes: - b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpNumberPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpNumber: - bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpInterfacePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInterface: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if p == seen { - return nil, errUnsupportedValue(code, p) - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, p) - iface := (*emptyInterface)(ptrToUnsafePtr(p)) - if iface.ptr == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(iface)) - ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(iface.typ))) - if err != nil { - return nil, err - } - - totalLength := uintptr(code.Length) + 3 - nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 - - var c *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - c = ifaceCodeSet.InterfaceEscapeKeyCode - } else { - c = ifaceCodeSet.InterfaceNoescapeKeyCode - } - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += totalLength * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + totalLength + nextTotalLength - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - end := ifaceCodeSet.EndCode - store(ctxptr, c.Idx, uintptr(iface.ptr)) - store(ctxptr, end.Idx, oldOffset) - store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, end, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpInterfaceEnd: - recursiveLevel-- - - // restore ctxptr - offset := load(ctxptr, code.Idx) - restoreIndent(ctx, code, ctxptr) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - b = append(b, `""`...) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpSlicePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpSlice: - p := load(ctxptr, code.Idx) - slice := ptrToSlice(p) - if p == 0 || slice.Data == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(slice.Len)) - store(ctxptr, code.Idx, uintptr(slice.Data)) - if slice.Len > 0 { - b = appendArrayHead(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, uintptr(slice.Data)) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpSliceElem: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if idx < length { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - data := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, data+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpArrayPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpArray: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - if code.Length > 0 { - b = appendArrayHead(ctx, code, b) - store(ctxptr, code.ElemIdx, 0) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpArrayElem: - idx := load(ctxptr, code.ElemIdx) - idx++ - if idx < uintptr(code.Length) { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - p := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, p+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpMapPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpMap: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - uptr := ptrToUnsafePtr(p) - mlen := maplen(uptr) - if mlen <= 0 { - b = appendEmptyObject(ctx, b) - code = code.End.Next - break - } - b = appendStructHead(ctx, b) - iter := mapiterinit(code.Type, uptr) - ctx.KeepRefs = append(ctx.KeepRefs, iter) - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(mlen)) - store(ctxptr, code.MapIter, uintptr(iter)) - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendMapKeyIndent(ctx, code.Next, b) - } else { - mapCtx := encoder.NewMapContext(mlen) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) - store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) - } - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - case encoder.OpMapKey: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - if idx < length { - b = appendMapKeyIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - b = appendObjectEnd(ctx, code, b) - code = code.End.Next - } - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - if idx < length { - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - store(ctxptr, code.ElemIdx, idx) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - code = code.End - } - } - case encoder.OpMapValue: - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendColon(ctx, b) - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - } - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - value := mapitervalue(iter) - store(ctxptr, code.Next.Idx, uintptr(value)) - mapiternext(iter) - code = code.Next - case encoder.OpMapEnd: - // this operation only used by sorted map. - length := int(load(ctxptr, code.Length)) - ptr := load(ctxptr, code.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - pos := mapCtx.Pos - for i := 0; i < length; i++ { - startKey := pos[i*2] - startValue := pos[i*2+1] - var endValue int - if i+1 < length { - endValue = pos[i*2+2] - } else { - endValue = len(b) - } - mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ - Key: b[startKey:startValue], - Value: b[startValue:endValue], - }) - } - sort.Sort(mapCtx.Slice) - buf := mapCtx.Buf - for _, item := range mapCtx.Slice.Items { - buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) - } - buf = appendMapEnd(ctx, code, buf) - b = b[:pos[0]] - b = append(b, buf...) - mapCtx.Buf = buf - encoder.ReleaseMapContext(mapCtx) - code = code.Next - case encoder.OpRecursivePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpRecursive: - ptr := load(ctxptr, code.Idx) - if ptr != 0 { - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if ptr == seen { - return nil, errUnsupportedValue(code, ptr) - } - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, ptr) - c := code.Jmp.Code - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += code.Jmp.CurLen * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - store(ctxptr, c.Idx, ptr) - store(ctxptr, c.End.Next.Idx, oldOffset) - store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpRecursiveEnd: - recursiveLevel-- - - // restore ctxptr - restoreIndent(ctx, code, ctxptr) - offset := load(ctxptr, code.Idx) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpStructPtrHead: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHead: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags&encoder.AnonymousKeyFlags) == 0 && len(code.Key) > 0 { - b = appendStructKey(ctx, code, b) - } - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - } - case encoder.OpStructPtrHeadNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructPtrHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyArray: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyArray: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptySlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptySlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - if maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructField: - if code.Flags&encoder.AnonymousKeyFlags == 0 { - b = appendStructKey(ctx, code, b) - } - p := load(ctxptr, code.Idx) + uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmpty: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringString: - p := load(ctxptr, code.Idx) - s := ptrToString(p + uintptr(code.Offset)) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldMarshalJSON: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalJSONPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldMarshalText: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalTextPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldArrayPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArrayPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldSlice: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlice: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldSlicePtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldMap: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMap: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldMapPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldStruct: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyStruct: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructAnonymousEnd: - code = code.Next - case encoder.OpStructEnd: - b = appendStructEndSkipLast(ctx, code, b) - code = code.Next - case encoder.OpStructEndInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendStructEnd(ctx, code, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - s := ptrToString(p + uintptr(code.Offset)) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytesPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - code = code.Next - case encoder.OpStructEndOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpEnd: - goto END - } - } -END: - return b, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/debug_vm.go deleted file mode 100644 index a68bbf6b..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/debug_vm.go +++ /dev/null @@ -1,34 +0,0 @@ -package vm_color_indent - -import ( - "fmt" - - "github.com/goccy/go-json/internal/encoder" -) - -func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - defer func() { - if err := recover(); err != nil { - fmt.Println("=============[DEBUG]===============") - fmt.Println("* [TYPE]") - fmt.Println(codeSet.Type) - fmt.Printf("\n") - fmt.Println("* [ALL OPCODE]") - fmt.Println(code.Dump()) - fmt.Printf("\n") - fmt.Println("* [CONTEXT]") - fmt.Printf("%+v\n", ctx) - fmt.Println("===================================") - panic(err) - } - }() - - return Run(ctx, b, codeSet) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/util.go deleted file mode 100644 index 9f98781b..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/util.go +++ /dev/null @@ -1,267 +0,0 @@ -package vm_color_indent - -import ( - "encoding/json" - "fmt" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" - "github.com/goccy/go-json/internal/runtime" -) - -const uintptrSize = 4 << (^uintptr(0) >> 63) - -var ( - appendIndent = encoder.AppendIndent - appendStructEnd = encoder.AppendStructEndIndent - errUnsupportedValue = encoder.ErrUnsupportedValue - errUnsupportedFloat = encoder.ErrUnsupportedFloat - mapiterinit = encoder.MapIterInit - mapiterkey = encoder.MapIterKey - mapitervalue = encoder.MapIterValue - mapiternext = encoder.MapIterNext - maplen = encoder.MapLen -) - -type emptyInterface struct { - typ *runtime.Type - ptr unsafe.Pointer -} - -func errUnimplementedOp(op encoder.OpType) error { - return fmt.Errorf("encoder (indent): opcode %s has not been implemented", op) -} - -func load(base uintptr, idx uint32) uintptr { - addr := base + uintptr(idx) - return **(**uintptr)(unsafe.Pointer(&addr)) -} - -func store(base uintptr, idx uint32, p uintptr) { - addr := base + uintptr(idx) - **(**uintptr)(unsafe.Pointer(&addr)) = p -} - -func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { - addr := base + uintptr(idx) - p := **(**uintptr)(unsafe.Pointer(&addr)) - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUint64(p uintptr) uint64 { return **(**uint64)(unsafe.Pointer(&p)) } -func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } -func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } -func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } -func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } -func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } -func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } -func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } -func ptrToPtr(p uintptr) uintptr { - return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) -} -func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUnsafePtr(p uintptr) unsafe.Pointer { - return *(*unsafe.Pointer)(unsafe.Pointer(&p)) -} -func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { - return *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: code.Type, - ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), - })) -} - -func appendInt(ctx *encoder.RuntimeContext, b []byte, v uint64, code *encoder.Opcode) []byte { - format := ctx.Option.ColorScheme.Int - b = append(b, format.Header...) - b = encoder.AppendInt(ctx, b, v, code) - return append(b, format.Footer...) -} - -func appendUint(ctx *encoder.RuntimeContext, b []byte, v uint64, code *encoder.Opcode) []byte { - format := ctx.Option.ColorScheme.Uint - b = append(b, format.Header...) - b = encoder.AppendUint(ctx, b, v, code) - return append(b, format.Footer...) -} - -func appendFloat32(ctx *encoder.RuntimeContext, b []byte, v float32) []byte { - format := ctx.Option.ColorScheme.Float - b = append(b, format.Header...) - b = encoder.AppendFloat32(ctx, b, v) - return append(b, format.Footer...) -} - -func appendFloat64(ctx *encoder.RuntimeContext, b []byte, v float64) []byte { - format := ctx.Option.ColorScheme.Float - b = append(b, format.Header...) - b = encoder.AppendFloat64(ctx, b, v) - return append(b, format.Footer...) -} - -func appendString(ctx *encoder.RuntimeContext, b []byte, v string) []byte { - format := ctx.Option.ColorScheme.String - b = append(b, format.Header...) - b = encoder.AppendString(ctx, b, v) - return append(b, format.Footer...) -} - -func appendByteSlice(ctx *encoder.RuntimeContext, b []byte, src []byte) []byte { - format := ctx.Option.ColorScheme.Binary - b = append(b, format.Header...) - b = encoder.AppendByteSlice(ctx, b, src) - return append(b, format.Footer...) -} - -func appendNumber(ctx *encoder.RuntimeContext, b []byte, n json.Number) ([]byte, error) { - format := ctx.Option.ColorScheme.Int - b = append(b, format.Header...) - bb, err := encoder.AppendNumber(ctx, b, n) - if err != nil { - return nil, err - } - return append(bb, format.Footer...), nil -} - -func appendBool(ctx *encoder.RuntimeContext, b []byte, v bool) []byte { - format := ctx.Option.ColorScheme.Bool - b = append(b, format.Header...) - if v { - b = append(b, "true"...) - } else { - b = append(b, "false"...) - } - return append(b, format.Footer...) -} - -func appendNull(ctx *encoder.RuntimeContext, b []byte) []byte { - format := ctx.Option.ColorScheme.Null - b = append(b, format.Header...) - b = append(b, "null"...) - return append(b, format.Footer...) -} - -func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, ',', '\n') -} - -func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, ':', ' ') -} - -func appendMapKeyValue(ctx *encoder.RuntimeContext, code *encoder.Opcode, b, key, value []byte) []byte { - b = appendIndent(ctx, b, code.Indent+1) - b = append(b, key...) - b[len(b)-2] = ':' - b[len(b)-1] = ' ' - return append(b, value...) -} - -func appendMapEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = b[:len(b)-2] - b = append(b, '\n') - b = appendIndent(ctx, b, code.Indent) - return append(b, '}', ',', '\n') -} - -func appendArrayHead(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = append(b, '[', '\n') - return appendIndent(ctx, b, code.Indent+1) -} - -func appendArrayEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = b[:len(b)-2] - b = append(b, '\n') - b = appendIndent(ctx, b, code.Indent) - return append(b, ']', ',', '\n') -} - -func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '[', ']', ',', '\n') -} - -func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{', '}', ',', '\n') -} - -func appendObjectEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - b[last] = '\n' - b = appendIndent(ctx, b, code.Indent-1) - return append(b, '}', ',', '\n') -} - -func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - return encoder.AppendMarshalJSONIndent(ctx, code, b, v) -} - -func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - format := ctx.Option.ColorScheme.String - b = append(b, format.Header...) - bb, err := encoder.AppendMarshalTextIndent(ctx, code, b, v) - if err != nil { - return nil, err - } - return append(bb, format.Footer...), nil -} - -func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{', '\n') -} - -func appendStructKey(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = appendIndent(ctx, b, code.Indent) - - format := ctx.Option.ColorScheme.ObjectKey - b = append(b, format.Header...) - b = append(b, code.Key[:len(code.Key)-1]...) - b = append(b, format.Footer...) - - return append(b, ':', ' ') -} - -func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - if b[last-1] == '{' { - b[last] = '}' - } else { - if b[last] == '\n' { - // to remove ',' and '\n' characters - b = b[:len(b)-2] - } - b = append(b, '\n') - b = appendIndent(ctx, b, code.Indent-1) - b = append(b, '}') - } - return appendComma(ctx, b) -} - -func restoreIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, ctxptr uintptr) { - ctx.BaseIndent = uint32(load(ctxptr, code.Length)) -} - -func storeIndent(ctxptr uintptr, code *encoder.Opcode, indent uintptr) { - store(ctxptr, code.Length, indent) -} - -func appendArrayElemIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - return appendIndent(ctx, b, code.Indent+1) -} - -func appendMapKeyIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - return appendIndent(ctx, b, code.Indent) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/vm.go deleted file mode 100644 index de8b858f..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/vm.go +++ /dev/null @@ -1,5041 +0,0 @@ -// Code generated by internal/cmd/generator. DO NOT EDIT! -package vm_color_indent - -import ( - "math" - "sort" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" -) - -func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - recursiveLevel := 0 - ptrOffset := uintptr(0) - ctxptr := ctx.Ptr() - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - for { - switch code.Op { - default: - return nil, errUnimplementedOp(code.Op) - case encoder.OpPtr: - p := load(ctxptr, code.Idx) - code = code.Next - store(ctxptr, code.Idx, ptrToPtr(p)) - case encoder.OpIntPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInt: - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpUint: - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpIntString: - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintString: - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat32Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat32: - b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat64Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat64: - v := ptrToFloat64(load(ctxptr, code.Idx)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStringPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpString: - b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBoolPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBool: - b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBytesPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBytes: - b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpNumberPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpNumber: - bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpInterfacePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInterface: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if p == seen { - return nil, errUnsupportedValue(code, p) - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, p) - iface := (*emptyInterface)(ptrToUnsafePtr(p)) - if iface.ptr == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(iface)) - ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(iface.typ))) - if err != nil { - return nil, err - } - - totalLength := uintptr(code.Length) + 3 - nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 - - var c *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - c = ifaceCodeSet.InterfaceEscapeKeyCode - } else { - c = ifaceCodeSet.InterfaceNoescapeKeyCode - } - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += totalLength * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + totalLength + nextTotalLength - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - end := ifaceCodeSet.EndCode - store(ctxptr, c.Idx, uintptr(iface.ptr)) - store(ctxptr, end.Idx, oldOffset) - store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, end, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpInterfaceEnd: - recursiveLevel-- - - // restore ctxptr - offset := load(ctxptr, code.Idx) - restoreIndent(ctx, code, ctxptr) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - b = append(b, `""`...) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpSlicePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpSlice: - p := load(ctxptr, code.Idx) - slice := ptrToSlice(p) - if p == 0 || slice.Data == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(slice.Len)) - store(ctxptr, code.Idx, uintptr(slice.Data)) - if slice.Len > 0 { - b = appendArrayHead(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, uintptr(slice.Data)) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpSliceElem: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if idx < length { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - data := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, data+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpArrayPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpArray: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - if code.Length > 0 { - b = appendArrayHead(ctx, code, b) - store(ctxptr, code.ElemIdx, 0) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpArrayElem: - idx := load(ctxptr, code.ElemIdx) - idx++ - if idx < uintptr(code.Length) { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - p := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, p+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpMapPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpMap: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - uptr := ptrToUnsafePtr(p) - mlen := maplen(uptr) - if mlen <= 0 { - b = appendEmptyObject(ctx, b) - code = code.End.Next - break - } - b = appendStructHead(ctx, b) - iter := mapiterinit(code.Type, uptr) - ctx.KeepRefs = append(ctx.KeepRefs, iter) - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(mlen)) - store(ctxptr, code.MapIter, uintptr(iter)) - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendMapKeyIndent(ctx, code.Next, b) - } else { - mapCtx := encoder.NewMapContext(mlen) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) - store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) - } - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - case encoder.OpMapKey: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - if idx < length { - b = appendMapKeyIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - b = appendObjectEnd(ctx, code, b) - code = code.End.Next - } - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - if idx < length { - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - store(ctxptr, code.ElemIdx, idx) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - code = code.End - } - } - case encoder.OpMapValue: - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendColon(ctx, b) - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - } - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - value := mapitervalue(iter) - store(ctxptr, code.Next.Idx, uintptr(value)) - mapiternext(iter) - code = code.Next - case encoder.OpMapEnd: - // this operation only used by sorted map. - length := int(load(ctxptr, code.Length)) - ptr := load(ctxptr, code.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - pos := mapCtx.Pos - for i := 0; i < length; i++ { - startKey := pos[i*2] - startValue := pos[i*2+1] - var endValue int - if i+1 < length { - endValue = pos[i*2+2] - } else { - endValue = len(b) - } - mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ - Key: b[startKey:startValue], - Value: b[startValue:endValue], - }) - } - sort.Sort(mapCtx.Slice) - buf := mapCtx.Buf - for _, item := range mapCtx.Slice.Items { - buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) - } - buf = appendMapEnd(ctx, code, buf) - b = b[:pos[0]] - b = append(b, buf...) - mapCtx.Buf = buf - encoder.ReleaseMapContext(mapCtx) - code = code.Next - case encoder.OpRecursivePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpRecursive: - ptr := load(ctxptr, code.Idx) - if ptr != 0 { - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if ptr == seen { - return nil, errUnsupportedValue(code, ptr) - } - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, ptr) - c := code.Jmp.Code - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += code.Jmp.CurLen * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - store(ctxptr, c.Idx, ptr) - store(ctxptr, c.End.Next.Idx, oldOffset) - store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpRecursiveEnd: - recursiveLevel-- - - // restore ctxptr - restoreIndent(ctx, code, ctxptr) - offset := load(ctxptr, code.Idx) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpStructPtrHead: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHead: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags&encoder.AnonymousKeyFlags) == 0 && len(code.Key) > 0 { - b = appendStructKey(ctx, code, b) - } - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - } - case encoder.OpStructPtrHeadNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructPtrHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyArray: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyArray: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptySlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptySlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - if maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructField: - if code.Flags&encoder.AnonymousKeyFlags == 0 { - b = appendStructKey(ctx, code, b) - } - p := load(ctxptr, code.Idx) + uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmpty: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringString: - p := load(ctxptr, code.Idx) - s := ptrToString(p + uintptr(code.Offset)) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldMarshalJSON: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalJSONPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldMarshalText: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalTextPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldArrayPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArrayPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldSlice: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlice: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldSlicePtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldMap: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMap: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldMapPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldStruct: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyStruct: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructAnonymousEnd: - code = code.Next - case encoder.OpStructEnd: - b = appendStructEndSkipLast(ctx, code, b) - code = code.Next - case encoder.OpStructEndInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendStructEnd(ctx, code, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - s := ptrToString(p + uintptr(code.Offset)) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytesPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - code = code.Next - case encoder.OpStructEndOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpEnd: - goto END - } - } -END: - return b, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/debug_vm.go deleted file mode 100644 index 4cfd17ab..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/debug_vm.go +++ /dev/null @@ -1,34 +0,0 @@ -package vm_indent - -import ( - "fmt" - - "github.com/goccy/go-json/internal/encoder" -) - -func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - defer func() { - if err := recover(); err != nil { - fmt.Println("=============[DEBUG]===============") - fmt.Println("* [TYPE]") - fmt.Println(codeSet.Type) - fmt.Printf("\n") - fmt.Println("* [ALL OPCODE]") - fmt.Println(code.Dump()) - fmt.Printf("\n") - fmt.Println("* [CONTEXT]") - fmt.Printf("%+v\n", ctx) - fmt.Println("===================================") - panic(err) - } - }() - - return Run(ctx, b, codeSet) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/hack.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/hack.go deleted file mode 100644 index 9e245bfe..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/hack.go +++ /dev/null @@ -1,9 +0,0 @@ -package vm_indent - -import ( - // HACK: compile order - // `vm`, `vm_indent`, `vm_color`, `vm_color_indent` packages uses a lot of memory to compile, - // so forcibly make dependencies and avoid compiling in concurrent. - // dependency order: vm => vm_indent => vm_color => vm_color_indent - _ "github.com/goccy/go-json/internal/encoder/vm_color" -) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/util.go deleted file mode 100644 index 5f5d8a58..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/util.go +++ /dev/null @@ -1,204 +0,0 @@ -package vm_indent - -import ( - "encoding/json" - "fmt" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" - "github.com/goccy/go-json/internal/runtime" -) - -const uintptrSize = 4 << (^uintptr(0) >> 63) - -var ( - appendInt = encoder.AppendInt - appendUint = encoder.AppendUint - appendFloat32 = encoder.AppendFloat32 - appendFloat64 = encoder.AppendFloat64 - appendString = encoder.AppendString - appendByteSlice = encoder.AppendByteSlice - appendNumber = encoder.AppendNumber - appendStructEnd = encoder.AppendStructEndIndent - appendIndent = encoder.AppendIndent - errUnsupportedValue = encoder.ErrUnsupportedValue - errUnsupportedFloat = encoder.ErrUnsupportedFloat - mapiterinit = encoder.MapIterInit - mapiterkey = encoder.MapIterKey - mapitervalue = encoder.MapIterValue - mapiternext = encoder.MapIterNext - maplen = encoder.MapLen -) - -type emptyInterface struct { - typ *runtime.Type - ptr unsafe.Pointer -} - -func errUnimplementedOp(op encoder.OpType) error { - return fmt.Errorf("encoder (indent): opcode %s has not been implemented", op) -} - -func load(base uintptr, idx uint32) uintptr { - addr := base + uintptr(idx) - return **(**uintptr)(unsafe.Pointer(&addr)) -} - -func store(base uintptr, idx uint32, p uintptr) { - addr := base + uintptr(idx) - **(**uintptr)(unsafe.Pointer(&addr)) = p -} - -func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { - addr := base + uintptr(idx) - p := **(**uintptr)(unsafe.Pointer(&addr)) - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUint64(p uintptr) uint64 { return **(**uint64)(unsafe.Pointer(&p)) } -func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } -func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } -func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } -func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } -func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } -func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } -func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } -func ptrToPtr(p uintptr) uintptr { - return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) -} -func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { - for i := uint8(0); i < ptrNum; i++ { - if p == 0 { - return 0 - } - p = ptrToPtr(p) - } - return p -} - -func ptrToUnsafePtr(p uintptr) unsafe.Pointer { - return *(*unsafe.Pointer)(unsafe.Pointer(&p)) -} -func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { - return *(*interface{})(unsafe.Pointer(&emptyInterface{ - typ: code.Type, - ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), - })) -} - -func appendBool(_ *encoder.RuntimeContext, b []byte, v bool) []byte { - if v { - return append(b, "true"...) - } - return append(b, "false"...) -} - -func appendNull(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, "null"...) -} - -func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, ',', '\n') -} - -func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, ':', ' ') -} - -func appendMapKeyValue(ctx *encoder.RuntimeContext, code *encoder.Opcode, b, key, value []byte) []byte { - b = appendIndent(ctx, b, code.Indent+1) - b = append(b, key...) - b[len(b)-2] = ':' - b[len(b)-1] = ' ' - return append(b, value...) -} - -func appendMapEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = b[:len(b)-2] - b = append(b, '\n') - b = appendIndent(ctx, b, code.Indent) - return append(b, '}', ',', '\n') -} - -func appendArrayHead(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = append(b, '[', '\n') - return appendIndent(ctx, b, code.Indent+1) -} - -func appendArrayEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = b[:len(b)-2] - b = append(b, '\n') - b = appendIndent(ctx, b, code.Indent) - return append(b, ']', ',', '\n') -} - -func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '[', ']', ',', '\n') -} - -func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{', '}', ',', '\n') -} - -func appendObjectEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - b[last] = '\n' - b = appendIndent(ctx, b, code.Indent-1) - return append(b, '}', ',', '\n') -} - -func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - return encoder.AppendMarshalJSONIndent(ctx, code, b, v) -} - -func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { - return encoder.AppendMarshalTextIndent(ctx, code, b, v) -} - -func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { - return append(b, '{', '\n') -} - -func appendStructKey(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - b = appendIndent(ctx, b, code.Indent) - b = append(b, code.Key...) - return append(b, ' ') -} - -func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - last := len(b) - 1 - if b[last-1] == '{' { - b[last] = '}' - } else { - if b[last] == '\n' { - // to remove ',' and '\n' characters - b = b[:len(b)-2] - } - b = append(b, '\n') - b = appendIndent(ctx, b, code.Indent-1) - b = append(b, '}') - } - return appendComma(ctx, b) -} - -func restoreIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, ctxptr uintptr) { - ctx.BaseIndent = uint32(load(ctxptr, code.Length)) -} - -func storeIndent(ctxptr uintptr, code *encoder.Opcode, indent uintptr) { - store(ctxptr, code.Length, indent) -} - -func appendArrayElemIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - return appendIndent(ctx, b, code.Indent+1) -} - -func appendMapKeyIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { - return appendIndent(ctx, b, code.Indent) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/vm.go deleted file mode 100644 index d10ce75c..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/vm.go +++ /dev/null @@ -1,5041 +0,0 @@ -// Code generated by internal/cmd/generator. DO NOT EDIT! -package vm_indent - -import ( - "math" - "sort" - "unsafe" - - "github.com/goccy/go-json/internal/encoder" -) - -func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { - recursiveLevel := 0 - ptrOffset := uintptr(0) - ctxptr := ctx.Ptr() - var code *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - code = codeSet.EscapeKeyCode - } else { - code = codeSet.NoescapeKeyCode - } - - for { - switch code.Op { - default: - return nil, errUnimplementedOp(code.Op) - case encoder.OpPtr: - p := load(ctxptr, code.Idx) - code = code.Next - store(ctxptr, code.Idx, ptrToPtr(p)) - case encoder.OpIntPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInt: - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpUint: - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpIntString: - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpUintString: - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(load(ctxptr, code.Idx)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat32Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat32: - b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpFloat64Ptr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpFloat64: - v := ptrToFloat64(load(ctxptr, code.Idx)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStringPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpString: - b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBoolPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBool: - b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpBytesPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpBytes: - b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpNumberPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpNumber: - bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpInterfacePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpInterface: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if p == seen { - return nil, errUnsupportedValue(code, p) - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, p) - iface := (*emptyInterface)(ptrToUnsafePtr(p)) - if iface.ptr == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(iface)) - ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(iface.typ))) - if err != nil { - return nil, err - } - - totalLength := uintptr(code.Length) + 3 - nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 - - var c *encoder.Opcode - if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { - c = ifaceCodeSet.InterfaceEscapeKeyCode - } else { - c = ifaceCodeSet.InterfaceNoescapeKeyCode - } - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += totalLength * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + totalLength + nextTotalLength - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - end := ifaceCodeSet.EndCode - store(ctxptr, c.Idx, uintptr(iface.ptr)) - store(ctxptr, end.Idx, oldOffset) - store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, end, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpInterfaceEnd: - recursiveLevel-- - - // restore ctxptr - offset := load(ctxptr, code.Idx) - restoreIndent(ctx, code, ctxptr) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToPtr(p)) - fallthrough - case encoder.OpMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - b = append(b, `""`...) - b = appendComma(ctx, b) - code = code.Next - break - } - if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p) - } - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpSlicePtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpSlice: - p := load(ctxptr, code.Idx) - slice := ptrToSlice(p) - if p == 0 || slice.Data == nil { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(slice.Len)) - store(ctxptr, code.Idx, uintptr(slice.Data)) - if slice.Len > 0 { - b = appendArrayHead(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, uintptr(slice.Data)) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpSliceElem: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if idx < length { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - data := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, data+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpArrayPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpArray: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - if code.Length > 0 { - b = appendArrayHead(ctx, code, b) - store(ctxptr, code.ElemIdx, 0) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - b = appendEmptyArray(ctx, b) - code = code.End.Next - } - case encoder.OpArrayElem: - idx := load(ctxptr, code.ElemIdx) - idx++ - if idx < uintptr(code.Length) { - b = appendArrayElemIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - p := load(ctxptr, code.Idx) - size := uintptr(code.Size) - code = code.Next - store(ctxptr, code.Idx, p+idx*size) - } else { - b = appendArrayEnd(ctx, code, b) - code = code.End.Next - } - case encoder.OpMapPtr: - p := loadNPtr(ctxptr, code.Idx, code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - store(ctxptr, code.Idx, p) - fallthrough - case encoder.OpMap: - p := load(ctxptr, code.Idx) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.End.Next - break - } - uptr := ptrToUnsafePtr(p) - mlen := maplen(uptr) - if mlen <= 0 { - b = appendEmptyObject(ctx, b) - code = code.End.Next - break - } - b = appendStructHead(ctx, b) - iter := mapiterinit(code.Type, uptr) - ctx.KeepRefs = append(ctx.KeepRefs, iter) - store(ctxptr, code.ElemIdx, 0) - store(ctxptr, code.Length, uintptr(mlen)) - store(ctxptr, code.MapIter, uintptr(iter)) - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendMapKeyIndent(ctx, code.Next, b) - } else { - mapCtx := encoder.NewMapContext(mlen) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) - store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) - } - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - case encoder.OpMapKey: - idx := load(ctxptr, code.ElemIdx) - length := load(ctxptr, code.Length) - idx++ - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - if idx < length { - b = appendMapKeyIndent(ctx, code, b) - store(ctxptr, code.ElemIdx, idx) - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - b = appendObjectEnd(ctx, code, b) - code = code.End.Next - } - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - if idx < length { - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - store(ctxptr, code.ElemIdx, idx) - key := mapiterkey(iter) - store(ctxptr, code.Next.Idx, uintptr(key)) - code = code.Next - } else { - code = code.End - } - } - case encoder.OpMapValue: - if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { - b = appendColon(ctx, b) - } else { - ptr := load(ctxptr, code.End.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - mapCtx.Pos = append(mapCtx.Pos, len(b)) - } - ptr := load(ctxptr, code.MapIter) - iter := ptrToUnsafePtr(ptr) - value := mapitervalue(iter) - store(ctxptr, code.Next.Idx, uintptr(value)) - mapiternext(iter) - code = code.Next - case encoder.OpMapEnd: - // this operation only used by sorted map. - length := int(load(ctxptr, code.Length)) - ptr := load(ctxptr, code.MapPos) - mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) - pos := mapCtx.Pos - for i := 0; i < length; i++ { - startKey := pos[i*2] - startValue := pos[i*2+1] - var endValue int - if i+1 < length { - endValue = pos[i*2+2] - } else { - endValue = len(b) - } - mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ - Key: b[startKey:startValue], - Value: b[startValue:endValue], - }) - } - sort.Sort(mapCtx.Slice) - buf := mapCtx.Buf - for _, item := range mapCtx.Slice.Items { - buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) - } - buf = appendMapEnd(ctx, code, buf) - b = b[:pos[0]] - b = append(b, buf...) - mapCtx.Buf = buf - encoder.ReleaseMapContext(mapCtx) - code = code.Next - case encoder.OpRecursivePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - code = code.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpRecursive: - ptr := load(ctxptr, code.Idx) - if ptr != 0 { - if recursiveLevel > encoder.StartDetectingCyclesAfter { - for _, seen := range ctx.SeenPtr { - if ptr == seen { - return nil, errUnsupportedValue(code, ptr) - } - } - } - } - ctx.SeenPtr = append(ctx.SeenPtr, ptr) - c := code.Jmp.Code - curlen := uintptr(len(ctx.Ptrs)) - offsetNum := ptrOffset / uintptrSize - oldOffset := ptrOffset - ptrOffset += code.Jmp.CurLen * uintptrSize - oldBaseIndent := ctx.BaseIndent - indentDiffFromTop := c.Indent - 1 - ctx.BaseIndent += code.Indent - indentDiffFromTop - - newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen - if curlen < newLen { - ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) - } - ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr - - store(ctxptr, c.Idx, ptr) - store(ctxptr, c.End.Next.Idx, oldOffset) - store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) - storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) - code = c - recursiveLevel++ - case encoder.OpRecursiveEnd: - recursiveLevel-- - - // restore ctxptr - restoreIndent(ctx, code, ctxptr) - offset := load(ctxptr, code.Idx) - ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] - - codePtr := load(ctxptr, code.ElemIdx) - code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) - ctxptr = ctx.Ptr() + offset - ptrOffset = offset - case encoder.OpStructPtrHead: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHead: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags&encoder.AnonymousKeyFlags) == 0 && len(code.Key) > 0 { - b = appendStructKey(ctx, code, b) - } - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmpty: - p := load(ctxptr, code.Idx) - if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyInt: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyInt: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyIntString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUint: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUint: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyUintString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat32(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64String: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToFloat64(p + uintptr(code.Offset)) - if v == 0 { - code = code.NextField - } else { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyStringString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToString(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBool: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBool: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - } else { - code = code.NextField - } - case encoder.OpStructPtrHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytes: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyBytes: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumber: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumber: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - } - case encoder.OpStructPtrHeadNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberString: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - v := ptrToNumber(p + uintptr(code.Offset)) - if v == "" { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructPtrHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyArray: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyArray: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptySlice: - if (code.Flags & encoder.IndirectFlags) != 0 { - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptySlice: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructPtrHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMap: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { - p = ptrToPtr(p + uintptr(code.Offset)) - } - if maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - break - } - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 { - code = code.NextField - } else { - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructPtrHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - } - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { - p = ptrToPtr(p + uintptr(code.Offset)) - } - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructPtrHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - b = appendStructKey(ctx, code, b) - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) - fallthrough - case encoder.OpStructHeadOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - } - code = code.End.Next - break - } - if (code.Flags & encoder.IndirectFlags) != 0 { - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - } - if code.Flags&encoder.AnonymousHeadFlags == 0 { - b = appendStructHead(ctx, b) - } - if p == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - b = appendComma(ctx, b) - code = code.Next - } - case encoder.OpStructField: - if code.Flags&encoder.AnonymousKeyFlags == 0 { - b = appendStructKey(ctx, code, b) - } - p := load(ctxptr, code.Idx) + uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmpty: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - b = appendComma(ctx, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringString: - p := load(ctxptr, code.Idx) - s := ptrToString(p + uintptr(code.Offset)) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - b = appendStructKey(ctx, code, b) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendComma(ctx, b) - } - code = code.Next - case encoder.OpStructFieldMarshalJSON: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSON: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - iface := ptrToInterface(code, p) - if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, iface) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalJSONPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldMarshalText: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalText: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if (code.Flags & encoder.IsNilableTypeFlags) != 0 { - p = ptrToPtr(p) - } - if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { - code = code.NextField - break - } - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - code = code.Next - case encoder.OpStructFieldMarshalTextPtr: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendComma(ctx, b) - code = code.Next - case encoder.OpStructFieldOmitEmptyMarshalTextPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) - if err != nil { - return nil, err - } - b = appendComma(ctx, bb) - } - code = code.Next - case encoder.OpStructFieldArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArray: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldArrayPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyArrayPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldSlice: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlice: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - slice := ptrToSlice(p) - if slice.Len == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldSlicePtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptySlicePtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldMap: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMap: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructFieldMapPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyMapPtr: - p := load(ctxptr, code.Idx) - p = ptrToPtr(p + uintptr(code.Offset)) - if p != 0 { - p = ptrToNPtr(p, code.PtrNum) - } - if p != 0 { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } else { - code = code.NextField - } - case encoder.OpStructFieldStruct: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - code = code.Next - store(ctxptr, code.Idx, p) - case encoder.OpStructFieldOmitEmptyStruct: - p := load(ctxptr, code.Idx) - p += uintptr(code.Offset) - if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { - code = code.NextField - } else { - b = appendStructKey(ctx, code, b) - code = code.Next - store(ctxptr, code.Idx, p) - } - case encoder.OpStructAnonymousEnd: - code = code.Next - case encoder.OpStructEnd: - b = appendStructEndSkipLast(ctx, code, b) - code = code.Next - case encoder.OpStructEndInt: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyInt: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendInt(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendInt(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndIntPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyIntPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendInt(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUint: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUint: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, u64, code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p+uintptr(code.Offset)), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintString: - p := load(ctxptr, code.Idx) - u64 := ptrToUint64(p + uintptr(code.Offset)) - v := u64 & ((1 << code.NumBitSize) - 1) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, u64, code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendUint(ctx, b, ptrToUint64(p), code) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendUint(ctx, b, ptrToUint64(p), code) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndUintPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyUintPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendUint(ctx, b, ptrToUint64(p), code) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32String: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32String: - p := load(ctxptr, code.Idx) - v := ptrToFloat32(p + uintptr(code.Offset)) - if v != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendFloat32(ctx, b, ptrToFloat32(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat32PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat32PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat32(ctx, b, ptrToFloat32(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64String: - p := load(ctxptr, code.Idx) - v := ptrToFloat64(p + uintptr(code.Offset)) - if v != 0 { - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64Ptr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - b = appendStructEnd(ctx, code, b) - code = code.Next - break - } - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64Ptr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndFloat64PtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = appendFloat64(ctx, b, v) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyFloat64PtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - v := ptrToFloat64(p) - if math.IsInf(v, 0) || math.IsNaN(v) { - return nil, errUnsupportedFloat(v) - } - b = append(b, '"') - b = appendFloat64(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - s := ptrToString(p + uintptr(code.Offset)) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringString: - p := load(ctxptr, code.Idx) - v := ptrToString(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, ptrToString(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, ptrToString(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndStringPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyStringPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBool: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBool: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolString: - p := load(ctxptr, code.Idx) - v := ptrToBool(p + uintptr(code.Offset)) - if v { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, v) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendBool(ctx, b, ptrToBool(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendBool(ctx, b, ptrToBool(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBoolPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBoolPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - b = appendBool(ctx, b, ptrToBool(p)) - b = append(b, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytes: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytes: - p := load(ctxptr, code.Idx) - v := ptrToBytes(p + uintptr(code.Offset)) - if len(v) > 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, v) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndBytesPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = appendByteSlice(ctx, b, ptrToBytes(p)) - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyBytesPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = appendByteSlice(ctx, b, ptrToBytes(p)) - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumber: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - code = code.Next - case encoder.OpStructEndOmitEmptyNumber: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberString: - p := load(ctxptr, code.Idx) - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberString: - p := load(ctxptr, code.Idx) - v := ptrToNumber(p + uintptr(code.Offset)) - if v != "" { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, v) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtr: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = bb - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtr: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = appendStructEnd(ctx, code, bb) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpStructEndNumberPtrString: - b = appendStructKey(ctx, code, b) - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p == 0 { - b = appendNull(ctx, b) - } else { - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - } - b = appendStructEnd(ctx, code, b) - code = code.Next - case encoder.OpStructEndOmitEmptyNumberPtrString: - p := load(ctxptr, code.Idx) - p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) - if p != 0 { - b = appendStructKey(ctx, code, b) - b = append(b, '"') - bb, err := appendNumber(ctx, b, ptrToNumber(p)) - if err != nil { - return nil, err - } - b = append(bb, '"') - b = appendStructEnd(ctx, code, b) - } else { - b = appendStructEndSkipLast(ctx, code, b) - } - code = code.Next - case encoder.OpEnd: - goto END - } - } -END: - return b, nil -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/errors/error.go b/taskman-server/vendor/github.com/goccy/go-json/internal/errors/error.go deleted file mode 100644 index 329e2f12..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/errors/error.go +++ /dev/null @@ -1,157 +0,0 @@ -package errors - -import ( - "fmt" - "reflect" - "strconv" -) - -type InvalidUTF8Error struct { - S string // the whole string value that caused the error -} - -func (e *InvalidUTF8Error) Error() string { - return fmt.Sprintf("json: invalid UTF-8 in string: %s", strconv.Quote(e.S)) -} - -type InvalidUnmarshalError struct { - Type reflect.Type -} - -func (e *InvalidUnmarshalError) Error() string { - if e.Type == nil { - return "json: Unmarshal(nil)" - } - - if e.Type.Kind() != reflect.Ptr { - return fmt.Sprintf("json: Unmarshal(non-pointer %s)", e.Type) - } - return fmt.Sprintf("json: Unmarshal(nil %s)", e.Type) -} - -// A MarshalerError represents an error from calling a MarshalJSON or MarshalText method. -type MarshalerError struct { - Type reflect.Type - Err error - sourceFunc string -} - -func (e *MarshalerError) Error() string { - srcFunc := e.sourceFunc - if srcFunc == "" { - srcFunc = "MarshalJSON" - } - return fmt.Sprintf("json: error calling %s for type %s: %s", srcFunc, e.Type, e.Err.Error()) -} - -// Unwrap returns the underlying error. -func (e *MarshalerError) Unwrap() error { return e.Err } - -// A SyntaxError is a description of a JSON syntax error. -type SyntaxError struct { - msg string // description of error - Offset int64 // error occurred after reading Offset bytes -} - -func (e *SyntaxError) Error() string { return e.msg } - -// An UnmarshalFieldError describes a JSON object key that -// led to an unexported (and therefore unwritable) struct field. -// -// Deprecated: No longer used; kept for compatibility. -type UnmarshalFieldError struct { - Key string - Type reflect.Type - Field reflect.StructField -} - -func (e *UnmarshalFieldError) Error() string { - return fmt.Sprintf("json: cannot unmarshal object key %s into unexported field %s of type %s", - strconv.Quote(e.Key), e.Field.Name, e.Type.String(), - ) -} - -// An UnmarshalTypeError describes a JSON value that was -// not appropriate for a value of a specific Go type. -type UnmarshalTypeError struct { - Value string // description of JSON value - "bool", "array", "number -5" - Type reflect.Type // type of Go value it could not be assigned to - Offset int64 // error occurred after reading Offset bytes - Struct string // name of the struct type containing the field - Field string // the full path from root node to the field -} - -func (e *UnmarshalTypeError) Error() string { - if e.Struct != "" || e.Field != "" { - return fmt.Sprintf("json: cannot unmarshal %s into Go struct field %s.%s of type %s", - e.Value, e.Struct, e.Field, e.Type, - ) - } - return fmt.Sprintf("json: cannot unmarshal %s into Go value of type %s", e.Value, e.Type) -} - -// An UnsupportedTypeError is returned by Marshal when attempting -// to encode an unsupported value type. -type UnsupportedTypeError struct { - Type reflect.Type -} - -func (e *UnsupportedTypeError) Error() string { - return fmt.Sprintf("json: unsupported type: %s", e.Type) -} - -type UnsupportedValueError struct { - Value reflect.Value - Str string -} - -func (e *UnsupportedValueError) Error() string { - return fmt.Sprintf("json: unsupported value: %s", e.Str) -} - -func ErrSyntax(msg string, offset int64) *SyntaxError { - return &SyntaxError{msg: msg, Offset: offset} -} - -func ErrMarshaler(typ reflect.Type, err error, msg string) *MarshalerError { - return &MarshalerError{ - Type: typ, - Err: err, - sourceFunc: msg, - } -} - -func ErrExceededMaxDepth(c byte, cursor int64) *SyntaxError { - return &SyntaxError{ - msg: fmt.Sprintf(`invalid character "%c" exceeded max depth`, c), - Offset: cursor, - } -} - -func ErrNotAtBeginningOfValue(cursor int64) *SyntaxError { - return &SyntaxError{msg: "not at beginning of value", Offset: cursor} -} - -func ErrUnexpectedEndOfJSON(msg string, cursor int64) *SyntaxError { - return &SyntaxError{ - msg: fmt.Sprintf("json: %s unexpected end of JSON input", msg), - Offset: cursor, - } -} - -func ErrExpected(msg string, cursor int64) *SyntaxError { - return &SyntaxError{msg: fmt.Sprintf("expected %s", msg), Offset: cursor} -} - -func ErrInvalidCharacter(c byte, context string, cursor int64) *SyntaxError { - if c == 0 { - return &SyntaxError{ - msg: fmt.Sprintf("json: invalid character as %s", context), - Offset: cursor, - } - } - return &SyntaxError{ - msg: fmt.Sprintf("json: invalid character %c as %s", c, context), - Offset: cursor, - } -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/rtype.go b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/rtype.go deleted file mode 100644 index 4db10deb..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/rtype.go +++ /dev/null @@ -1,263 +0,0 @@ -package runtime - -import ( - "reflect" - "unsafe" -) - -// Type representing reflect.rtype for noescape trick -type Type struct{} - -//go:linkname rtype_Align reflect.(*rtype).Align -//go:noescape -func rtype_Align(*Type) int - -func (t *Type) Align() int { - return rtype_Align(t) -} - -//go:linkname rtype_FieldAlign reflect.(*rtype).FieldAlign -//go:noescape -func rtype_FieldAlign(*Type) int - -func (t *Type) FieldAlign() int { - return rtype_FieldAlign(t) -} - -//go:linkname rtype_Method reflect.(*rtype).Method -//go:noescape -func rtype_Method(*Type, int) reflect.Method - -func (t *Type) Method(a0 int) reflect.Method { - return rtype_Method(t, a0) -} - -//go:linkname rtype_MethodByName reflect.(*rtype).MethodByName -//go:noescape -func rtype_MethodByName(*Type, string) (reflect.Method, bool) - -func (t *Type) MethodByName(a0 string) (reflect.Method, bool) { - return rtype_MethodByName(t, a0) -} - -//go:linkname rtype_NumMethod reflect.(*rtype).NumMethod -//go:noescape -func rtype_NumMethod(*Type) int - -func (t *Type) NumMethod() int { - return rtype_NumMethod(t) -} - -//go:linkname rtype_Name reflect.(*rtype).Name -//go:noescape -func rtype_Name(*Type) string - -func (t *Type) Name() string { - return rtype_Name(t) -} - -//go:linkname rtype_PkgPath reflect.(*rtype).PkgPath -//go:noescape -func rtype_PkgPath(*Type) string - -func (t *Type) PkgPath() string { - return rtype_PkgPath(t) -} - -//go:linkname rtype_Size reflect.(*rtype).Size -//go:noescape -func rtype_Size(*Type) uintptr - -func (t *Type) Size() uintptr { - return rtype_Size(t) -} - -//go:linkname rtype_String reflect.(*rtype).String -//go:noescape -func rtype_String(*Type) string - -func (t *Type) String() string { - return rtype_String(t) -} - -//go:linkname rtype_Kind reflect.(*rtype).Kind -//go:noescape -func rtype_Kind(*Type) reflect.Kind - -func (t *Type) Kind() reflect.Kind { - return rtype_Kind(t) -} - -//go:linkname rtype_Implements reflect.(*rtype).Implements -//go:noescape -func rtype_Implements(*Type, reflect.Type) bool - -func (t *Type) Implements(u reflect.Type) bool { - return rtype_Implements(t, u) -} - -//go:linkname rtype_AssignableTo reflect.(*rtype).AssignableTo -//go:noescape -func rtype_AssignableTo(*Type, reflect.Type) bool - -func (t *Type) AssignableTo(u reflect.Type) bool { - return rtype_AssignableTo(t, u) -} - -//go:linkname rtype_ConvertibleTo reflect.(*rtype).ConvertibleTo -//go:noescape -func rtype_ConvertibleTo(*Type, reflect.Type) bool - -func (t *Type) ConvertibleTo(u reflect.Type) bool { - return rtype_ConvertibleTo(t, u) -} - -//go:linkname rtype_Comparable reflect.(*rtype).Comparable -//go:noescape -func rtype_Comparable(*Type) bool - -func (t *Type) Comparable() bool { - return rtype_Comparable(t) -} - -//go:linkname rtype_Bits reflect.(*rtype).Bits -//go:noescape -func rtype_Bits(*Type) int - -func (t *Type) Bits() int { - return rtype_Bits(t) -} - -//go:linkname rtype_ChanDir reflect.(*rtype).ChanDir -//go:noescape -func rtype_ChanDir(*Type) reflect.ChanDir - -func (t *Type) ChanDir() reflect.ChanDir { - return rtype_ChanDir(t) -} - -//go:linkname rtype_IsVariadic reflect.(*rtype).IsVariadic -//go:noescape -func rtype_IsVariadic(*Type) bool - -func (t *Type) IsVariadic() bool { - return rtype_IsVariadic(t) -} - -//go:linkname rtype_Elem reflect.(*rtype).Elem -//go:noescape -func rtype_Elem(*Type) reflect.Type - -func (t *Type) Elem() *Type { - return Type2RType(rtype_Elem(t)) -} - -//go:linkname rtype_Field reflect.(*rtype).Field -//go:noescape -func rtype_Field(*Type, int) reflect.StructField - -func (t *Type) Field(i int) reflect.StructField { - return rtype_Field(t, i) -} - -//go:linkname rtype_FieldByIndex reflect.(*rtype).FieldByIndex -//go:noescape -func rtype_FieldByIndex(*Type, []int) reflect.StructField - -func (t *Type) FieldByIndex(index []int) reflect.StructField { - return rtype_FieldByIndex(t, index) -} - -//go:linkname rtype_FieldByName reflect.(*rtype).FieldByName -//go:noescape -func rtype_FieldByName(*Type, string) (reflect.StructField, bool) - -func (t *Type) FieldByName(name string) (reflect.StructField, bool) { - return rtype_FieldByName(t, name) -} - -//go:linkname rtype_FieldByNameFunc reflect.(*rtype).FieldByNameFunc -//go:noescape -func rtype_FieldByNameFunc(*Type, func(string) bool) (reflect.StructField, bool) - -func (t *Type) FieldByNameFunc(match func(string) bool) (reflect.StructField, bool) { - return rtype_FieldByNameFunc(t, match) -} - -//go:linkname rtype_In reflect.(*rtype).In -//go:noescape -func rtype_In(*Type, int) reflect.Type - -func (t *Type) In(i int) reflect.Type { - return rtype_In(t, i) -} - -//go:linkname rtype_Key reflect.(*rtype).Key -//go:noescape -func rtype_Key(*Type) reflect.Type - -func (t *Type) Key() *Type { - return Type2RType(rtype_Key(t)) -} - -//go:linkname rtype_Len reflect.(*rtype).Len -//go:noescape -func rtype_Len(*Type) int - -func (t *Type) Len() int { - return rtype_Len(t) -} - -//go:linkname rtype_NumField reflect.(*rtype).NumField -//go:noescape -func rtype_NumField(*Type) int - -func (t *Type) NumField() int { - return rtype_NumField(t) -} - -//go:linkname rtype_NumIn reflect.(*rtype).NumIn -//go:noescape -func rtype_NumIn(*Type) int - -func (t *Type) NumIn() int { - return rtype_NumIn(t) -} - -//go:linkname rtype_NumOut reflect.(*rtype).NumOut -//go:noescape -func rtype_NumOut(*Type) int - -func (t *Type) NumOut() int { - return rtype_NumOut(t) -} - -//go:linkname rtype_Out reflect.(*rtype).Out -//go:noescape -func rtype_Out(*Type, int) reflect.Type - -//go:linkname PtrTo reflect.(*rtype).ptrTo -//go:noescape -func PtrTo(*Type) *Type - -func (t *Type) Out(i int) reflect.Type { - return rtype_Out(t, i) -} - -//go:linkname IfaceIndir reflect.ifaceIndir -//go:noescape -func IfaceIndir(*Type) bool - -//go:linkname RType2Type reflect.toType -//go:noescape -func RType2Type(t *Type) reflect.Type - -//go:nolint structcheck -type emptyInterface struct { - _ *Type - ptr unsafe.Pointer -} - -func Type2RType(t reflect.Type) *Type { - return (*Type)(((*emptyInterface)(unsafe.Pointer(&t))).ptr) -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/struct_field.go b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/struct_field.go deleted file mode 100644 index c321180a..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/struct_field.go +++ /dev/null @@ -1,87 +0,0 @@ -package runtime - -import ( - "reflect" - "strings" - "unicode" -) - -func getTag(field reflect.StructField) string { - return field.Tag.Get("json") -} - -func IsIgnoredStructField(field reflect.StructField) bool { - if field.PkgPath != "" { - if field.Anonymous { - if !(field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct) && field.Type.Kind() != reflect.Struct { - return true - } - } else { - // private field - return true - } - } - tag := getTag(field) - return tag == "-" -} - -type StructTag struct { - Key string - IsTaggedKey bool - IsOmitEmpty bool - IsString bool - Field reflect.StructField -} - -type StructTags []*StructTag - -func (t StructTags) ExistsKey(key string) bool { - for _, tt := range t { - if tt.Key == key { - return true - } - } - return false -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - case !unicode.IsLetter(c) && !unicode.IsDigit(c): - return false - } - } - return true -} - -func StructTagFromField(field reflect.StructField) *StructTag { - keyName := field.Name - tag := getTag(field) - st := &StructTag{Field: field} - opts := strings.Split(tag, ",") - if len(opts) > 0 { - if opts[0] != "" && isValidTag(opts[0]) { - keyName = opts[0] - st.IsTaggedKey = true - } - } - st.Key = keyName - if len(opts) > 1 { - for _, opt := range opts[1:] { - switch opt { - case "omitempty": - st.IsOmitEmpty = true - case "string": - st.IsString = true - } - } - } - return st -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/type.go b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/type.go deleted file mode 100644 index 0167cd2c..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/type.go +++ /dev/null @@ -1,100 +0,0 @@ -package runtime - -import ( - "reflect" - "unsafe" -) - -type SliceHeader struct { - Data unsafe.Pointer - Len int - Cap int -} - -const ( - maxAcceptableTypeAddrRange = 1024 * 1024 * 2 // 2 Mib -) - -type TypeAddr struct { - BaseTypeAddr uintptr - MaxTypeAddr uintptr - AddrRange uintptr - AddrShift uintptr -} - -var ( - typeAddr *TypeAddr - alreadyAnalyzed bool -) - -//go:linkname typelinks reflect.typelinks -func typelinks() ([]unsafe.Pointer, [][]int32) - -//go:linkname rtypeOff reflect.rtypeOff -func rtypeOff(unsafe.Pointer, int32) unsafe.Pointer - -func AnalyzeTypeAddr() *TypeAddr { - defer func() { - alreadyAnalyzed = true - }() - if alreadyAnalyzed { - return typeAddr - } - sections, offsets := typelinks() - if len(sections) != 1 { - return nil - } - if len(offsets) != 1 { - return nil - } - section := sections[0] - offset := offsets[0] - var ( - min uintptr = uintptr(^uint(0)) - max uintptr = 0 - isAligned64 = true - isAligned32 = true - ) - for i := 0; i < len(offset); i++ { - typ := (*Type)(rtypeOff(section, offset[i])) - addr := uintptr(unsafe.Pointer(typ)) - if min > addr { - min = addr - } - if max < addr { - max = addr - } - if typ.Kind() == reflect.Ptr { - addr = uintptr(unsafe.Pointer(typ.Elem())) - if min > addr { - min = addr - } - if max < addr { - max = addr - } - } - isAligned64 = isAligned64 && (addr-min)&63 == 0 - isAligned32 = isAligned32 && (addr-min)&31 == 0 - } - addrRange := max - min - if addrRange == 0 { - return nil - } - var addrShift uintptr - if isAligned64 { - addrShift = 6 - } else if isAligned32 { - addrShift = 5 - } - cacheSize := addrRange >> addrShift - if cacheSize > maxAcceptableTypeAddrRange { - return nil - } - typeAddr = &TypeAddr{ - BaseTypeAddr: min, - MaxTypeAddr: max, - AddrRange: addrRange, - AddrShift: addrShift, - } - return typeAddr -} diff --git a/taskman-server/vendor/github.com/goccy/go-json/json.go b/taskman-server/vendor/github.com/goccy/go-json/json.go deleted file mode 100644 index 5c9448d8..00000000 --- a/taskman-server/vendor/github.com/goccy/go-json/json.go +++ /dev/null @@ -1,366 +0,0 @@ -package json - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/goccy/go-json/internal/encoder" -) - -// Marshaler is the interface implemented by types that -// can marshal themselves into valid JSON. -type Marshaler interface { - MarshalJSON() ([]byte, error) -} - -// MarshalerContext is the interface implemented by types that -// can marshal themselves into valid JSON with context.Context. -type MarshalerContext interface { - MarshalJSON(context.Context) ([]byte, error) -} - -// Unmarshaler is the interface implemented by types -// that can unmarshal a JSON description of themselves. -// The input can be assumed to be a valid encoding of -// a JSON value. UnmarshalJSON must copy the JSON data -// if it wishes to retain the data after returning. -// -// By convention, to approximate the behavior of Unmarshal itself, -// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. -type Unmarshaler interface { - UnmarshalJSON([]byte) error -} - -// UnmarshalerContext is the interface implemented by types -// that can unmarshal with context.Context a JSON description of themselves. -type UnmarshalerContext interface { - UnmarshalJSON(context.Context, []byte) error -} - -// Marshal returns the JSON encoding of v. -// -// Marshal traverses the value v recursively. -// If an encountered value implements the Marshaler interface -// and is not a nil pointer, Marshal calls its MarshalJSON method -// to produce JSON. If no MarshalJSON method is present but the -// value implements encoding.TextMarshaler instead, Marshal calls -// its MarshalText method and encodes the result as a JSON string. -// The nil pointer exception is not strictly necessary -// but mimics a similar, necessary exception in the behavior of -// UnmarshalJSON. -// -// Otherwise, Marshal uses the following type-dependent default encodings: -// -// Boolean values encode as JSON booleans. -// -// Floating point, integer, and Number values encode as JSON numbers. -// -// String values encode as JSON strings coerced to valid UTF-8, -// replacing invalid bytes with the Unicode replacement rune. -// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" -// to keep some browsers from misinterpreting JSON output as HTML. -// Ampersand "&" is also escaped to "\u0026" for the same reason. -// This escaping can be disabled using an Encoder that had SetEscapeHTML(false) -// called on it. -// -// Array and slice values encode as JSON arrays, except that -// []byte encodes as a base64-encoded string, and a nil slice -// encodes as the null JSON value. -// -// Struct values encode as JSON objects. -// Each exported struct field becomes a member of the object, using the -// field name as the object key, unless the field is omitted for one of the -// reasons given below. -// -// The encoding of each struct field can be customized by the format string -// stored under the "json" key in the struct field's tag. -// The format string gives the name of the field, possibly followed by a -// comma-separated list of options. The name may be empty in order to -// specify options without overriding the default field name. -// -// The "omitempty" option specifies that the field should be omitted -// from the encoding if the field has an empty value, defined as -// false, 0, a nil pointer, a nil interface value, and any empty array, -// slice, map, or string. -// -// As a special case, if the field tag is "-", the field is always omitted. -// Note that a field with name "-" can still be generated using the tag "-,". -// -// Examples of struct field tags and their meanings: -// -// // Field appears in JSON as key "myName". -// Field int `json:"myName"` -// -// // Field appears in JSON as key "myName" and -// // the field is omitted from the object if its value is empty, -// // as defined above. -// Field int `json:"myName,omitempty"` -// -// // Field appears in JSON as key "Field" (the default), but -// // the field is skipped if empty. -// // Note the leading comma. -// Field int `json:",omitempty"` -// -// // Field is ignored by this package. -// Field int `json:"-"` -// -// // Field appears in JSON as key "-". -// Field int `json:"-,"` -// -// The "string" option signals that a field is stored as JSON inside a -// JSON-encoded string. It applies only to fields of string, floating point, -// integer, or boolean types. This extra level of encoding is sometimes used -// when communicating with JavaScript programs: -// -// Int64String int64 `json:",string"` -// -// The key name will be used if it's a non-empty string consisting of -// only Unicode letters, digits, and ASCII punctuation except quotation -// marks, backslash, and comma. -// -// Anonymous struct fields are usually marshaled as if their inner exported fields -// were fields in the outer struct, subject to the usual Go visibility rules amended -// as described in the next paragraph. -// An anonymous struct field with a name given in its JSON tag is treated as -// having that name, rather than being anonymous. -// An anonymous struct field of interface type is treated the same as having -// that type as its name, rather than being anonymous. -// -// The Go visibility rules for struct fields are amended for JSON when -// deciding which field to marshal or unmarshal. If there are -// multiple fields at the same level, and that level is the least -// nested (and would therefore be the nesting level selected by the -// usual Go rules), the following extra rules apply: -// -// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, -// even if there are multiple untagged fields that would otherwise conflict. -// -// 2) If there is exactly one field (tagged or not according to the first rule), that is selected. -// -// 3) Otherwise there are multiple fields, and all are ignored; no error occurs. -// -// Handling of anonymous struct fields is new in Go 1.1. -// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of -// an anonymous struct field in both current and earlier versions, give the field -// a JSON tag of "-". -// -// Map values encode as JSON objects. The map's key type must either be a -// string, an integer type, or implement encoding.TextMarshaler. The map keys -// are sorted and used as JSON object keys by applying the following rules, -// subject to the UTF-8 coercion described for string values above: -// - string keys are used directly -// - encoding.TextMarshalers are marshaled -// - integer keys are converted to strings -// -// Pointer values encode as the value pointed to. -// A nil pointer encodes as the null JSON value. -// -// Interface values encode as the value contained in the interface. -// A nil interface value encodes as the null JSON value. -// -// Channel, complex, and function values cannot be encoded in JSON. -// Attempting to encode such a value causes Marshal to return -// an UnsupportedTypeError. -// -// JSON cannot represent cyclic data structures and Marshal does not -// handle them. Passing cyclic structures to Marshal will result in -// an infinite recursion. -// -func Marshal(v interface{}) ([]byte, error) { - return MarshalWithOption(v) -} - -// MarshalNoEscape returns the JSON encoding of v and doesn't escape v. -func MarshalNoEscape(v interface{}) ([]byte, error) { - return marshalNoEscape(v) -} - -// MarshalContext returns the JSON encoding of v with context.Context and EncodeOption. -func MarshalContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { - return marshalContext(ctx, v, optFuncs...) -} - -// MarshalWithOption returns the JSON encoding of v with EncodeOption. -func MarshalWithOption(v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { - return marshal(v, optFuncs...) -} - -// MarshalIndent is like Marshal but applies Indent to format the output. -// Each JSON element in the output will begin on a new line beginning with prefix -// followed by one or more copies of indent according to the indentation nesting. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - return MarshalIndentWithOption(v, prefix, indent) -} - -// MarshalIndentWithOption is like Marshal but applies Indent to format the output with EncodeOption. -func MarshalIndentWithOption(v interface{}, prefix, indent string, optFuncs ...EncodeOptionFunc) ([]byte, error) { - return marshalIndent(v, prefix, indent, optFuncs...) -} - -// Unmarshal parses the JSON-encoded data and stores the result -// in the value pointed to by v. If v is nil or not a pointer, -// Unmarshal returns an InvalidUnmarshalError. -// -// Unmarshal uses the inverse of the encodings that -// Marshal uses, allocating maps, slices, and pointers as necessary, -// with the following additional rules: -// -// To unmarshal JSON into a pointer, Unmarshal first handles the case of -// the JSON being the JSON literal null. In that case, Unmarshal sets -// the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into -// the value pointed at by the pointer. If the pointer is nil, Unmarshal -// allocates a new value for it to point to. -// -// To unmarshal JSON into a value implementing the Unmarshaler interface, -// Unmarshal calls that value's UnmarshalJSON method, including -// when the input is a JSON null. -// Otherwise, if the value implements encoding.TextUnmarshaler -// and the input is a JSON quoted string, Unmarshal calls that value's -// UnmarshalText method with the unquoted form of the string. -// -// To unmarshal JSON into a struct, Unmarshal matches incoming object -// keys to the keys used by Marshal (either the struct field name or its tag), -// preferring an exact match but also accepting a case-insensitive match. By -// default, object keys which don't have a corresponding struct field are -// ignored (see Decoder.DisallowUnknownFields for an alternative). -// -// To unmarshal JSON into an interface value, -// Unmarshal stores one of these in the interface value: -// -// bool, for JSON booleans -// float64, for JSON numbers -// string, for JSON strings -// []interface{}, for JSON arrays -// map[string]interface{}, for JSON objects -// nil for JSON null -// -// To unmarshal a JSON array into a slice, Unmarshal resets the slice length -// to zero and then appends each element to the slice. -// As a special case, to unmarshal an empty JSON array into a slice, -// Unmarshal replaces the slice with a new empty slice. -// -// To unmarshal a JSON array into a Go array, Unmarshal decodes -// JSON array elements into corresponding Go array elements. -// If the Go array is smaller than the JSON array, -// the additional JSON array elements are discarded. -// If the JSON array is smaller than the Go array, -// the additional Go array elements are set to zero values. -// -// To unmarshal a JSON object into a map, Unmarshal first establishes a map to -// use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal -// reuses the existing map, keeping existing entries. Unmarshal then stores -// key-value pairs from the JSON object into the map. The map's key type must -// either be any string type, an integer, implement json.Unmarshaler, or -// implement encoding.TextUnmarshaler. -// -// If a JSON value is not appropriate for a given target type, -// or if a JSON number overflows the target type, Unmarshal -// skips that field and completes the unmarshaling as best it can. -// If no more serious errors are encountered, Unmarshal returns -// an UnmarshalTypeError describing the earliest such error. In any -// case, it's not guaranteed that all the remaining fields following -// the problematic one will be unmarshaled into the target object. -// -// The JSON null value unmarshals into an interface, map, pointer, or slice -// by setting that Go value to nil. Because null is often used in JSON to mean -// ``not present,'' unmarshaling a JSON null into any other Go type has no effect -// on the value and produces no error. -// -// When unmarshaling quoted strings, invalid UTF-8 or -// invalid UTF-16 surrogate pairs are not treated as an error. -// Instead, they are replaced by the Unicode replacement -// character U+FFFD. -// -func Unmarshal(data []byte, v interface{}) error { - return unmarshal(data, v) -} - -// UnmarshalContext parses the JSON-encoded data and stores the result -// in the value pointed to by v. If you implement the UnmarshalerContext interface, -// call it with ctx as an argument. -func UnmarshalContext(ctx context.Context, data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { - return unmarshalContext(ctx, data, v) -} - -func UnmarshalWithOption(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { - return unmarshal(data, v, optFuncs...) -} - -func UnmarshalNoEscape(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { - return unmarshalNoEscape(data, v, optFuncs...) -} - -// A Token holds a value of one of these types: -// -// Delim, for the four JSON delimiters [ ] { } -// bool, for JSON booleans -// float64, for JSON numbers -// Number, for JSON numbers -// string, for JSON string literals -// nil, for JSON null -// -type Token = json.Token - -// A Number represents a JSON number literal. -type Number = json.Number - -// RawMessage is a raw encoded JSON value. -// It implements Marshaler and Unmarshaler and can -// be used to delay JSON decoding or precompute a JSON encoding. -type RawMessage = json.RawMessage - -// A Delim is a JSON array or object delimiter, one of [ ] { or }. -type Delim = json.Delim - -// Compact appends to dst the JSON-encoded src with -// insignificant space characters elided. -func Compact(dst *bytes.Buffer, src []byte) error { - return encoder.Compact(dst, src, false) -} - -// Indent appends to dst an indented form of the JSON-encoded src. -// Each element in a JSON object or array begins on a new, -// indented line beginning with prefix followed by one or more -// copies of indent according to the indentation nesting. -// The data appended to dst does not begin with the prefix nor -// any indentation, to make it easier to embed inside other formatted JSON data. -// Although leading space characters (space, tab, carriage return, newline) -// at the beginning of src are dropped, trailing space characters -// at the end of src are preserved and copied to dst. -// For example, if src has no trailing spaces, neither will dst; -// if src ends in a trailing newline, so will dst. -func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { - return encoder.Indent(dst, src, prefix, indent) -} - -// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 -// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 -// so that the JSON will be safe to embed inside HTML + + +

Welcome, Ginner!

+ + +`)) + +func main() { + r := gin.Default() + r.Static("/assets", "./assets") + r.SetHTMLTemplate(html) + + r.GET("/", func(c *gin.Context) { + if pusher := c.Writer.Pusher(); pusher != nil { + // use pusher.Push() to do server push + if err := pusher.Push("/assets/app.js", nil); err != nil { + log.Printf("Failed to push: %v", err) + } + } + c.HTML(200, "https", gin.H{ + "status": "success", + }) + }) + + // Listen and Server in https://127.0.0.1:8080 + r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key") +} +``` + +### Define format for the log of routes + +The default log of routes is: +``` +[GIN-debug] POST /foo --> main.main.func1 (3 handlers) +[GIN-debug] GET /bar --> main.main.func2 (3 handlers) +[GIN-debug] GET /status --> main.main.func3 (3 handlers) +``` + +If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`. +In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs. +```go +import ( + "log" + "net/http" + + "github.com/gin-gonic/gin" +) + +func main() { + r := gin.Default() + gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { + log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) + } + + r.POST("/foo", func(c *gin.Context) { + c.JSON(http.StatusOK, "foo") + }) + + r.GET("/bar", func(c *gin.Context) { + c.JSON(http.StatusOK, "bar") + }) + + r.GET("/status", func(c *gin.Context) { + c.JSON(http.StatusOK, "ok") + }) + + // Listen and Server in http://0.0.0.0:8080 + r.Run() +} +``` + +### Set and get a cookie + +```go +import ( + "fmt" + + "github.com/gin-gonic/gin" +) + +func main() { + + router := gin.Default() + + router.GET("/cookie", func(c *gin.Context) { + + cookie, err := c.Cookie("gin_cookie") + + if err != nil { + cookie = "NotSet" + c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) + } + + fmt.Printf("Cookie value: %s \n", cookie) + }) + + router.Run() +} +``` + +## Don't trust all proxies + +Gin lets you specify which headers to hold the real client IP (if any), +as well as specifying which proxies (or direct clients) you trust to +specify one of these headers. + +The `TrustedProxies` slice on your `gin.Engine` specifes network addresses or +network CIDRs from where clients which their request headers related to client +IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or +IPv6 CIDRs. + +```go +import ( + "fmt" + + "github.com/gin-gonic/gin" +) + +func main() { + + router := gin.Default() + router.TrustedProxies = []string{"192.168.1.2"} + + router.GET("/", func(c *gin.Context) { + // If the client is 192.168.1.2, use the X-Forwarded-For + // header to deduce the original client IP from the trust- + // worthy parts of that header. + // Otherwise, simply return the direct client IP + fmt.Printf("ClientIP: %s\n", c.ClientIP()) + }) + router.Run() +} +``` + +## Testing + +The `net/http/httptest` package is preferable way for HTTP testing. + +```go +package main + +func setupRouter() *gin.Engine { + r := gin.Default() + r.GET("/ping", func(c *gin.Context) { + c.String(200, "pong") + }) + return r +} + +func main() { + r := setupRouter() + r.Run(":8080") +} +``` + +Test for code example above: + +```go +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestPingRoute(t *testing.T) { + router := setupRouter() + + w := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "/ping", nil) + router.ServeHTTP(w, req) + + assert.Equal(t, 200, w.Code) + assert.Equal(t, "pong", w.Body.String()) +} +``` + +## Users + +Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework. + +* [gorush](https://github.com/appleboy/gorush): A push notification server written in Go. +* [fnproject](https://github.com/fnproject/fn): The container native, cloud agnostic serverless platform. +* [photoprism](https://github.com/photoprism/photoprism): Personal photo management powered by Go and Google TensorFlow. +* [krakend](https://github.com/devopsfaith/krakend): Ultra performant API Gateway with middlewares. +* [picfit](https://github.com/thoas/picfit): An image resizing server written in Go. +* [brigade](https://github.com/brigadecore/brigade): Event-based Scripting for Kubernetes. +* [dkron](https://github.com/distribworks/dkron): Distributed, fault tolerant job scheduling system. diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/auth.go b/taskman-server/vendor/github.com/gin-gonic/gin/auth.go new file mode 100644 index 00000000..4d8a6ce4 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/auth.go @@ -0,0 +1,91 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "crypto/subtle" + "encoding/base64" + "net/http" + "strconv" + + "github.com/gin-gonic/gin/internal/bytesconv" +) + +// AuthUserKey is the cookie name for user credential in basic auth. +const AuthUserKey = "user" + +// Accounts defines a key/value for user/pass list of authorized logins. +type Accounts map[string]string + +type authPair struct { + value string + user string +} + +type authPairs []authPair + +func (a authPairs) searchCredential(authValue string) (string, bool) { + if authValue == "" { + return "", false + } + for _, pair := range a { + if subtle.ConstantTimeCompare([]byte(pair.value), []byte(authValue)) == 1 { + return pair.user, true + } + } + return "", false +} + +// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where +// the key is the user name and the value is the password, as well as the name of the Realm. +// If the realm is empty, "Authorization Required" will be used by default. +// (see http://tools.ietf.org/html/rfc2617#section-1.2) +func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { + if realm == "" { + realm = "Authorization Required" + } + realm = "Basic realm=" + strconv.Quote(realm) + pairs := processAccounts(accounts) + return func(c *Context) { + // Search user in the slice of allowed credentials + user, found := pairs.searchCredential(c.requestHeader("Authorization")) + if !found { + // Credentials doesn't match, we return 401 and abort handlers chain. + c.Header("WWW-Authenticate", realm) + c.AbortWithStatus(http.StatusUnauthorized) + return + } + + // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using + // c.MustGet(gin.AuthUserKey). + c.Set(AuthUserKey, user) + } +} + +// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where +// the key is the user name and the value is the password. +func BasicAuth(accounts Accounts) HandlerFunc { + return BasicAuthForRealm(accounts, "") +} + +func processAccounts(accounts Accounts) authPairs { + length := len(accounts) + assert1(length > 0, "Empty list of authorized credentials") + pairs := make(authPairs, 0, length) + for user, password := range accounts { + assert1(user != "", "User can not be empty") + value := authorizationHeader(user, password) + pairs = append(pairs, authPair{ + value: value, + user: user, + }) + } + return pairs +} + +func authorizationHeader(user, password string) string { + base := user + ":" + password + return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base)) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding.go new file mode 100644 index 00000000..5caeb581 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding.go @@ -0,0 +1,118 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build !nomsgpack +// +build !nomsgpack + +package binding + +import "net/http" + +// Content-Type MIME of the most common data formats. +const ( + MIMEJSON = "application/json" + MIMEHTML = "text/html" + MIMEXML = "application/xml" + MIMEXML2 = "text/xml" + MIMEPlain = "text/plain" + MIMEPOSTForm = "application/x-www-form-urlencoded" + MIMEMultipartPOSTForm = "multipart/form-data" + MIMEPROTOBUF = "application/x-protobuf" + MIMEMSGPACK = "application/x-msgpack" + MIMEMSGPACK2 = "application/msgpack" + MIMEYAML = "application/x-yaml" +) + +// Binding describes the interface which needs to be implemented for binding the +// data present in the request such as JSON request body, query parameters or +// the form POST. +type Binding interface { + Name() string + Bind(*http.Request, interface{}) error +} + +// BindingBody adds BindBody method to Binding. BindBody is similar with Bind, +// but it reads the body from supplied bytes instead of req.Body. +type BindingBody interface { + Binding + BindBody([]byte, interface{}) error +} + +// BindingUri adds BindUri method to Binding. BindUri is similar with Bind, +// but it read the Params. +type BindingUri interface { + Name() string + BindUri(map[string][]string, interface{}) error +} + +// StructValidator is the minimal interface which needs to be implemented in +// order for it to be used as the validator engine for ensuring the correctness +// of the request. Gin provides a default implementation for this using +// https://github.com/go-playground/validator/tree/v8.18.2. +type StructValidator interface { + // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. + // If the received type is a slice|array, the validation should be performed travel on every element. + // If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned. + // If the received type is a struct or pointer to a struct, the validation should be performed. + // If the struct is not valid or the validation itself fails, a descriptive error should be returned. + // Otherwise nil must be returned. + ValidateStruct(interface{}) error + + // Engine returns the underlying validator engine which powers the + // StructValidator implementation. + Engine() interface{} +} + +// Validator is the default validator which implements the StructValidator +// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2 +// under the hood. +var Validator StructValidator = &defaultValidator{} + +// These implement the Binding interface and can be used to bind the data +// present in the request to struct instances. +var ( + JSON = jsonBinding{} + XML = xmlBinding{} + Form = formBinding{} + Query = queryBinding{} + FormPost = formPostBinding{} + FormMultipart = formMultipartBinding{} + ProtoBuf = protobufBinding{} + MsgPack = msgpackBinding{} + YAML = yamlBinding{} + Uri = uriBinding{} + Header = headerBinding{} +) + +// Default returns the appropriate Binding instance based on the HTTP method +// and the content type. +func Default(method, contentType string) Binding { + if method == http.MethodGet { + return Form + } + + switch contentType { + case MIMEJSON: + return JSON + case MIMEXML, MIMEXML2: + return XML + case MIMEPROTOBUF: + return ProtoBuf + case MIMEMSGPACK, MIMEMSGPACK2: + return MsgPack + case MIMEYAML: + return YAML + case MIMEMultipartPOSTForm: + return FormMultipart + default: // case MIMEPOSTForm: + return Form + } +} + +func validate(obj interface{}) error { + if Validator == nil { + return nil + } + return Validator.ValidateStruct(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go new file mode 100644 index 00000000..9afa3dcf --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/binding_nomsgpack.go @@ -0,0 +1,112 @@ +// Copyright 2020 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build nomsgpack +// +build nomsgpack + +package binding + +import "net/http" + +// Content-Type MIME of the most common data formats. +const ( + MIMEJSON = "application/json" + MIMEHTML = "text/html" + MIMEXML = "application/xml" + MIMEXML2 = "text/xml" + MIMEPlain = "text/plain" + MIMEPOSTForm = "application/x-www-form-urlencoded" + MIMEMultipartPOSTForm = "multipart/form-data" + MIMEPROTOBUF = "application/x-protobuf" + MIMEYAML = "application/x-yaml" +) + +// Binding describes the interface which needs to be implemented for binding the +// data present in the request such as JSON request body, query parameters or +// the form POST. +type Binding interface { + Name() string + Bind(*http.Request, interface{}) error +} + +// BindingBody adds BindBody method to Binding. BindBody is similar with Bind, +// but it reads the body from supplied bytes instead of req.Body. +type BindingBody interface { + Binding + BindBody([]byte, interface{}) error +} + +// BindingUri adds BindUri method to Binding. BindUri is similar with Bind, +// but it read the Params. +type BindingUri interface { + Name() string + BindUri(map[string][]string, interface{}) error +} + +// StructValidator is the minimal interface which needs to be implemented in +// order for it to be used as the validator engine for ensuring the correctness +// of the request. Gin provides a default implementation for this using +// https://github.com/go-playground/validator/tree/v8.18.2. +type StructValidator interface { + // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. + // If the received type is not a struct, any validation should be skipped and nil must be returned. + // If the received type is a struct or pointer to a struct, the validation should be performed. + // If the struct is not valid or the validation itself fails, a descriptive error should be returned. + // Otherwise nil must be returned. + ValidateStruct(interface{}) error + + // Engine returns the underlying validator engine which powers the + // StructValidator implementation. + Engine() interface{} +} + +// Validator is the default validator which implements the StructValidator +// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2 +// under the hood. +var Validator StructValidator = &defaultValidator{} + +// These implement the Binding interface and can be used to bind the data +// present in the request to struct instances. +var ( + JSON = jsonBinding{} + XML = xmlBinding{} + Form = formBinding{} + Query = queryBinding{} + FormPost = formPostBinding{} + FormMultipart = formMultipartBinding{} + ProtoBuf = protobufBinding{} + YAML = yamlBinding{} + Uri = uriBinding{} + Header = headerBinding{} +) + +// Default returns the appropriate Binding instance based on the HTTP method +// and the content type. +func Default(method, contentType string) Binding { + if method == "GET" { + return Form + } + + switch contentType { + case MIMEJSON: + return JSON + case MIMEXML, MIMEXML2: + return XML + case MIMEPROTOBUF: + return ProtoBuf + case MIMEYAML: + return YAML + case MIMEMultipartPOSTForm: + return FormMultipart + default: // case MIMEPOSTForm: + return Form + } +} + +func validate(obj interface{}) error { + if Validator == nil { + return nil + } + return Validator.ValidateStruct(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/default_validator.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/default_validator.go new file mode 100644 index 00000000..c57a120f --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/default_validator.go @@ -0,0 +1,85 @@ +// Copyright 2017 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "fmt" + "reflect" + "strings" + "sync" + + "github.com/go-playground/validator/v10" +) + +type defaultValidator struct { + once sync.Once + validate *validator.Validate +} + +type sliceValidateError []error + +func (err sliceValidateError) Error() string { + var errMsgs []string + for i, e := range err { + if e == nil { + continue + } + errMsgs = append(errMsgs, fmt.Sprintf("[%d]: %s", i, e.Error())) + } + return strings.Join(errMsgs, "\n") +} + +var _ StructValidator = &defaultValidator{} + +// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type. +func (v *defaultValidator) ValidateStruct(obj interface{}) error { + if obj == nil { + return nil + } + + value := reflect.ValueOf(obj) + switch value.Kind() { + case reflect.Ptr: + return v.ValidateStruct(value.Elem().Interface()) + case reflect.Struct: + return v.validateStruct(obj) + case reflect.Slice, reflect.Array: + count := value.Len() + validateRet := make(sliceValidateError, 0) + for i := 0; i < count; i++ { + if err := v.ValidateStruct(value.Index(i).Interface()); err != nil { + validateRet = append(validateRet, err) + } + } + if len(validateRet) == 0 { + return nil + } + return validateRet + default: + return nil + } +} + +// validateStruct receives struct type +func (v *defaultValidator) validateStruct(obj interface{}) error { + v.lazyinit() + return v.validate.Struct(obj) +} + +// Engine returns the underlying validator engine which powers the default +// Validator instance. This is useful if you want to register custom validations +// or struct level validations. See validator GoDoc for more info - +// https://godoc.org/gopkg.in/go-playground/validator.v8 +func (v *defaultValidator) Engine() interface{} { + v.lazyinit() + return v.validate +} + +func (v *defaultValidator) lazyinit() { + v.once.Do(func() { + v.validate = validator.New() + v.validate.SetTagName("binding") + }) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/form.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/form.go new file mode 100644 index 00000000..b93c34cf --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/form.go @@ -0,0 +1,63 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "net/http" +) + +const defaultMemory = 32 << 20 + +type formBinding struct{} +type formPostBinding struct{} +type formMultipartBinding struct{} + +func (formBinding) Name() string { + return "form" +} + +func (formBinding) Bind(req *http.Request, obj interface{}) error { + if err := req.ParseForm(); err != nil { + return err + } + if err := req.ParseMultipartForm(defaultMemory); err != nil { + if err != http.ErrNotMultipart { + return err + } + } + if err := mapForm(obj, req.Form); err != nil { + return err + } + return validate(obj) +} + +func (formPostBinding) Name() string { + return "form-urlencoded" +} + +func (formPostBinding) Bind(req *http.Request, obj interface{}) error { + if err := req.ParseForm(); err != nil { + return err + } + if err := mapForm(obj, req.PostForm); err != nil { + return err + } + return validate(obj) +} + +func (formMultipartBinding) Name() string { + return "multipart/form-data" +} + +func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error { + if err := req.ParseMultipartForm(defaultMemory); err != nil { + return err + } + if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { + return err + } + + return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/form_mapping.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/form_mapping.go new file mode 100644 index 00000000..2f4e45b4 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/form_mapping.go @@ -0,0 +1,392 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin/internal/bytesconv" + "github.com/gin-gonic/gin/internal/json" +) + +var errUnknownType = errors.New("unknown type") + +func mapUri(ptr interface{}, m map[string][]string) error { + return mapFormByTag(ptr, m, "uri") +} + +func mapForm(ptr interface{}, form map[string][]string) error { + return mapFormByTag(ptr, form, "form") +} + +var emptyField = reflect.StructField{} + +func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error { + // Check if ptr is a map + ptrVal := reflect.ValueOf(ptr) + var pointed interface{} + if ptrVal.Kind() == reflect.Ptr { + ptrVal = ptrVal.Elem() + pointed = ptrVal.Interface() + } + if ptrVal.Kind() == reflect.Map && + ptrVal.Type().Key().Kind() == reflect.String { + if pointed != nil { + ptr = pointed + } + return setFormMap(ptr, form) + } + + return mappingByPtr(ptr, formSource(form), tag) +} + +// setter tries to set value on a walking by fields of a struct +type setter interface { + TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSetted bool, err error) +} + +type formSource map[string][]string + +var _ setter = formSource(nil) + +// TrySet tries to set a value by request's form source (like map[string][]string) +func (form formSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) { + return setByForm(value, field, form, tagValue, opt) +} + +func mappingByPtr(ptr interface{}, setter setter, tag string) error { + _, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag) + return err +} + +func mapping(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) { + if field.Tag.Get(tag) == "-" { // just ignoring this field + return false, nil + } + + var vKind = value.Kind() + + if vKind == reflect.Ptr { + var isNew bool + vPtr := value + if value.IsNil() { + isNew = true + vPtr = reflect.New(value.Type().Elem()) + } + isSetted, err := mapping(vPtr.Elem(), field, setter, tag) + if err != nil { + return false, err + } + if isNew && isSetted { + value.Set(vPtr) + } + return isSetted, nil + } + + if vKind != reflect.Struct || !field.Anonymous { + ok, err := tryToSetValue(value, field, setter, tag) + if err != nil { + return false, err + } + if ok { + return true, nil + } + } + + if vKind == reflect.Struct { + tValue := value.Type() + + var isSetted bool + for i := 0; i < value.NumField(); i++ { + sf := tValue.Field(i) + if sf.PkgPath != "" && !sf.Anonymous { // unexported + continue + } + ok, err := mapping(value.Field(i), tValue.Field(i), setter, tag) + if err != nil { + return false, err + } + isSetted = isSetted || ok + } + return isSetted, nil + } + return false, nil +} + +type setOptions struct { + isDefaultExists bool + defaultValue string +} + +func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) { + var tagValue string + var setOpt setOptions + + tagValue = field.Tag.Get(tag) + tagValue, opts := head(tagValue, ",") + + if tagValue == "" { // default value is FieldName + tagValue = field.Name + } + if tagValue == "" { // when field is "emptyField" variable + return false, nil + } + + var opt string + for len(opts) > 0 { + opt, opts = head(opts, ",") + + if k, v := head(opt, "="); k == "default" { + setOpt.isDefaultExists = true + setOpt.defaultValue = v + } + } + + return setter.TrySet(value, field, tagValue, setOpt) +} + +func setByForm(value reflect.Value, field reflect.StructField, form map[string][]string, tagValue string, opt setOptions) (isSetted bool, err error) { + vs, ok := form[tagValue] + if !ok && !opt.isDefaultExists { + return false, nil + } + + switch value.Kind() { + case reflect.Slice: + if !ok { + vs = []string{opt.defaultValue} + } + return true, setSlice(vs, value, field) + case reflect.Array: + if !ok { + vs = []string{opt.defaultValue} + } + if len(vs) != value.Len() { + return false, fmt.Errorf("%q is not valid value for %s", vs, value.Type().String()) + } + return true, setArray(vs, value, field) + default: + var val string + if !ok { + val = opt.defaultValue + } + + if len(vs) > 0 { + val = vs[0] + } + return true, setWithProperType(val, value, field) + } +} + +func setWithProperType(val string, value reflect.Value, field reflect.StructField) error { + switch value.Kind() { + case reflect.Int: + return setIntField(val, 0, value) + case reflect.Int8: + return setIntField(val, 8, value) + case reflect.Int16: + return setIntField(val, 16, value) + case reflect.Int32: + return setIntField(val, 32, value) + case reflect.Int64: + switch value.Interface().(type) { + case time.Duration: + return setTimeDuration(val, value, field) + } + return setIntField(val, 64, value) + case reflect.Uint: + return setUintField(val, 0, value) + case reflect.Uint8: + return setUintField(val, 8, value) + case reflect.Uint16: + return setUintField(val, 16, value) + case reflect.Uint32: + return setUintField(val, 32, value) + case reflect.Uint64: + return setUintField(val, 64, value) + case reflect.Bool: + return setBoolField(val, value) + case reflect.Float32: + return setFloatField(val, 32, value) + case reflect.Float64: + return setFloatField(val, 64, value) + case reflect.String: + value.SetString(val) + case reflect.Struct: + switch value.Interface().(type) { + case time.Time: + return setTimeField(val, field, value) + } + return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface()) + case reflect.Map: + return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface()) + default: + return errUnknownType + } + return nil +} + +func setIntField(val string, bitSize int, field reflect.Value) error { + if val == "" { + val = "0" + } + intVal, err := strconv.ParseInt(val, 10, bitSize) + if err == nil { + field.SetInt(intVal) + } + return err +} + +func setUintField(val string, bitSize int, field reflect.Value) error { + if val == "" { + val = "0" + } + uintVal, err := strconv.ParseUint(val, 10, bitSize) + if err == nil { + field.SetUint(uintVal) + } + return err +} + +func setBoolField(val string, field reflect.Value) error { + if val == "" { + val = "false" + } + boolVal, err := strconv.ParseBool(val) + if err == nil { + field.SetBool(boolVal) + } + return err +} + +func setFloatField(val string, bitSize int, field reflect.Value) error { + if val == "" { + val = "0.0" + } + floatVal, err := strconv.ParseFloat(val, bitSize) + if err == nil { + field.SetFloat(floatVal) + } + return err +} + +func setTimeField(val string, structField reflect.StructField, value reflect.Value) error { + timeFormat := structField.Tag.Get("time_format") + if timeFormat == "" { + timeFormat = time.RFC3339 + } + + switch tf := strings.ToLower(timeFormat); tf { + case "unix", "unixnano": + tv, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return err + } + + d := time.Duration(1) + if tf == "unixnano" { + d = time.Second + } + + t := time.Unix(tv/int64(d), tv%int64(d)) + value.Set(reflect.ValueOf(t)) + return nil + + } + + if val == "" { + value.Set(reflect.ValueOf(time.Time{})) + return nil + } + + l := time.Local + if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC { + l = time.UTC + } + + if locTag := structField.Tag.Get("time_location"); locTag != "" { + loc, err := time.LoadLocation(locTag) + if err != nil { + return err + } + l = loc + } + + t, err := time.ParseInLocation(timeFormat, val, l) + if err != nil { + return err + } + + value.Set(reflect.ValueOf(t)) + return nil +} + +func setArray(vals []string, value reflect.Value, field reflect.StructField) error { + for i, s := range vals { + err := setWithProperType(s, value.Index(i), field) + if err != nil { + return err + } + } + return nil +} + +func setSlice(vals []string, value reflect.Value, field reflect.StructField) error { + slice := reflect.MakeSlice(value.Type(), len(vals), len(vals)) + err := setArray(vals, slice, field) + if err != nil { + return err + } + value.Set(slice) + return nil +} + +func setTimeDuration(val string, value reflect.Value, field reflect.StructField) error { + d, err := time.ParseDuration(val) + if err != nil { + return err + } + value.Set(reflect.ValueOf(d)) + return nil +} + +func head(str, sep string) (head string, tail string) { + idx := strings.Index(str, sep) + if idx < 0 { + return str, "" + } + return str[:idx], str[idx+len(sep):] +} + +func setFormMap(ptr interface{}, form map[string][]string) error { + el := reflect.TypeOf(ptr).Elem() + + if el.Kind() == reflect.Slice { + ptrMap, ok := ptr.(map[string][]string) + if !ok { + return errors.New("cannot convert to map slices of strings") + } + for k, v := range form { + ptrMap[k] = v + } + + return nil + } + + ptrMap, ok := ptr.(map[string]string) + if !ok { + return errors.New("cannot convert to map of strings") + } + for k, v := range form { + ptrMap[k] = v[len(v)-1] // pick last + } + + return nil +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/header.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/header.go new file mode 100644 index 00000000..179ce4ea --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/header.go @@ -0,0 +1,34 @@ +package binding + +import ( + "net/http" + "net/textproto" + "reflect" +) + +type headerBinding struct{} + +func (headerBinding) Name() string { + return "header" +} + +func (headerBinding) Bind(req *http.Request, obj interface{}) error { + + if err := mapHeader(obj, req.Header); err != nil { + return err + } + + return validate(obj) +} + +func mapHeader(ptr interface{}, h map[string][]string) error { + return mappingByPtr(ptr, headerSource(h), "header") +} + +type headerSource map[string][]string + +var _ setter = headerSource(nil) + +func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) { + return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/json.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/json.go new file mode 100644 index 00000000..d62e0705 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/json.go @@ -0,0 +1,56 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "bytes" + "fmt" + "io" + "net/http" + + "github.com/gin-gonic/gin/internal/json" +) + +// EnableDecoderUseNumber is used to call the UseNumber method on the JSON +// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an +// interface{} as a Number instead of as a float64. +var EnableDecoderUseNumber = false + +// EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method +// on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to +// return an error when the destination is a struct and the input contains object +// keys which do not match any non-ignored, exported fields in the destination. +var EnableDecoderDisallowUnknownFields = false + +type jsonBinding struct{} + +func (jsonBinding) Name() string { + return "json" +} + +func (jsonBinding) Bind(req *http.Request, obj interface{}) error { + if req == nil || req.Body == nil { + return fmt.Errorf("invalid request") + } + return decodeJSON(req.Body, obj) +} + +func (jsonBinding) BindBody(body []byte, obj interface{}) error { + return decodeJSON(bytes.NewReader(body), obj) +} + +func decodeJSON(r io.Reader, obj interface{}) error { + decoder := json.NewDecoder(r) + if EnableDecoderUseNumber { + decoder.UseNumber() + } + if EnableDecoderDisallowUnknownFields { + decoder.DisallowUnknownFields() + } + if err := decoder.Decode(obj); err != nil { + return err + } + return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/msgpack.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/msgpack.go new file mode 100644 index 00000000..2a442996 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/msgpack.go @@ -0,0 +1,38 @@ +// Copyright 2017 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build !nomsgpack +// +build !nomsgpack + +package binding + +import ( + "bytes" + "io" + "net/http" + + "github.com/ugorji/go/codec" +) + +type msgpackBinding struct{} + +func (msgpackBinding) Name() string { + return "msgpack" +} + +func (msgpackBinding) Bind(req *http.Request, obj interface{}) error { + return decodeMsgPack(req.Body, obj) +} + +func (msgpackBinding) BindBody(body []byte, obj interface{}) error { + return decodeMsgPack(bytes.NewReader(body), obj) +} + +func decodeMsgPack(r io.Reader, obj interface{}) error { + cdc := new(codec.MsgpackHandle) + if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil { + return err + } + return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go new file mode 100644 index 00000000..f85a1aa6 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/multipart_form_mapping.go @@ -0,0 +1,66 @@ +// Copyright 2019 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "errors" + "mime/multipart" + "net/http" + "reflect" +) + +type multipartRequest http.Request + +var _ setter = (*multipartRequest)(nil) + +// TrySet tries to set a value by the multipart request with the binding a form file +func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSetted bool, err error) { + if files := r.MultipartForm.File[key]; len(files) != 0 { + return setByMultipartFormFile(value, field, files) + } + + return setByForm(value, field, r.MultipartForm.Value, key, opt) +} + +func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSetted bool, err error) { + switch value.Kind() { + case reflect.Ptr: + switch value.Interface().(type) { + case *multipart.FileHeader: + value.Set(reflect.ValueOf(files[0])) + return true, nil + } + case reflect.Struct: + switch value.Interface().(type) { + case multipart.FileHeader: + value.Set(reflect.ValueOf(*files[0])) + return true, nil + } + case reflect.Slice: + slice := reflect.MakeSlice(value.Type(), len(files), len(files)) + isSetted, err = setArrayOfMultipartFormFiles(slice, field, files) + if err != nil || !isSetted { + return isSetted, err + } + value.Set(slice) + return true, nil + case reflect.Array: + return setArrayOfMultipartFormFiles(value, field, files) + } + return false, errors.New("unsupported field type for multipart.FileHeader") +} + +func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSetted bool, err error) { + if value.Len() != len(files) { + return false, errors.New("unsupported len of array for []*multipart.FileHeader") + } + for i := range files { + setted, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1]) + if err != nil || !setted { + return setted, err + } + } + return true, nil +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/protobuf.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/protobuf.go new file mode 100644 index 00000000..f9ece928 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/protobuf.go @@ -0,0 +1,36 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "io/ioutil" + "net/http" + + "github.com/golang/protobuf/proto" +) + +type protobufBinding struct{} + +func (protobufBinding) Name() string { + return "protobuf" +} + +func (b protobufBinding) Bind(req *http.Request, obj interface{}) error { + buf, err := ioutil.ReadAll(req.Body) + if err != nil { + return err + } + return b.BindBody(buf, obj) +} + +func (protobufBinding) BindBody(body []byte, obj interface{}) error { + if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil { + return err + } + // Here it's same to return validate(obj), but util now we can't add + // `binding:""` to the struct which automatically generate by gen-proto + return nil + // return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/query.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/query.go new file mode 100644 index 00000000..219743f2 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/query.go @@ -0,0 +1,21 @@ +// Copyright 2017 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import "net/http" + +type queryBinding struct{} + +func (queryBinding) Name() string { + return "query" +} + +func (queryBinding) Bind(req *http.Request, obj interface{}) error { + values := req.URL.Query() + if err := mapForm(obj, values); err != nil { + return err + } + return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/uri.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/uri.go new file mode 100644 index 00000000..f91ec381 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/uri.go @@ -0,0 +1,18 @@ +// Copyright 2018 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +type uriBinding struct{} + +func (uriBinding) Name() string { + return "uri" +} + +func (uriBinding) BindUri(m map[string][]string, obj interface{}) error { + if err := mapUri(obj, m); err != nil { + return err + } + return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/xml.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/xml.go new file mode 100644 index 00000000..4e901149 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/xml.go @@ -0,0 +1,33 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "bytes" + "encoding/xml" + "io" + "net/http" +) + +type xmlBinding struct{} + +func (xmlBinding) Name() string { + return "xml" +} + +func (xmlBinding) Bind(req *http.Request, obj interface{}) error { + return decodeXML(req.Body, obj) +} + +func (xmlBinding) BindBody(body []byte, obj interface{}) error { + return decodeXML(bytes.NewReader(body), obj) +} +func decodeXML(r io.Reader, obj interface{}) error { + decoder := xml.NewDecoder(r) + if err := decoder.Decode(obj); err != nil { + return err + } + return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/binding/yaml.go b/taskman-server/vendor/github.com/gin-gonic/gin/binding/yaml.go new file mode 100644 index 00000000..a2d36d6a --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/binding/yaml.go @@ -0,0 +1,35 @@ +// Copyright 2018 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package binding + +import ( + "bytes" + "io" + "net/http" + + "gopkg.in/yaml.v2" +) + +type yamlBinding struct{} + +func (yamlBinding) Name() string { + return "yaml" +} + +func (yamlBinding) Bind(req *http.Request, obj interface{}) error { + return decodeYAML(req.Body, obj) +} + +func (yamlBinding) BindBody(body []byte, obj interface{}) error { + return decodeYAML(bytes.NewReader(body), obj) +} + +func decodeYAML(r io.Reader, obj interface{}) error { + decoder := yaml.NewDecoder(r) + if err := decoder.Decode(obj); err != nil { + return err + } + return validate(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/codecov.yml b/taskman-server/vendor/github.com/gin-gonic/gin/codecov.yml new file mode 100644 index 00000000..c9c9a522 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/codecov.yml @@ -0,0 +1,5 @@ +coverage: + notify: + gitter: + default: + url: https://webhooks.gitter.im/e/d90dcdeeab2f1e357165 diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/context.go b/taskman-server/vendor/github.com/gin-gonic/gin/context.go new file mode 100644 index 00000000..dc03c358 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/context.go @@ -0,0 +1,1178 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "errors" + "fmt" + "io" + "io/ioutil" + "math" + "mime/multipart" + "net" + "net/http" + "net/url" + "os" + "strings" + "sync" + "time" + + "github.com/gin-contrib/sse" + "github.com/gin-gonic/gin/binding" + "github.com/gin-gonic/gin/render" +) + +// Content-Type MIME of the most common data formats. +const ( + MIMEJSON = binding.MIMEJSON + MIMEHTML = binding.MIMEHTML + MIMEXML = binding.MIMEXML + MIMEXML2 = binding.MIMEXML2 + MIMEPlain = binding.MIMEPlain + MIMEPOSTForm = binding.MIMEPOSTForm + MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm + MIMEYAML = binding.MIMEYAML +) + +// BodyBytesKey indicates a default body bytes key. +const BodyBytesKey = "_gin-gonic/gin/bodybyteskey" + +const abortIndex int8 = math.MaxInt8 / 2 + +// Context is the most important part of gin. It allows us to pass variables between middleware, +// manage the flow, validate the JSON of a request and render a JSON response for example. +type Context struct { + writermem responseWriter + Request *http.Request + Writer ResponseWriter + + Params Params + handlers HandlersChain + index int8 + fullPath string + + engine *Engine + params *Params + + // This mutex protect Keys map + mu sync.RWMutex + + // Keys is a key/value pair exclusively for the context of each request. + Keys map[string]interface{} + + // Errors is a list of errors attached to all the handlers/middlewares who used this context. + Errors errorMsgs + + // Accepted defines a list of manually accepted formats for content negotiation. + Accepted []string + + // queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query() + queryCache url.Values + + // formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH, + // or PUT body parameters. + formCache url.Values + + // SameSite allows a server to define a cookie attribute making it impossible for + // the browser to send this cookie along with cross-site requests. + sameSite http.SameSite +} + +/************************************/ +/********** CONTEXT CREATION ********/ +/************************************/ + +func (c *Context) reset() { + c.Writer = &c.writermem + c.Params = c.Params[0:0] + c.handlers = nil + c.index = -1 + + c.fullPath = "" + c.Keys = nil + c.Errors = c.Errors[0:0] + c.Accepted = nil + c.queryCache = nil + c.formCache = nil + *c.params = (*c.params)[0:0] +} + +// Copy returns a copy of the current context that can be safely used outside the request's scope. +// This has to be used when the context has to be passed to a goroutine. +func (c *Context) Copy() *Context { + cp := Context{ + writermem: c.writermem, + Request: c.Request, + Params: c.Params, + engine: c.engine, + } + cp.writermem.ResponseWriter = nil + cp.Writer = &cp.writermem + cp.index = abortIndex + cp.handlers = nil + cp.Keys = map[string]interface{}{} + for k, v := range c.Keys { + cp.Keys[k] = v + } + paramCopy := make([]Param, len(cp.Params)) + copy(paramCopy, cp.Params) + cp.Params = paramCopy + return &cp +} + +// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", +// this function will return "main.handleGetUsers". +func (c *Context) HandlerName() string { + return nameOfFunction(c.handlers.Last()) +} + +// HandlerNames returns a list of all registered handlers for this context in descending order, +// following the semantics of HandlerName() +func (c *Context) HandlerNames() []string { + hn := make([]string, 0, len(c.handlers)) + for _, val := range c.handlers { + hn = append(hn, nameOfFunction(val)) + } + return hn +} + +// Handler returns the main handler. +func (c *Context) Handler() HandlerFunc { + return c.handlers.Last() +} + +// FullPath returns a matched route full path. For not found routes +// returns an empty string. +// router.GET("/user/:id", func(c *gin.Context) { +// c.FullPath() == "/user/:id" // true +// }) +func (c *Context) FullPath() string { + return c.fullPath +} + +/************************************/ +/*********** FLOW CONTROL ***********/ +/************************************/ + +// Next should be used only inside middleware. +// It executes the pending handlers in the chain inside the calling handler. +// See example in GitHub. +func (c *Context) Next() { + c.index++ + for c.index < int8(len(c.handlers)) { + c.handlers[c.index](c) + c.index++ + } +} + +// IsAborted returns true if the current context was aborted. +func (c *Context) IsAborted() bool { + return c.index >= abortIndex +} + +// Abort prevents pending handlers from being called. Note that this will not stop the current handler. +// Let's say you have an authorization middleware that validates that the current request is authorized. +// If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers +// for this request are not called. +func (c *Context) Abort() { + c.index = abortIndex +} + +// AbortWithStatus calls `Abort()` and writes the headers with the specified status code. +// For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401). +func (c *Context) AbortWithStatus(code int) { + c.Status(code) + c.Writer.WriteHeaderNow() + c.Abort() +} + +// AbortWithStatusJSON calls `Abort()` and then `JSON` internally. +// This method stops the chain, writes the status code and return a JSON body. +// It also sets the Content-Type as "application/json". +func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) { + c.Abort() + c.JSON(code, jsonObj) +} + +// AbortWithError calls `AbortWithStatus()` and `Error()` internally. +// This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. +// See Context.Error() for more details. +func (c *Context) AbortWithError(code int, err error) *Error { + c.AbortWithStatus(code) + return c.Error(err) +} + +/************************************/ +/********* ERROR MANAGEMENT *********/ +/************************************/ + +// Error attaches an error to the current context. The error is pushed to a list of errors. +// It's a good idea to call Error for each error that occurred during the resolution of a request. +// A middleware can be used to collect all the errors and push them to a database together, +// print a log, or append it in the HTTP response. +// Error will panic if err is nil. +func (c *Context) Error(err error) *Error { + if err == nil { + panic("err is nil") + } + + parsedError, ok := err.(*Error) + if !ok { + parsedError = &Error{ + Err: err, + Type: ErrorTypePrivate, + } + } + + c.Errors = append(c.Errors, parsedError) + return parsedError +} + +/************************************/ +/******** METADATA MANAGEMENT********/ +/************************************/ + +// Set is used to store a new key/value pair exclusively for this context. +// It also lazy initializes c.Keys if it was not used previously. +func (c *Context) Set(key string, value interface{}) { + c.mu.Lock() + if c.Keys == nil { + c.Keys = make(map[string]interface{}) + } + + c.Keys[key] = value + c.mu.Unlock() +} + +// Get returns the value for the given key, ie: (value, true). +// If the value does not exists it returns (nil, false) +func (c *Context) Get(key string) (value interface{}, exists bool) { + c.mu.RLock() + value, exists = c.Keys[key] + c.mu.RUnlock() + return +} + +// MustGet returns the value for the given key if it exists, otherwise it panics. +func (c *Context) MustGet(key string) interface{} { + if value, exists := c.Get(key); exists { + return value + } + panic("Key \"" + key + "\" does not exist") +} + +// GetString returns the value associated with the key as a string. +func (c *Context) GetString(key string) (s string) { + if val, ok := c.Get(key); ok && val != nil { + s, _ = val.(string) + } + return +} + +// GetBool returns the value associated with the key as a boolean. +func (c *Context) GetBool(key string) (b bool) { + if val, ok := c.Get(key); ok && val != nil { + b, _ = val.(bool) + } + return +} + +// GetInt returns the value associated with the key as an integer. +func (c *Context) GetInt(key string) (i int) { + if val, ok := c.Get(key); ok && val != nil { + i, _ = val.(int) + } + return +} + +// GetInt64 returns the value associated with the key as an integer. +func (c *Context) GetInt64(key string) (i64 int64) { + if val, ok := c.Get(key); ok && val != nil { + i64, _ = val.(int64) + } + return +} + +// GetUint returns the value associated with the key as an unsigned integer. +func (c *Context) GetUint(key string) (ui uint) { + if val, ok := c.Get(key); ok && val != nil { + ui, _ = val.(uint) + } + return +} + +// GetUint64 returns the value associated with the key as an unsigned integer. +func (c *Context) GetUint64(key string) (ui64 uint64) { + if val, ok := c.Get(key); ok && val != nil { + ui64, _ = val.(uint64) + } + return +} + +// GetFloat64 returns the value associated with the key as a float64. +func (c *Context) GetFloat64(key string) (f64 float64) { + if val, ok := c.Get(key); ok && val != nil { + f64, _ = val.(float64) + } + return +} + +// GetTime returns the value associated with the key as time. +func (c *Context) GetTime(key string) (t time.Time) { + if val, ok := c.Get(key); ok && val != nil { + t, _ = val.(time.Time) + } + return +} + +// GetDuration returns the value associated with the key as a duration. +func (c *Context) GetDuration(key string) (d time.Duration) { + if val, ok := c.Get(key); ok && val != nil { + d, _ = val.(time.Duration) + } + return +} + +// GetStringSlice returns the value associated with the key as a slice of strings. +func (c *Context) GetStringSlice(key string) (ss []string) { + if val, ok := c.Get(key); ok && val != nil { + ss, _ = val.([]string) + } + return +} + +// GetStringMap returns the value associated with the key as a map of interfaces. +func (c *Context) GetStringMap(key string) (sm map[string]interface{}) { + if val, ok := c.Get(key); ok && val != nil { + sm, _ = val.(map[string]interface{}) + } + return +} + +// GetStringMapString returns the value associated with the key as a map of strings. +func (c *Context) GetStringMapString(key string) (sms map[string]string) { + if val, ok := c.Get(key); ok && val != nil { + sms, _ = val.(map[string]string) + } + return +} + +// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. +func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) { + if val, ok := c.Get(key); ok && val != nil { + smss, _ = val.(map[string][]string) + } + return +} + +/************************************/ +/************ INPUT DATA ************/ +/************************************/ + +// Param returns the value of the URL param. +// It is a shortcut for c.Params.ByName(key) +// router.GET("/user/:id", func(c *gin.Context) { +// // a GET request to /user/john +// id := c.Param("id") // id == "john" +// }) +func (c *Context) Param(key string) string { + return c.Params.ByName(key) +} + +// Query returns the keyed url query value if it exists, +// otherwise it returns an empty string `("")`. +// It is shortcut for `c.Request.URL.Query().Get(key)` +// GET /path?id=1234&name=Manu&value= +// c.Query("id") == "1234" +// c.Query("name") == "Manu" +// c.Query("value") == "" +// c.Query("wtf") == "" +func (c *Context) Query(key string) string { + value, _ := c.GetQuery(key) + return value +} + +// DefaultQuery returns the keyed url query value if it exists, +// otherwise it returns the specified defaultValue string. +// See: Query() and GetQuery() for further information. +// GET /?name=Manu&lastname= +// c.DefaultQuery("name", "unknown") == "Manu" +// c.DefaultQuery("id", "none") == "none" +// c.DefaultQuery("lastname", "none") == "" +func (c *Context) DefaultQuery(key, defaultValue string) string { + if value, ok := c.GetQuery(key); ok { + return value + } + return defaultValue +} + +// GetQuery is like Query(), it returns the keyed url query value +// if it exists `(value, true)` (even when the value is an empty string), +// otherwise it returns `("", false)`. +// It is shortcut for `c.Request.URL.Query().Get(key)` +// GET /?name=Manu&lastname= +// ("Manu", true) == c.GetQuery("name") +// ("", false) == c.GetQuery("id") +// ("", true) == c.GetQuery("lastname") +func (c *Context) GetQuery(key string) (string, bool) { + if values, ok := c.GetQueryArray(key); ok { + return values[0], ok + } + return "", false +} + +// QueryArray returns a slice of strings for a given query key. +// The length of the slice depends on the number of params with the given key. +func (c *Context) QueryArray(key string) []string { + values, _ := c.GetQueryArray(key) + return values +} + +func (c *Context) initQueryCache() { + if c.queryCache == nil { + if c.Request != nil { + c.queryCache = c.Request.URL.Query() + } else { + c.queryCache = url.Values{} + } + } +} + +// GetQueryArray returns a slice of strings for a given query key, plus +// a boolean value whether at least one value exists for the given key. +func (c *Context) GetQueryArray(key string) ([]string, bool) { + c.initQueryCache() + if values, ok := c.queryCache[key]; ok && len(values) > 0 { + return values, true + } + return []string{}, false +} + +// QueryMap returns a map for a given query key. +func (c *Context) QueryMap(key string) map[string]string { + dicts, _ := c.GetQueryMap(key) + return dicts +} + +// GetQueryMap returns a map for a given query key, plus a boolean value +// whether at least one value exists for the given key. +func (c *Context) GetQueryMap(key string) (map[string]string, bool) { + c.initQueryCache() + return c.get(c.queryCache, key) +} + +// PostForm returns the specified key from a POST urlencoded form or multipart form +// when it exists, otherwise it returns an empty string `("")`. +func (c *Context) PostForm(key string) string { + value, _ := c.GetPostForm(key) + return value +} + +// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form +// when it exists, otherwise it returns the specified defaultValue string. +// See: PostForm() and GetPostForm() for further information. +func (c *Context) DefaultPostForm(key, defaultValue string) string { + if value, ok := c.GetPostForm(key); ok { + return value + } + return defaultValue +} + +// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded +// form or multipart form when it exists `(value, true)` (even when the value is an empty string), +// otherwise it returns ("", false). +// For example, during a PATCH request to update the user's email: +// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" +// email= --> ("", true) := GetPostForm("email") // set email to "" +// --> ("", false) := GetPostForm("email") // do nothing with email +func (c *Context) GetPostForm(key string) (string, bool) { + if values, ok := c.GetPostFormArray(key); ok { + return values[0], ok + } + return "", false +} + +// PostFormArray returns a slice of strings for a given form key. +// The length of the slice depends on the number of params with the given key. +func (c *Context) PostFormArray(key string) []string { + values, _ := c.GetPostFormArray(key) + return values +} + +func (c *Context) initFormCache() { + if c.formCache == nil { + c.formCache = make(url.Values) + req := c.Request + if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { + if err != http.ErrNotMultipart { + debugPrint("error on parse multipart form array: %v", err) + } + } + c.formCache = req.PostForm + } +} + +// GetPostFormArray returns a slice of strings for a given form key, plus +// a boolean value whether at least one value exists for the given key. +func (c *Context) GetPostFormArray(key string) ([]string, bool) { + c.initFormCache() + if values := c.formCache[key]; len(values) > 0 { + return values, true + } + return []string{}, false +} + +// PostFormMap returns a map for a given form key. +func (c *Context) PostFormMap(key string) map[string]string { + dicts, _ := c.GetPostFormMap(key) + return dicts +} + +// GetPostFormMap returns a map for a given form key, plus a boolean value +// whether at least one value exists for the given key. +func (c *Context) GetPostFormMap(key string) (map[string]string, bool) { + c.initFormCache() + return c.get(c.formCache, key) +} + +// get is an internal method and returns a map which satisfy conditions. +func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) { + dicts := make(map[string]string) + exist := false + for k, v := range m { + if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key { + if j := strings.IndexByte(k[i+1:], ']'); j >= 1 { + exist = true + dicts[k[i+1:][:j]] = v[0] + } + } + } + return dicts, exist +} + +// FormFile returns the first file for the provided form key. +func (c *Context) FormFile(name string) (*multipart.FileHeader, error) { + if c.Request.MultipartForm == nil { + if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { + return nil, err + } + } + f, fh, err := c.Request.FormFile(name) + if err != nil { + return nil, err + } + f.Close() + return fh, err +} + +// MultipartForm is the parsed multipart form, including file uploads. +func (c *Context) MultipartForm() (*multipart.Form, error) { + err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory) + return c.Request.MultipartForm, err +} + +// SaveUploadedFile uploads the form file to specific dst. +func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error { + src, err := file.Open() + if err != nil { + return err + } + defer src.Close() + + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, src) + return err +} + +// Bind checks the Content-Type to select a binding engine automatically, +// Depending the "Content-Type" header different bindings are used: +// "application/json" --> JSON binding +// "application/xml" --> XML binding +// otherwise --> returns an error. +// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. +// It decodes the json payload into the struct specified as a pointer. +// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid. +func (c *Context) Bind(obj interface{}) error { + b := binding.Default(c.Request.Method, c.ContentType()) + return c.MustBindWith(obj, b) +} + +// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON). +func (c *Context) BindJSON(obj interface{}) error { + return c.MustBindWith(obj, binding.JSON) +} + +// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML). +func (c *Context) BindXML(obj interface{}) error { + return c.MustBindWith(obj, binding.XML) +} + +// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query). +func (c *Context) BindQuery(obj interface{}) error { + return c.MustBindWith(obj, binding.Query) +} + +// BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML). +func (c *Context) BindYAML(obj interface{}) error { + return c.MustBindWith(obj, binding.YAML) +} + +// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header). +func (c *Context) BindHeader(obj interface{}) error { + return c.MustBindWith(obj, binding.Header) +} + +// BindUri binds the passed struct pointer using binding.Uri. +// It will abort the request with HTTP 400 if any error occurs. +func (c *Context) BindUri(obj interface{}) error { + if err := c.ShouldBindUri(obj); err != nil { + c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck + return err + } + return nil +} + +// MustBindWith binds the passed struct pointer using the specified binding engine. +// It will abort the request with HTTP 400 if any error occurs. +// See the binding package. +func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error { + if err := c.ShouldBindWith(obj, b); err != nil { + c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck + return err + } + return nil +} + +// ShouldBind checks the Content-Type to select a binding engine automatically, +// Depending the "Content-Type" header different bindings are used: +// "application/json" --> JSON binding +// "application/xml" --> XML binding +// otherwise --> returns an error +// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. +// It decodes the json payload into the struct specified as a pointer. +// Like c.Bind() but this method does not set the response status code to 400 and abort if the json is not valid. +func (c *Context) ShouldBind(obj interface{}) error { + b := binding.Default(c.Request.Method, c.ContentType()) + return c.ShouldBindWith(obj, b) +} + +// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON). +func (c *Context) ShouldBindJSON(obj interface{}) error { + return c.ShouldBindWith(obj, binding.JSON) +} + +// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML). +func (c *Context) ShouldBindXML(obj interface{}) error { + return c.ShouldBindWith(obj, binding.XML) +} + +// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query). +func (c *Context) ShouldBindQuery(obj interface{}) error { + return c.ShouldBindWith(obj, binding.Query) +} + +// ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML). +func (c *Context) ShouldBindYAML(obj interface{}) error { + return c.ShouldBindWith(obj, binding.YAML) +} + +// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header). +func (c *Context) ShouldBindHeader(obj interface{}) error { + return c.ShouldBindWith(obj, binding.Header) +} + +// ShouldBindUri binds the passed struct pointer using the specified binding engine. +func (c *Context) ShouldBindUri(obj interface{}) error { + m := make(map[string][]string) + for _, v := range c.Params { + m[v.Key] = []string{v.Value} + } + return binding.Uri.BindUri(m, obj) +} + +// ShouldBindWith binds the passed struct pointer using the specified binding engine. +// See the binding package. +func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error { + return b.Bind(c.Request, obj) +} + +// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request +// body into the context, and reuse when it is called again. +// +// NOTE: This method reads the body before binding. So you should use +// ShouldBindWith for better performance if you need to call only once. +func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) { + var body []byte + if cb, ok := c.Get(BodyBytesKey); ok { + if cbb, ok := cb.([]byte); ok { + body = cbb + } + } + if body == nil { + body, err = ioutil.ReadAll(c.Request.Body) + if err != nil { + return err + } + c.Set(BodyBytesKey, body) + } + return bb.BindBody(body, obj) +} + +// ClientIP implements a best effort algorithm to return the real client IP. +// It called c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. +// If it's it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]). +// If the headers are nots syntactically valid OR the remote IP does not correspong to a trusted proxy, +// the remote IP (coming form Request.RemoteAddr) is returned. +func (c *Context) ClientIP() string { + if c.engine.AppEngine { + if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" { + return addr + } + } + + remoteIP, trusted := c.RemoteIP() + if remoteIP == nil { + return "" + } + + if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil { + for _, headerName := range c.engine.RemoteIPHeaders { + ip, valid := validateHeader(c.requestHeader(headerName)) + if valid { + return ip + } + } + } + return remoteIP.String() +} + +// RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). +// It also checks if the remoteIP is a trusted proxy or not. +// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks +// defined in Engine.TrustedProxies +func (c *Context) RemoteIP() (net.IP, bool) { + ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)) + if err != nil { + return nil, false + } + remoteIP := net.ParseIP(ip) + if remoteIP == nil { + return nil, false + } + + if c.engine.trustedCIDRs != nil { + for _, cidr := range c.engine.trustedCIDRs { + if cidr.Contains(remoteIP) { + return remoteIP, true + } + } + } + + return remoteIP, false +} + +func validateHeader(header string) (clientIP string, valid bool) { + if header == "" { + return "", false + } + items := strings.Split(header, ",") + for i, ipStr := range items { + ipStr = strings.TrimSpace(ipStr) + ip := net.ParseIP(ipStr) + if ip == nil { + return "", false + } + + // We need to return the first IP in the list, but, + // we should not early return since we need to validate that + // the rest of the header is syntactically valid + if i == 0 { + clientIP = ipStr + valid = true + } + } + return +} + +// ContentType returns the Content-Type header of the request. +func (c *Context) ContentType() string { + return filterFlags(c.requestHeader("Content-Type")) +} + +// IsWebsocket returns true if the request headers indicate that a websocket +// handshake is being initiated by the client. +func (c *Context) IsWebsocket() bool { + if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") && + strings.EqualFold(c.requestHeader("Upgrade"), "websocket") { + return true + } + return false +} + +func (c *Context) requestHeader(key string) string { + return c.Request.Header.Get(key) +} + +/************************************/ +/******** RESPONSE RENDERING ********/ +/************************************/ + +// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function. +func bodyAllowedForStatus(status int) bool { + switch { + case status >= 100 && status <= 199: + return false + case status == http.StatusNoContent: + return false + case status == http.StatusNotModified: + return false + } + return true +} + +// Status sets the HTTP response code. +func (c *Context) Status(code int) { + c.Writer.WriteHeader(code) +} + +// Header is a intelligent shortcut for c.Writer.Header().Set(key, value). +// It writes a header in the response. +// If value == "", this method removes the header `c.Writer.Header().Del(key)` +func (c *Context) Header(key, value string) { + if value == "" { + c.Writer.Header().Del(key) + return + } + c.Writer.Header().Set(key, value) +} + +// GetHeader returns value from request headers. +func (c *Context) GetHeader(key string) string { + return c.requestHeader(key) +} + +// GetRawData return stream data. +func (c *Context) GetRawData() ([]byte, error) { + return ioutil.ReadAll(c.Request.Body) +} + +// SetSameSite with cookie +func (c *Context) SetSameSite(samesite http.SameSite) { + c.sameSite = samesite +} + +// SetCookie adds a Set-Cookie header to the ResponseWriter's headers. +// The provided cookie must have a valid Name. Invalid cookies may be +// silently dropped. +func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) { + if path == "" { + path = "/" + } + http.SetCookie(c.Writer, &http.Cookie{ + Name: name, + Value: url.QueryEscape(value), + MaxAge: maxAge, + Path: path, + Domain: domain, + SameSite: c.sameSite, + Secure: secure, + HttpOnly: httpOnly, + }) +} + +// Cookie returns the named cookie provided in the request or +// ErrNoCookie if not found. And return the named cookie is unescaped. +// If multiple cookies match the given name, only one cookie will +// be returned. +func (c *Context) Cookie(name string) (string, error) { + cookie, err := c.Request.Cookie(name) + if err != nil { + return "", err + } + val, _ := url.QueryUnescape(cookie.Value) + return val, nil +} + +// Render writes the response headers and calls render.Render to render data. +func (c *Context) Render(code int, r render.Render) { + c.Status(code) + + if !bodyAllowedForStatus(code) { + r.WriteContentType(c.Writer) + c.Writer.WriteHeaderNow() + return + } + + if err := r.Render(c.Writer); err != nil { + panic(err) + } +} + +// HTML renders the HTTP template specified by its file name. +// It also updates the HTTP code and sets the Content-Type as "text/html". +// See http://golang.org/doc/articles/wiki/ +func (c *Context) HTML(code int, name string, obj interface{}) { + instance := c.engine.HTMLRender.Instance(name, obj) + c.Render(code, instance) +} + +// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. +// It also sets the Content-Type as "application/json". +// WARNING: we recommend to use this only for development purposes since printing pretty JSON is +// more CPU and bandwidth consuming. Use Context.JSON() instead. +func (c *Context) IndentedJSON(code int, obj interface{}) { + c.Render(code, render.IndentedJSON{Data: obj}) +} + +// SecureJSON serializes the given struct as Secure JSON into the response body. +// Default prepends "while(1)," to response body if the given struct is array values. +// It also sets the Content-Type as "application/json". +func (c *Context) SecureJSON(code int, obj interface{}) { + c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj}) +} + +// JSONP serializes the given struct as JSON into the response body. +// It adds padding to response body to request data from a server residing in a different domain than the client. +// It also sets the Content-Type as "application/javascript". +func (c *Context) JSONP(code int, obj interface{}) { + callback := c.DefaultQuery("callback", "") + if callback == "" { + c.Render(code, render.JSON{Data: obj}) + return + } + c.Render(code, render.JsonpJSON{Callback: callback, Data: obj}) +} + +// JSON serializes the given struct as JSON into the response body. +// It also sets the Content-Type as "application/json". +func (c *Context) JSON(code int, obj interface{}) { + c.Render(code, render.JSON{Data: obj}) +} + +// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string. +// It also sets the Content-Type as "application/json". +func (c *Context) AsciiJSON(code int, obj interface{}) { + c.Render(code, render.AsciiJSON{Data: obj}) +} + +// PureJSON serializes the given struct as JSON into the response body. +// PureJSON, unlike JSON, does not replace special html characters with their unicode entities. +func (c *Context) PureJSON(code int, obj interface{}) { + c.Render(code, render.PureJSON{Data: obj}) +} + +// XML serializes the given struct as XML into the response body. +// It also sets the Content-Type as "application/xml". +func (c *Context) XML(code int, obj interface{}) { + c.Render(code, render.XML{Data: obj}) +} + +// YAML serializes the given struct as YAML into the response body. +func (c *Context) YAML(code int, obj interface{}) { + c.Render(code, render.YAML{Data: obj}) +} + +// ProtoBuf serializes the given struct as ProtoBuf into the response body. +func (c *Context) ProtoBuf(code int, obj interface{}) { + c.Render(code, render.ProtoBuf{Data: obj}) +} + +// String writes the given string into the response body. +func (c *Context) String(code int, format string, values ...interface{}) { + c.Render(code, render.String{Format: format, Data: values}) +} + +// Redirect returns a HTTP redirect to the specific location. +func (c *Context) Redirect(code int, location string) { + c.Render(-1, render.Redirect{ + Code: code, + Location: location, + Request: c.Request, + }) +} + +// Data writes some data into the body stream and updates the HTTP code. +func (c *Context) Data(code int, contentType string, data []byte) { + c.Render(code, render.Data{ + ContentType: contentType, + Data: data, + }) +} + +// DataFromReader writes the specified reader into the body stream and updates the HTTP code. +func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) { + c.Render(code, render.Reader{ + Headers: extraHeaders, + ContentType: contentType, + ContentLength: contentLength, + Reader: reader, + }) +} + +// File writes the specified file into the body stream in an efficient way. +func (c *Context) File(filepath string) { + http.ServeFile(c.Writer, c.Request, filepath) +} + +// FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way. +func (c *Context) FileFromFS(filepath string, fs http.FileSystem) { + defer func(old string) { + c.Request.URL.Path = old + }(c.Request.URL.Path) + + c.Request.URL.Path = filepath + + http.FileServer(fs).ServeHTTP(c.Writer, c.Request) +} + +// FileAttachment writes the specified file into the body stream in an efficient way +// On the client side, the file will typically be downloaded with the given filename +func (c *Context) FileAttachment(filepath, filename string) { + c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename)) + http.ServeFile(c.Writer, c.Request, filepath) +} + +// SSEvent writes a Server-Sent Event into the body stream. +func (c *Context) SSEvent(name string, message interface{}) { + c.Render(-1, sse.Event{ + Event: name, + Data: message, + }) +} + +// Stream sends a streaming response and returns a boolean +// indicates "Is client disconnected in middle of stream" +func (c *Context) Stream(step func(w io.Writer) bool) bool { + w := c.Writer + clientGone := w.CloseNotify() + for { + select { + case <-clientGone: + return true + default: + keepOpen := step(w) + w.Flush() + if !keepOpen { + return false + } + } + } +} + +/************************************/ +/******** CONTENT NEGOTIATION *******/ +/************************************/ + +// Negotiate contains all negotiations data. +type Negotiate struct { + Offered []string + HTMLName string + HTMLData interface{} + JSONData interface{} + XMLData interface{} + YAMLData interface{} + Data interface{} +} + +// Negotiate calls different Render according acceptable Accept format. +func (c *Context) Negotiate(code int, config Negotiate) { + switch c.NegotiateFormat(config.Offered...) { + case binding.MIMEJSON: + data := chooseData(config.JSONData, config.Data) + c.JSON(code, data) + + case binding.MIMEHTML: + data := chooseData(config.HTMLData, config.Data) + c.HTML(code, config.HTMLName, data) + + case binding.MIMEXML: + data := chooseData(config.XMLData, config.Data) + c.XML(code, data) + + case binding.MIMEYAML: + data := chooseData(config.YAMLData, config.Data) + c.YAML(code, data) + + default: + c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck + } +} + +// NegotiateFormat returns an acceptable Accept format. +func (c *Context) NegotiateFormat(offered ...string) string { + assert1(len(offered) > 0, "you must provide at least one offer") + + if c.Accepted == nil { + c.Accepted = parseAccept(c.requestHeader("Accept")) + } + if len(c.Accepted) == 0 { + return offered[0] + } + for _, accepted := range c.Accepted { + for _, offer := range offered { + // According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers, + // therefore we can just iterate over the string without casting it into []rune + i := 0 + for ; i < len(accepted); i++ { + if accepted[i] == '*' || offer[i] == '*' { + return offer + } + if accepted[i] != offer[i] { + break + } + } + if i == len(accepted) { + return offer + } + } + } + return "" +} + +// SetAccepted sets Accept header data. +func (c *Context) SetAccepted(formats ...string) { + c.Accepted = formats +} + +/************************************/ +/***** GOLANG.ORG/X/NET/CONTEXT *****/ +/************************************/ + +// Deadline always returns that there is no deadline (ok==false), +// maybe you want to use Request.Context().Deadline() instead. +func (c *Context) Deadline() (deadline time.Time, ok bool) { + return +} + +// Done always returns nil (chan which will wait forever), +// if you want to abort your work when the connection was closed +// you should use Request.Context().Done() instead. +func (c *Context) Done() <-chan struct{} { + return nil +} + +// Err always returns nil, maybe you want to use Request.Context().Err() instead. +func (c *Context) Err() error { + return nil +} + +// Value returns the value associated with this context for key, or nil +// if no value is associated with key. Successive calls to Value with +// the same key returns the same result. +func (c *Context) Value(key interface{}) interface{} { + if key == 0 { + return c.Request + } + if keyAsString, ok := key.(string); ok { + val, _ := c.Get(keyAsString) + return val + } + return nil +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/context_appengine.go b/taskman-server/vendor/github.com/gin-gonic/gin/context_appengine.go new file mode 100644 index 00000000..d5658434 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/context_appengine.go @@ -0,0 +1,12 @@ +// Copyright 2017 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build appengine +// +build appengine + +package gin + +func init() { + defaultAppEngine = true +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/debug.go b/taskman-server/vendor/github.com/gin-gonic/gin/debug.go new file mode 100644 index 00000000..4c7cd0c3 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/debug.go @@ -0,0 +1,103 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "fmt" + "html/template" + "runtime" + "strconv" + "strings" +) + +const ginSupportMinGoVer = 12 + +// IsDebugging returns true if the framework is running in debug mode. +// Use SetMode(gin.ReleaseMode) to disable debug mode. +func IsDebugging() bool { + return ginMode == debugCode +} + +// DebugPrintRouteFunc indicates debug log output format. +var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int) + +func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { + if IsDebugging() { + nuHandlers := len(handlers) + handlerName := nameOfFunction(handlers.Last()) + if DebugPrintRouteFunc == nil { + debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) + } else { + DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) + } + } +} + +func debugPrintLoadTemplate(tmpl *template.Template) { + if IsDebugging() { + var buf strings.Builder + for _, tmpl := range tmpl.Templates() { + buf.WriteString("\t- ") + buf.WriteString(tmpl.Name()) + buf.WriteString("\n") + } + debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) + } +} + +func debugPrint(format string, values ...interface{}) { + if IsDebugging() { + if !strings.HasSuffix(format, "\n") { + format += "\n" + } + fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) + } +} + +func getMinVer(v string) (uint64, error) { + first := strings.IndexByte(v, '.') + last := strings.LastIndexByte(v, '.') + if first == last { + return strconv.ParseUint(v[first+1:], 10, 64) + } + return strconv.ParseUint(v[first+1:last], 10, 64) +} + +func debugPrintWARNINGDefault() { + if v, e := getMinVer(runtime.Version()); e == nil && v <= ginSupportMinGoVer { + debugPrint(`[WARNING] Now Gin requires Go 1.12+. + +`) + } + debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. + +`) +} + +func debugPrintWARNINGNew() { + debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. + - using env: export GIN_MODE=release + - using code: gin.SetMode(gin.ReleaseMode) + +`) +} + +func debugPrintWARNINGSetHTMLTemplate() { + debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called +at initialization. ie. before any route is registered or the router is listening in a socket: + + router := gin.Default() + router.SetHTMLTemplate(template) // << good place + +`) +} + +func debugPrintError(err error) { + if err != nil { + if IsDebugging() { + fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) + } + } +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/deprecated.go b/taskman-server/vendor/github.com/gin-gonic/gin/deprecated.go new file mode 100644 index 00000000..ab447429 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/deprecated.go @@ -0,0 +1,21 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "log" + + "github.com/gin-gonic/gin/binding" +) + +// BindWith binds the passed struct pointer using the specified binding engine. +// See the binding package. +func (c *Context) BindWith(obj interface{}, b binding.Binding) error { + log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to + be deprecated, please check issue #662 and either use MustBindWith() if you + want HTTP 400 to be automatically returned if any error occur, or use + ShouldBindWith() if you need to manage the error.`) + return c.MustBindWith(obj, b) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/doc.go b/taskman-server/vendor/github.com/gin-gonic/gin/doc.go new file mode 100644 index 00000000..1bd03864 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/doc.go @@ -0,0 +1,6 @@ +/* +Package gin implements a HTTP web framework called gin. + +See https://gin-gonic.com/ for more information about gin. +*/ +package gin // import "github.com/gin-gonic/gin" diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/errors.go b/taskman-server/vendor/github.com/gin-gonic/gin/errors.go new file mode 100644 index 00000000..0f276c13 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/errors.go @@ -0,0 +1,174 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "fmt" + "reflect" + "strings" + + "github.com/gin-gonic/gin/internal/json" +) + +// ErrorType is an unsigned 64-bit error code as defined in the gin spec. +type ErrorType uint64 + +const ( + // ErrorTypeBind is used when Context.Bind() fails. + ErrorTypeBind ErrorType = 1 << 63 + // ErrorTypeRender is used when Context.Render() fails. + ErrorTypeRender ErrorType = 1 << 62 + // ErrorTypePrivate indicates a private error. + ErrorTypePrivate ErrorType = 1 << 0 + // ErrorTypePublic indicates a public error. + ErrorTypePublic ErrorType = 1 << 1 + // ErrorTypeAny indicates any other error. + ErrorTypeAny ErrorType = 1<<64 - 1 + // ErrorTypeNu indicates any other error. + ErrorTypeNu = 2 +) + +// Error represents a error's specification. +type Error struct { + Err error + Type ErrorType + Meta interface{} +} + +type errorMsgs []*Error + +var _ error = &Error{} + +// SetType sets the error's type. +func (msg *Error) SetType(flags ErrorType) *Error { + msg.Type = flags + return msg +} + +// SetMeta sets the error's meta data. +func (msg *Error) SetMeta(data interface{}) *Error { + msg.Meta = data + return msg +} + +// JSON creates a properly formatted JSON +func (msg *Error) JSON() interface{} { + jsonData := H{} + if msg.Meta != nil { + value := reflect.ValueOf(msg.Meta) + switch value.Kind() { + case reflect.Struct: + return msg.Meta + case reflect.Map: + for _, key := range value.MapKeys() { + jsonData[key.String()] = value.MapIndex(key).Interface() + } + default: + jsonData["meta"] = msg.Meta + } + } + if _, ok := jsonData["error"]; !ok { + jsonData["error"] = msg.Error() + } + return jsonData +} + +// MarshalJSON implements the json.Marshaller interface. +func (msg *Error) MarshalJSON() ([]byte, error) { + return json.Marshal(msg.JSON()) +} + +// Error implements the error interface. +func (msg Error) Error() string { + return msg.Err.Error() +} + +// IsType judges one error. +func (msg *Error) IsType(flags ErrorType) bool { + return (msg.Type & flags) > 0 +} + +// Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap() +func (msg *Error) Unwrap() error { + return msg.Err +} + +// ByType returns a readonly copy filtered the byte. +// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic. +func (a errorMsgs) ByType(typ ErrorType) errorMsgs { + if len(a) == 0 { + return nil + } + if typ == ErrorTypeAny { + return a + } + var result errorMsgs + for _, msg := range a { + if msg.IsType(typ) { + result = append(result, msg) + } + } + return result +} + +// Last returns the last error in the slice. It returns nil if the array is empty. +// Shortcut for errors[len(errors)-1]. +func (a errorMsgs) Last() *Error { + if length := len(a); length > 0 { + return a[length-1] + } + return nil +} + +// Errors returns an array will all the error messages. +// Example: +// c.Error(errors.New("first")) +// c.Error(errors.New("second")) +// c.Error(errors.New("third")) +// c.Errors.Errors() // == []string{"first", "second", "third"} +func (a errorMsgs) Errors() []string { + if len(a) == 0 { + return nil + } + errorStrings := make([]string, len(a)) + for i, err := range a { + errorStrings[i] = err.Error() + } + return errorStrings +} + +func (a errorMsgs) JSON() interface{} { + switch length := len(a); length { + case 0: + return nil + case 1: + return a.Last().JSON() + default: + jsonData := make([]interface{}, length) + for i, err := range a { + jsonData[i] = err.JSON() + } + return jsonData + } +} + +// MarshalJSON implements the json.Marshaller interface. +func (a errorMsgs) MarshalJSON() ([]byte, error) { + return json.Marshal(a.JSON()) +} + +func (a errorMsgs) String() string { + if len(a) == 0 { + return "" + } + var buffer strings.Builder + for i, msg := range a { + fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err) + if msg.Meta != nil { + fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) + } + } + return buffer.String() +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/fs.go b/taskman-server/vendor/github.com/gin-gonic/gin/fs.go new file mode 100644 index 00000000..007d9b75 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/fs.go @@ -0,0 +1,45 @@ +// Copyright 2017 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "net/http" + "os" +) + +type onlyFilesFS struct { + fs http.FileSystem +} + +type neuteredReaddirFile struct { + http.File +} + +// Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally +// in router.Static(). +// if listDirectory == true, then it works the same as http.Dir() otherwise it returns +// a filesystem that prevents http.FileServer() to list the directory files. +func Dir(root string, listDirectory bool) http.FileSystem { + fs := http.Dir(root) + if listDirectory { + return fs + } + return &onlyFilesFS{fs} +} + +// Open conforms to http.Filesystem. +func (fs onlyFilesFS) Open(name string) (http.File, error) { + f, err := fs.fs.Open(name) + if err != nil { + return nil, err + } + return neuteredReaddirFile{f}, nil +} + +// Readdir overrides the http.File default implementation. +func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) { + // this disables directory listing + return nil, nil +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/gin.go b/taskman-server/vendor/github.com/gin-gonic/gin/gin.go new file mode 100644 index 00000000..03a0e127 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/gin.go @@ -0,0 +1,577 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "fmt" + "html/template" + "net" + "net/http" + "os" + "path" + "strings" + "sync" + + "github.com/gin-gonic/gin/internal/bytesconv" + "github.com/gin-gonic/gin/render" +) + +const defaultMultipartMemory = 32 << 20 // 32 MB + +var ( + default404Body = []byte("404 page not found") + default405Body = []byte("405 method not allowed") +) + +var defaultAppEngine bool + +// HandlerFunc defines the handler used by gin middleware as return value. +type HandlerFunc func(*Context) + +// HandlersChain defines a HandlerFunc array. +type HandlersChain []HandlerFunc + +// Last returns the last handler in the chain. ie. the last handler is the main one. +func (c HandlersChain) Last() HandlerFunc { + if length := len(c); length > 0 { + return c[length-1] + } + return nil +} + +// RouteInfo represents a request route's specification which contains method and path and its handler. +type RouteInfo struct { + Method string + Path string + Handler string + HandlerFunc HandlerFunc +} + +// RoutesInfo defines a RouteInfo array. +type RoutesInfo []RouteInfo + +// Engine is the framework's instance, it contains the muxer, middleware and configuration settings. +// Create an instance of Engine, by using New() or Default() +type Engine struct { + RouterGroup + + // Enables automatic redirection if the current route can't be matched but a + // handler for the path with (without) the trailing slash exists. + // For example if /foo/ is requested but a route only exists for /foo, the + // client is redirected to /foo with http status code 301 for GET requests + // and 307 for all other request methods. + RedirectTrailingSlash bool + + // If enabled, the router tries to fix the current request path, if no + // handle is registered for it. + // First superfluous path elements like ../ or // are removed. + // Afterwards the router does a case-insensitive lookup of the cleaned path. + // If a handle can be found for this route, the router makes a redirection + // to the corrected path with status code 301 for GET requests and 307 for + // all other request methods. + // For example /FOO and /..//Foo could be redirected to /foo. + // RedirectTrailingSlash is independent of this option. + RedirectFixedPath bool + + // If enabled, the router checks if another method is allowed for the + // current route, if the current request can not be routed. + // If this is the case, the request is answered with 'Method Not Allowed' + // and HTTP status code 405. + // If no other Method is allowed, the request is delegated to the NotFound + // handler. + HandleMethodNotAllowed bool + + // If enabled, client IP will be parsed from the request's headers that + // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was + // fetched, it falls back to the IP obtained from + // `(*gin.Context).Request.RemoteAddr`. + ForwardedByClientIP bool + + // List of headers used to obtain the client IP when + // `(*gin.Engine).ForwardedByClientIP` is `true` and + // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the + // network origins of `(*gin.Engine).TrustedProxies`. + RemoteIPHeaders []string + + // List of network origins (IPv4 addresses, IPv4 CIDRs, IPv6 addresses or + // IPv6 CIDRs) from which to trust request's headers that contain + // alternative client IP when `(*gin.Engine).ForwardedByClientIP` is + // `true`. + TrustedProxies []string + + // #726 #755 If enabled, it will trust some headers starting with + // 'X-AppEngine...' for better integration with that PaaS. + AppEngine bool + + // If enabled, the url.RawPath will be used to find parameters. + UseRawPath bool + + // If true, the path value will be unescaped. + // If UseRawPath is false (by default), the UnescapePathValues effectively is true, + // as url.Path gonna be used, which is already unescaped. + UnescapePathValues bool + + // Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm + // method call. + MaxMultipartMemory int64 + + // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. + // See the PR #1817 and issue #1644 + RemoveExtraSlash bool + + delims render.Delims + secureJSONPrefix string + HTMLRender render.HTMLRender + FuncMap template.FuncMap + allNoRoute HandlersChain + allNoMethod HandlersChain + noRoute HandlersChain + noMethod HandlersChain + pool sync.Pool + trees methodTrees + maxParams uint16 + trustedCIDRs []*net.IPNet +} + +var _ IRouter = &Engine{} + +// New returns a new blank Engine instance without any middleware attached. +// By default the configuration is: +// - RedirectTrailingSlash: true +// - RedirectFixedPath: false +// - HandleMethodNotAllowed: false +// - ForwardedByClientIP: true +// - UseRawPath: false +// - UnescapePathValues: true +func New() *Engine { + debugPrintWARNINGNew() + engine := &Engine{ + RouterGroup: RouterGroup{ + Handlers: nil, + basePath: "/", + root: true, + }, + FuncMap: template.FuncMap{}, + RedirectTrailingSlash: true, + RedirectFixedPath: false, + HandleMethodNotAllowed: false, + ForwardedByClientIP: true, + RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, + TrustedProxies: []string{"0.0.0.0/0"}, + AppEngine: defaultAppEngine, + UseRawPath: false, + RemoveExtraSlash: false, + UnescapePathValues: true, + MaxMultipartMemory: defaultMultipartMemory, + trees: make(methodTrees, 0, 9), + delims: render.Delims{Left: "{{", Right: "}}"}, + secureJSONPrefix: "while(1);", + } + engine.RouterGroup.engine = engine + engine.pool.New = func() interface{} { + return engine.allocateContext() + } + return engine +} + +// Default returns an Engine instance with the Logger and Recovery middleware already attached. +func Default() *Engine { + debugPrintWARNINGDefault() + engine := New() + engine.Use(Logger(), Recovery()) + return engine +} + +func (engine *Engine) allocateContext() *Context { + v := make(Params, 0, engine.maxParams) + return &Context{engine: engine, params: &v} +} + +// Delims sets template left and right delims and returns a Engine instance. +func (engine *Engine) Delims(left, right string) *Engine { + engine.delims = render.Delims{Left: left, Right: right} + return engine +} + +// SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. +func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { + engine.secureJSONPrefix = prefix + return engine +} + +// LoadHTMLGlob loads HTML files identified by glob pattern +// and associates the result with HTML renderer. +func (engine *Engine) LoadHTMLGlob(pattern string) { + left := engine.delims.Left + right := engine.delims.Right + templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) + + if IsDebugging() { + debugPrintLoadTemplate(templ) + engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} + return + } + + engine.SetHTMLTemplate(templ) +} + +// LoadHTMLFiles loads a slice of HTML files +// and associates the result with HTML renderer. +func (engine *Engine) LoadHTMLFiles(files ...string) { + if IsDebugging() { + engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} + return + } + + templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) + engine.SetHTMLTemplate(templ) +} + +// SetHTMLTemplate associate a template with HTML renderer. +func (engine *Engine) SetHTMLTemplate(templ *template.Template) { + if len(engine.trees) > 0 { + debugPrintWARNINGSetHTMLTemplate() + } + + engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} +} + +// SetFuncMap sets the FuncMap used for template.FuncMap. +func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { + engine.FuncMap = funcMap +} + +// NoRoute adds handlers for NoRoute. It return a 404 code by default. +func (engine *Engine) NoRoute(handlers ...HandlerFunc) { + engine.noRoute = handlers + engine.rebuild404Handlers() +} + +// NoMethod sets the handlers called when... TODO. +func (engine *Engine) NoMethod(handlers ...HandlerFunc) { + engine.noMethod = handlers + engine.rebuild405Handlers() +} + +// Use attaches a global middleware to the router. ie. the middleware attached though Use() will be +// included in the handlers chain for every single request. Even 404, 405, static files... +// For example, this is the right place for a logger or error management middleware. +func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { + engine.RouterGroup.Use(middleware...) + engine.rebuild404Handlers() + engine.rebuild405Handlers() + return engine +} + +func (engine *Engine) rebuild404Handlers() { + engine.allNoRoute = engine.combineHandlers(engine.noRoute) +} + +func (engine *Engine) rebuild405Handlers() { + engine.allNoMethod = engine.combineHandlers(engine.noMethod) +} + +func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { + assert1(path[0] == '/', "path must begin with '/'") + assert1(method != "", "HTTP method can not be empty") + assert1(len(handlers) > 0, "there must be at least one handler") + + debugPrintRoute(method, path, handlers) + + root := engine.trees.get(method) + if root == nil { + root = new(node) + root.fullPath = "/" + engine.trees = append(engine.trees, methodTree{method: method, root: root}) + } + root.addRoute(path, handlers) + + // Update maxParams + if paramsCount := countParams(path); paramsCount > engine.maxParams { + engine.maxParams = paramsCount + } +} + +// Routes returns a slice of registered routes, including some useful information, such as: +// the http method, path and the handler name. +func (engine *Engine) Routes() (routes RoutesInfo) { + for _, tree := range engine.trees { + routes = iterate("", tree.method, routes, tree.root) + } + return routes +} + +func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { + path += root.path + if len(root.handlers) > 0 { + handlerFunc := root.handlers.Last() + routes = append(routes, RouteInfo{ + Method: method, + Path: path, + Handler: nameOfFunction(handlerFunc), + HandlerFunc: handlerFunc, + }) + } + for _, child := range root.children { + routes = iterate(path, method, routes, child) + } + return routes +} + +// Run attaches the router to a http.Server and starts listening and serving HTTP requests. +// It is a shortcut for http.ListenAndServe(addr, router) +// Note: this method will block the calling goroutine indefinitely unless an error happens. +func (engine *Engine) Run(addr ...string) (err error) { + defer func() { debugPrintError(err) }() + + trustedCIDRs, err := engine.prepareTrustedCIDRs() + if err != nil { + return err + } + engine.trustedCIDRs = trustedCIDRs + address := resolveAddress(addr) + debugPrint("Listening and serving HTTP on %s\n", address) + err = http.ListenAndServe(address, engine) + return +} + +func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { + if engine.TrustedProxies == nil { + return nil, nil + } + + cidr := make([]*net.IPNet, 0, len(engine.TrustedProxies)) + for _, trustedProxy := range engine.TrustedProxies { + if !strings.Contains(trustedProxy, "/") { + ip := parseIP(trustedProxy) + if ip == nil { + return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} + } + + switch len(ip) { + case net.IPv4len: + trustedProxy += "/32" + case net.IPv6len: + trustedProxy += "/128" + } + } + _, cidrNet, err := net.ParseCIDR(trustedProxy) + if err != nil { + return cidr, err + } + cidr = append(cidr, cidrNet) + } + return cidr, nil +} + +// parseIP parse a string representation of an IP and returns a net.IP with the +// minimum byte representation or nil if input is invalid. +func parseIP(ip string) net.IP { + parsedIP := net.ParseIP(ip) + + if ipv4 := parsedIP.To4(); ipv4 != nil { + // return ip in a 4-byte representation + return ipv4 + } + + // return ip in a 16-byte representation or nil + return parsedIP +} + +// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. +// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) +// Note: this method will block the calling goroutine indefinitely unless an error happens. +func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { + debugPrint("Listening and serving HTTPS on %s\n", addr) + defer func() { debugPrintError(err) }() + + err = http.ListenAndServeTLS(addr, certFile, keyFile, engine) + return +} + +// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests +// through the specified unix socket (ie. a file). +// Note: this method will block the calling goroutine indefinitely unless an error happens. +func (engine *Engine) RunUnix(file string) (err error) { + debugPrint("Listening and serving HTTP on unix:/%s", file) + defer func() { debugPrintError(err) }() + + listener, err := net.Listen("unix", file) + if err != nil { + return + } + defer listener.Close() + defer os.Remove(file) + + err = http.Serve(listener, engine) + return +} + +// RunFd attaches the router to a http.Server and starts listening and serving HTTP requests +// through the specified file descriptor. +// Note: this method will block the calling goroutine indefinitely unless an error happens. +func (engine *Engine) RunFd(fd int) (err error) { + debugPrint("Listening and serving HTTP on fd@%d", fd) + defer func() { debugPrintError(err) }() + + f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) + listener, err := net.FileListener(f) + if err != nil { + return + } + defer listener.Close() + err = engine.RunListener(listener) + return +} + +// RunListener attaches the router to a http.Server and starts listening and serving HTTP requests +// through the specified net.Listener +func (engine *Engine) RunListener(listener net.Listener) (err error) { + debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) + defer func() { debugPrintError(err) }() + err = http.Serve(listener, engine) + return +} + +// ServeHTTP conforms to the http.Handler interface. +func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { + c := engine.pool.Get().(*Context) + c.writermem.reset(w) + c.Request = req + c.reset() + + engine.handleHTTPRequest(c) + + engine.pool.Put(c) +} + +// HandleContext re-enter a context that has been rewritten. +// This can be done by setting c.Request.URL.Path to your new target. +// Disclaimer: You can loop yourself to death with this, use wisely. +func (engine *Engine) HandleContext(c *Context) { + oldIndexValue := c.index + c.reset() + engine.handleHTTPRequest(c) + + c.index = oldIndexValue +} + +func (engine *Engine) handleHTTPRequest(c *Context) { + httpMethod := c.Request.Method + rPath := c.Request.URL.Path + unescape := false + if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { + rPath = c.Request.URL.RawPath + unescape = engine.UnescapePathValues + } + + if engine.RemoveExtraSlash { + rPath = cleanPath(rPath) + } + + // Find root of the tree for the given HTTP method + t := engine.trees + for i, tl := 0, len(t); i < tl; i++ { + if t[i].method != httpMethod { + continue + } + root := t[i].root + // Find route in tree + value := root.getValue(rPath, c.params, unescape) + if value.params != nil { + c.Params = *value.params + } + if value.handlers != nil { + c.handlers = value.handlers + c.fullPath = value.fullPath + c.Next() + c.writermem.WriteHeaderNow() + return + } + if httpMethod != "CONNECT" && rPath != "/" { + if value.tsr && engine.RedirectTrailingSlash { + redirectTrailingSlash(c) + return + } + if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { + return + } + } + break + } + + if engine.HandleMethodNotAllowed { + for _, tree := range engine.trees { + if tree.method == httpMethod { + continue + } + if value := tree.root.getValue(rPath, nil, unescape); value.handlers != nil { + c.handlers = engine.allNoMethod + serveError(c, http.StatusMethodNotAllowed, default405Body) + return + } + } + } + c.handlers = engine.allNoRoute + serveError(c, http.StatusNotFound, default404Body) +} + +var mimePlain = []string{MIMEPlain} + +func serveError(c *Context, code int, defaultMessage []byte) { + c.writermem.status = code + c.Next() + if c.writermem.Written() { + return + } + if c.writermem.Status() == code { + c.writermem.Header()["Content-Type"] = mimePlain + _, err := c.Writer.Write(defaultMessage) + if err != nil { + debugPrint("cannot write message to writer during serve error: %v", err) + } + return + } + c.writermem.WriteHeaderNow() +} + +func redirectTrailingSlash(c *Context) { + req := c.Request + p := req.URL.Path + if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { + p = prefix + "/" + req.URL.Path + } + req.URL.Path = p + "/" + if length := len(p); length > 1 && p[length-1] == '/' { + req.URL.Path = p[:length-1] + } + redirectRequest(c) +} + +func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { + req := c.Request + rPath := req.URL.Path + + if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { + req.URL.Path = bytesconv.BytesToString(fixedPath) + redirectRequest(c) + return true + } + return false +} + +func redirectRequest(c *Context) { + req := c.Request + rPath := req.URL.Path + rURL := req.URL.String() + + code := http.StatusMovedPermanently // Permanent redirect, request with GET method + if req.Method != http.MethodGet { + code = http.StatusTemporaryRedirect + } + debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) + http.Redirect(c.Writer, req, rURL, code) + c.writermem.WriteHeaderNow() +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv.go b/taskman-server/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv.go new file mode 100644 index 00000000..86e4c4d4 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/internal/bytesconv/bytesconv.go @@ -0,0 +1,24 @@ +// Copyright 2020 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package bytesconv + +import ( + "unsafe" +) + +// StringToBytes converts string to byte slice without a memory allocation. +func StringToBytes(s string) []byte { + return *(*[]byte)(unsafe.Pointer( + &struct { + string + Cap int + }{s, len(s)}, + )) +} + +// BytesToString converts byte slice to string without a memory allocation. +func BytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/json.go b/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/json.go new file mode 100644 index 00000000..172aeb24 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/json.go @@ -0,0 +1,23 @@ +// Copyright 2017 Bo-Yi Wu. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build !jsoniter +// +build !jsoniter + +package json + +import "encoding/json" + +var ( + // Marshal is exported by gin/json package. + Marshal = json.Marshal + // Unmarshal is exported by gin/json package. + Unmarshal = json.Unmarshal + // MarshalIndent is exported by gin/json package. + MarshalIndent = json.MarshalIndent + // NewDecoder is exported by gin/json package. + NewDecoder = json.NewDecoder + // NewEncoder is exported by gin/json package. + NewEncoder = json.NewEncoder +) diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go b/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go new file mode 100644 index 00000000..232f8dca --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/internal/json/jsoniter.go @@ -0,0 +1,24 @@ +// Copyright 2017 Bo-Yi Wu. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build jsoniter +// +build jsoniter + +package json + +import jsoniter "github.com/json-iterator/go" + +var ( + json = jsoniter.ConfigCompatibleWithStandardLibrary + // Marshal is exported by gin/json package. + Marshal = json.Marshal + // Unmarshal is exported by gin/json package. + Unmarshal = json.Unmarshal + // MarshalIndent is exported by gin/json package. + MarshalIndent = json.MarshalIndent + // NewDecoder is exported by gin/json package. + NewDecoder = json.NewDecoder + // NewEncoder is exported by gin/json package. + NewEncoder = json.NewEncoder +) diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/logger.go b/taskman-server/vendor/github.com/gin-gonic/gin/logger.go new file mode 100644 index 00000000..d361b74d --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/logger.go @@ -0,0 +1,271 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "fmt" + "io" + "net/http" + "os" + "time" + + "github.com/mattn/go-isatty" +) + +type consoleColorModeValue int + +const ( + autoColor consoleColorModeValue = iota + disableColor + forceColor +) + +const ( + green = "\033[97;42m" + white = "\033[90;47m" + yellow = "\033[90;43m" + red = "\033[97;41m" + blue = "\033[97;44m" + magenta = "\033[97;45m" + cyan = "\033[97;46m" + reset = "\033[0m" +) + +var consoleColorMode = autoColor + +// LoggerConfig defines the config for Logger middleware. +type LoggerConfig struct { + // Optional. Default value is gin.defaultLogFormatter + Formatter LogFormatter + + // Output is a writer where logs are written. + // Optional. Default value is gin.DefaultWriter. + Output io.Writer + + // SkipPaths is a url path array which logs are not written. + // Optional. + SkipPaths []string +} + +// LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter +type LogFormatter func(params LogFormatterParams) string + +// LogFormatterParams is the structure any formatter will be handed when time to log comes +type LogFormatterParams struct { + Request *http.Request + + // TimeStamp shows the time after the server returns a response. + TimeStamp time.Time + // StatusCode is HTTP response code. + StatusCode int + // Latency is how much time the server cost to process a certain request. + Latency time.Duration + // ClientIP equals Context's ClientIP method. + ClientIP string + // Method is the HTTP method given to the request. + Method string + // Path is a path the client requests. + Path string + // ErrorMessage is set if error has occurred in processing the request. + ErrorMessage string + // isTerm shows whether does gin's output descriptor refers to a terminal. + isTerm bool + // BodySize is the size of the Response Body + BodySize int + // Keys are the keys set on the request's context. + Keys map[string]interface{} +} + +// StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal. +func (p *LogFormatterParams) StatusCodeColor() string { + code := p.StatusCode + + switch { + case code >= http.StatusOK && code < http.StatusMultipleChoices: + return green + case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: + return white + case code >= http.StatusBadRequest && code < http.StatusInternalServerError: + return yellow + default: + return red + } +} + +// MethodColor is the ANSI color for appropriately logging http method to a terminal. +func (p *LogFormatterParams) MethodColor() string { + method := p.Method + + switch method { + case http.MethodGet: + return blue + case http.MethodPost: + return cyan + case http.MethodPut: + return yellow + case http.MethodDelete: + return red + case http.MethodPatch: + return green + case http.MethodHead: + return magenta + case http.MethodOptions: + return white + default: + return reset + } +} + +// ResetColor resets all escape attributes. +func (p *LogFormatterParams) ResetColor() string { + return reset +} + +// IsOutputColor indicates whether can colors be outputted to the log. +func (p *LogFormatterParams) IsOutputColor() bool { + return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm) +} + +// defaultLogFormatter is the default log format function Logger middleware uses. +var defaultLogFormatter = func(param LogFormatterParams) string { + var statusColor, methodColor, resetColor string + if param.IsOutputColor() { + statusColor = param.StatusCodeColor() + methodColor = param.MethodColor() + resetColor = param.ResetColor() + } + + if param.Latency > time.Minute { + // Truncate in a golang < 1.8 safe way + param.Latency = param.Latency - param.Latency%time.Second + } + return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s", + param.TimeStamp.Format("2006/01/02 - 15:04:05"), + statusColor, param.StatusCode, resetColor, + param.Latency, + param.ClientIP, + methodColor, param.Method, resetColor, + param.Path, + param.ErrorMessage, + ) +} + +// DisableConsoleColor disables color output in the console. +func DisableConsoleColor() { + consoleColorMode = disableColor +} + +// ForceConsoleColor force color output in the console. +func ForceConsoleColor() { + consoleColorMode = forceColor +} + +// ErrorLogger returns a handlerfunc for any error type. +func ErrorLogger() HandlerFunc { + return ErrorLoggerT(ErrorTypeAny) +} + +// ErrorLoggerT returns a handlerfunc for a given error type. +func ErrorLoggerT(typ ErrorType) HandlerFunc { + return func(c *Context) { + c.Next() + errors := c.Errors.ByType(typ) + if len(errors) > 0 { + c.JSON(-1, errors) + } + } +} + +// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. +// By default gin.DefaultWriter = os.Stdout. +func Logger() HandlerFunc { + return LoggerWithConfig(LoggerConfig{}) +} + +// LoggerWithFormatter instance a Logger middleware with the specified log format function. +func LoggerWithFormatter(f LogFormatter) HandlerFunc { + return LoggerWithConfig(LoggerConfig{ + Formatter: f, + }) +} + +// LoggerWithWriter instance a Logger middleware with the specified writer buffer. +// Example: os.Stdout, a file opened in write mode, a socket... +func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { + return LoggerWithConfig(LoggerConfig{ + Output: out, + SkipPaths: notlogged, + }) +} + +// LoggerWithConfig instance a Logger middleware with config. +func LoggerWithConfig(conf LoggerConfig) HandlerFunc { + formatter := conf.Formatter + if formatter == nil { + formatter = defaultLogFormatter + } + + out := conf.Output + if out == nil { + out = DefaultWriter + } + + notlogged := conf.SkipPaths + + isTerm := true + + if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" || + (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) { + isTerm = false + } + + var skip map[string]struct{} + + if length := len(notlogged); length > 0 { + skip = make(map[string]struct{}, length) + + for _, path := range notlogged { + skip[path] = struct{}{} + } + } + + return func(c *Context) { + // Start timer + start := time.Now() + path := c.Request.URL.Path + raw := c.Request.URL.RawQuery + + // Process request + c.Next() + + // Log only when path is not being skipped + if _, ok := skip[path]; !ok { + param := LogFormatterParams{ + Request: c.Request, + isTerm: isTerm, + Keys: c.Keys, + } + + // Stop timer + param.TimeStamp = time.Now() + param.Latency = param.TimeStamp.Sub(start) + + param.ClientIP = c.ClientIP() + param.Method = c.Request.Method + param.StatusCode = c.Writer.Status() + param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String() + + param.BodySize = c.Writer.Size() + + if raw != "" { + path = path + "?" + raw + } + + param.Path = path + + fmt.Fprint(out, formatter(param)) + } + } +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/mode.go b/taskman-server/vendor/github.com/gin-gonic/gin/mode.go new file mode 100644 index 00000000..c8813aff --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/mode.go @@ -0,0 +1,92 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "io" + "os" + + "github.com/gin-gonic/gin/binding" +) + +// EnvGinMode indicates environment name for gin mode. +const EnvGinMode = "GIN_MODE" + +const ( + // DebugMode indicates gin mode is debug. + DebugMode = "debug" + // ReleaseMode indicates gin mode is release. + ReleaseMode = "release" + // TestMode indicates gin mode is test. + TestMode = "test" +) + +const ( + debugCode = iota + releaseCode + testCode +) + +// DefaultWriter is the default io.Writer used by Gin for debug output and +// middleware output like Logger() or Recovery(). +// Note that both Logger and Recovery provides custom ways to configure their +// output io.Writer. +// To support coloring in Windows use: +// import "github.com/mattn/go-colorable" +// gin.DefaultWriter = colorable.NewColorableStdout() +var DefaultWriter io.Writer = os.Stdout + +// DefaultErrorWriter is the default io.Writer used by Gin to debug errors +var DefaultErrorWriter io.Writer = os.Stderr + +var ginMode = debugCode +var modeName = DebugMode + +func init() { + mode := os.Getenv(EnvGinMode) + SetMode(mode) +} + +// SetMode sets gin mode according to input string. +func SetMode(value string) { + if value == "" { + value = DebugMode + } + + switch value { + case DebugMode: + ginMode = debugCode + case ReleaseMode: + ginMode = releaseCode + case TestMode: + ginMode = testCode + default: + panic("gin mode unknown: " + value + " (available mode: debug release test)") + } + + modeName = value +} + +// DisableBindValidation closes the default validator. +func DisableBindValidation() { + binding.Validator = nil +} + +// EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to +// call the UseNumber method on the JSON Decoder instance. +func EnableJsonDecoderUseNumber() { + binding.EnableDecoderUseNumber = true +} + +// EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to +// call the DisallowUnknownFields method on the JSON Decoder instance. +func EnableJsonDecoderDisallowUnknownFields() { + binding.EnableDecoderDisallowUnknownFields = true +} + +// Mode returns currently gin mode. +func Mode() string { + return modeName +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/path.go b/taskman-server/vendor/github.com/gin-gonic/gin/path.go new file mode 100644 index 00000000..d42d6b9d --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/path.go @@ -0,0 +1,150 @@ +// Copyright 2013 Julien Schmidt. All rights reserved. +// Based on the path package, Copyright 2009 The Go Authors. +// Use of this source code is governed by a BSD-style license that can be found +// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE. + +package gin + +// cleanPath is the URL version of path.Clean, it returns a canonical URL path +// for p, eliminating . and .. elements. +// +// The following rules are applied iteratively until no further processing can +// be done: +// 1. Replace multiple slashes with a single slash. +// 2. Eliminate each . path name element (the current directory). +// 3. Eliminate each inner .. path name element (the parent directory) +// along with the non-.. element that precedes it. +// 4. Eliminate .. elements that begin a rooted path: +// that is, replace "/.." by "/" at the beginning of a path. +// +// If the result of this process is an empty string, "/" is returned. +func cleanPath(p string) string { + const stackBufSize = 128 + // Turn empty string into "/" + if p == "" { + return "/" + } + + // Reasonably sized buffer on stack to avoid allocations in the common case. + // If a larger buffer is required, it gets allocated dynamically. + buf := make([]byte, 0, stackBufSize) + + n := len(p) + + // Invariants: + // reading from path; r is index of next byte to process. + // writing to buf; w is index of next byte to write. + + // path must start with '/' + r := 1 + w := 1 + + if p[0] != '/' { + r = 0 + + if n+1 > stackBufSize { + buf = make([]byte, n+1) + } else { + buf = buf[:n+1] + } + buf[0] = '/' + } + + trailing := n > 1 && p[n-1] == '/' + + // A bit more clunky without a 'lazybuf' like the path package, but the loop + // gets completely inlined (bufApp calls). + // loop has no expensive function calls (except 1x make) // So in contrast to the path package this loop has no expensive function + // calls (except make, if needed). + + for r < n { + switch { + case p[r] == '/': + // empty path element, trailing slash is added after the end + r++ + + case p[r] == '.' && r+1 == n: + trailing = true + r++ + + case p[r] == '.' && p[r+1] == '/': + // . element + r += 2 + + case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): + // .. element: remove to last / + r += 3 + + if w > 1 { + // can backtrack + w-- + + if len(buf) == 0 { + for w > 1 && p[w] != '/' { + w-- + } + } else { + for w > 1 && buf[w] != '/' { + w-- + } + } + } + + default: + // Real path element. + // Add slash if needed + if w > 1 { + bufApp(&buf, p, w, '/') + w++ + } + + // Copy element + for r < n && p[r] != '/' { + bufApp(&buf, p, w, p[r]) + w++ + r++ + } + } + } + + // Re-append trailing slash + if trailing && w > 1 { + bufApp(&buf, p, w, '/') + w++ + } + + // If the original string was not modified (or only shortened at the end), + // return the respective substring of the original string. + // Otherwise return a new string from the buffer. + if len(buf) == 0 { + return p[:w] + } + return string(buf[:w]) +} + +// Internal helper to lazily create a buffer if necessary. +// Calls to this function get inlined. +func bufApp(buf *[]byte, s string, w int, c byte) { + b := *buf + if len(b) == 0 { + // No modification of the original string so far. + // If the next character is the same as in the original string, we do + // not yet have to allocate a buffer. + if s[w] == c { + return + } + + // Otherwise use either the stack buffer, if it is large enough, or + // allocate a new buffer on the heap, and copy all previous characters. + length := len(s) + if length > cap(b) { + *buf = make([]byte, length) + } else { + *buf = (*buf)[:length] + } + b = *buf + + copy(b, s[:w]) + } + b[w] = c +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/recovery.go b/taskman-server/vendor/github.com/gin-gonic/gin/recovery.go new file mode 100644 index 00000000..563f5aaa --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/recovery.go @@ -0,0 +1,171 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "log" + "net" + "net/http" + "net/http/httputil" + "os" + "runtime" + "strings" + "time" +) + +var ( + dunno = []byte("???") + centerDot = []byte("·") + dot = []byte(".") + slash = []byte("/") +) + +// RecoveryFunc defines the function passable to CustomRecovery. +type RecoveryFunc func(c *Context, err interface{}) + +// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. +func Recovery() HandlerFunc { + return RecoveryWithWriter(DefaultErrorWriter) +} + +//CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it. +func CustomRecovery(handle RecoveryFunc) HandlerFunc { + return RecoveryWithWriter(DefaultErrorWriter, handle) +} + +// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one. +func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc { + if len(recovery) > 0 { + return CustomRecoveryWithWriter(out, recovery[0]) + } + return CustomRecoveryWithWriter(out, defaultHandleRecovery) +} + +// CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it. +func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc { + var logger *log.Logger + if out != nil { + logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags) + } + return func(c *Context) { + defer func() { + if err := recover(); err != nil { + // Check for a broken connection, as it is not really a + // condition that warrants a panic stack trace. + var brokenPipe bool + if ne, ok := err.(*net.OpError); ok { + if se, ok := ne.Err.(*os.SyscallError); ok { + if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { + brokenPipe = true + } + } + } + if logger != nil { + stack := stack(3) + httpRequest, _ := httputil.DumpRequest(c.Request, false) + headers := strings.Split(string(httpRequest), "\r\n") + for idx, header := range headers { + current := strings.Split(header, ":") + if current[0] == "Authorization" { + headers[idx] = current[0] + ": *" + } + } + headersToStr := strings.Join(headers, "\r\n") + if brokenPipe { + logger.Printf("%s\n%s%s", err, headersToStr, reset) + } else if IsDebugging() { + logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s", + timeFormat(time.Now()), headersToStr, err, stack, reset) + } else { + logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s", + timeFormat(time.Now()), err, stack, reset) + } + } + if brokenPipe { + // If the connection is dead, we can't write a status to it. + c.Error(err.(error)) // nolint: errcheck + c.Abort() + } else { + handle(c, err) + } + } + }() + c.Next() + } +} + +func defaultHandleRecovery(c *Context, err interface{}) { + c.AbortWithStatus(http.StatusInternalServerError) +} + +// stack returns a nicely formatted stack frame, skipping skip frames. +func stack(skip int) []byte { + buf := new(bytes.Buffer) // the returned data + // As we loop, we open files and read them. These variables record the currently + // loaded file. + var lines [][]byte + var lastFile string + for i := skip; ; i++ { // Skip the expected number of frames + pc, file, line, ok := runtime.Caller(i) + if !ok { + break + } + // Print this much at least. If we can't find the source, it won't show. + fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) + if file != lastFile { + data, err := ioutil.ReadFile(file) + if err != nil { + continue + } + lines = bytes.Split(data, []byte{'\n'}) + lastFile = file + } + fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) + } + return buf.Bytes() +} + +// source returns a space-trimmed slice of the n'th line. +func source(lines [][]byte, n int) []byte { + n-- // in stack trace, lines are 1-indexed but our array is 0-indexed + if n < 0 || n >= len(lines) { + return dunno + } + return bytes.TrimSpace(lines[n]) +} + +// function returns, if possible, the name of the function containing the PC. +func function(pc uintptr) []byte { + fn := runtime.FuncForPC(pc) + if fn == nil { + return dunno + } + name := []byte(fn.Name()) + // The name includes the path name to the package, which is unnecessary + // since the file name is already included. Plus, it has center dots. + // That is, we see + // runtime/debug.*T·ptrmethod + // and want + // *T.ptrmethod + // Also the package path might contains dot (e.g. code.google.com/...), + // so first eliminate the path prefix + if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 { + name = name[lastSlash+1:] + } + if period := bytes.Index(name, dot); period >= 0 { + name = name[period+1:] + } + name = bytes.Replace(name, centerDot, dot, -1) + return name +} + +func timeFormat(t time.Time) string { + timeString := t.Format("2006/01/02 - 15:04:05") + return timeString +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/data.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/data.go new file mode 100644 index 00000000..6ba657ba --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/data.go @@ -0,0 +1,25 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import "net/http" + +// Data contains ContentType and bytes data. +type Data struct { + ContentType string + Data []byte +} + +// Render (Data) writes data with custom ContentType. +func (r Data) Render(w http.ResponseWriter) (err error) { + r.WriteContentType(w) + _, err = w.Write(r.Data) + return +} + +// WriteContentType (Data) writes custom ContentType. +func (r Data) WriteContentType(w http.ResponseWriter) { + writeContentType(w, []string{r.ContentType}) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/html.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/html.go new file mode 100644 index 00000000..6696ece9 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/html.go @@ -0,0 +1,92 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "html/template" + "net/http" +) + +// Delims represents a set of Left and Right delimiters for HTML template rendering. +type Delims struct { + // Left delimiter, defaults to {{. + Left string + // Right delimiter, defaults to }}. + Right string +} + +// HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. +type HTMLRender interface { + // Instance returns an HTML instance. + Instance(string, interface{}) Render +} + +// HTMLProduction contains template reference and its delims. +type HTMLProduction struct { + Template *template.Template + Delims Delims +} + +// HTMLDebug contains template delims and pattern and function with file list. +type HTMLDebug struct { + Files []string + Glob string + Delims Delims + FuncMap template.FuncMap +} + +// HTML contains template reference and its name with given interface object. +type HTML struct { + Template *template.Template + Name string + Data interface{} +} + +var htmlContentType = []string{"text/html; charset=utf-8"} + +// Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. +func (r HTMLProduction) Instance(name string, data interface{}) Render { + return HTML{ + Template: r.Template, + Name: name, + Data: data, + } +} + +// Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. +func (r HTMLDebug) Instance(name string, data interface{}) Render { + return HTML{ + Template: r.loadTemplate(), + Name: name, + Data: data, + } +} +func (r HTMLDebug) loadTemplate() *template.Template { + if r.FuncMap == nil { + r.FuncMap = template.FuncMap{} + } + if len(r.Files) > 0 { + return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) + } + if r.Glob != "" { + return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) + } + panic("the HTML debug render was created without files or glob pattern") +} + +// Render (HTML) executes template and writes its result with custom ContentType for response. +func (r HTML) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + + if r.Name == "" { + return r.Template.Execute(w, r.Data) + } + return r.Template.ExecuteTemplate(w, r.Name, r.Data) +} + +// WriteContentType (HTML) writes HTML ContentType. +func (r HTML) WriteContentType(w http.ResponseWriter) { + writeContentType(w, htmlContentType) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/json.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/json.go new file mode 100644 index 00000000..41863093 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/json.go @@ -0,0 +1,193 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "bytes" + "fmt" + "html/template" + "net/http" + + "github.com/gin-gonic/gin/internal/bytesconv" + "github.com/gin-gonic/gin/internal/json" +) + +// JSON contains the given interface object. +type JSON struct { + Data interface{} +} + +// IndentedJSON contains the given interface object. +type IndentedJSON struct { + Data interface{} +} + +// SecureJSON contains the given interface object and its prefix. +type SecureJSON struct { + Prefix string + Data interface{} +} + +// JsonpJSON contains the given interface object its callback. +type JsonpJSON struct { + Callback string + Data interface{} +} + +// AsciiJSON contains the given interface object. +type AsciiJSON struct { + Data interface{} +} + +// PureJSON contains the given interface object. +type PureJSON struct { + Data interface{} +} + +var jsonContentType = []string{"application/json; charset=utf-8"} +var jsonpContentType = []string{"application/javascript; charset=utf-8"} +var jsonAsciiContentType = []string{"application/json"} + +// Render (JSON) writes data with custom ContentType. +func (r JSON) Render(w http.ResponseWriter) (err error) { + if err = WriteJSON(w, r.Data); err != nil { + panic(err) + } + return +} + +// WriteContentType (JSON) writes JSON ContentType. +func (r JSON) WriteContentType(w http.ResponseWriter) { + writeContentType(w, jsonContentType) +} + +// WriteJSON marshals the given interface object and writes it with custom ContentType. +func WriteJSON(w http.ResponseWriter, obj interface{}) error { + writeContentType(w, jsonContentType) + jsonBytes, err := json.Marshal(obj) + if err != nil { + return err + } + _, err = w.Write(jsonBytes) + return err +} + +// Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType. +func (r IndentedJSON) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + jsonBytes, err := json.MarshalIndent(r.Data, "", " ") + if err != nil { + return err + } + _, err = w.Write(jsonBytes) + return err +} + +// WriteContentType (IndentedJSON) writes JSON ContentType. +func (r IndentedJSON) WriteContentType(w http.ResponseWriter) { + writeContentType(w, jsonContentType) +} + +// Render (SecureJSON) marshals the given interface object and writes it with custom ContentType. +func (r SecureJSON) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + jsonBytes, err := json.Marshal(r.Data) + if err != nil { + return err + } + // if the jsonBytes is array values + if bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes("[")) && bytes.HasSuffix(jsonBytes, + bytesconv.StringToBytes("]")) { + _, err = w.Write(bytesconv.StringToBytes(r.Prefix)) + if err != nil { + return err + } + } + _, err = w.Write(jsonBytes) + return err +} + +// WriteContentType (SecureJSON) writes JSON ContentType. +func (r SecureJSON) WriteContentType(w http.ResponseWriter) { + writeContentType(w, jsonContentType) +} + +// Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType. +func (r JsonpJSON) Render(w http.ResponseWriter) (err error) { + r.WriteContentType(w) + ret, err := json.Marshal(r.Data) + if err != nil { + return err + } + + if r.Callback == "" { + _, err = w.Write(ret) + return err + } + + callback := template.JSEscapeString(r.Callback) + _, err = w.Write(bytesconv.StringToBytes(callback)) + if err != nil { + return err + } + _, err = w.Write(bytesconv.StringToBytes("(")) + if err != nil { + return err + } + _, err = w.Write(ret) + if err != nil { + return err + } + _, err = w.Write(bytesconv.StringToBytes(");")) + if err != nil { + return err + } + + return nil +} + +// WriteContentType (JsonpJSON) writes Javascript ContentType. +func (r JsonpJSON) WriteContentType(w http.ResponseWriter) { + writeContentType(w, jsonpContentType) +} + +// Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType. +func (r AsciiJSON) Render(w http.ResponseWriter) (err error) { + r.WriteContentType(w) + ret, err := json.Marshal(r.Data) + if err != nil { + return err + } + + var buffer bytes.Buffer + for _, r := range bytesconv.BytesToString(ret) { + cvt := string(r) + if r >= 128 { + cvt = fmt.Sprintf("\\u%04x", int64(r)) + } + buffer.WriteString(cvt) + } + + _, err = w.Write(buffer.Bytes()) + return err +} + +// WriteContentType (AsciiJSON) writes JSON ContentType. +func (r AsciiJSON) WriteContentType(w http.ResponseWriter) { + writeContentType(w, jsonAsciiContentType) +} + +// Render (PureJSON) writes custom ContentType and encodes the given interface object. +func (r PureJSON) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + encoder := json.NewEncoder(w) + encoder.SetEscapeHTML(false) + return encoder.Encode(r.Data) +} + +// WriteContentType (PureJSON) writes custom ContentType. +func (r PureJSON) WriteContentType(w http.ResponseWriter) { + writeContentType(w, jsonContentType) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/msgpack.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/msgpack.go new file mode 100644 index 00000000..6ef5b6e5 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/msgpack.go @@ -0,0 +1,42 @@ +// Copyright 2017 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build !nomsgpack +// +build !nomsgpack + +package render + +import ( + "net/http" + + "github.com/ugorji/go/codec" +) + +var ( + _ Render = MsgPack{} +) + +// MsgPack contains the given interface object. +type MsgPack struct { + Data interface{} +} + +var msgpackContentType = []string{"application/msgpack; charset=utf-8"} + +// WriteContentType (MsgPack) writes MsgPack ContentType. +func (r MsgPack) WriteContentType(w http.ResponseWriter) { + writeContentType(w, msgpackContentType) +} + +// Render (MsgPack) encodes the given interface object and writes data with custom ContentType. +func (r MsgPack) Render(w http.ResponseWriter) error { + return WriteMsgPack(w, r.Data) +} + +// WriteMsgPack writes MsgPack ContentType and encodes the given interface object. +func WriteMsgPack(w http.ResponseWriter, obj interface{}) error { + writeContentType(w, msgpackContentType) + var mh codec.MsgpackHandle + return codec.NewEncoder(w, &mh).Encode(obj) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/protobuf.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/protobuf.go new file mode 100644 index 00000000..15aca995 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/protobuf.go @@ -0,0 +1,36 @@ +// Copyright 2018 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "net/http" + + "github.com/golang/protobuf/proto" +) + +// ProtoBuf contains the given interface object. +type ProtoBuf struct { + Data interface{} +} + +var protobufContentType = []string{"application/x-protobuf"} + +// Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType. +func (r ProtoBuf) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + + bytes, err := proto.Marshal(r.Data.(proto.Message)) + if err != nil { + return err + } + + _, err = w.Write(bytes) + return err +} + +// WriteContentType (ProtoBuf) writes ProtoBuf ContentType. +func (r ProtoBuf) WriteContentType(w http.ResponseWriter) { + writeContentType(w, protobufContentType) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/reader.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/reader.go new file mode 100644 index 00000000..d5282e49 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/reader.go @@ -0,0 +1,48 @@ +// Copyright 2018 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "io" + "net/http" + "strconv" +) + +// Reader contains the IO reader and its length, and custom ContentType and other headers. +type Reader struct { + ContentType string + ContentLength int64 + Reader io.Reader + Headers map[string]string +} + +// Render (Reader) writes data with custom ContentType and headers. +func (r Reader) Render(w http.ResponseWriter) (err error) { + r.WriteContentType(w) + if r.ContentLength >= 0 { + if r.Headers == nil { + r.Headers = map[string]string{} + } + r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10) + } + r.writeHeaders(w, r.Headers) + _, err = io.Copy(w, r.Reader) + return +} + +// WriteContentType (Reader) writes custom ContentType. +func (r Reader) WriteContentType(w http.ResponseWriter) { + writeContentType(w, []string{r.ContentType}) +} + +// writeHeaders writes custom Header. +func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) { + header := w.Header() + for k, v := range headers { + if header.Get(k) == "" { + header.Set(k, v) + } + } +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/redirect.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/redirect.go new file mode 100644 index 00000000..c006691c --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/redirect.go @@ -0,0 +1,29 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "fmt" + "net/http" +) + +// Redirect contains the http request reference and redirects status code and location. +type Redirect struct { + Code int + Request *http.Request + Location string +} + +// Render (Redirect) redirects the http request to new location and writes redirect response. +func (r Redirect) Render(w http.ResponseWriter) error { + if (r.Code < http.StatusMultipleChoices || r.Code > http.StatusPermanentRedirect) && r.Code != http.StatusCreated { + panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code)) + } + http.Redirect(w, r.Request, r.Location, r.Code) + return nil +} + +// WriteContentType (Redirect) don't write any ContentType. +func (r Redirect) WriteContentType(http.ResponseWriter) {} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/render.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/render.go new file mode 100644 index 00000000..bcd568bf --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/render.go @@ -0,0 +1,40 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import "net/http" + +// Render interface is to be implemented by JSON, XML, HTML, YAML and so on. +type Render interface { + // Render writes data with custom ContentType. + Render(http.ResponseWriter) error + // WriteContentType writes custom ContentType. + WriteContentType(w http.ResponseWriter) +} + +var ( + _ Render = JSON{} + _ Render = IndentedJSON{} + _ Render = SecureJSON{} + _ Render = JsonpJSON{} + _ Render = XML{} + _ Render = String{} + _ Render = Redirect{} + _ Render = Data{} + _ Render = HTML{} + _ HTMLRender = HTMLDebug{} + _ HTMLRender = HTMLProduction{} + _ Render = YAML{} + _ Render = Reader{} + _ Render = AsciiJSON{} + _ Render = ProtoBuf{} +) + +func writeContentType(w http.ResponseWriter, value []string) { + header := w.Header() + if val := header["Content-Type"]; len(val) == 0 { + header["Content-Type"] = value + } +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/text.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/text.go new file mode 100644 index 00000000..461b720a --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/text.go @@ -0,0 +1,41 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "fmt" + "net/http" + + "github.com/gin-gonic/gin/internal/bytesconv" +) + +// String contains the given interface object slice and its format. +type String struct { + Format string + Data []interface{} +} + +var plainContentType = []string{"text/plain; charset=utf-8"} + +// Render (String) writes data with custom ContentType. +func (r String) Render(w http.ResponseWriter) error { + return WriteString(w, r.Format, r.Data) +} + +// WriteContentType (String) writes Plain ContentType. +func (r String) WriteContentType(w http.ResponseWriter) { + writeContentType(w, plainContentType) +} + +// WriteString writes data according to its format and write custom ContentType. +func WriteString(w http.ResponseWriter, format string, data []interface{}) (err error) { + writeContentType(w, plainContentType) + if len(data) > 0 { + _, err = fmt.Fprintf(w, format, data...) + return + } + _, err = w.Write(bytesconv.StringToBytes(format)) + return +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/xml.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/xml.go new file mode 100644 index 00000000..cc5390a2 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/xml.go @@ -0,0 +1,28 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "encoding/xml" + "net/http" +) + +// XML contains the given interface object. +type XML struct { + Data interface{} +} + +var xmlContentType = []string{"application/xml; charset=utf-8"} + +// Render (XML) encodes the given interface object and writes data with custom ContentType. +func (r XML) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + return xml.NewEncoder(w).Encode(r.Data) +} + +// WriteContentType (XML) writes XML ContentType for response. +func (r XML) WriteContentType(w http.ResponseWriter) { + writeContentType(w, xmlContentType) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/render/yaml.go b/taskman-server/vendor/github.com/gin-gonic/gin/render/yaml.go new file mode 100644 index 00000000..0df78360 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/render/yaml.go @@ -0,0 +1,36 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "net/http" + + "gopkg.in/yaml.v2" +) + +// YAML contains the given interface object. +type YAML struct { + Data interface{} +} + +var yamlContentType = []string{"application/x-yaml; charset=utf-8"} + +// Render (YAML) marshals the given interface object and writes data with custom ContentType. +func (r YAML) Render(w http.ResponseWriter) error { + r.WriteContentType(w) + + bytes, err := yaml.Marshal(r.Data) + if err != nil { + return err + } + + _, err = w.Write(bytes) + return err +} + +// WriteContentType (YAML) writes YAML ContentType for response. +func (r YAML) WriteContentType(w http.ResponseWriter) { + writeContentType(w, yamlContentType) +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/response_writer.go b/taskman-server/vendor/github.com/gin-gonic/gin/response_writer.go new file mode 100644 index 00000000..26826689 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/response_writer.go @@ -0,0 +1,126 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "bufio" + "io" + "net" + "net/http" +) + +const ( + noWritten = -1 + defaultStatus = http.StatusOK +) + +// ResponseWriter ... +type ResponseWriter interface { + http.ResponseWriter + http.Hijacker + http.Flusher + http.CloseNotifier + + // Returns the HTTP response status code of the current request. + Status() int + + // Returns the number of bytes already written into the response http body. + // See Written() + Size() int + + // Writes the string into the response body. + WriteString(string) (int, error) + + // Returns true if the response body was already written. + Written() bool + + // Forces to write the http header (status code + headers). + WriteHeaderNow() + + // get the http.Pusher for server push + Pusher() http.Pusher +} + +type responseWriter struct { + http.ResponseWriter + size int + status int +} + +var _ ResponseWriter = &responseWriter{} + +func (w *responseWriter) reset(writer http.ResponseWriter) { + w.ResponseWriter = writer + w.size = noWritten + w.status = defaultStatus +} + +func (w *responseWriter) WriteHeader(code int) { + if code > 0 && w.status != code { + if w.Written() { + debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) + } + w.status = code + } +} + +func (w *responseWriter) WriteHeaderNow() { + if !w.Written() { + w.size = 0 + w.ResponseWriter.WriteHeader(w.status) + } +} + +func (w *responseWriter) Write(data []byte) (n int, err error) { + w.WriteHeaderNow() + n, err = w.ResponseWriter.Write(data) + w.size += n + return +} + +func (w *responseWriter) WriteString(s string) (n int, err error) { + w.WriteHeaderNow() + n, err = io.WriteString(w.ResponseWriter, s) + w.size += n + return +} + +func (w *responseWriter) Status() int { + return w.status +} + +func (w *responseWriter) Size() int { + return w.size +} + +func (w *responseWriter) Written() bool { + return w.size != noWritten +} + +// Hijack implements the http.Hijacker interface. +func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + if w.size < 0 { + w.size = 0 + } + return w.ResponseWriter.(http.Hijacker).Hijack() +} + +// CloseNotify implements the http.CloseNotify interface. +func (w *responseWriter) CloseNotify() <-chan bool { + return w.ResponseWriter.(http.CloseNotifier).CloseNotify() +} + +// Flush implements the http.Flush interface. +func (w *responseWriter) Flush() { + w.WriteHeaderNow() + w.ResponseWriter.(http.Flusher).Flush() +} + +func (w *responseWriter) Pusher() (pusher http.Pusher) { + if pusher, ok := w.ResponseWriter.(http.Pusher); ok { + return pusher + } + return nil +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/routergroup.go b/taskman-server/vendor/github.com/gin-gonic/gin/routergroup.go new file mode 100644 index 00000000..15d9930d --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/routergroup.go @@ -0,0 +1,230 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "net/http" + "path" + "regexp" + "strings" +) + +// IRouter defines all router handle interface includes single and group router. +type IRouter interface { + IRoutes + Group(string, ...HandlerFunc) *RouterGroup +} + +// IRoutes defines all router handle interface. +type IRoutes interface { + Use(...HandlerFunc) IRoutes + + Handle(string, string, ...HandlerFunc) IRoutes + Any(string, ...HandlerFunc) IRoutes + GET(string, ...HandlerFunc) IRoutes + POST(string, ...HandlerFunc) IRoutes + DELETE(string, ...HandlerFunc) IRoutes + PATCH(string, ...HandlerFunc) IRoutes + PUT(string, ...HandlerFunc) IRoutes + OPTIONS(string, ...HandlerFunc) IRoutes + HEAD(string, ...HandlerFunc) IRoutes + + StaticFile(string, string) IRoutes + Static(string, string) IRoutes + StaticFS(string, http.FileSystem) IRoutes +} + +// RouterGroup is used internally to configure router, a RouterGroup is associated with +// a prefix and an array of handlers (middleware). +type RouterGroup struct { + Handlers HandlersChain + basePath string + engine *Engine + root bool +} + +var _ IRouter = &RouterGroup{} + +// Use adds middleware to the group, see example code in GitHub. +func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { + group.Handlers = append(group.Handlers, middleware...) + return group.returnObj() +} + +// Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. +// For example, all the routes that use a common middleware for authorization could be grouped. +func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { + return &RouterGroup{ + Handlers: group.combineHandlers(handlers), + basePath: group.calculateAbsolutePath(relativePath), + engine: group.engine, + } +} + +// BasePath returns the base path of router group. +// For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api". +func (group *RouterGroup) BasePath() string { + return group.basePath +} + +func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { + absolutePath := group.calculateAbsolutePath(relativePath) + handlers = group.combineHandlers(handlers) + group.engine.addRoute(httpMethod, absolutePath, handlers) + return group.returnObj() +} + +// Handle registers a new request handle and middleware with the given path and method. +// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. +// See the example code in GitHub. +// +// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut +// functions can be used. +// +// This function is intended for bulk loading and to allow the usage of less +// frequently used, non-standardized or custom methods (e.g. for internal +// communication with a proxy). +func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { + if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil { + panic("http method " + httpMethod + " is not valid") + } + return group.handle(httpMethod, relativePath, handlers) +} + +// POST is a shortcut for router.Handle("POST", path, handle). +func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(http.MethodPost, relativePath, handlers) +} + +// GET is a shortcut for router.Handle("GET", path, handle). +func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(http.MethodGet, relativePath, handlers) +} + +// DELETE is a shortcut for router.Handle("DELETE", path, handle). +func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(http.MethodDelete, relativePath, handlers) +} + +// PATCH is a shortcut for router.Handle("PATCH", path, handle). +func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(http.MethodPatch, relativePath, handlers) +} + +// PUT is a shortcut for router.Handle("PUT", path, handle). +func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(http.MethodPut, relativePath, handlers) +} + +// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle). +func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(http.MethodOptions, relativePath, handlers) +} + +// HEAD is a shortcut for router.Handle("HEAD", path, handle). +func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle(http.MethodHead, relativePath, handlers) +} + +// Any registers a route that matches all the HTTP methods. +// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. +func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { + group.handle(http.MethodGet, relativePath, handlers) + group.handle(http.MethodPost, relativePath, handlers) + group.handle(http.MethodPut, relativePath, handlers) + group.handle(http.MethodPatch, relativePath, handlers) + group.handle(http.MethodHead, relativePath, handlers) + group.handle(http.MethodOptions, relativePath, handlers) + group.handle(http.MethodDelete, relativePath, handlers) + group.handle(http.MethodConnect, relativePath, handlers) + group.handle(http.MethodTrace, relativePath, handlers) + return group.returnObj() +} + +// StaticFile registers a single route in order to serve a single file of the local filesystem. +// router.StaticFile("favicon.ico", "./resources/favicon.ico") +func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { + if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { + panic("URL parameters can not be used when serving a static file") + } + handler := func(c *Context) { + c.File(filepath) + } + group.GET(relativePath, handler) + group.HEAD(relativePath, handler) + return group.returnObj() +} + +// Static serves files from the given file system root. +// Internally a http.FileServer is used, therefore http.NotFound is used instead +// of the Router's NotFound handler. +// To use the operating system's file system implementation, +// use : +// router.Static("/static", "/var/www") +func (group *RouterGroup) Static(relativePath, root string) IRoutes { + return group.StaticFS(relativePath, Dir(root, false)) +} + +// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. +// Gin by default user: gin.Dir() +func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { + if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { + panic("URL parameters can not be used when serving a static folder") + } + handler := group.createStaticHandler(relativePath, fs) + urlPattern := path.Join(relativePath, "/*filepath") + + // Register GET and HEAD handlers + group.GET(urlPattern, handler) + group.HEAD(urlPattern, handler) + return group.returnObj() +} + +func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { + absolutePath := group.calculateAbsolutePath(relativePath) + fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) + + return func(c *Context) { + if _, noListing := fs.(*onlyFilesFS); noListing { + c.Writer.WriteHeader(http.StatusNotFound) + } + + file := c.Param("filepath") + // Check if file exists and/or if we have permission to access it + f, err := fs.Open(file) + if err != nil { + c.Writer.WriteHeader(http.StatusNotFound) + c.handlers = group.engine.noRoute + // Reset index + c.index = -1 + return + } + f.Close() + + fileServer.ServeHTTP(c.Writer, c.Request) + } +} + +func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { + finalSize := len(group.Handlers) + len(handlers) + if finalSize >= int(abortIndex) { + panic("too many handlers") + } + mergedHandlers := make(HandlersChain, finalSize) + copy(mergedHandlers, group.Handlers) + copy(mergedHandlers[len(group.Handlers):], handlers) + return mergedHandlers +} + +func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { + return joinPaths(group.basePath, relativePath) +} + +func (group *RouterGroup) returnObj() IRoutes { + if group.root { + return group.engine + } + return group +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/test_helpers.go b/taskman-server/vendor/github.com/gin-gonic/gin/test_helpers.go new file mode 100644 index 00000000..3a7a5ddf --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/test_helpers.go @@ -0,0 +1,16 @@ +// Copyright 2017 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import "net/http" + +// CreateTestContext returns a fresh engine and context for testing purposes +func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { + r = New() + c = r.allocateContext() + c.reset() + c.writermem.reset(w) + return +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/tree.go b/taskman-server/vendor/github.com/gin-gonic/gin/tree.go new file mode 100644 index 00000000..5eb09348 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/tree.go @@ -0,0 +1,831 @@ +// Copyright 2013 Julien Schmidt. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE + +package gin + +import ( + "bytes" + "net/url" + "strings" + "unicode" + "unicode/utf8" + + "github.com/gin-gonic/gin/internal/bytesconv" +) + +var ( + strColon = []byte(":") + strStar = []byte("*") +) + +// Param is a single URL parameter, consisting of a key and a value. +type Param struct { + Key string + Value string +} + +// Params is a Param-slice, as returned by the router. +// The slice is ordered, the first URL parameter is also the first slice value. +// It is therefore safe to read values by the index. +type Params []Param + +// Get returns the value of the first Param which key matches the given name. +// If no matching Param is found, an empty string is returned. +func (ps Params) Get(name string) (string, bool) { + for _, entry := range ps { + if entry.Key == name { + return entry.Value, true + } + } + return "", false +} + +// ByName returns the value of the first Param which key matches the given name. +// If no matching Param is found, an empty string is returned. +func (ps Params) ByName(name string) (va string) { + va, _ = ps.Get(name) + return +} + +type methodTree struct { + method string + root *node +} + +type methodTrees []methodTree + +func (trees methodTrees) get(method string) *node { + for _, tree := range trees { + if tree.method == method { + return tree.root + } + } + return nil +} + +func min(a, b int) int { + if a <= b { + return a + } + return b +} + +func longestCommonPrefix(a, b string) int { + i := 0 + max := min(len(a), len(b)) + for i < max && a[i] == b[i] { + i++ + } + return i +} + +// addChild will add a child node, keeping wildcards at the end +func (n *node) addChild(child *node) { + if n.wildChild && len(n.children) > 0 { + wildcardChild := n.children[len(n.children)-1] + n.children = append(n.children[:len(n.children)-1], child, wildcardChild) + } else { + n.children = append(n.children, child) + } +} + +func countParams(path string) uint16 { + var n uint16 + s := bytesconv.StringToBytes(path) + n += uint16(bytes.Count(s, strColon)) + n += uint16(bytes.Count(s, strStar)) + return n +} + +type nodeType uint8 + +const ( + static nodeType = iota // default + root + param + catchAll +) + +type node struct { + path string + indices string + wildChild bool + nType nodeType + priority uint32 + children []*node // child nodes, at most 1 :param style node at the end of the array + handlers HandlersChain + fullPath string +} + +// Increments priority of the given child and reorders if necessary +func (n *node) incrementChildPrio(pos int) int { + cs := n.children + cs[pos].priority++ + prio := cs[pos].priority + + // Adjust position (move to front) + newPos := pos + for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- { + // Swap node positions + cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1] + } + + // Build new index char string + if newPos != pos { + n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty + n.indices[pos:pos+1] + // The index char we move + n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos' + } + + return newPos +} + +// addRoute adds a node with the given handle to the path. +// Not concurrency-safe! +func (n *node) addRoute(path string, handlers HandlersChain) { + fullPath := path + n.priority++ + + // Empty tree + if len(n.path) == 0 && len(n.children) == 0 { + n.insertChild(path, fullPath, handlers) + n.nType = root + return + } + + parentFullPathIndex := 0 + +walk: + for { + // Find the longest common prefix. + // This also implies that the common prefix contains no ':' or '*' + // since the existing key can't contain those chars. + i := longestCommonPrefix(path, n.path) + + // Split edge + if i < len(n.path) { + child := node{ + path: n.path[i:], + wildChild: n.wildChild, + indices: n.indices, + children: n.children, + handlers: n.handlers, + priority: n.priority - 1, + fullPath: n.fullPath, + } + + n.children = []*node{&child} + // []byte for proper unicode char conversion, see #65 + n.indices = bytesconv.BytesToString([]byte{n.path[i]}) + n.path = path[:i] + n.handlers = nil + n.wildChild = false + n.fullPath = fullPath[:parentFullPathIndex+i] + } + + // Make new node a child of this node + if i < len(path) { + path = path[i:] + c := path[0] + + // '/' after param + if n.nType == param && c == '/' && len(n.children) == 1 { + parentFullPathIndex += len(n.path) + n = n.children[0] + n.priority++ + continue walk + } + + // Check if a child with the next path byte exists + for i, max := 0, len(n.indices); i < max; i++ { + if c == n.indices[i] { + parentFullPathIndex += len(n.path) + i = n.incrementChildPrio(i) + n = n.children[i] + continue walk + } + } + + // Otherwise insert it + if c != ':' && c != '*' && n.nType != catchAll { + // []byte for proper unicode char conversion, see #65 + n.indices += bytesconv.BytesToString([]byte{c}) + child := &node{ + fullPath: fullPath, + } + n.addChild(child) + n.incrementChildPrio(len(n.indices) - 1) + n = child + } else if n.wildChild { + // inserting a wildcard node, need to check if it conflicts with the existing wildcard + n = n.children[len(n.children)-1] + n.priority++ + + // Check if the wildcard matches + if len(path) >= len(n.path) && n.path == path[:len(n.path)] && + // Adding a child to a catchAll is not possible + n.nType != catchAll && + // Check for longer wildcard, e.g. :name and :names + (len(n.path) >= len(path) || path[len(n.path)] == '/') { + continue walk + } + + // Wildcard conflict + pathSeg := path + if n.nType != catchAll { + pathSeg = strings.SplitN(pathSeg, "/", 2)[0] + } + prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path + panic("'" + pathSeg + + "' in new path '" + fullPath + + "' conflicts with existing wildcard '" + n.path + + "' in existing prefix '" + prefix + + "'") + } + + n.insertChild(path, fullPath, handlers) + return + } + + // Otherwise add handle to current node + if n.handlers != nil { + panic("handlers are already registered for path '" + fullPath + "'") + } + n.handlers = handlers + n.fullPath = fullPath + return + } +} + +// Search for a wildcard segment and check the name for invalid characters. +// Returns -1 as index, if no wildcard was found. +func findWildcard(path string) (wildcard string, i int, valid bool) { + // Find start + for start, c := range []byte(path) { + // A wildcard starts with ':' (param) or '*' (catch-all) + if c != ':' && c != '*' { + continue + } + + // Find end and check for invalid characters + valid = true + for end, c := range []byte(path[start+1:]) { + switch c { + case '/': + return path[start : start+1+end], start, valid + case ':', '*': + valid = false + } + } + return path[start:], start, valid + } + return "", -1, false +} + +func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) { + for { + // Find prefix until first wildcard + wildcard, i, valid := findWildcard(path) + if i < 0 { // No wildcard found + break + } + + // The wildcard name must not contain ':' and '*' + if !valid { + panic("only one wildcard per path segment is allowed, has: '" + + wildcard + "' in path '" + fullPath + "'") + } + + // check if the wildcard has a name + if len(wildcard) < 2 { + panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") + } + + if wildcard[0] == ':' { // param + if i > 0 { + // Insert prefix before the current wildcard + n.path = path[:i] + path = path[i:] + } + + child := &node{ + nType: param, + path: wildcard, + fullPath: fullPath, + } + n.addChild(child) + n.wildChild = true + n = child + n.priority++ + + // if the path doesn't end with the wildcard, then there + // will be another non-wildcard subpath starting with '/' + if len(wildcard) < len(path) { + path = path[len(wildcard):] + + child := &node{ + priority: 1, + fullPath: fullPath, + } + n.addChild(child) + n = child + continue + } + + // Otherwise we're done. Insert the handle in the new leaf + n.handlers = handlers + return + } + + // catchAll + if i+len(wildcard) != len(path) { + panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") + } + + if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { + panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'") + } + + // currently fixed width 1 for '/' + i-- + if path[i] != '/' { + panic("no / before catch-all in path '" + fullPath + "'") + } + + n.path = path[:i] + + // First node: catchAll node with empty path + child := &node{ + wildChild: true, + nType: catchAll, + fullPath: fullPath, + } + + n.addChild(child) + n.indices = string('/') + n = child + n.priority++ + + // second node: node holding the variable + child = &node{ + path: path[i:], + nType: catchAll, + handlers: handlers, + priority: 1, + fullPath: fullPath, + } + n.children = []*node{child} + + return + } + + // If no wildcard was found, simply insert the path and handle + n.path = path + n.handlers = handlers + n.fullPath = fullPath +} + +// nodeValue holds return values of (*Node).getValue method +type nodeValue struct { + handlers HandlersChain + params *Params + tsr bool + fullPath string +} + +// Returns the handle registered with the given path (key). The values of +// wildcards are saved to a map. +// If no handle can be found, a TSR (trailing slash redirect) recommendation is +// made if a handle exists with an extra (without the) trailing slash for the +// given path. +func (n *node) getValue(path string, params *Params, unescape bool) (value nodeValue) { + var ( + skippedPath string + latestNode = n // Caching the latest node + ) + +walk: // Outer loop for walking the tree + for { + prefix := n.path + if len(path) > len(prefix) { + if path[:len(prefix)] == prefix { + path = path[len(prefix):] + + // Try all the non-wildcard children first by matching the indices + idxc := path[0] + for i, c := range []byte(n.indices) { + if c == idxc { + // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild + if n.wildChild { + skippedPath = prefix + path + latestNode = &node{ + path: n.path, + wildChild: n.wildChild, + nType: n.nType, + priority: n.priority, + children: n.children, + handlers: n.handlers, + fullPath: n.fullPath, + } + } + + n = n.children[i] + continue walk + } + } + // If the path at the end of the loop is not equal to '/' and the current node has no child nodes + // the current node needs to be equal to the latest matching node + matched := path != "/" && !n.wildChild + if matched { + n = latestNode + } + + // If there is no wildcard pattern, recommend a redirection + if !n.wildChild { + // Nothing found. + // We can recommend to redirect to the same URL without a + // trailing slash if a leaf exists for that path. + value.tsr = path == "/" && n.handlers != nil + return + } + + // Handle wildcard child, which is always at the end of the array + n = n.children[len(n.children)-1] + + switch n.nType { + case param: + // fix truncate the parameter + // tree_test.go line: 204 + if matched { + path = prefix + path + // The saved path is used after the prefix route is intercepted by matching + if n.indices == "/" { + path = skippedPath[1:] + } + } + + // Find param end (either '/' or path end) + end := 0 + for end < len(path) && path[end] != '/' { + end++ + } + + // Save param value + if params != nil { + if value.params == nil { + value.params = params + } + // Expand slice within preallocated capacity + i := len(*value.params) + *value.params = (*value.params)[:i+1] + val := path[:end] + if unescape { + if v, err := url.QueryUnescape(val); err == nil { + val = v + } + } + (*value.params)[i] = Param{ + Key: n.path[1:], + Value: val, + } + } + + // we need to go deeper! + if end < len(path) { + if len(n.children) > 0 { + path = path[end:] + n = n.children[0] + continue walk + } + + // ... but we can't + value.tsr = (len(path) == end+1) + return + } + + if value.handlers = n.handlers; value.handlers != nil { + value.fullPath = n.fullPath + return + } + if len(n.children) == 1 { + // No handle found. Check if a handle for this path + a + // trailing slash exists for TSR recommendation + n = n.children[0] + value.tsr = (n.path == "/" && n.handlers != nil) + } + return + + case catchAll: + // Save param value + if params != nil { + if value.params == nil { + value.params = params + } + // Expand slice within preallocated capacity + i := len(*value.params) + *value.params = (*value.params)[:i+1] + val := path + if unescape { + if v, err := url.QueryUnescape(path); err == nil { + val = v + } + } + (*value.params)[i] = Param{ + Key: n.path[2:], + Value: val, + } + } + + value.handlers = n.handlers + value.fullPath = n.fullPath + return + + default: + panic("invalid node type") + } + } + } + + if path == prefix { + // If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node + // the current node needs to be equal to the latest matching node + if latestNode.wildChild && n.handlers == nil && path != "/" { + n = latestNode.children[len(latestNode.children)-1] + } + // We should have reached the node containing the handle. + // Check if this node has a handle registered. + if value.handlers = n.handlers; value.handlers != nil { + value.fullPath = n.fullPath + return + } + + // If there is no handle for this route, but this route has a + // wildcard child, there must be a handle for this path with an + // additional trailing slash + if path == "/" && n.wildChild && n.nType != root { + value.tsr = true + return + } + + // No handle found. Check if a handle for this path + a + // trailing slash exists for trailing slash recommendation + for i, c := range []byte(n.indices) { + if c == '/' { + n = n.children[i] + value.tsr = (len(n.path) == 1 && n.handlers != nil) || + (n.nType == catchAll && n.children[0].handlers != nil) + return + } + } + + return + } + + if path != "/" && len(skippedPath) > 0 && strings.HasSuffix(skippedPath, path) { + path = skippedPath + // Reduce the number of cycles + n, latestNode = latestNode, n + // skippedPath cannot execute + // example: + // * /:cc/cc + // call /a/cc expectations:match/200 Actual:match/200 + // call /a/dd expectations:unmatch/404 Actual: panic + // call /addr/dd/aa expectations:unmatch/404 Actual: panic + // skippedPath: It can only be executed if the secondary route is not found + skippedPath = "" + continue walk + } + + // Nothing found. We can recommend to redirect to the same URL with an + // extra trailing slash if a leaf exists for that path + value.tsr = path == "/" || + (len(prefix) == len(path)+1 && n.handlers != nil) + return + } +} + +// Makes a case-insensitive lookup of the given path and tries to find a handler. +// It can optionally also fix trailing slashes. +// It returns the case-corrected path and a bool indicating whether the lookup +// was successful. +func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) { + const stackBufSize = 128 + + // Use a static sized buffer on the stack in the common case. + // If the path is too long, allocate a buffer on the heap instead. + buf := make([]byte, 0, stackBufSize) + if length := len(path) + 1; length > stackBufSize { + buf = make([]byte, 0, length) + } + + ciPath := n.findCaseInsensitivePathRec( + path, + buf, // Preallocate enough memory for new path + [4]byte{}, // Empty rune buffer + fixTrailingSlash, + ) + + return ciPath, ciPath != nil +} + +// Shift bytes in array by n bytes left +func shiftNRuneBytes(rb [4]byte, n int) [4]byte { + switch n { + case 0: + return rb + case 1: + return [4]byte{rb[1], rb[2], rb[3], 0} + case 2: + return [4]byte{rb[2], rb[3]} + case 3: + return [4]byte{rb[3]} + default: + return [4]byte{} + } +} + +// Recursive case-insensitive lookup function used by n.findCaseInsensitivePath +func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte { + npLen := len(n.path) + +walk: // Outer loop for walking the tree + for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) { + // Add common prefix to result + oldPath := path + path = path[npLen:] + ciPath = append(ciPath, n.path...) + + if len(path) == 0 { + // We should have reached the node containing the handle. + // Check if this node has a handle registered. + if n.handlers != nil { + return ciPath + } + + // No handle found. + // Try to fix the path by adding a trailing slash + if fixTrailingSlash { + for i, c := range []byte(n.indices) { + if c == '/' { + n = n.children[i] + if (len(n.path) == 1 && n.handlers != nil) || + (n.nType == catchAll && n.children[0].handlers != nil) { + return append(ciPath, '/') + } + return nil + } + } + } + return nil + } + + // If this node does not have a wildcard (param or catchAll) child, + // we can just look up the next child node and continue to walk down + // the tree + if !n.wildChild { + // Skip rune bytes already processed + rb = shiftNRuneBytes(rb, npLen) + + if rb[0] != 0 { + // Old rune not finished + idxc := rb[0] + for i, c := range []byte(n.indices) { + if c == idxc { + // continue with child node + n = n.children[i] + npLen = len(n.path) + continue walk + } + } + } else { + // Process a new rune + var rv rune + + // Find rune start. + // Runes are up to 4 byte long, + // -4 would definitely be another rune. + var off int + for max := min(npLen, 3); off < max; off++ { + if i := npLen - off; utf8.RuneStart(oldPath[i]) { + // read rune from cached path + rv, _ = utf8.DecodeRuneInString(oldPath[i:]) + break + } + } + + // Calculate lowercase bytes of current rune + lo := unicode.ToLower(rv) + utf8.EncodeRune(rb[:], lo) + + // Skip already processed bytes + rb = shiftNRuneBytes(rb, off) + + idxc := rb[0] + for i, c := range []byte(n.indices) { + // Lowercase matches + if c == idxc { + // must use a recursive approach since both the + // uppercase byte and the lowercase byte might exist + // as an index + if out := n.children[i].findCaseInsensitivePathRec( + path, ciPath, rb, fixTrailingSlash, + ); out != nil { + return out + } + break + } + } + + // If we found no match, the same for the uppercase rune, + // if it differs + if up := unicode.ToUpper(rv); up != lo { + utf8.EncodeRune(rb[:], up) + rb = shiftNRuneBytes(rb, off) + + idxc := rb[0] + for i, c := range []byte(n.indices) { + // Uppercase matches + if c == idxc { + // Continue with child node + n = n.children[i] + npLen = len(n.path) + continue walk + } + } + } + } + + // Nothing found. We can recommend to redirect to the same URL + // without a trailing slash if a leaf exists for that path + if fixTrailingSlash && path == "/" && n.handlers != nil { + return ciPath + } + return nil + } + + n = n.children[0] + switch n.nType { + case param: + // Find param end (either '/' or path end) + end := 0 + for end < len(path) && path[end] != '/' { + end++ + } + + // Add param value to case insensitive path + ciPath = append(ciPath, path[:end]...) + + // We need to go deeper! + if end < len(path) { + if len(n.children) > 0 { + // Continue with child node + n = n.children[0] + npLen = len(n.path) + path = path[end:] + continue + } + + // ... but we can't + if fixTrailingSlash && len(path) == end+1 { + return ciPath + } + return nil + } + + if n.handlers != nil { + return ciPath + } + + if fixTrailingSlash && len(n.children) == 1 { + // No handle found. Check if a handle for this path + a + // trailing slash exists + n = n.children[0] + if n.path == "/" && n.handlers != nil { + return append(ciPath, '/') + } + } + + return nil + + case catchAll: + return append(ciPath, path...) + + default: + panic("invalid node type") + } + } + + // Nothing found. + // Try to fix the path by adding / removing a trailing slash + if fixTrailingSlash { + if path == "/" { + return ciPath + } + if len(path)+1 == npLen && n.path[len(path)] == '/' && + strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil { + return append(ciPath, n.path...) + } + } + return nil +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/utils.go b/taskman-server/vendor/github.com/gin-gonic/gin/utils.go new file mode 100644 index 00000000..c32f0eeb --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/utils.go @@ -0,0 +1,153 @@ +// Copyright 2014 Manu Martinez-Almeida. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +import ( + "encoding/xml" + "net/http" + "os" + "path" + "reflect" + "runtime" + "strings" +) + +// BindKey indicates a default bind key. +const BindKey = "_gin-gonic/gin/bindkey" + +// Bind is a helper function for given interface object and returns a Gin middleware. +func Bind(val interface{}) HandlerFunc { + value := reflect.ValueOf(val) + if value.Kind() == reflect.Ptr { + panic(`Bind struct can not be a pointer. Example: + Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{}) +`) + } + typ := value.Type() + + return func(c *Context) { + obj := reflect.New(typ).Interface() + if c.Bind(obj) == nil { + c.Set(BindKey, obj) + } + } +} + +// WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware. +func WrapF(f http.HandlerFunc) HandlerFunc { + return func(c *Context) { + f(c.Writer, c.Request) + } +} + +// WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. +func WrapH(h http.Handler) HandlerFunc { + return func(c *Context) { + h.ServeHTTP(c.Writer, c.Request) + } +} + +// H is a shortcut for map[string]interface{} +type H map[string]interface{} + +// MarshalXML allows type H to be used with xml.Marshal. +func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + start.Name = xml.Name{ + Space: "", + Local: "map", + } + if err := e.EncodeToken(start); err != nil { + return err + } + for key, value := range h { + elem := xml.StartElement{ + Name: xml.Name{Space: "", Local: key}, + Attr: []xml.Attr{}, + } + if err := e.EncodeElement(value, elem); err != nil { + return err + } + } + + return e.EncodeToken(xml.EndElement{Name: start.Name}) +} + +func assert1(guard bool, text string) { + if !guard { + panic(text) + } +} + +func filterFlags(content string) string { + for i, char := range content { + if char == ' ' || char == ';' { + return content[:i] + } + } + return content +} + +func chooseData(custom, wildcard interface{}) interface{} { + if custom != nil { + return custom + } + if wildcard != nil { + return wildcard + } + panic("negotiation config is invalid") +} + +func parseAccept(acceptHeader string) []string { + parts := strings.Split(acceptHeader, ",") + out := make([]string, 0, len(parts)) + for _, part := range parts { + if i := strings.IndexByte(part, ';'); i > 0 { + part = part[:i] + } + if part = strings.TrimSpace(part); part != "" { + out = append(out, part) + } + } + return out +} + +func lastChar(str string) uint8 { + if str == "" { + panic("The length of the string can't be 0") + } + return str[len(str)-1] +} + +func nameOfFunction(f interface{}) string { + return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() +} + +func joinPaths(absolutePath, relativePath string) string { + if relativePath == "" { + return absolutePath + } + + finalPath := path.Join(absolutePath, relativePath) + if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' { + return finalPath + "/" + } + return finalPath +} + +func resolveAddress(addr []string) string { + switch len(addr) { + case 0: + if port := os.Getenv("PORT"); port != "" { + debugPrint("Environment variable PORT=\"%s\"", port) + return ":" + port + } + debugPrint("Environment variable PORT is undefined. Using port :8080 by default") + return ":8080" + case 1: + return addr[0] + default: + panic("too many parameters") + } +} diff --git a/taskman-server/vendor/github.com/gin-gonic/gin/version.go b/taskman-server/vendor/github.com/gin-gonic/gin/version.go new file mode 100644 index 00000000..535bfc82 --- /dev/null +++ b/taskman-server/vendor/github.com/gin-gonic/gin/version.go @@ -0,0 +1,8 @@ +// Copyright 2018 Gin Core Team. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package gin + +// Version is the current gin framework's version. +const Version = "v1.7.3" diff --git a/taskman-server/vendor/github.com/go-playground/locales/.gitignore b/taskman-server/vendor/github.com/go-playground/locales/.gitignore new file mode 100644 index 00000000..daf913b1 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/locales/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/taskman-server/vendor/github.com/go-playground/locales/.travis.yml b/taskman-server/vendor/github.com/go-playground/locales/.travis.yml new file mode 100644 index 00000000..d50237a6 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/locales/.travis.yml @@ -0,0 +1,26 @@ +language: go +go: + - 1.13.1 + - tip +matrix: + allow_failures: + - go: tip + +notifications: + email: + recipients: dean.karn@gmail.com + on_success: change + on_failure: always + +before_install: + - go install github.com/mattn/goveralls + +# Only clone the most recent commit. +git: + depth: 1 + +script: + - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... + +after_success: | + goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/locales/LICENSE b/taskman-server/vendor/github.com/go-playground/locales/LICENSE new file mode 100644 index 00000000..75854ac4 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/locales/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Go Playground + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/locales/README.md b/taskman-server/vendor/github.com/go-playground/locales/README.md new file mode 100644 index 00000000..ba1b0680 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/locales/README.md @@ -0,0 +1,172 @@ +## locales +![Project status](https://img.shields.io/badge/version-0.13.0-green.svg) +[![Build Status](https://travis-ci.org/go-playground/locales.svg?branch=master)](https://travis-ci.org/go-playground/locales) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/locales)](https://goreportcard.com/report/github.com/go-playground/locales) +[![GoDoc](https://godoc.org/github.com/go-playground/locales?status.svg)](https://godoc.org/github.com/go-playground/locales) +![License](https://img.shields.io/dub/l/vibe-d.svg) +[![Gitter](https://badges.gitter.im/go-playground/locales.svg)](https://gitter.im/go-playground/locales?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Locales is a set of locales generated from the [Unicode CLDR Project](http://cldr.unicode.org/) which can be used independently or within +an i18n package; these were built for use with, but not exclusive to, [Universal Translator](https://github.com/go-playground/universal-translator). + +Features +-------- +- [x] Rules generated from the latest [CLDR](http://cldr.unicode.org/index/downloads) data, v31.0.1 +- [x] Contains Cardinal, Ordinal and Range Plural Rules +- [x] Contains Month, Weekday and Timezone translations built in +- [x] Contains Date & Time formatting functions +- [x] Contains Number, Currency, Accounting and Percent formatting functions +- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) + +Full Tests +-------------------- +I could sure use your help adding tests for every locale, it is a huge undertaking and I just don't have the free time to do it all at the moment; +any help would be **greatly appreciated!!!!** please see [issue](https://github.com/go-playground/locales/issues/1) for details. + +Installation +----------- + +Use go get + +```shell +go get github.com/go-playground/locales +``` + +NOTES +-------- +You'll notice most return types are []byte, this is because most of the time the results will be concatenated with a larger body +of text and can avoid some allocations if already appending to a byte array, otherwise just cast as string. + +Usage +------- +```go +package main + +import ( + "fmt" + "time" + + "github.com/go-playground/locales/currency" + "github.com/go-playground/locales/en_CA" +) + +func main() { + + loc, _ := time.LoadLocation("America/Toronto") + datetime := time.Date(2016, 02, 03, 9, 0, 1, 0, loc) + + l := en_CA.New() + + // Dates + fmt.Println(l.FmtDateFull(datetime)) + fmt.Println(l.FmtDateLong(datetime)) + fmt.Println(l.FmtDateMedium(datetime)) + fmt.Println(l.FmtDateShort(datetime)) + + // Times + fmt.Println(l.FmtTimeFull(datetime)) + fmt.Println(l.FmtTimeLong(datetime)) + fmt.Println(l.FmtTimeMedium(datetime)) + fmt.Println(l.FmtTimeShort(datetime)) + + // Months Wide + fmt.Println(l.MonthWide(time.January)) + fmt.Println(l.MonthWide(time.February)) + fmt.Println(l.MonthWide(time.March)) + // ... + + // Months Abbreviated + fmt.Println(l.MonthAbbreviated(time.January)) + fmt.Println(l.MonthAbbreviated(time.February)) + fmt.Println(l.MonthAbbreviated(time.March)) + // ... + + // Months Narrow + fmt.Println(l.MonthNarrow(time.January)) + fmt.Println(l.MonthNarrow(time.February)) + fmt.Println(l.MonthNarrow(time.March)) + // ... + + // Weekdays Wide + fmt.Println(l.WeekdayWide(time.Sunday)) + fmt.Println(l.WeekdayWide(time.Monday)) + fmt.Println(l.WeekdayWide(time.Tuesday)) + // ... + + // Weekdays Abbreviated + fmt.Println(l.WeekdayAbbreviated(time.Sunday)) + fmt.Println(l.WeekdayAbbreviated(time.Monday)) + fmt.Println(l.WeekdayAbbreviated(time.Tuesday)) + // ... + + // Weekdays Short + fmt.Println(l.WeekdayShort(time.Sunday)) + fmt.Println(l.WeekdayShort(time.Monday)) + fmt.Println(l.WeekdayShort(time.Tuesday)) + // ... + + // Weekdays Narrow + fmt.Println(l.WeekdayNarrow(time.Sunday)) + fmt.Println(l.WeekdayNarrow(time.Monday)) + fmt.Println(l.WeekdayNarrow(time.Tuesday)) + // ... + + var f64 float64 + + f64 = -10356.4523 + + // Number + fmt.Println(l.FmtNumber(f64, 2)) + + // Currency + fmt.Println(l.FmtCurrency(f64, 2, currency.CAD)) + fmt.Println(l.FmtCurrency(f64, 2, currency.USD)) + + // Accounting + fmt.Println(l.FmtAccounting(f64, 2, currency.CAD)) + fmt.Println(l.FmtAccounting(f64, 2, currency.USD)) + + f64 = 78.12 + + // Percent + fmt.Println(l.FmtPercent(f64, 0)) + + // Plural Rules for locale, so you know what rules you must cover + fmt.Println(l.PluralsCardinal()) + fmt.Println(l.PluralsOrdinal()) + + // Cardinal Plural Rules + fmt.Println(l.CardinalPluralRule(1, 0)) + fmt.Println(l.CardinalPluralRule(1.0, 0)) + fmt.Println(l.CardinalPluralRule(1.0, 1)) + fmt.Println(l.CardinalPluralRule(3, 0)) + + // Ordinal Plural Rules + fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st + fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd + fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd + fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th + + // Range Plural Rules + fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 + fmt.Println(l.RangePluralRule(1, 0, 2, 0)) // 1-2 + fmt.Println(l.RangePluralRule(5, 0, 8, 0)) // 5-8 +} +``` + +NOTES: +------- +These rules were generated from the [Unicode CLDR Project](http://cldr.unicode.org/), if you encounter any issues +I strongly encourage contributing to the CLDR project to get the locale information corrected and the next time +these locales are regenerated the fix will come with. + +I do however realize that time constraints are often important and so there are two options: + +1. Create your own locale, copy, paste and modify, and ensure it complies with the `Translator` interface. +2. Add an exception in the locale generation code directly and once regenerated, fix will be in place. + +Please to not make fixes inside the locale files, they WILL get overwritten when the locales are regenerated. + +License +------ +Distributed under MIT License, please see license file in code for more details. diff --git a/taskman-server/vendor/github.com/go-playground/locales/currency/currency.go b/taskman-server/vendor/github.com/go-playground/locales/currency/currency.go new file mode 100644 index 00000000..cdaba596 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/locales/currency/currency.go @@ -0,0 +1,308 @@ +package currency + +// Type is the currency type associated with the locales currency enum +type Type int + +// locale currencies +const ( + ADP Type = iota + AED + AFA + AFN + ALK + ALL + AMD + ANG + AOA + AOK + AON + AOR + ARA + ARL + ARM + ARP + ARS + ATS + AUD + AWG + AZM + AZN + BAD + BAM + BAN + BBD + BDT + BEC + BEF + BEL + BGL + BGM + BGN + BGO + BHD + BIF + BMD + BND + BOB + BOL + BOP + BOV + BRB + BRC + BRE + BRL + BRN + BRR + BRZ + BSD + BTN + BUK + BWP + BYB + BYN + BYR + BZD + CAD + CDF + CHE + CHF + CHW + CLE + CLF + CLP + CNH + CNX + CNY + COP + COU + CRC + CSD + CSK + CUC + CUP + CVE + CYP + CZK + DDM + DEM + DJF + DKK + DOP + DZD + ECS + ECV + EEK + EGP + ERN + ESA + ESB + ESP + ETB + EUR + FIM + FJD + FKP + FRF + GBP + GEK + GEL + GHC + GHS + GIP + GMD + GNF + GNS + GQE + GRD + GTQ + GWE + GWP + GYD + HKD + HNL + HRD + HRK + HTG + HUF + IDR + IEP + ILP + ILR + ILS + INR + IQD + IRR + ISJ + ISK + ITL + JMD + JOD + JPY + KES + KGS + KHR + KMF + KPW + KRH + KRO + KRW + KWD + KYD + KZT + LAK + LBP + LKR + LRD + LSL + LTL + LTT + LUC + LUF + LUL + LVL + LVR + LYD + MAD + MAF + MCF + MDC + MDL + MGA + MGF + MKD + MKN + MLF + MMK + MNT + MOP + MRO + MTL + MTP + MUR + MVP + MVR + MWK + MXN + MXP + MXV + MYR + MZE + MZM + MZN + NAD + NGN + NIC + NIO + NLG + NOK + NPR + NZD + OMR + PAB + PEI + PEN + PES + PGK + PHP + PKR + PLN + PLZ + PTE + PYG + QAR + RHD + ROL + RON + RSD + RUB + RUR + RWF + SAR + SBD + SCR + SDD + SDG + SDP + SEK + SGD + SHP + SIT + SKK + SLL + SOS + SRD + SRG + SSP + STD + STN + SUR + SVC + SYP + SZL + THB + TJR + TJS + TMM + TMT + TND + TOP + TPE + TRL + TRY + TTD + TWD + TZS + UAH + UAK + UGS + UGX + USD + USN + USS + UYI + UYP + UYU + UZS + VEB + VEF + VND + VNN + VUV + WST + XAF + XAG + XAU + XBA + XBB + XBC + XBD + XCD + XDR + XEU + XFO + XFU + XOF + XPD + XPF + XPT + XRE + XSU + XTS + XUA + XXX + YDD + YER + YUD + YUM + YUN + YUR + ZAL + ZAR + ZMK + ZMW + ZRN + ZRZ + ZWD + ZWL + ZWR +) diff --git a/taskman-server/vendor/github.com/go-playground/locales/logo.png b/taskman-server/vendor/github.com/go-playground/locales/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..3038276e6873076ecd542099e95b25037b1c0c34 GIT binary patch literal 37360 zcmV(-K-|BHP)ysx*JK zMpBX=dbK}5gAy}y3R{{beYQe$t~_(EI9HY=983!yQ4BbH2t9fee6m7kr7b^x7%_4X zJ9`gfp(=T?K~s?>F>nbtbqz;?9&D*HLWLAVf)p1<2qIzzh`mlUaSo2aQfQ+xioj4u zi57RSK09+4J$n}=VG1>K6C+;`IdT#dKnQiRIYfOMa;!RRrZpi|42HT(K7kH5Z51D0 z2RV8bBU%zznI$e~3~;G9N{kpKWf73XRDQWdPL3KgZV)nR5J7tvJAVu-VG5JQScJDo zR+bL!Ta3IbT6ncoYNbC?j4!6pWoxTBl*n#=wPJ6nPG_V?T&y%kcr-zED1W(DRHZFT zhB7~qA6u3+V3JBCZ4gs{L}jKoF=`!luS|!&X@DUWZdUYba2WIU7L}XOvil!bU7wAXuO|PIN?OtwU_FF?ptGuGegAxjs8(G9yYG zg|%{%%2R#1JvUt~pwDwIP%5I+ft0_2vEYw`$yQ3QA)Db+A{7b_0054wNkl}YE}wrc9DS+rDCwcq-kLn z6*rr9Gievg)&9W#+|En4X(tdH=fj-$InQ~{3w3k;I<^V903k*-k%?L`+gy zD<80`%CcVCt7&b)>-AWo}M*k4L#h*SN=*WN=wOPGQCc(S19x{GH}}yZ*TGF ziK2LMaUoYPF2r$dT&q?u0Q}(MpEI#8)^7>wy*j~dU6yeGL|G)4Z!`D?6v$J?4GNiF zGNUM+N-|jqFSt^;^pX20u^KaC*wKL1)CJS$%Vk@iEmQRU!98y?czh5h263h#&UI8G~>;F&}3tQ$@xhmG@h5396##KW2c6&nD-->t* zzH&?cgu?c})WwUscng4f{a@;`oGHloVP3&K8 zYWaY-m3_Qz=Z77^NgMadOSSCt@E=Ps4GgQlTkY0kAe~EC|Lpg z0C`J&DPN2UyU7&Gu-tM7^CfvM>!_q$|F7zV-={;NRk*zX^&Xy|sN>Mfv~agPsrszZ zST{=H##(12j$1JtBfT5p%`HZ(R~kw8ecKQFg5WJ*x&2m`V}}Y*yZ+#L(7tQhrOc;? zl-q4QvB#(*`_Y3X_Vss0x8Fk3#a~Y$nt>$Qn2*D~V85{yB8iQ{r9&gU|I zev9S7uL8Gt)I|dF=Y>|QegWzPvP@{V3Nn!IR4VydvXh@BKI2xUMBh(6aBL~@%r!AuWVG?f=&mJDxzGOktCLsq`D9Be0N@V+ zw0ap7DLEZtMdX4AhRfVstkov-f;^PxlkxbXr%Y<&X1CewisGbJ`y`1>y^eD%RgLHX zYcVG7w{0ENyVVm($?-3NBx$ln5*EKMtyUbD4wv+JlvSVUD^3~+YL43}RqjpaZ>3ze_N$kOC+VOY{hW+5B@jP%seQ7^>9XbyLO_reD=`#sdf2i+$u9o?M zdc~#Q*=#JUW~0w|6Dzl8Ec<(uJGK{c1uP-ECFnFoEcE?p>b=X@zgJgrNs7N?y_(l62vH_2aOTu; zH1Wkuhrd?fG^jc{yVoI7S9+u_MCut_7!Id3v9PUUb&ldf@7>y_JFay%O|e@o7B~1R zR>f}jzhMAekSBme7+=8B<$4CP2M`qy9;PHYV6Jyi@gzzQxufnYeT4}(ia$$dqsPwU z5sO*J_umWFSAy&Qz_!oZ_MFx;KV|fIOpaJ^|IlRj`#mo`7L%L${sFWDr)GmSX15!x z-ju0rqgjo2_ERjgP*qK!X^q!LX;y>Hu?d|?f1KrU_f9eo=CJlH^$aSqrQQSef(+VI zC|ev?=iM66d@OdmUC?cIyVcDG)WLl$UUUh>iAb>R_igW2u?(N61L7?ic^SATn9E7n zNxqRMszu^JF zAl2kMNq7&8r$ZVW%4{j9Mn@?q+c73i$N&u<3-i9;kLlEE%cl5$T`V6CkTnyOJ+mDaOaDWQ*^ecn!U$EDGLmsW}B zARh3Q)rAo6JL!FggZ3F6jy>B;&&!jW5FMg-Pfri`&2I0*$r<%!@Z{{~#$u(6L5tIC z^ct$p<0cjz2bs`3+o&=gg zN0I9tG<<%Iswa`AOAJdUZZ^xs-z{*A5120pqimm1%e$$8lj2Rz-5n3_^+!xU`FD3; z?p{7vc6^8QYfHemZ=l>~d!hFs`#E}j$4Ogk{OLe2Q=08L;!#{n!QPLNUsaV8bX6T_ zoZeWG8?W;fL^?9qw}QvFOlz1NW~S4EBF|xQlOZ}B-97Er#?yIiJSVn3uGPB5yDgsX za>d8T9K^q@j<*wkQ>~J@2auzPFOmx}x0!EFdB9!yU9WwxvgjR&?#kfg)Re^ zU-wz6Z!-%j`#HxBkmxujd;G3VYpX;y0Xtz}E(t{V$~uW0lOc^)=|GS@GK+e7MHx=# z!*RE|?AE3ejI;Sv?ZxLMm2b0E0P-M#%6ch}d~Pk7{t#OF7gYEvW_6V_EC`1%sm z;p`;DqvO$3nU9KswqGY#rE*CRhZCi6Vg+4BzY4?O1Z^=|F|5~1w-IQ|ecyr0B;3%> z6NBS&$4u{pLhhSaJ04eT@6<#cQlX#RA=lns%xy$Iav8;|8b2CeW=l2{s^~`vfxD{}nt5yRf<*f`crJol5KDpU+ooq#9&8 zolytKS$vp#7S*yGSBhp|TzSfi1;>|pT8b=!z8&|j&*(e&+8TUqFrCtl8|%?a$FBL@ z{y>@BXE$djM^uFJTU_rioz{q{e5Fbf#|)xZ>^Gwk$Huc-c9m^sKiA@Euns4o_3#?h z5i=0rkge;=Umc~s?o7dWGHh16c;nOB7RtO!P^{%PB)h}wuHU|SgU1_E^|#l+Q}qdS zH#zt}!9}+!7OMbK0D7Km3rMzut~&X`M`exqrYM-~VVJwhgjJnk7U?*AzI_a9V$zJD zYHhE&WAk}!5pOwiZ;S039$dytin18|FPwW+$P$X}!sSCocO(=%2_8{qAMNLT)*Y5M ztEsG{FE zcd6Zz*ty+c+4me7W7MhL5el9=Tt?^XuMb_;vSwBV%E_{HLRF>yV3AH_j|HcTm^;>a zvC_jO>{*oxChK<3CbtTePO|dXP!_ATF7#edCex`hO``srW-Zsv6_-_5+@v|i8We%Y zyMIuG>bHs?7YPXYC-gp6qnLxi$pt8CqEy8~wN7FkrU^!Uudp5tkYr|StbYSr7gfDV zsM%*}B(Tv6Atx0*<3}nIIDfx$@1=y-X3vRdKeE41dk)V6r>|lW>)}zv|MC*Fy`WVDgB%|{yeSf>k=9~(Lk%M*Vv}w0f(3C@}$xW z=X;gp5Q-lcaybmN2}XLiG@bn1#U(Pt?#M*{@CI`K@ZrY~KmPdP15Q4?y(75}eD891 zC_7n)=49M0h?tLJO|BA$D3Dz}f!wJx7^$#1Y~R+{IWt^h(BQN*7k{Rg64=2xqpssD zn`W{H_xI(6YZSCPV+TC8tNs^9A%it&I(jN+PxAE94F2TRn(Smgm^H4&{6j33fOh zZjjt+-FdS%$#sj9&A8U=j_334usFvB82#hjhsQtOJig5p-xephIDsOb#>Knora0d; z5&SmI<#x`^b0pP@Q&HaT3K3^9*D>9aop88;9J?Or>4dJ6EzBUTMqjBY_GmR4Fe6FO z3~ldwf$o=IUERAW(~Wh{VsiKmmaF?;oDlu_3w%;_Zb7fRgLaG6Y~wF^?Tgs-~d>j&DCZN@>`>j_xTR{}t_f9U)W2S+R648V8hb{3Dmp813n?7e z6LF4tmd&OUt5Qilew8{x$Uy@An?-AlX{&(3EiElA<#AhfOL=T557!owu4yP~DebPa ztx)PswzAR!84X=8C4fe0x=1Ru)JJIjfz$+3Ov@v(L?jKOMvF@vC=8ABl}ra>#Kgob zYE1lL)E|Bqy)c%ACEK~@obP-O%4%vKqpYuMEaDb% z>Xe*wLNU)%FK*z7Jri6>qYAqoQ~6u3ywE}DD8MH{89OM0G^)dF;hsksFBVOkXtT0L zA)0_y?A`NfeW$BFX`cjk;gmBhQ?bvFCP#gkc*f;o0ClWv2_(_=U@$V0blZKCc3>Z- zBH*?Mrjtn*NIp28+w$lrc+K<-%I$&t#c9`?SWEITs|_o5YRdX)Clyr@1azy>;plKs zILBxE2xv?d84A5>{!r^s^r5BjTb85%_(J2Zgm{-@VQR0h$oiG zruagSqDUa91*Hjf5jbT!=~D(dN$Ax^u%=i_N2ScHLF4s8w)Nt}WP($HD+eob4+B3P z2EH?PEIFp0@qxWyt=$peI9dq>gRu@o0?Cm`BpwOQCWH9i=%n2qna56ySnw)tT9SZx z7W;3W%9&~C7}KMVF^|Hnz%@C&C$MdCP+=BOb8{&*LJl6^&o&ZZ4|lRKcdWUR5qED&dJGwX)i)6B?n$ zOosG;3l-6!Kd&dR7|)UkH5H9Iqee`1;=ypJmBx9KQkSgDkU6M&@Vi>>Nx#3cdf>G)y~J z&y#G)I3rK8{v8dNM(U#AD~htsQ86ORxE5|0tFhji;NKFrW=+J=$c#L1JJ;M3Mo_yeqOj zI*IXjLAHKtzljb9u;77UFc6Gj1l&oB<)$6oo{t240gG#7-W|uHxO+xnbWFQPvFn(8 z06vU5$U{urHQalQn-%>gb9(cFpCbKaOy_`aLnc}uni3iZLGy;BwGx#%B&?Pz`TT~< zFIEW7G%Cug1j7}YPEPZslA;&+91*slk5kMm7b`V6lCvX`*`#a40zeNW<2d^Ek(+jmJ02821OEzy2yukV2AJ!GIcxE4Ry$&BNVa08W#W3>t(6_>z^&514EIOeh48)L8Is~0v&gIH(NED?41y597-PtVe ztf&wb7hftBovGq@#uW{fb@gJ6a7rT=iAw}xLt+TXNf>nJ_2#p+1oW!jxIpLhY~ImD z)3g=0m8H?JDzsiy-{OUD>}momhezG8Bi!@ho?h3ew`JS6?XyoO?MX`{Ih#D(y!*>9 z+lTvccHUpd#|p+Dy$89$(8o`yZD0gi7RQifvXf1ZYH!*`dtl5$w6P=Kgt*4kqBS`k zZ87L|XlFX4PEgbw;V@nSjrSXf1d#yj8;QQY>e`_$saY=MD$1%SN@bU1&CUD<4__hV z);A6)J(s#KahiuakvBoOl!z)MwHkBvl!nWJ!}XfO2yB<)O8EN?dLu~@C>lNY(lkk7 z%>nDC$81b5fCsm>ZD!Jk+96JX>F(s=w?{|5h$UdRj7(eX(}C@~J3Bka`S;#<@4-$0 zs&(!CIG#W-fb9;T-S`X!lEL|TOC(^QwOb;}TLyyISCYV#&QNUdD#Y z8cn6pZ6c?m`rBi=tFajL1t5>Cl`71}b}+o5E}^8lt4sD`?W>%+@rl6-nShT&4y3zu z8==dP>3Wy1BO2Ja{(tAGGVi5@LkIAJwZ<;7?X>ZyThF6J~`Y z)dCX%APghL<^pjCuKBRackk|hcl*w*Z@=B1Y#ROVdfolx?VXeNj^BImX<_HkJrc05 zj6_zF$ys;A9uG$1zIf2h-uU^X9kUJ%=Y~_m(xIEDwiTcqN6i|B)e9EEdXumwL8`1& zMpfH^;0e_3JWWwVDArE2OAW1aF%rh2G&ZEFl#M;DktuGJb$6dB@|-KL@Kn@^M9re{ zhQ2{g5qM3txY(o6C^cf4CS(u*89P+chm7aXN)cmGdP*JDJM<|%kEnDhfBfDX$0tW? zAoA>p2jW0=7V%I26rcSc=fUTpc+l`3#xgzGV?*%LG};1-3g@H=8*c-DhDDXIB6tJT zr5tkcWhiB#^XZIIm1NVpA^G9I5_BDio#spM7E7oU-V+LUlO z4fsyEh|j4W6I6>PM6!tv%1n_lIQmi&c7>6|9Ca9}s2ai{ipE?0aO7Z*GreB;q7}Kubavrj@AubsZ=XzW9AwkkEC&9KH}c1afW4b6*s)YD zhzARg)~`io0r_Y>i}1b~@L*74Bok~L#RinfAsDTdZgXPfuCWdqal^+`jaeh0fc2EuRfs}21N(Wucufk-eWo4VJO@TRbITCj|;iwPI3 z1%1Yu%S>+Uj_#b?-A|{dJj<)ku0H$4Zl-X1=iueT&4a0Qb}4_nxpU{>zRwbAdjF<< z#WKHQ58~KI;_j8Wdln22EEd`Ybk;qCgE(Vx2Uwi%VY4XQ&o){M|Jww}ga41D8AfPS z?I8TRJ~BpuZRphiB&omMIA}Ds8;H;i5Lu+{;Ka8 zjzHW{*EtRfFB|KtmGEwu`yh75Nb^Gp74AB28zK&*j9pPZ%7bJ@@?b*5*6VF)Q!{j1 zrjWUp$=qZ1!h0^)^ufu4^won0X|z54$mY8{yE~t}a_9bsZ|~g7ZebR_Iyzcgiv%od zcaKu8;0m!87n4#^Z#FKMQfWtRskx*I$t7X%HQl4ee4k?0&e z=jqeVA`sR->zDR%cc6xa!o83J4WaIv= z{lK4_CvT$6wfO%!W{v%f2UphcLfC<~!^gFQ9AVd4mlB>&3+5|)&BSD)pGK6meIzMVeKuIEwv`uggJnf^Ohf13E{t)+ba?R@_D_&E3A)6YNu z^ysf&e*Ja-@XcUwWn?A(=IqFdeFdLEh?*oT)+27;G<=(x86f;=BnSLtv>3QV8w%H+ zhS|tl;Y{Msbd=PO>4$0_A}KXqfjUNz{&tn>s+15Cp{^G>!m)|2nu!<7#v7h~y1t}@ zgIzBwI#=H~F)+Ys7}xN)-P~#cU(A**htCpJGhxb^JvD-(;$%ZrQ4 zi_7cl>)HI$`X`4=U*>N^qOQ$Dy{)kpWn>KxJM1GEe0*giNtE0(ZFeEBvuW|dZB{1S zW`j3ysvg*c4_${NONQp=q;SVCrocl~p^!?alU})qyDl}io8dRr+z@k1U*ai;i_cUP z^AwGB^^GNEobK*tlurZUmG#XR_`C|vm|Q9y>{6A14n9m0=hcMKK^sxOns(03MF}Iq zCMOMp4C2KG-N<-p#u3eAavO!rwM?N<$lUt=+uM7)Ki#_XRXV-y`QejyKYM<4@fDQ4 zwY8OAPN&n^d_JGu-vG|<2iPmdmdS267~Rpz>8>BHS?qyP-@MB`13y#S(*oK69Tdic zFQ%}~i_5OH0`Gu&=sK-tX{?HN_#Gr9y2{)N8QX3oC>g| zXU$OB6#RcscMw^Kv*~O17!*%$4sSn5uWzm2`tIvzpMB-o)yEfC zS5f@(@_KrG=}X+UU-EC{ckGr~cYMSi4bSp6msiLj;2dNjDu$sapwhfG|r#9TaG%npBZ&Y*wR__7PL^>hj{! zhSJLC#F_~K`?Cb1649CKGA>W^Dn~F;<|(Z&;_&32b|L?&+{`hD&N})jI)!MX7MB9v zR3?{!M5FiFNgC)>ByvrE|@PjEy=b-Tkq=Zw-B>wiqn3eAY9GuJ=o(q0QQg?kxmfzA}X_tOpOcW>u!zq_>b<9Ej= z7Z0|+$A+(>7``SsB%8%S6Mug<@ z_U9@EFYy)QV*D)4_2>9iMUC~B&+v=OMM{oLSrRVcs=E3IjZ#=mB^Nc-+X^+f;%C7}i4*&k=@UQ!y7VZb!M;2H&tOT;d zwMPWun}j;R#Ggt87z6!nY_{I(@M>WRTQTe@u-SzaITqDjA+8{EBM`W%DN03v>$DGP zifYEMOpS9C7rKjh`~gKV3WZ=99;hm+;*^x*qhU-bn;N?!mlV~6Zs_}U3u*{Kf1g8Y zq;pmr5gNr)>`zieO;)XyO@7pLKdsJWG8;hn%*Izge3X0b?caV#FMsq00PWqomS2C} z+xbGXzP069U*BTez78Ubw&$~7qI4v2kSKQh2nIe7S-E>}XXCHKjeQ^%@n(GN~bst8Gk zv^}ON<(3z7J={vqAV(uB?<{{+R54s!RD8MnOgX1iQzkA`@I1V+=7(idax=-rt|zDj zJh*yJoj9WS#cr^YO)|G@n$Hd23R`dQppMU!KCx7lAjU0~Lv><~( zR)y4#fw}FPoUC%e?Fg^z+?p<}J=66#)ITdnb`Ybn|1SX6^|F z&1eSc=uzx}EzriYEwckj;no(|Elv)0PS#iq2J7g)*=n=vW(p~)kVGnWb#Wv6F%bd$ zL69v(G6ly$BNz&S4>b;g4Vqg3OqO|ZVwhnD1^PIVIbg8Uq%2<6ESr_LUMzQMhA&<; z)Xpoq+9Ao|YQF{-9GKxzyYJk1xGO0Q07&TG`2bdNVU1f_U+P?6`l_Kd79t@Yc&Icu zD7M*H4$R%_dFry)->(J86Uv+rQ1}ReP!JKs1Vzhn;K0ctArSPA36XVd#!f=APZ%wj z%%U>@qpM>uf?baWM&Yunu|TzziGgJ`PGTbb~05fO#S>Cx;DFzWV-e>SdLCJx8S}7zx{Zv{UQYY#S7-kNwt?-Tcxc@T!3r2Qs8377nzGH zE}xqZ#SaEJ2zbD;fq{At;{A10mGp5?Z9qgk;6j`a(4G!`4L**?F`=2EkOD&gjF6d1 zW`s0>XgGus$)eK=pj;(0QbdemLap=wn;Qu>uAAbmzLy_ODPtXjj z2lIsT1+B1C|4=caxpjATJ>o-Cd)I{@Z~f=>c3535La-0az;#tS-t&?Vg}s4`f>aV2 zd~A%bk3-})yi(XCC7~Q7%2Jodmx16euPg}I*0LZ7`~Xx?0dfXF$38%nb7a3LpWMP^ zeB6lw@^Q%e$T~k_fe$S*B!n1=_uI3V;ep#^>w>p;am3nStT65XKSz7)b)sUeQyi%n zM^f@$yq6``$>bqgGPJ9KL|34T?Z$8jBLp*nNlsvcCK5J+gph;~IzmMJ{MeBRad|LE z!NN;c9ut|O7`J%~u;~JdyF4XJjCU*y*3OG0J z44B5#e#xn9h)t8kN?T>XNz^XQgVUuFAf?cmJ|FnF%CDf@)h0n#Q%~z^UoXpp?p_-Z zP%D707NPw5p*%#a;bN; z2Tsue6a{-7FwR?TtZWWYx42_0tSDRdkQ{+w##p!(6xK!hve^fjG#WdM+!PnVgdhhk zE=Lr~q0>U?en>>X#|e2bO~URRFlKtNYSac9mSf{P7ss_P=3XqkP|n?6n=%HdYv)Zc z&p^Q6ZHIa0;dZ(b>F&mOZZkQrn$Z-#l9Fvq2PU7!x+xN z082&|oIuENO)P{(rW2Z=)FT`=B80IHA_2-CCn16W%4A_)xoJ-QXPa?;_K{9#?C&2m zDM!@mGPQ9eZR}C}eWSu)FkQRVbqgB%H7IizFW!Km2Cj833PATr_zk0A?x>V21vnaI zX29pL$w0}^IW&LhP-|XVUfKK$W4lf+hg}`+k89ugEl9nn))s$_y<2~7QXfN)D&!Qh zXe)_?( z<V}u8invj{s)^GKhDyeJdBx z15F*R@B2SBSw0!c}C!c-R)*O|2u#nh76OfxS zKncajV1S;c7*9$8B{bE^!`ssX>tt1eLQEk(^&sYU^*>3Jn61DZ}9 zP+MlWV3OwvBg8BO5{{W5H1~EDUAlDFtK*V)J@2HFUV8Z0;ZK{7eH#1H_liA`2kj*$5(lN6!%o1&CjZsBdUisW9tJ3Sp4k zJZLTtFqx-;cbK0q4;ULe0u0&5dAgv5T-4`x1_sbbpMimOVBqg*zN`mwy&+%Hlk=6V zb=PR6Od?gG7vwr9OQD^k;@a}Xua_a%KN#$kqet9n)=YU<)x*xs%jTV|xqZDQ{a8%Q zCvDdcx3#n!ON?obilGq;X{^FTRn zt*g9KFk9?NR*s%nU#f4lH6WONb#9R-SSOGs;93aq5a=9)AZGgsLy=H2!Uj|_4i+_3 zyCgg=pDpgXq*R;`Bjw^w+2g_?kHdOY!tmEXg}xjM^zGuOvUF*xKQACC4rpu(2*p=)S?{h?nJ~wwmd|x&@A_M z@h$~=dKMMce>XHYH`m|acDR4I?|O?*>0w&iXKlw~XrC6x96MZ?OLQTVLDwBd!5_{2 z+{MNx%_6!G>F=ojwEixyKK!m{RsG44{)(Ch=O^c;e)j)<>a)Yw zzwj%LE=?uwtWIVGlM16^aG8uuP_*x1WRP5O7^-b<(Wlu(MbUPE+1OfJVh&h=JQzo! zI1_Q3DVsLgSl}66j7WD;=s}?$S-cy80-8+ch&XVIL_$si1Og)D2z>-dZ~}Q}gudOS z{YC!;=wbbGwMO6f$MWLF!zUv*^b3aRq_o%5)MaV%TD9TEjVBK$z}XWMPr&V3fMaC& zNitQXET?ibsZw%?4@3kXjd%$<&8M|WVQ~XgB2I0b)j^zh4yp}Cn*GdE&~LRUd`SPow+4*`|gHqVR$=w@X_Oi6YY;hr3xNXL}?J20+TtEm8CF9r}LIQyWdSD+i^Z0Ip zh{57;(m5glB7lk?3Fx~R+MNDz;B949efHFprWaApu8fS_U!ttNxUgoJrH{9M1;ASD zduj0_7w$Zqm;tX(47^(0))&SvOY1*=Z`|{2R?cLsS~_jt?qF?+-R!Z|0fR}gx3Tnc zv87N*pfJV|8L6R7VJ8w`M@6-1AqdnqA5mgd-(kJEH(eAeM1&%=u?g60(a-&6^KyOk zvHF!+Jx8Hgm^IFuW(^O~QGMDlAOCJ6=x5$BXu;plC*bR0+`z=ZlZ7YaGPJ6rxjmZC zg^y84dQ~MLRg%$GZi9qd2@F*HSnc%MoI)o?Ezg(8%F04K_N|aa|M~KJ;lYU8V4JjbM8Sq z+i-V}Dy#5p=V&UZrl|I|7%I-5LUE!{d~p=Q9yTDmO$F#{B_~d>VUUdo>J$k2MkeRx z^u5xZ@*Ti3&@*a zn0|s*Hz;#Z-Pz+y@BS^7E?wsLr1b!umQ>jQaC919C6Tp$wXyM6Qa-4pK`sgFTAyxM zqf20m&9gk7VRCZy%%A&tHDB(p0JF3FOWr6c>4vkdySt?1_n%I`QF1yftK0uf$-UdR z=lW8EiK&q5(AbaeVK` zwXdsdVu25fLlEv3!bS}1Famw8RI$8r?%cUajY6R?r^6g4>>GO8JEdRg{rTtBOT2Hx zr(Q%1z9>|xwZ^rzsc|JBuWREV2~r;#n;+LgVMjy$`OMWDzb$QyFC=lf@4+bZOa}gj zI9Ewqfp<}D{GooN|4X{7^<_Rlv6ti1?rV*Z>|(`QJ#Tf2cmCA9Q~OV!^4||9YoGrc zZ)}5m8$5xMH_mP=DLGqm<;vOan>YP$-aOM`rqL69`byK&n~RGB1E~&FFDlj1+SwO4 zCwLjc*4fU%5>OkAGsa@eQ5$Q##byegQHLj!@u6fIA(Vx#f=3YsEkV$Su=M(>qAFh1 z$#ds;9V`6`p+dR5I<>qyq*U}j=(yC;vGREJk-}is=+flI1%pw$b_ckIrKEQcjlHim zY@q&zA_snlxPLe@`Vv~2tS5(is3Ephs)F!GOZ?LGqx&;6kH#h3*tFK##@ct@7Iz8} zv(l^>=GClroUAzo4nJSI4N0@-~&5Ot|!i)Me4|u$jypwSAfLEA;UFEiy=YwO-ZFZ3YBk9c=WLC0w5Qrp z9lX7>v#C|#ftXycz})6&-*6Ho5I}3+OgfH32qyRiGt!d_qkf+3Eln?NnLBm<`h(Sb3;XDv?N%%BAI%5@_-83ebk~>T@RGwG$Vw-qJSiT3FEP z{#Y<5hu1E7dCh&>aqq#?@6i9~pM^Sj+nZ<4g5Ccg_z|o=y92(TJqw=i2It?*I&<^P znKL)De(3)+)xtKnnOfxJbk4IV+Z$w(ILqzO-0d*dHh60W-qj6{PjPh2ZT=|g)2No_ z^y@M7QXjDS%8>m&PR7_^Yku>hp;K?Z#+B&Ms9CEa_iee(l||{MSG&#gBc) z?-{>y_2I<8KzsWPkhJTy+Tq2qmHK~~xc0Cn>nJ?#7ZE`q!4v^?6v3Kgk&i_*77q~? z1414GvI#^YY($PGd!~aJw}%aJlb914EH26#A><%Q0^=HD$W1U*KoLO!#qe6a-xk%` zw+s7&Z|`@`dC%o{eqVjQl*OV7cpP5yjq4%?557+E6f-?NJ)m?T)vEp5Z=w3_+wsI_ zToWg!k|OB-B;dRog z^%m>bS-ks6tc8~)3IV!0fnG>g(}z4yitqQPoLion17apFIR(%OA+ABPNDSN}9#5*| zm7x*SpFJ+QIl6TGvj5r9{@RAl+B**)jOE5OE;gcEJJoaIX=SKiT>8Vyqn(`#8SyW7 zd>q*E#es;7^!8n?Wp60POO>Xl>gDsJrMG^6dQc!AJg8(j7c)34*--N}c$g=X$t2jk z#K{BLR@_{Ncm+B%|IgP&S}94Me!a+JNK>6d02lK4QMLj48#W@wZQZ+-MCC(rl6=!_ z;Ok+uFmh5fndTmy6&)Q`m@t29h%(iCZECv2(-W$O1OYle>t4h`GKM$^k(MQv>K2)n znwP$Q<@n{kHiWm%*2k4`s=O-`NMaWoXCFUJeURJU9@p8{x%l=(MY`V>|9DIg#O1|w zv@Q0JOU66fuF7lce;dD3Cn-*1v4nhNFd{L9fru>@F=QY(oF2b|IJu7Db>abcCxGi< z!}y8ILvX@L&*}R^w@Q|WI0agf<>VLh6MdbjW|2lHTS==(_N&&}SeTeZ3E6CFrjW}P z(%5Viz%+FNw;`vu6eTx3^p17uXjKK%y<*D)_ z`nv0DC5pPbHiB+1X0@pM5PkYRE#GvYS@HQ?zKuKj=m&{t%|3JBAm zo_eIA%-t)1ax^gdf}F&}99!E>k(Q=wEDbjxs$1!Y2LwdLCdI}^Me*4o!mO;!LOMHv zoxtU*s|(b<%|GX8TBeFTa84MymSk`cdWZXg{onJuB%{}6iieEduCqct^(np179=wy{~ zCAH_2Wh|*&AlNI&AJKr^f`DI4sGPZ?@a_M(I^K2AbymM(?Fe>|=|^)6j#yKm)p}wM z#MU=5U{k;beLGV-QfRfE`B2|4^N&ZHP>}goJe*yu z?H|1|q34kHNf1` z+|tZo(}p)m&dyXMdd8&i@HC6(9gV}t#$FQ;mgub=xMj_5m z=pFVCJA^(!bTXCzYl}VKb)5R>c*FUg%iV2bJ$)FLscd?XSNRxCn#W(nv`3_>o?(M_ zQ{4Lpki@9c|CsSle^A+1qmY-Dw$}ArJyj!}tdZ|kyeU;4%vWM0qnO8Gh{Uk?AVgFc zJiJYd9l#+vl>(vTy<0?J7H*=!i1yUZ@GOtnJ67_dOWnm zCx$(8cnl4)yxzLw!{2=K<1cq^7D{@$D^*A1;`*AZ;+j-#zy5kW%K+#CUB@ZJB)Z?xm}8IZIlm+$$*K9Fua2M~-oh!PF@Pui*ekK)Aoj zbV`Qawce&fOvsALaS%e7`nMh}_m*$n$5+eusyP~srXYu3Pz~^W-$be}_BfesG_}R* zi%p;YkG|L1HlvxuQk}eFr6Lp~K{~M5FU{ zoz+8hA9N`Vk<>Z0+@=h*OwSF?wJ-=L*FK53&bOuVsR3q2tMyl}F)}hU+(@!=TW9yK z)oM&xJ^$qkn6uj!wQY~hTE~#AtOW49kSpX?bGa9qmy?}}TAGJ?h3cPsZxlV+?g86N zCW>ZM6$LB-kLBz#_|q>xb{wBQ|JLQYhFZm$)GMQ%ss#-FS5)OLl*hEkS1sh_rm6xD zRpf>4%d1fNEq=Oq>HP6$7ZtUF`cmcmhZ9S!1IlWp;2=*a6CcbM33x%GW60QHZn}_4 zq!U_((-HehNMB+1`;Q(?FE2m3Q6ReaX#QHkg&d(!2nWX-4t}I%W@Lbao`Igdsl5To zj*4tf-_lH)BXXc)59zW66$5
Date: Wed, 21 Feb 2024 14:35:35 +0800 Subject: [PATCH 031/618] =?UTF-8?q?=E6=A8=A1=E7=89=88=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/request_template_service.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index cdc5a67d..cf9b3f91 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -388,8 +388,12 @@ func (s RequestTemplateService) UpdateRequestTemplate(param *models.RequestTempl var actions []*dao.ExecAction nowTime := time.Now().Format(models.DateTimeFormat) result = models.RequestTemplateQueryObj{RequestTemplateTable: param.RequestTemplateTable, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} - updateAction := dao.ExecAction{Sql: "update request_template set status='created',`group`=?,name=?,description=?,tags=?,package_name=?,entity_name=?,proc_def_key=?,proc_def_id=?,proc_def_name=?,expire_day=?,handler=?,updated_by=?,updated_time=?,type=? where id=?"} - updateAction.Param = []interface{}{param.Group, param.Name, param.Description, param.Tags, param.PackageName, param.EntityName, param.ProcDefKey, param.ProcDefId, param.ProcDefName, param.ExpireDay, param.Handler, param.UpdatedBy, nowTime, param.Type, param.Id} + updateAction := dao.ExecAction{Sql: "update request_template set status='created',`group`=?,name=?,description=?,tags=?,package_name=?,entity_name=?," + + "proc_def_key=?,proc_def_id=?,proc_def_name=?,expire_day=?,handler=?,updated_by=?,updated_time=?,type=?,operator_obj_type=?,approve_by=?,pending_switch=?," + + "pending_role=?,pending_handler=?,confirm_switch=?,confirm_expire_day=? where id=?"} + updateAction.Param = []interface{}{param.Group, param.Name, param.Description, param.Tags, param.PackageName, param.EntityName, param.ProcDefKey, + param.ProcDefId, param.ProcDefName, param.ExpireDay, param.Handler, param.UpdatedBy, nowTime, param.Type, param.OperatorObjType, param.ApproveBy, + param.PendingSwitch, param.PendingRole, param.PendingHandler, param.ConfirmSwitch, param.ConfirmExpireDay, param.Id} actions = append(actions, &updateAction) actions = append(actions, &dao.ExecAction{Sql: "delete from request_template_role where request_template=?", Param: []interface{}{param.Id}}) for _, v := range param.MGMTRoles { From 3c40a015e59b693ad5c2c482c78d827835eff94c Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 21 Feb 2024 15:39:31 +0800 Subject: [PATCH 032/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/param.go | 2 +- taskman-server/service/request_service.go | 18 +++++++++++++----- .../service/request_template_service.go | 10 ++++++---- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/taskman-server/models/param.go b/taskman-server/models/param.go index 9459aa6c..63387624 100644 --- a/taskman-server/models/param.go +++ b/taskman-server/models/param.go @@ -36,7 +36,7 @@ type TransFiltersParam struct { type PlatformRequestParam struct { Tab string `json:"tab"` // 标签,取值有:pending 待处理 hasProcessed 已处理 submit 我提交的 draft 我的暂存 collect 收藏 Action int `json:"action"` // 行为, 1表示发布行为,2请求,3问题,4事件, 5变更 - Type string `json:"type"` // Pending 表示请求定版,Task 表示任务处理,InApproval 表示审批,Confirm表示请求确认 + Type int `json:"type"` // 0 所有,1表示请求定版,2 任务处理,3 审批 4确认发版 Rollback int `json:"rollback"` // 0代表所有,1表示被退回,2表示其他,3表示自己撤销(submit 我提交的tab下才有这个筛选生效) CommonRequestParam } diff --git a/taskman-server/service/request_service.go b/taskman-server/service/request_service.go index e0f78f65..4cd88610 100644 --- a/taskman-server/service/request_service.go +++ b/taskman-server/service/request_service.go @@ -250,7 +250,7 @@ func collectSQL(templateType int, user string) (sql string, queryParam []interfa func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, user, language string) (pageInfo models.PageInfo, rowData []*models.PlatformDataObj, err error) { // 先拼接查询条件 var templateType int - var sql string + var sql, status string var queryParam []interface{} where := transPlatConditionToSQL(param) if param.Action == 1 { @@ -269,17 +269,25 @@ func DataList(param *models.PlatformRequestParam, userRoles []string, userToken, } roleFilterSql = strings.Join(roleFilterList, " or ") } - if param.Type == "Task" { + if param.Type == 1 { sql, queryParam = pendingTaskSQL(templateType, userRolesFilterSql, userRolesFilterParam, roleFilterSql) pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatTaskSQL(where, sql), language, true) return } else { - sql, queryParam = pendingRequestSQL(templateType, param.Type, userRolesFilterSql, userRolesFilterParam) + switch param.Type { + case 1: + status = string(models.RequestStatusPending) + case 3: + status = string(models.RequestStatusInApproval) + case 4: + status = string(models.RequestStatusConfirm) + } + sql, queryParam = pendingRequestSQL(templateType, status, userRolesFilterSql, userRolesFilterParam) } case "hasProcessed": - if param.Type == string(models.RequestStatusPending) { + if param.Type == 1 { sql, queryParam = hasProcessedRequestSQL(templateType, user) - } else if param.Type == "Task" { + } else if param.Type == 2 { sql, queryParam = hasProcessedTaskSQL(templateType, user) pageInfo, rowData, err = getPlatData(models.PlatDataParam{Param: param.CommonRequestParam, QueryParam: queryParam, UserToken: userToken}, getPlatTaskSQL(where, sql), language, true) return diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index cf9b3f91..2bbf9ea3 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -121,10 +121,12 @@ func (s RequestTemplateService) QueryRequestTemplate(param *models.QueryRequestP } if isQueryMessage { for _, v := range rowData { - tmpErr := s.SyncProcDefId(v.Id, v.ProcDefId, v.ProcDefName, v.ProcDefKey, commonParam.Token, commonParam.Language) - if tmpErr != nil { - err = fmt.Errorf("Try to sync proDefId fail,%s ", tmpErr.Error()) - break + if v.ProcDefId != "" { + tmpErr := s.SyncProcDefId(v.Id, v.ProcDefId, v.ProcDefName, v.ProcDefKey, commonParam.Token, commonParam.Language) + if tmpErr != nil { + err = fmt.Errorf("Try to sync proDefId fail,%s ", tmpErr.Error()) + break + } } } if err != nil { From d6679c0c9d2bb9049e1171c442f1e6d85f618f98 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 21 Feb 2024 17:35:16 +0800 Subject: [PATCH 033/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 5 + taskman-server/api/v1/form/form_template.go | 96 +++++++++++++- taskman-server/models/form_template.go | 28 ++-- .../service/form_item_template_service.go | 4 + .../service/form_template_service.go | 120 ++++++++++++++++-- 5 files changed, 225 insertions(+), 28 deletions(-) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index ffe67f31..8fa321cb 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -63,8 +63,13 @@ func init() { &handlerFuncObj{Url: "/request-form-template/:id", Method: "GET", HandlerFunc: form.GetRequestFormTemplate}, &handlerFuncObj{Url: "/request-form-template/:id", Method: "POST", HandlerFunc: form.UpdateRequestFormTemplate}, &handlerFuncObj{Url: "/request-form-template/:id/data-form", Method: "GET", HandlerFunc: form.GetDataFormTemplate}, + &handlerFuncObj{Url: "/request-form-template/form/:from-template-id", Method: "GET", HandlerFunc: form.GetFormTemplate}, + &handlerFuncObj{Url: "/request-form-template/:id/global-form", Method: "GET", HandlerFunc: form.GetGlobalFormEntity}, + &handlerFuncObj{Url: "/data-form-template/item-group-config", Method: "GET", HandlerFunc: form.GetDataFormTemplateItemGroupConfig}, + &handlerFuncObj{Url: "/data-form-template/item-group-config", Method: "POST", HandlerFunc: form.UpdateDataFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group-config", Method: "GET", HandlerFunc: form.GetFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group-config", Method: "POST", HandlerFunc: form.UpdateFormTemplateItemGroupConfig}, + &handlerFuncObj{Url: "/form-template/item-group/copy", Method: "POST", HandlerFunc: form.CopyDataFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group", Method: "DELETE", HandlerFunc: form.DeleteFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group", Method: "POST", HandlerFunc: form.UpdateFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group/sort", Method: "POST", HandlerFunc: form.SortFormTemplateItemGroup}, diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index 51120af5..195408af 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -102,8 +102,42 @@ func GetDataFormTemplate(c *gin.Context) { middleware.ReturnData(c, result) } -// GetFormTemplateItemGroupConfig 获取配置表单组配置 -func GetFormTemplateItemGroupConfig(c *gin.Context) { +// GetFormTemplate 获取数据表单模板 +func GetFormTemplate(c *gin.Context) { + var result *models.SimpleFormTemplateDto + var err error + formTemplateId := c.Param("from-template-id") + if formTemplateId == "" { + middleware.ReturnParamEmptyError(c, "from-template-id") + return + } + result, err = service.GetFormTemplateService().GetFormTemplate(formTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// GetGlobalFormEntity 获取全局表单 entity +func GetGlobalFormEntity(c *gin.Context) { + var entityList []string + var err error + requestTemplateId := c.Param("id") + if requestTemplateId == "" { + middleware.ReturnParamEmptyError(c, "id") + return + } + entityList, err = service.GetFormTemplateService().GetDataFormTemplateItemGroups(requestTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, entityList) +} + +// GetDataFormTemplateItemGroupConfig 获取配置表单组配置 +func GetDataFormTemplateItemGroupConfig(c *gin.Context) { var configureDto *models.FormTemplateGroupConfigureDto var err error formTemplateId := c.Query("form-template-id") @@ -125,7 +159,25 @@ func GetFormTemplateItemGroupConfig(c *gin.Context) { return } } - configureDto, err = service.GetFormTemplateService().GetConfigureForm(formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + configureDto, err = service.GetFormTemplateService().GetDataFormConfig(formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, configureDto) +} + +// GetFormTemplateItemGroupConfig 获取配置表单组配置 +func GetFormTemplateItemGroupConfig(c *gin.Context) { + var configureDto *models.FormTemplateGroupConfigureDto + var err error + formTemplateId := c.Query("form-template-id") + itemGroupName := c.Query("item-group-name") + if itemGroupName == "" { + middleware.ReturnParamEmptyError(c, "request-template-id or item-group-name") + return + } + configureDto, err = service.GetFormTemplateService().GetFormConfig(formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -133,6 +185,28 @@ func GetFormTemplateItemGroupConfig(c *gin.Context) { middleware.ReturnData(c, configureDto) } +// UpdateDataFormTemplateItemGroupConfig 新增更新数据表单组 +func UpdateDataFormTemplateItemGroupConfig(c *gin.Context) { + var param models.FormTemplateGroupConfigureDto + var err error + if err := c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + // 校验是否有修改权限 + err = service.GetRequestTemplateService().CheckPermission(param.RequestTemplateId, middleware.GetRequestUser(c)) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + err = service.GetFormItemTemplateService().UpdateFormTemplateItemGroupConfig(param) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnSuccess(c) +} + // UpdateFormTemplateItemGroupConfig 新增更新表单组 func UpdateFormTemplateItemGroupConfig(c *gin.Context) { var param models.FormTemplateGroupConfigureDto @@ -215,6 +289,22 @@ func DeleteFormTemplateItemGroup(c *gin.Context) { middleware.ReturnSuccess(c) } +// CopyDataFormTemplateItemGroup 数据表单模板组copy +func CopyDataFormTemplateItemGroup(c *gin.Context) { + formTemplateId := c.Query("form-template-id") + itemGroupName := c.Query("item-group-name") + if formTemplateId == "" || itemGroupName == "" { + middleware.ReturnParamEmptyError(c, "form-template-id or item-group-name") + return + } + err := service.GetFormItemTemplateService().CopyDataFormTemplateItemGroup(formTemplateId, itemGroupName) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnSuccess(c) +} + // createDataFormTemplate 创建数据表单 func createDataFormTemplate(requestTemplateId string) (formTemplateId string, err error) { var requestTemplate *models.RequestTemplateTable diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index b519b691..14eaf122 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -30,15 +30,20 @@ type FormTemplateDto struct { // DataFormTemplateDto 全局表单模板 dto type DataFormTemplateDto struct { - DataFormTemplateId string `json:"dataFormTemplateId"` // 数据表单模板ID - AssociationWorkflow bool `json:"associationWorkflow"` // 是否关联编排 - UpdatedBy string `json:"updatedBy"` // 更新人 - UpdatedTime string `json:"updatedTime"` // 更新时间 - Groups []*DataFormTemplateGroupDto `json:"groups"` + DataFormTemplateId string `json:"dataFormTemplateId"` // 数据表单模板ID + AssociationWorkflow bool `json:"associationWorkflow"` // 是否关联编排 + UpdatedBy string `json:"updatedBy"` // 更新人 + Groups []*FormTemplateGroupDto `json:"groups"` } -// DataFormTemplateGroupDto 全局表单模板组dto -type DataFormTemplateGroupDto struct { +type SimpleFormTemplateDto struct { + FormTemplateId string `json:"formTemplateId"` // 数据表单模板ID + UpdatedBy string `json:"updatedBy"` // 更新人 + Groups []*FormTemplateGroupDto `json:"groups"` +} + +// FormTemplateGroupDto 表单模板组dto +type FormTemplateGroupDto struct { ItemGroup string `json:"itemGroup"` ItemGroupType string `json:"itemGroupType"` // 表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName"` @@ -116,7 +121,6 @@ func ConvertDataFormTemplate2FormTemplateDto(dto DataFormTemplateDto) FormTempla Description: "", ExpireDay: 0, UpdatedBy: dto.UpdatedBy, - UpdatedTime: dto.UpdatedTime, Items: items, } } @@ -159,17 +163,17 @@ func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfi } } -type DataFormTemplateGroupDtoSort []*DataFormTemplateGroupDto +type FormTemplateGroupDtoSort []*FormTemplateGroupDto -func (s DataFormTemplateGroupDtoSort) Len() int { +func (s FormTemplateGroupDtoSort) Len() int { return len(s) } -func (s DataFormTemplateGroupDtoSort) Swap(i, j int) { +func (s FormTemplateGroupDtoSort) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s DataFormTemplateGroupDtoSort) Less(i, j int) bool { +func (s FormTemplateGroupDtoSort) Less(i, j int) bool { if s[i].ItemGroupSort < s[j].ItemGroupSort { return true } diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 4e5d8c3b..23924cbd 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -169,6 +169,10 @@ func (s FormItemTemplateService) SortFormTemplateItemGroup(param models.FormTemp return } +func (s FormItemTemplateService) CopyDataFormTemplateItemGroup(formTemplateId, itemGroupName string) (err error) { + return +} + func (s FormItemTemplateService) buildFormTemplateGroupSortMap(itemGroupNameSort []string) map[string]int { hashMap := make(map[string]int) for i, groupName := range itemGroupNameSort { diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index d559625a..355b146a 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -128,10 +128,6 @@ func (s FormTemplateService) GetRequestFormTemplate(requestTemplateId string) (r func (s FormTemplateService) GetDataFormTemplate(requestTemplateId string) (result *models.DataFormTemplateDto, err error) { var requestTemplate *models.RequestTemplateTable - var formItemTemplateList []*models.FormItemTemplateTable - var itemGroupMap = make(map[string][]*models.FormItemTemplateTable) - var itemGroupType, itemGroupName string - var itemGroupSort int var associationWorkflow bool requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) if err != nil { @@ -145,8 +141,24 @@ func (s FormTemplateService) GetDataFormTemplate(requestTemplateId string) (resu if strings.TrimSpace(requestTemplate.ProcDefId) != "" { associationWorkflow = true } - result = &models.DataFormTemplateDto{DataFormTemplateId: requestTemplate.DataFormTemplate, Groups: make([]*models.DataFormTemplateGroupDto, 0), AssociationWorkflow: associationWorkflow} - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplate(requestTemplate.DataFormTemplate) + result = &models.DataFormTemplateDto{DataFormTemplateId: requestTemplate.DataFormTemplate, Groups: make([]*models.FormTemplateGroupDto, 0), AssociationWorkflow: associationWorkflow} + result.Groups, err = s.getFormTemplateGroups(requestTemplate.DataFormTemplate) + return +} + +func (s FormTemplateService) GetFormTemplate(formTemplateId string) (result *models.SimpleFormTemplateDto, err error) { + result = &models.SimpleFormTemplateDto{FormTemplateId: formTemplateId, Groups: make([]*models.FormTemplateGroupDto, 0)} + result.Groups, err = s.getFormTemplateGroups(formTemplateId) + return +} + +func (s FormTemplateService) getFormTemplateGroups(formTemplateId string) (groups []*models.FormTemplateGroupDto, err error) { + var formItemTemplateList []*models.FormItemTemplateTable + var itemGroupMap = make(map[string][]*models.FormItemTemplateTable) + var itemGroupType, itemGroupName string + var itemGroupSort int + groups = []*models.FormTemplateGroupDto{} + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplate(formTemplateId) if err != nil { return } @@ -169,7 +181,7 @@ func (s FormTemplateService) GetDataFormTemplate(requestTemplateId string) (resu itemGroupName = formItemTemplateArr[0].ItemGroupName itemGroupSort = formItemTemplateArr[0].ItemGroupSort } - result.Groups = append(result.Groups, &models.DataFormTemplateGroupDto{ + groups = append(groups, &models.FormTemplateGroupDto{ ItemGroup: itemGroup, ItemGroupType: itemGroupType, ItemGroupName: itemGroupName, @@ -178,12 +190,40 @@ func (s FormTemplateService) GetDataFormTemplate(requestTemplateId string) (resu }) } // 设置排序,保证前端展示数据顺序一致 - for _, DataFormTemplateGroupDto := range result.Groups { - if len(DataFormTemplateGroupDto.Items) > 0 { - sort.Sort(models.FormItemTemplateTableSort(DataFormTemplateGroupDto.Items)) + for _, FormTemplateGroupDto := range groups { + if len(FormTemplateGroupDto.Items) > 0 { + sort.Sort(models.FormItemTemplateTableSort(FormTemplateGroupDto.Items)) } } - sort.Sort(models.DataFormTemplateGroupDtoSort(result.Groups)) + sort.Sort(models.FormTemplateGroupDtoSort(groups)) + return +} + +func (s FormTemplateService) GetDataFormTemplateItemGroups(requestTemplateId string) (entityList []string, err error) { + var itemGroupNameMap = make(map[string]bool) + var requestTemplate *models.RequestTemplateTable + var formItemTemplateList []*models.FormItemTemplateTable + entityList = []string{} + requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) + if err != nil { + return + } + if requestTemplate == nil { + err = fmt.Errorf("requestTemplate not exist") + return + } + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplate(requestTemplate.DataFormTemplate) + if err != nil { + return + } + for _, formItemTemplate := range formItemTemplateList { + itemGroupNameMap[formItemTemplate.ItemGroupName] = true + } + for groupName, _ := range itemGroupNameMap { + entityList = append(entityList, groupName) + } + // 排序 + sort.Strings(entityList) return } @@ -288,8 +328,58 @@ func (s FormTemplateService) CreateDataFormTemplate(formTemplateDto models.DataF return } -// GetConfigureForm 获取配置表单 -func (s FormTemplateService) GetConfigureForm(formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { +// GetFormConfig 获取配置表单,数据基于数据表单数据 +func (s FormTemplateService) GetFormConfig(formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { + var formItemTemplate []*models.FormItemTemplateTable + var entitiesList []*models.ExpressionEntities + var entity *models.ExpressionEntities + var existAttrMap = make(map[string]bool) + configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateTable{}} + // 1.先查询用户配置数据 + formItemTemplate, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + if err != nil { + return + } + if len(formItemTemplate) > 0 { + configureDto.ItemGroup = formItemTemplate[0].ItemGroup + configureDto.ItemGroupName = formItemTemplate[0].ItemGroupName + configureDto.ItemGroupType = formItemTemplate[0].ItemGroupType + configureDto.ItemGroupRule = formItemTemplate[0].ItemGroupRule + for _, formItem := range formItemTemplate { + if formItem.ItemGroupType == string(models.FormItemGroupTypeCustom) { + configureDto.CustomItems = append(configureDto.CustomItems, formItem) + } else { + existAttrMap[formItem.AttrDefId] = true + } + } + } + // 2.查询entity 属性集合 + entitiesList, err = rpc.QueryEntityAttributes(models.QueryExpressionDataParam{DataModelExpression: itemGroupName}, userToken, language) + if err != nil { + return + } + if len(entitiesList) > 0 && len(entitiesList[0].Attributes) > 0 { + entity = entitiesList[0] + if configureDto.ItemGroup == "" { + configureDto.ItemGroup = itemGroupName + configureDto.ItemGroupName = itemGroupName + configureDto.ItemGroupType = string(models.FormItemGroupTypeOptional) + } + for _, attribute := range entitiesList[0].Attributes { + attribute.Id = fmt.Sprintf("%s:%s:%s", entitiesList[0].PackageName, entitiesList[0].EntityName, attribute.Name) + attribute.EntityName = entity.EntityName + attribute.EntityPackage = entity.PackageName + if existAttrMap[attribute.Id] { + attribute.Active = true + } + configureDto.SystemItems = append(configureDto.SystemItems, attribute) + } + } + return +} + +// GetDataFormConfig 获取数据表单配置 +func (s FormTemplateService) GetDataFormConfig(formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { var formItemTemplate []*models.FormItemTemplateTable var entitiesList []*models.ExpressionEntities var entity *models.ExpressionEntities @@ -337,3 +427,7 @@ func (s FormTemplateService) GetConfigureForm(formTemplateId, itemGroupName, use } return } + +func (s FormTemplateService) CopyDataFormTemplateItemGroup(formTemplateId, itemGroupName string) { + +} From 2153dfb141c1404e98c8521139cb42d000c8e7bb Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 21 Feb 2024 19:37:23 +0800 Subject: [PATCH 034/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 3 +- taskman-server/api/v1/form/form_template.go | 29 ++-------- taskman-server/models/form_item_template.go | 2 +- .../service/form_item_template_service.go | 20 +++++++ .../service/form_template_service.go | 54 ++++++------------- .../service/request_template_service.go | 6 +-- 6 files changed, 46 insertions(+), 68 deletions(-) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 8fa321cb..fe027ccf 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -66,9 +66,8 @@ func init() { &handlerFuncObj{Url: "/request-form-template/form/:from-template-id", Method: "GET", HandlerFunc: form.GetFormTemplate}, &handlerFuncObj{Url: "/request-form-template/:id/global-form", Method: "GET", HandlerFunc: form.GetGlobalFormEntity}, &handlerFuncObj{Url: "/data-form-template/item-group-config", Method: "GET", HandlerFunc: form.GetDataFormTemplateItemGroupConfig}, - &handlerFuncObj{Url: "/data-form-template/item-group-config", Method: "POST", HandlerFunc: form.UpdateDataFormTemplateItemGroupConfig}, - &handlerFuncObj{Url: "/form-template/item-group-config", Method: "GET", HandlerFunc: form.GetFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group-config", Method: "POST", HandlerFunc: form.UpdateFormTemplateItemGroupConfig}, + &handlerFuncObj{Url: "/form-template/item-group-config", Method: "GET", HandlerFunc: form.GetFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group/copy", Method: "POST", HandlerFunc: form.CopyDataFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group", Method: "DELETE", HandlerFunc: form.DeleteFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group", Method: "POST", HandlerFunc: form.UpdateFormTemplateItemGroup}, diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index 195408af..371f5a89 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -173,11 +173,12 @@ func GetFormTemplateItemGroupConfig(c *gin.Context) { var err error formTemplateId := c.Query("form-template-id") itemGroupName := c.Query("item-group-name") - if itemGroupName == "" { - middleware.ReturnParamEmptyError(c, "request-template-id or item-group-name") + requestTemplateId := c.Query("request-template-id") + if itemGroupName == "" || formTemplateId == "" || requestTemplateId == "" { + middleware.ReturnParamEmptyError(c, "request-template-id or item-group-name or form-template-id") return } - configureDto, err = service.GetFormTemplateService().GetFormConfig(formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + configureDto, err = service.GetFormTemplateService().GetFormConfig(requestTemplateId, formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -185,28 +186,6 @@ func GetFormTemplateItemGroupConfig(c *gin.Context) { middleware.ReturnData(c, configureDto) } -// UpdateDataFormTemplateItemGroupConfig 新增更新数据表单组 -func UpdateDataFormTemplateItemGroupConfig(c *gin.Context) { - var param models.FormTemplateGroupConfigureDto - var err error - if err := c.ShouldBindJSON(¶m); err != nil { - middleware.ReturnParamValidateError(c, err) - return - } - // 校验是否有修改权限 - err = service.GetRequestTemplateService().CheckPermission(param.RequestTemplateId, middleware.GetRequestUser(c)) - if err != nil { - middleware.ReturnServerHandleError(c, err) - return - } - err = service.GetFormItemTemplateService().UpdateFormTemplateItemGroupConfig(param) - if err != nil { - middleware.ReturnServerHandleError(c, err) - return - } - middleware.ReturnSuccess(c) -} - // UpdateFormTemplateItemGroupConfig 新增更新表单组 func UpdateFormTemplateItemGroupConfig(c *gin.Context) { var param models.FormTemplateGroupConfigureDto diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index 46285473..8af77ac5 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -32,7 +32,7 @@ type FormItemTemplateTable struct { IsRefInside string `json:"isRefInside" xorm:"is_ref_inside"` Multiple string `json:"multiple" xorm:"multiple"` DefaultClear string `json:"defaultClear" xorm:"default_clear"` - CopyId string `json:"-" xorm:"copy_id"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 + CopyId string `json:"copyId" xorm:"copy_id"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 SelectList []*EntityDataObj `json:"selectList" xorm:"-"` } diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 23924cbd..28b62175 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -170,6 +170,26 @@ func (s FormItemTemplateService) SortFormTemplateItemGroup(param models.FormTemp } func (s FormItemTemplateService) CopyDataFormTemplateItemGroup(formTemplateId, itemGroupName string) (err error) { + var formItemTemplateList []*models.FormItemTemplateTable + // 1. 查询表单组是否存在,不存在则新增 + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + if err != nil { + return + } + // 新增数据 + if len(formItemTemplateList) > 0 { + err = transaction(func(session *xorm.Session) error { + for _, formItemTemplate := range formItemTemplateList { + formItemTemplate.CopyId = formItemTemplate.Id + formItemTemplate.Id = guid.CreateGuid() + _, err = s.formItemTemplateDao.Add(session, formItemTemplate) + if err != nil { + return err + } + } + return nil + }) + } return } diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index 355b146a..b6f27bfd 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -329,52 +329,32 @@ func (s FormTemplateService) CreateDataFormTemplate(formTemplateDto models.DataF } // GetFormConfig 获取配置表单,数据基于数据表单数据 -func (s FormTemplateService) GetFormConfig(formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { - var formItemTemplate []*models.FormItemTemplateTable +func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { + var requestTemplate *models.RequestTemplateTable + /*var formItemTemplate []*models.FormItemTemplateTable var entitiesList []*models.ExpressionEntities var entity *models.ExpressionEntities - var existAttrMap = make(map[string]bool) - configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateTable{}} - // 1.先查询用户配置数据 - formItemTemplate, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + var existAttrMap = make(map[string]bool)*/ + requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) if err != nil { return } - if len(formItemTemplate) > 0 { - configureDto.ItemGroup = formItemTemplate[0].ItemGroup - configureDto.ItemGroupName = formItemTemplate[0].ItemGroupName - configureDto.ItemGroupType = formItemTemplate[0].ItemGroupType - configureDto.ItemGroupRule = formItemTemplate[0].ItemGroupRule - for _, formItem := range formItemTemplate { - if formItem.ItemGroupType == string(models.FormItemGroupTypeCustom) { - configureDto.CustomItems = append(configureDto.CustomItems, formItem) - } else { - existAttrMap[formItem.AttrDefId] = true - } - } + if requestTemplate == nil { + err = exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param requestTemplateId is invalid")) + return } - // 2.查询entity 属性集合 - entitiesList, err = rpc.QueryEntityAttributes(models.QueryExpressionDataParam{DataModelExpression: itemGroupName}, userToken, language) - if err != nil { + if requestTemplate.DataFormTemplate == "" { + err = fmt.Errorf("requestTemplate:%s DataFormTemplate is empty", requestTemplate.Id) return } - if len(entitiesList) > 0 && len(entitiesList[0].Attributes) > 0 { - entity = entitiesList[0] - if configureDto.ItemGroup == "" { - configureDto.ItemGroup = itemGroupName - configureDto.ItemGroupName = itemGroupName - configureDto.ItemGroupType = string(models.FormItemGroupTypeOptional) - } - for _, attribute := range entitiesList[0].Attributes { - attribute.Id = fmt.Sprintf("%s:%s:%s", entitiesList[0].PackageName, entitiesList[0].EntityName, attribute.Name) - attribute.EntityName = entity.EntityName - attribute.EntityPackage = entity.PackageName - if existAttrMap[attribute.Id] { - attribute.Active = true - } - configureDto.SystemItems = append(configureDto.SystemItems, attribute) - } + configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateTable{}} + // 1.先查询用户配置数据 + //formItemTemplate, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + if err != nil { + return } + // 2. 查询数据表单 + //s.GetDataFormConfig(requestTemplate.DataFormTemplate) return } diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 2bbf9ea3..c427de89 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -216,7 +216,7 @@ func (s RequestTemplateService) QueryRequestTemplateEntity(requestTemplateId, us return } entityList = append(entityList, &models.RequestTemplateEntityDto{ - FormType: "1.自定义表单", + FormType: string(models.FormItemGroupTypeCustom), Entities: nil, }) // 配置了编排数据 @@ -232,7 +232,7 @@ func (s RequestTemplateService) QueryRequestTemplateEntity(requestTemplateId, us entities = append(entities, entityStr) workflowEntityMap[entityStr] = true } - entityList = append(entityList, &models.RequestTemplateEntityDto{FormType: "2.编排数据项表单", Entities: entities}) + entityList = append(entityList, &models.RequestTemplateEntityDto{FormType: string(models.FormItemGroupTypeWorkflow), Entities: entities}) } } // 自选数据项表单 @@ -252,7 +252,7 @@ func (s RequestTemplateService) QueryRequestTemplateEntity(requestTemplateId, us } } } - entityList = append(entityList, &models.RequestTemplateEntityDto{FormType: "3.自选数据项表单", Entities: entities}) + entityList = append(entityList, &models.RequestTemplateEntityDto{FormType: string(models.FormItemGroupTypeOptional), Entities: entities}) } return } From dc3d2c34025cdebbc0e7add828e6e22010324c77 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 21 Feb 2024 20:07:06 +0800 Subject: [PATCH 035/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/process_defintions.go | 2 +- taskman-server/service/proc_def_service.go | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/taskman-server/models/process_defintions.go b/taskman-server/models/process_defintions.go index e578122f..6ce62698 100644 --- a/taskman-server/models/process_defintions.go +++ b/taskman-server/models/process_defintions.go @@ -103,7 +103,7 @@ type ProcNodeObj struct { ServiceName string `json:"serviceName"` OrderedNo string `json:"orderedNo"` OrderedNum int `json:"-"` - DynamicBind bool `json:"dynamicBind"` + DynamicBind string `json:"dynamicBind"` BoundEntities []*ProcEntity `json:"boundEntities"` } diff --git a/taskman-server/service/proc_def_service.go b/taskman-server/service/proc_def_service.go index 59acdd71..6f05443c 100644 --- a/taskman-server/service/proc_def_service.go +++ b/taskman-server/service/proc_def_service.go @@ -118,10 +118,8 @@ func (s ProcDefService) GetProcessDefineTaskNodes(requestTemplate *models.Reques if node.NodeType != string(models.ProcDefNodeTypeHuman) { continue } - } else if filterType == "bind" { - if node.DynamicBind { - continue - } + } else if filterType == "bind" && node.DynamicBind == "Y" { + continue } nodeList = append(nodeList, node) } From 0b6c3762ad6721f9cbd3d05605aafd5a48adc838 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 21 Feb 2024 20:38:10 +0800 Subject: [PATCH 036/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/form_template_service.go | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index b6f27bfd..941b94f1 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -331,10 +331,9 @@ func (s FormTemplateService) CreateDataFormTemplate(formTemplateDto models.DataF // GetFormConfig 获取配置表单,数据基于数据表单数据 func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { var requestTemplate *models.RequestTemplateTable - /*var formItemTemplate []*models.FormItemTemplateTable - var entitiesList []*models.ExpressionEntities - var entity *models.ExpressionEntities - var existAttrMap = make(map[string]bool)*/ + var dataFormConfigureDto *models.FormTemplateGroupConfigureDto + var formItemTemplateList []*models.FormItemTemplateTable + var existAttrMap = make(map[string]bool) requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) if err != nil { return @@ -349,12 +348,33 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it } configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateTable{}} // 1.先查询用户配置数据 - //formItemTemplate, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) if err != nil { return } + for _, formItemTemplate := range formItemTemplateList { + if formItemTemplate.AttrDefId != "" { + existAttrMap[formItemTemplate.AttrDefId] = true + } else { + configureDto.CustomItems = append(configureDto.CustomItems, formItemTemplate) + } + } // 2. 查询数据表单 - //s.GetDataFormConfig(requestTemplate.DataFormTemplate) + dataFormConfigureDto, err = s.GetDataFormConfig(requestTemplate.DataFormTemplate, itemGroupName, userToken, language) + if err != nil { + return + } + // 将数据表单的选中作为 审批、任务表单的全量 + if len(dataFormConfigureDto.SystemItems) > 0 { + for _, systemItem := range dataFormConfigureDto.SystemItems { + if systemItem.Active { + configureDto.SystemItems = append(configureDto.SystemItems, systemItem) + if !existAttrMap[systemItem.Id] { + systemItem.Active = false + } + } + } + } return } From 3bc8f17dc078ca4a3227461222f0305dfe1dfd04 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 21 Feb 2024 22:12:58 +0800 Subject: [PATCH 037/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/form/form_template.go | 26 ++++++++++++++++++- taskman-server/models/form_item_template.go | 4 +-- taskman-server/models/form_template.go | 3 +++ .../service/form_item_template_service.go | 2 ++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index 371f5a89..c7c7e7c6 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -102,7 +102,7 @@ func GetDataFormTemplate(c *gin.Context) { middleware.ReturnData(c, result) } -// GetFormTemplate 获取数据表单模板 +// GetFormTemplate 获取表单模板 func GetFormTemplate(c *gin.Context) { var result *models.SimpleFormTemplateDto var err error @@ -194,6 +194,10 @@ func UpdateFormTemplateItemGroupConfig(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } + if err = validateFormTemplateItemGroupConfigParam(param); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } // 校验是否有修改权限 err = service.GetRequestTemplateService().CheckPermission(param.RequestTemplateId, middleware.GetRequestUser(c)) if err != nil { @@ -308,3 +312,23 @@ func createDataFormTemplate(requestTemplateId string) (formTemplateId string, er } return } + +func validateFormTemplateItemGroupConfigParam(param models.FormTemplateGroupConfigureDto) error { + if param.RequestTemplateId == "" { + return fmt.Errorf("param RequestTemplateId is empty") + } + if param.FormTemplateId == "" { + return fmt.Errorf("param FormTemplateId is empty") + } + if param.ItemGroup == "" || param.ItemGroupType == "" || param.ItemGroupName == "" || param.ItemGroupRule == "" { + return fmt.Errorf("param ItemGroup is empty") + } + if len(param.CustomItems) > 0 { + for _, item := range param.CustomItems { + if item.ItemGroup != param.ItemGroup || item.ItemGroupName != param.ItemGroupName || item.ItemGroupType != param.ItemGroupType || item.ItemGroupRule != param.ItemGroupRule { + return fmt.Errorf("param CustomItems Id:%s is invalid", item.Id) + } + } + } + return nil +} diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index 8af77ac5..73efa741 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -7,8 +7,8 @@ type FormItemTemplateTable struct { ItemGroup string `json:"itemGroup" xorm:"item_group"` ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` - ItemGroupSort int `json:"ItemGroupSort" xorm:"item_group_sort"` // item_group 排序 - ItemGroupRule string `json:"item_group_rule" xorm:"item_group_rule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 + ItemGroupSort int `json:"ItemGroupSort" xorm:"item_group_sort"` // item_group 排序 + ItemGroupRule string `json:"itemGroupRule" xorm:"item_group_rule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 FormTemplate string `json:"formTemplate" xorm:"form_template"` DefaultValue string `json:"defaultValue" xorm:"default_value"` Sort int `json:"sort" xorm:"sort"` diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index 14eaf122..1993c73d 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -133,6 +133,7 @@ func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfi return &FormItemTemplateTable{ Id: guid.CreateGuid(), Name: workflowEntityAttribute.Name, + Description: workflowEntityAttribute.Description, ItemGroup: param.ItemGroup, ItemGroupType: param.ItemGroupType, ItemGroupName: param.ItemGroupName, @@ -152,6 +153,7 @@ func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfi RefEntity: workflowEntityAttribute.Name, DataOptions: "", Required: "no", + Regular: "", IsEdit: "yes", IsView: "yes", IsOutput: "no", @@ -160,6 +162,7 @@ func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfi Multiple: workflowEntityAttribute.Multiple, DefaultClear: "no", CopyId: "", + SelectList: nil, } } diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 28b62175..c2ed8454 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -36,6 +36,7 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. } if len(param.CustomItems) > 0 { for _, customItem := range param.CustomItems { + customItem.FormTemplate = param.FormTemplateId customItem.ElementType = string(models.FormItemElementTypeCalculate) insertItems = append(insertItems, customItem) } @@ -65,6 +66,7 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. } } if !customItemExist { + customItem.FormTemplate = param.FormTemplateId insertItems = append(insertItems, customItem) } } From 7ce9ab2f32b984ff63d68909e37ecc4cee168f4d Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Thu, 22 Feb 2024 14:39:10 +0800 Subject: [PATCH 038/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/form_template.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index 1993c73d..9806c9ae 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -58,10 +58,10 @@ type FormTemplateGroupConfigureDto struct { ItemGroup string `json:"itemGroup"` ItemGroupType string `json:"itemGroupType"` // 表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName"` - ItemGroupRule string `json:"item_group_rule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 - ItemGroupSort int `json:"item_group_sort"` // 表单组排序 - SystemItems []*ProcEntityAttributeObj `json:"systemItems"` // 系统表单项 - CustomItems []*FormItemTemplateTable `json:"customItems"` // 自定义表单项 + ItemGroupRule string `json:"itemGroupRule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 + ItemGroupSort int `json:"itemGroupSort"` // 表单组排序 + SystemItems []*ProcEntityAttributeObj `json:"systemItems"` // 系统表单项 + CustomItems []*FormItemTemplateTable `json:"customItems"` // 自定义表单项 } // FormTemplateGroupCustomDataDto 表单组自定义数据dto From bcb5cc567bc8b0d071801812763c59273b40e4a7 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Thu, 22 Feb 2024 16:55:21 +0800 Subject: [PATCH 039/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 1 - taskman-server/service/form_template_service.go | 4 ---- taskman-server/service/request_template_service.go | 4 ++-- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index fe027ccf..4db9e877 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -66,7 +66,6 @@ func init() { &handlerFuncObj{Url: "/request-form-template/form/:from-template-id", Method: "GET", HandlerFunc: form.GetFormTemplate}, &handlerFuncObj{Url: "/request-form-template/:id/global-form", Method: "GET", HandlerFunc: form.GetGlobalFormEntity}, &handlerFuncObj{Url: "/data-form-template/item-group-config", Method: "GET", HandlerFunc: form.GetDataFormTemplateItemGroupConfig}, - &handlerFuncObj{Url: "/form-template/item-group-config", Method: "POST", HandlerFunc: form.UpdateFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group-config", Method: "GET", HandlerFunc: form.GetFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group/copy", Method: "POST", HandlerFunc: form.CopyDataFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group", Method: "DELETE", HandlerFunc: form.DeleteFormTemplateItemGroup}, diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index 941b94f1..2ba1a6c4 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -308,10 +308,6 @@ func (s FormTemplateService) CreateDataFormTemplate(formTemplateDto models.DataF if requestTemplate == nil { return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param id is invalid")) } - // 请求模板的处理不是当前用户,不允许操作 - if requestTemplate.Handler != formTemplateDto.UpdatedBy { - return exterror.New().DataPermissionDeny - } err = transactionWithoutForeignCheck(func(session *xorm.Session) error { // 添加表单模板 formTemplateDto.DataFormTemplateId, err = s.AddFormTemplate(session, models.ConvertDataFormTemplate2FormTemplateDto(formTemplateDto)) diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index c427de89..0b6234d8 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -1274,8 +1274,8 @@ func (s RequestTemplateService) CheckPermission(requestTemplateId, user string) return } // 请求模板的处理不是当前用户,不允许操作 - if requestTemplate.Handler != user { + /*if requestTemplate.CreatedBy != user { err = exterror.New().DataPermissionDeny - } + }*/ return } From b200fe6999c1b960a79ddbc578b1c1746c84f1a6 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Thu, 22 Feb 2024 17:29:36 +0800 Subject: [PATCH 040/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 1 + taskman-server/models/form_item_template.go | 1 + taskman-server/service/form_template_service.go | 12 ++++++++++++ 3 files changed, 14 insertions(+) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 4db9e877..fe027ccf 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -66,6 +66,7 @@ func init() { &handlerFuncObj{Url: "/request-form-template/form/:from-template-id", Method: "GET", HandlerFunc: form.GetFormTemplate}, &handlerFuncObj{Url: "/request-form-template/:id/global-form", Method: "GET", HandlerFunc: form.GetGlobalFormEntity}, &handlerFuncObj{Url: "/data-form-template/item-group-config", Method: "GET", HandlerFunc: form.GetDataFormTemplateItemGroupConfig}, + &handlerFuncObj{Url: "/form-template/item-group-config", Method: "POST", HandlerFunc: form.UpdateFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group-config", Method: "GET", HandlerFunc: form.GetFormTemplateItemGroupConfig}, &handlerFuncObj{Url: "/form-template/item-group/copy", Method: "POST", HandlerFunc: form.CopyDataFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group", Method: "DELETE", HandlerFunc: form.DeleteFormTemplateItemGroup}, diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index 73efa741..dba75a3d 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -34,6 +34,7 @@ type FormItemTemplateTable struct { DefaultClear string `json:"defaultClear" xorm:"default_clear"` CopyId string `json:"copyId" xorm:"copy_id"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 SelectList []*EntityDataObj `json:"selectList" xorm:"-"` + Active bool `json:"active" xorm:"-"` // 是否选中状态 } func (FormItemTemplateTable) TableName() string { diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index 2ba1a6c4..a9cd8ff8 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -330,6 +330,7 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it var dataFormConfigureDto *models.FormTemplateGroupConfigureDto var formItemTemplateList []*models.FormItemTemplateTable var existAttrMap = make(map[string]bool) + var existCustomItemsMap = make(map[string]string) requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) if err != nil { return @@ -353,6 +354,7 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it existAttrMap[formItemTemplate.AttrDefId] = true } else { configureDto.CustomItems = append(configureDto.CustomItems, formItemTemplate) + existCustomItemsMap[formItemTemplate.CopyId] = formItemTemplate.Id } } // 2. 查询数据表单 @@ -371,6 +373,16 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it } } } + if len(dataFormConfigureDto.CustomItems) > 0 { + for _, customItem := range dataFormConfigureDto.CustomItems { + if existCustomItemsMap[customItem.Id] != "" { + customItem.Id = existCustomItemsMap[customItem.Id] + } else { + customItem.Id = "" + } + configureDto.CustomItems = append(configureDto.CustomItems, customItem) + } + } return } From 5db62288e1de7c142bb1650506f4353120dcb5a3 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Thu, 22 Feb 2024 17:32:41 +0800 Subject: [PATCH 041/618] =?UTF-8?q?=E5=AE=A1=E6=89=B9=E5=92=8C=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E4=BB=A3=E7=A0=81=E6=A1=86=E6=9E=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 14 +++ .../api/v1/approval/approval_template.go | 94 +++++++++++++++++++ taskman-server/api/v1/task/task_template.go | 86 +++++++++++++++++ taskman-server/dao/approval_dao.go | 7 ++ taskman-server/dao/approval_role_dao.go | 7 ++ taskman-server/dao/approval_template_dao.go | 7 ++ .../dao/approval_template_role_dao.go | 7 ++ taskman-server/dao/task_role_dao.go | 7 ++ taskman-server/models/approval.go | 33 +++++++ taskman-server/models/approval_template.go | 71 ++++++++++++++ taskman-server/models/task.go | 24 +++++ taskman-server/models/task_template.go | 54 ++++++++++- taskman-server/service/approval_service.go | 31 ++++++ .../service/approval_template_service.go | 40 ++++++++ taskman-server/service/service.go | 23 ++++- taskman-server/service/task_service.go | 21 +++++ .../service/task_template_service.go | 29 ++++++ 17 files changed, 550 insertions(+), 5 deletions(-) create mode 100644 taskman-server/api/v1/approval/approval_template.go create mode 100644 taskman-server/dao/approval_dao.go create mode 100644 taskman-server/dao/approval_role_dao.go create mode 100644 taskman-server/dao/approval_template_dao.go create mode 100644 taskman-server/dao/approval_template_role_dao.go create mode 100644 taskman-server/dao/task_role_dao.go create mode 100644 taskman-server/models/approval.go create mode 100644 taskman-server/models/approval_template.go create mode 100644 taskman-server/service/approval_service.go create mode 100644 taskman-server/service/approval_template_service.go diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 4db9e877..44d7c94b 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -6,6 +6,7 @@ import ( "time" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/v1/approval" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/v1/collect" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/v1/form" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/v1/request" @@ -72,8 +73,21 @@ func init() { &handlerFuncObj{Url: "/form-template/item-group", Method: "POST", HandlerFunc: form.UpdateFormTemplateItemGroup}, &handlerFuncObj{Url: "/form-template/item-group/sort", Method: "POST", HandlerFunc: form.SortFormTemplateItemGroup}, + &handlerFuncObj{Url: "/approval-template", Method: "POST", HandlerFunc: approval.CreateApprovalTemplate}, + &handlerFuncObj{Url: "/approval-template", Method: "PUT", HandlerFunc: approval.UpdateApprovalTemplate}, + &handlerFuncObj{Url: "/approval-template", Method: "DELETE", HandlerFunc: approval.DeleteApprovalTemplate}, + &handlerFuncObj{Url: "/approval-template/:requestTemplateId/:id", Method: "GET", HandlerFunc: approval.GetApprovalTemplate}, + &handlerFuncObj{Url: "/approval-template/:requestTemplateId/ids", Method: "GET", HandlerFunc: approval.ListApprovalTemplateIds}, + &handlerFuncObj{Url: "/approval-template/:requestTemplateId", Method: "GET", HandlerFunc: approval.ListApprovalTemplate}, + &handlerFuncObj{Url: "/task-template/:requestTemplateId/:proNodeId", Method: "GET", HandlerFunc: task.GetTaskTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplateId", Method: "POST", HandlerFunc: task.UpdateTaskTemplate}, + &handlerFuncObj{Url: "/task-template/custom", Method: "POST", HandlerFunc: task.CreateCustomTaskTemplate}, + &handlerFuncObj{Url: "/task-template/custom", Method: "PUT", HandlerFunc: task.UpdateCustomTaskTemplate}, + &handlerFuncObj{Url: "/task-template/custom", Method: "DELETE", HandlerFunc: task.DeleteCustomTaskTemplate}, + &handlerFuncObj{Url: "/task-template/custom/:requestTemplateId/:id", Method: "GET", HandlerFunc: task.GetCustomTaskTemplate}, + &handlerFuncObj{Url: "/task-template/custom/:requestTemplateId/ids", Method: "GET", HandlerFunc: task.ListCustomTaskTemplateIds}, + &handlerFuncObj{Url: "/task-template/custom/:requestTemplateId", Method: "GET", HandlerFunc: task.ListCustomTaskTemplate}, &handlerFuncObj{Url: "/user/template/collect", Method: "POST", HandlerFunc: collect.AddTemplateCollect}, &handlerFuncObj{Url: "/user/template/collect/:templateId", Method: "DELETE", HandlerFunc: collect.CancelTemplateCollect}, diff --git a/taskman-server/api/v1/approval/approval_template.go b/taskman-server/api/v1/approval/approval_template.go new file mode 100644 index 00000000..97238648 --- /dev/null +++ b/taskman-server/api/v1/approval/approval_template.go @@ -0,0 +1,94 @@ +package approval + +import ( + "errors" + + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" + "github.com/gin-gonic/gin" +) + +// 新建审批模板 +func CreateApprovalTemplate(c *gin.Context) { + var param models.ApprovalTemplateCreateParam + if err := c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + result, err := service.GetApprovalTemplateService().CreateApprovalTemplate(¶m) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 更新审批模板 +func UpdateApprovalTemplate(c *gin.Context) { + var param models.ApprovalTemplateDto + if err := c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + err := service.GetApprovalTemplateService().UpdateApprovalTemplate(¶m) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnSuccess(c) +} + +// 删除审批模板 +func DeleteApprovalTemplate(c *gin.Context) { + id := c.Query("id") + if id == "" { + middleware.ReturnParamEmptyError(c, "id") + return + } + result, err := service.GetApprovalTemplateService().DeleteApprovalTemplate(id) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 读取审批模板 +func GetApprovalTemplate(c *gin.Context) { + requestTemplateId := c.Param("requestTemplateId") + id := c.Param("id") + result, err := service.GetApprovalTemplateService().GetApprovalTemplate(id) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + if result.RequestTemplate != requestTemplateId { + err = errors.New("param id and requestTemplateId not match") + middleware.ReturnParamValidateError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 审批模板id列表 +func ListApprovalTemplateIds(c *gin.Context) { + requestTemplateId := c.Param("requestTemplateId") + result, err := service.GetApprovalTemplateService().ListApprovalTemplateIds(requestTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 审批模板列表 +func ListApprovalTemplate(c *gin.Context) { + requestTemplateId := c.Param("requestTemplateId") + result, err := service.GetApprovalTemplateService().ListApprovalTemplate(requestTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} diff --git a/taskman-server/api/v1/task/task_template.go b/taskman-server/api/v1/task/task_template.go index afde8e00..8a7b21ef 100644 --- a/taskman-server/api/v1/task/task_template.go +++ b/taskman-server/api/v1/task/task_template.go @@ -1,7 +1,9 @@ package task import ( + "errors" "fmt" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/api/middleware" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" @@ -72,3 +74,87 @@ func validateTaskTemplateParam(param models.TaskTemplateDto) error { } return nil } + +// 新建自定义任务模板 +func CreateCustomTaskTemplate(c *gin.Context) { + var param models.CustomTaskTemplateCreateParam + if err := c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + result, err := service.GetTaskTemplateService().CreateCustomTaskTemplate(¶m) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 更新任务模板 +func UpdateCustomTaskTemplate(c *gin.Context) { + var param models.TaskTemplateDto + if err := c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + err := service.GetTaskTemplateService().UpdateCustomTaskTemplate(¶m) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnSuccess(c) +} + +// 删除自定义任务模板 +func DeleteCustomTaskTemplate(c *gin.Context) { + id := c.Query("id") + if id == "" { + middleware.ReturnParamEmptyError(c, "id") + return + } + result, err := service.GetTaskTemplateService().DeleteCustomTaskTemplate(id) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 读取自定义任务模板 +func GetCustomTaskTemplate(c *gin.Context) { + requestTemplateId := c.Param("requestTemplateId") + id := c.Param("id") + result, err := service.GetTaskTemplateService().GetCustomTaskTemplate(id) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + if result.RequestTemplateId != requestTemplateId { + err = errors.New("param id and requestTemplateId not match") + middleware.ReturnParamValidateError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 自定义任务模板id列表 +func ListCustomTaskTemplateIds(c *gin.Context) { + requestTemplateId := c.Param("requestTemplateId") + result, err := service.GetTaskTemplateService().ListCustomTaskTemplateIds(requestTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} + +// 任务模板列表 +func ListCustomTaskTemplate(c *gin.Context) { + requestTemplateId := c.Param("requestTemplateId") + result, err := service.GetTaskTemplateService().ListCustomTaskTemplate(requestTemplateId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + middleware.ReturnData(c, result) +} diff --git a/taskman-server/dao/approval_dao.go b/taskman-server/dao/approval_dao.go new file mode 100644 index 00000000..ae95d104 --- /dev/null +++ b/taskman-server/dao/approval_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type ApprovalDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/approval_role_dao.go b/taskman-server/dao/approval_role_dao.go new file mode 100644 index 00000000..bd569ed3 --- /dev/null +++ b/taskman-server/dao/approval_role_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type ApprovalRoleDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/approval_template_dao.go b/taskman-server/dao/approval_template_dao.go new file mode 100644 index 00000000..907d50e7 --- /dev/null +++ b/taskman-server/dao/approval_template_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type ApprovalTemplateDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/approval_template_role_dao.go b/taskman-server/dao/approval_template_role_dao.go new file mode 100644 index 00000000..e02aa402 --- /dev/null +++ b/taskman-server/dao/approval_template_role_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type ApprovalTemplateRoleDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/dao/task_role_dao.go b/taskman-server/dao/task_role_dao.go new file mode 100644 index 00000000..c210837c --- /dev/null +++ b/taskman-server/dao/task_role_dao.go @@ -0,0 +1,7 @@ +package dao + +import "xorm.io/xorm" + +type TaskRoleDao struct { + DB *xorm.Engine +} diff --git a/taskman-server/models/approval.go b/taskman-server/models/approval.go new file mode 100644 index 00000000..90a43f54 --- /dev/null +++ b/taskman-server/models/approval.go @@ -0,0 +1,33 @@ +package models + +type ApprovalTable struct { + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Sort int `json:"sort" xorm:"sort"` + ApprovalTemplate string `json:"approvalTemplate" xorm:"approval_template"` + Request string `json:"request" xorm:"request"` +} + +type ApprovalRoleTable struct { + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Sort int `json:"sort" xorm:"sort"` + ApprovalTemplateRole string `json:"approvalTemplateRole" xorm:"approval_template_role"` + Approval string `json:"approval" xorm:"approval"` + Role string `json:"role" xorm:"role"` + Handler string `json:"handler" xorm:"handler"` + Approve string `json:"approve" xorm:"approve"` +} + +type ApprovalDto struct { + Id string `json:"id"` + Sort int `json:"sort"` + ApprovalTemplate string `json:"approvalTemplate"` + Request string `json:"request" xorm:"request"` + RoleObjs []*ApprovalRoleDto `json:"roleObjs"` +} + +type ApprovalRoleDto struct { + ApprovalTemplateRole string `json:"approvalTemplateRole"` + Role string `json:"role"` + Handler string `json:"handler"` + Approve string `json:"approve"` +} diff --git a/taskman-server/models/approval_template.go b/taskman-server/models/approval_template.go new file mode 100644 index 00000000..b9bfcc1d --- /dev/null +++ b/taskman-server/models/approval_template.go @@ -0,0 +1,71 @@ +package models + +type ApprovalTemplateTable struct { + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Sort int `json:"sort" xorm:"sort"` + RequestTemplate string `json:"requestTemplate" xorm:"request_template"` + Name string `json:"name" xorm:"name"` + ExpireDay int `json:"expireDay" xorm:"expire_day"` + Description string `json:"description" xorm:"description"` + RoleType string `json:"roleType" xorm:"role_type"` + CreatedBy string `json:"createdBy" xorm:"created_by"` + CreatedTime string `json:"createdTime" xorm:"created_time"` + UpdatedBy string `json:"updatedBy" xorm:"updated_by"` + UpdatedTime string `json:"updatedTime" xorm:"updated_time"` +} + +type ApprovalTemplateRoleTable struct { + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Sort int `json:"sort" xorm:"sort"` + ApprovalTemplate string `json:"approvalTemplate" xorm:"approval_template"` + RoleType string `json:"roleType" xorm:"role_type"` + HandlerType string `json:"handlerType" xorm:"handler_type"` + Role string `json:"role" xorm:"role"` + Handler string `json:"handler" xorm:"handler"` +} + +type ApprovalTemplateDto struct { + Id string `json:"id"` + Sort int `json:"sort"` + RequestTemplate string `json:"requestTemplate"` + Name string `json:"name"` + ExpireDay int `json:"expireDay"` + Description string `json:"description"` + RoleType string `json:"roleType"` + RoleObjs []*ApprovalTemplateRoleDto `json:"roleObjs"` +} + +type ApprovalTemplateRoleDto struct { + RoleType string `json:"roleType"` + HandlerType string `json:"handlerType"` + Role string `json:"role"` + Handler string `json:"handler"` +} + +type ApprovalTemplateIdObj struct { + Id string `json:"id"` + Sort int `json:"sort"` + Name string `json:"name"` +} + +type ApprovalTemplateCreateParam struct { + Sort int `json:"sort"` + RequestTemplate string `json:"requestTemplate"` + Name string `json:"name"` +} + +type ApprovalTemplateCreateResponse struct { + Id string `json:"id"` + Sort int `json:"sort"` + RequestTemplate string `json:"requestTemplate"` + Name string `json:"name"` + Ids []*ApprovalTemplateIdObj `json:"ids"` +} + +type ApprovalTemplateDeleteResponse struct { + Ids []*ApprovalTemplateIdObj `json:"ids"` +} + +type ApprovalTemplateListIdsResponse struct { + Ids []*ApprovalTemplateIdObj `json:"ids"` +} diff --git a/taskman-server/models/task.go b/taskman-server/models/task.go index bfad7eff..84916dbe 100644 --- a/taskman-server/models/task.go +++ b/taskman-server/models/task.go @@ -2,6 +2,7 @@ package models type TaskTable struct { Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Type string `json:"type" xorm:"type"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` Form string `json:"form" xorm:"form"` @@ -40,6 +41,29 @@ type TaskTable struct { ExpireTime string `json:"expireTime" xorm:"expire_time"` NotifyCount int `json:"notifyCount" xorm:"notify_count"` TemplateType int `json:"templateType" xorm:"template_type"` // 请求模板类型 0表示请求,1表示发布 + Sort int `json:"sort" xorm:"sort"` +} + +type TaskRoleTable struct { + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + TaskTemplateRole string `json:"taskTemplateRole" xorm:"task_template_role"` + Task string `json:"task" xorm:"task"` + Role string `json:"role" xorm:"role"` + Handler string `json:"handler" xorm:"handler"` +} + +type TaskDto struct { + Id string `json:"id"` + Sort int `json:"sort"` + TaskTemplate string `json:"taskTemplate"` + Request string `json:"request" xorm:"request"` + RoleObjs []*TaskRoleDto `json:"roleObjs"` +} + +type TaskRoleDto struct { + TaskTemplateRole string `json:"taskTemplateRole"` + Role string `json:"role"` + Handler string `json:"handler"` } type TaskListObj struct { diff --git a/taskman-server/models/task_template.go b/taskman-server/models/task_template.go index 4cdb9ad4..1ca43722 100644 --- a/taskman-server/models/task_template.go +++ b/taskman-server/models/task_template.go @@ -2,6 +2,7 @@ package models type TaskTemplateTable struct { Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Type string `json:"type" xorm:"type"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` FormTemplate string `json:"formTemplate" xorm:"form_template"` @@ -16,6 +17,8 @@ type TaskTemplateTable struct { UpdatedBy string `json:"updatedBy" xorm:"updated_by"` UpdatedTime string `json:"updatedTime" xorm:"updated_time"` DelFlag int `json:"delFlag" xorm:"del_flag"` + Sort int `json:"sort" xorm:"sort"` + RoleType string `json:"roleType" xorm:"role_type"` } type TaskTemplateVo struct { @@ -25,14 +28,19 @@ type TaskTemplateVo struct { } type TaskTemplateRoleTable struct { - Id string `json:"id" xorm:"'id' pk" primary-key:"id"` - TaskTemplate string `json:"taskTemplate" xorm:"task_template"` - Role string `json:"role" xorm:"role"` - RoleType string `json:"roleType" xorm:"role_type"` + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + TaskTemplate string `json:"taskTemplate" xorm:"task_template"` + Role string `json:"role" xorm:"role"` + RoleType string `json:"roleType" xorm:"role_type"` + CustomRoleType string `json:"customRoleType" xorm:"custom_role_type"` + HandlerType string `json:"handlerType" xorm:"handler_type"` + CustomRole string `json:"customRole" xorm:"custom_role"` + Handler string `json:"handler" xorm:"handler"` } type TaskTemplateDto struct { Id string `json:"id"` + Type string `json:"type"` NodeId string `json:"nodeId"` NodeDefId string `json:"nodeDefId"` NodeDefName string `json:"nodeDefName"` @@ -48,4 +56,42 @@ type TaskTemplateDto struct { USERoleObjs []*RoleTable `json:"useRoleObjs"` Items []*FormItemTemplateTable `json:"items"` RequestTemplateId string `json:"requestTemplateId"` + Sort int `json:"sort"` + RoleType string `json:"roleType"` + RoleObjs []*TaskTemplateRoleDto `json:"roleObjs"` +} + +type TaskTemplateRoleDto struct { + RoleType string `json:"roleType"` + HandlerType string `json:"handlerType"` + Role string `json:"role"` + Handler string `json:"handler"` +} + +type CustomTaskTemplateIdObj struct { + Id string `json:"id"` + Sort int `json:"sort"` + Name string `json:"name"` +} + +type CustomTaskTemplateCreateParam struct { + Sort int `json:"sort"` + RequestTemplate string `json:"requestTemplate"` + Name string `json:"name"` +} + +type CustomTaskTemplateCreateResponse struct { + Id string `json:"id"` + Sort int `json:"sort"` + RequestTemplate string `json:"requestTemplate"` + Name string `json:"name"` + Ids []*CustomTaskTemplateIdObj `json:"ids"` +} + +type CustomTaskTemplateDeleteResponse struct { + Ids []*CustomTaskTemplateIdObj `json:"ids"` +} + +type CustomTaskTemplateListIdsResponse struct { + Ids []*CustomTaskTemplateIdObj `json:"ids"` } diff --git a/taskman-server/service/approval_service.go b/taskman-server/service/approval_service.go new file mode 100644 index 00000000..90a4f866 --- /dev/null +++ b/taskman-server/service/approval_service.go @@ -0,0 +1,31 @@ +package service + +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" +) + +type ApprovalService struct { + approvalDao dao.ApprovalDao + approvalRoleDao dao.ApprovalRoleDao +} + +func (s *ApprovalService) CreateApprovals(param []*models.ApprovalDto) ([]*dao.ExecAction, error) { + actions := []*dao.ExecAction{} + return actions, nil +} + +func (s *ApprovalService) UpdateApprovals(param []*models.ApprovalDto) ([]*dao.ExecAction, error) { + actions := []*dao.ExecAction{} + return actions, nil +} + +func (s *ApprovalService) DeleteApprovals(param []*models.ApprovalDto) ([]*dao.ExecAction, error) { + actions := []*dao.ExecAction{} + return actions, nil +} + +func (s *ApprovalService) ListApproval(requestId string) ([]*models.ApprovalDto, error) { + result := []*models.ApprovalDto{} + return result, nil +} diff --git a/taskman-server/service/approval_template_service.go b/taskman-server/service/approval_template_service.go new file mode 100644 index 00000000..300f460e --- /dev/null +++ b/taskman-server/service/approval_template_service.go @@ -0,0 +1,40 @@ +package service + +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" +) + +type ApprovalTemplateService struct { + approvalTemplateDao dao.ApprovalTemplateDao + approvalTemplateRoleDao dao.ApprovalTemplateRoleDao +} + +func (s *ApprovalTemplateService) CreateApprovalTemplate(param *models.ApprovalTemplateCreateParam) (*models.ApprovalTemplateCreateResponse, error) { + result := &models.ApprovalTemplateCreateResponse{} + return result, nil +} + +func (s *ApprovalTemplateService) UpdateApprovalTemplate(param *models.ApprovalTemplateDto) error { + return nil +} + +func (s *ApprovalTemplateService) DeleteApprovalTemplate(id string) (*models.ApprovalTemplateDeleteResponse, error) { + result := &models.ApprovalTemplateDeleteResponse{} + return result, nil +} + +func (s *ApprovalTemplateService) GetApprovalTemplate(id string) (*models.ApprovalTemplateDto, error) { + result := &models.ApprovalTemplateDto{} + return result, nil +} + +func (s *ApprovalTemplateService) ListApprovalTemplateIds(requestTemplateId string) (*models.ApprovalTemplateListIdsResponse, error) { + result := &models.ApprovalTemplateListIdsResponse{} + return result, nil +} + +func (s *ApprovalTemplateService) ListApprovalTemplate(requestTemplateId string) ([]*models.ApprovalTemplateDto, error) { + result := []*models.ApprovalTemplateDto{} + return result, nil +} diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index 2607f10c..e6c71fa6 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -36,6 +36,10 @@ var ( taskTemplateService TaskTemplateService // 角色 service roleService RoleService + // 审批模板 service + approvalTemplateService *ApprovalTemplateService + // 审批 service + approvalService *ApprovalService ) func New() (err error) { @@ -58,8 +62,13 @@ func New() (err error) { requestTemplateGroupDao := dao.RequestTemplateGroupDao{DB: engine} requestTemplateRoleDao := dao.RequestTemplateRoleDao{DB: engine} taskDao := dao.TaskDao{DB: engine} + taskRoleDao := dao.TaskRoleDao{DB: engine} taskTemplateDao := dao.TaskTemplateDao{DB: engine} taskTemplateRoleDao := dao.TaskTemplateRoleDao{DB: engine} + approvalTemplateDao := dao.ApprovalTemplateDao{DB: engine} + approvalTemplateRoleDao := dao.ApprovalTemplateRoleDao{DB: engine} + approvalDao := dao.ApprovalDao{DB: engine} + approvalRoleDao := dao.ApprovalRoleDao{DB: engine} // 初始化Service collectTemplateService = CollectTemplateService{collectTemplateDao: collectTemplateDao} requestService = RequestService{requestDao: requestDao} @@ -68,7 +77,7 @@ func New() (err error) { procDefService = ProcDefService{} refSelectService = RefSelectService{} requestService = RequestService{requestDao: requestDao} - taskService = TaskService{taskDao: taskDao} + taskService = TaskService{taskDao: taskDao, taskRoleDao: taskRoleDao} taskTemplateService = TaskTemplateService{taskTemplateDao: taskTemplateDao, taskTemplateRoleDao: taskTemplateRoleDao} formService = FormService{formDao: formDao, formItemDao: formItemDao} requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao, operationLogDao: operationLogDao, requestTemplateRoleDao: requestTemplateRoleDao} @@ -76,6 +85,8 @@ func New() (err error) { formTemplateService = FormTemplateService{formTemplateDao: formTemplateDao, formItemTemplateDao: formItemTemplateDao, formDao: formDao} formItemTemplateService = FormItemTemplateService{formItemTemplateDao: formItemTemplateDao} roleService = RoleService{} + approvalTemplateService = &ApprovalTemplateService{approvalTemplateDao: approvalTemplateDao, approvalTemplateRoleDao: approvalTemplateRoleDao} + approvalService = &ApprovalService{approvalDao: approvalDao, approvalRoleDao: approvalRoleDao} db = engine return } @@ -140,6 +151,16 @@ func GetRoleService() RoleService { return roleService } +// GetApprovalTemplateService 获取审批模板 service +func GetApprovalTemplateService() *ApprovalTemplateService { + return approvalTemplateService +} + +// GetApprovalService 获取审批 service +func GetApprovalService() *ApprovalService { + return approvalService +} + // GetRequestTemplateGroupService 获取请求模板组 service func GetRequestTemplateGroupService() RequestTemplateGroupService { return requestTemplateGroupService diff --git a/taskman-server/service/task_service.go b/taskman-server/service/task_service.go index e663bb0f..592f34fc 100644 --- a/taskman-server/service/task_service.go +++ b/taskman-server/service/task_service.go @@ -17,6 +17,7 @@ import ( type TaskService struct { taskDao dao.TaskDao + taskRoleDao dao.TaskRoleDao } func GetTaskFormStruct(procInstId, nodeDefId string) (result models.TaskMetaResult, err error) { @@ -848,3 +849,23 @@ func GetSimpleTask(taskId string) (task models.TaskTable, err error) { task = *taskTable[0] return } + +func (s TaskService) CreateTasks(param []*models.TaskDto) ([]*dao.ExecAction, error) { + actions := []*dao.ExecAction{} + return actions, nil +} + +func (s TaskService) UpdateTasks(param []*models.TaskDto) ([]*dao.ExecAction, error) { + actions := []*dao.ExecAction{} + return actions, nil +} + +func (s TaskService) DeleteTasks(param []*models.TaskDto) ([]*dao.ExecAction, error) { + actions := []*dao.ExecAction{} + return actions, nil +} + +func (s TaskService) ListTask(requestId string) ([]*models.TaskDto, error) { + result := []*models.TaskDto{} + return result, nil +} diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 9f5978c6..ded8b751 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -240,3 +240,32 @@ func GetTaskTemplateMapByRequestTemplate(requestTemplate string) (taskTemplateMa } return } + +func (s TaskTemplateService) CreateCustomTaskTemplate(param *models.CustomTaskTemplateCreateParam) (*models.CustomTaskTemplateCreateResponse, error) { + result := &models.CustomTaskTemplateCreateResponse{} + return result, nil +} + +func (s TaskTemplateService) UpdateCustomTaskTemplate(param *models.TaskTemplateDto) error { + return nil +} + +func (s TaskTemplateService) DeleteCustomTaskTemplate(id string) (*models.CustomTaskTemplateDeleteResponse, error) { + result := &models.CustomTaskTemplateDeleteResponse{} + return result, nil +} + +func (s TaskTemplateService) GetCustomTaskTemplate(id string) (*models.TaskTemplateDto, error) { + result := &models.TaskTemplateDto{} + return result, nil +} + +func (s TaskTemplateService) ListCustomTaskTemplateIds(requestTemplateId string) (*models.CustomTaskTemplateListIdsResponse, error) { + result := &models.CustomTaskTemplateListIdsResponse{} + return result, nil +} + +func (s TaskTemplateService) ListCustomTaskTemplate(requestTemplateId string) ([]*models.TaskTemplateDto, error) { + result := []*models.TaskTemplateDto{} + return result, nil +} From b02e1aa4ef2169e87e98f0ea974303250c6d040a Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Thu, 22 Feb 2024 19:12:11 +0800 Subject: [PATCH 042/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E8=A1=A8=E5=8D=95=E7=BB=84=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/form/form_template.go | 43 +------- taskman-server/dao/form_item_template_dao.go | 6 ++ taskman-server/models/form_item_template.go | 8 ++ .../service/form_item_template_service.go | 99 +++++++++++++++---- .../service/form_template_service.go | 15 ++- 5 files changed, 107 insertions(+), 64 deletions(-) diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index c7c7e7c6..f4091b79 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -143,22 +143,10 @@ func GetDataFormTemplateItemGroupConfig(c *gin.Context) { formTemplateId := c.Query("form-template-id") itemGroupName := c.Query("item-group-name") requestTemplateId := c.Query("request-template-id") - if itemGroupName == "" || requestTemplateId == "" { - middleware.ReturnParamEmptyError(c, "request-template-id or item-group-name") + if itemGroupName == "" || requestTemplateId == "" || formTemplateId == "" { + middleware.ReturnParamEmptyError(c, "request-template-id or item-group-name or form-template-id") return } - // formTemplateId 为空,查询数据表单模板是否为空,为空则新建(只有数据表单的formTemplateId会传递"",任务和审批表单不会) - if formTemplateId == "" { - formTemplateId, err = createDataFormTemplate(requestTemplateId) - if err != nil { - middleware.ReturnServerHandleError(c, err) - return - } - if formTemplateId == "" { - middleware.ReturnParamEmptyError(c, "form-template-id") - return - } - } configureDto, err = service.GetFormTemplateService().GetDataFormConfig(formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) @@ -288,31 +276,6 @@ func CopyDataFormTemplateItemGroup(c *gin.Context) { middleware.ReturnSuccess(c) } -// createDataFormTemplate 创建数据表单 -func createDataFormTemplate(requestTemplateId string) (formTemplateId string, err error) { - var requestTemplate *models.RequestTemplateTable - requestTemplate, err = service.GetRequestTemplateService().GetRequestTemplate(requestTemplateId) - if err != nil { - return - } - if requestTemplate == nil { - err = fmt.Errorf("param request-template-id is vailid") - return - } - // 新建数据表单 - if requestTemplate.DataFormTemplate == "" { - err = service.GetFormTemplateService().CreateDataFormTemplate(models.DataFormTemplateDto{}, requestTemplateId) - if err != nil { - return - } - requestTemplate, _ = service.GetRequestTemplateService().GetRequestTemplate(requestTemplateId) - formTemplateId = requestTemplate.DataFormTemplate - } else { - err = fmt.Errorf("form-template-id is empty") - } - return -} - func validateFormTemplateItemGroupConfigParam(param models.FormTemplateGroupConfigureDto) error { if param.RequestTemplateId == "" { return fmt.Errorf("param RequestTemplateId is empty") @@ -320,7 +283,7 @@ func validateFormTemplateItemGroupConfigParam(param models.FormTemplateGroupConf if param.FormTemplateId == "" { return fmt.Errorf("param FormTemplateId is empty") } - if param.ItemGroup == "" || param.ItemGroupType == "" || param.ItemGroupName == "" || param.ItemGroupRule == "" { + if param.ItemGroupType == "" || param.ItemGroupName == "" || param.ItemGroupRule == "" { return fmt.Errorf("param ItemGroup is empty") } if len(param.CustomItems) > 0 { diff --git a/taskman-server/dao/form_item_template_dao.go b/taskman-server/dao/form_item_template_dao.go index 11e1d1b4..21ac8311 100644 --- a/taskman-server/dao/form_item_template_dao.go +++ b/taskman-server/dao/form_item_template_dao.go @@ -65,6 +65,12 @@ func (d FormItemTemplateDao) QueryByFormTemplateAndItemGroupName(formTemplate, i return } +func (d FormItemTemplateDao) QueryByFormTemplateAndItemGroup(formTemplate, itemGroup string) (formItemTemplate []*models.FormItemTemplateTable, err error) { + formItemTemplate = []*models.FormItemTemplateTable{} + err = d.DB.Where("form_template = ? and item_group = ?", formTemplate, itemGroup).Find(&formItemTemplate) + return +} + func (d FormItemTemplateDao) DeleteByIdOrCopyId(session *xorm.Session, id string) (err error) { var affected int64 if session == nil { diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index dba75a3d..b4eb4c08 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -57,3 +57,11 @@ func (s FormItemTemplateTableSort) Less(i, j int) bool { } return false } + +func ConvertFormItemTemplateList2Map(formItemTemplateList []*FormItemTemplateTable) map[string]*FormItemTemplateTable { + hashMap := make(map[string]*FormItemTemplateTable) + for _, table := range formItemTemplateList { + hashMap[table.Id] = table + } + return hashMap +} diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index c2ed8454..6d061211 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -1,12 +1,16 @@ package service import ( + "fmt" + "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "xorm.io/xorm" ) +const defaultCustomFormItemName = "taskman-custom-form" + type FormItemTemplateService struct { formItemTemplateDao dao.FormItemTemplateDao } @@ -22,6 +26,10 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. if len(param.CustomItems) == 0 { param.CustomItems = []*models.FormItemTemplateTable{} } + // 自定义类型 单独处理 + if param.ItemGroupType == string(models.FormItemGroupTypeCustom) { + return s.UpdateFormTemplateCustomItemGroupConfig(param) + } // 1. 查询表单组是否存在,不存在则新增 formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(param.FormTemplateId, param.ItemGroupName) if err != nil { @@ -76,33 +84,84 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. } } } - err = transaction(func(session *xorm.Session) error { - if len(insertItems) > 0 { - for _, item := range insertItems { - _, err = s.formItemTemplateDao.Add(session, item) - if err != nil { - return err + if len(insertItems) > 0 || len(updateItems) > 0 || len(deleteItems) > 0 { + err = transaction(func(session *xorm.Session) error { + if len(insertItems) > 0 { + for _, item := range insertItems { + _, err = s.formItemTemplateDao.Add(session, item) + if err != nil { + return err + } } } - } - if len(updateItems) > 0 { - for _, item := range updateItems { - err = s.formItemTemplateDao.Update(session, item) - if err != nil { - return err + if len(updateItems) > 0 { + for _, item := range updateItems { + err = s.formItemTemplateDao.Update(session, item) + if err != nil { + return err + } } } - } - if len(deleteItems) > 0 { - for _, item := range deleteItems { - err = s.formItemTemplateDao.Delete(session, item.Id) - if err != nil { - return err + if len(deleteItems) > 0 { + for _, item := range deleteItems { + err = s.formItemTemplateDao.Delete(session, item.Id) + if err != nil { + return err + } } } + return err + }) + } + return +} + +func (s FormItemTemplateService) UpdateFormTemplateCustomItemGroupConfig(param models.FormTemplateGroupConfigureDto) (err error) { + var formItemTemplateList, tempFormItemTemplateList []*models.FormItemTemplateTable + var addFormItemTemplate *models.FormItemTemplateTable + // 1. 查询表单组是否存在,不存在则新增 + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroup(param.FormTemplateId, param.ItemGroup) + if err != nil { + return + } + if len(formItemTemplateList) == 0 { + formItemTemplateList = []*models.FormItemTemplateTable{} + } + formItemTemplateMap := models.ConvertFormItemTemplateList2Map(formItemTemplateList) + tempFormItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(param.FormTemplateId, param.ItemGroupName) + if err != nil { + return + } + + if len(tempFormItemTemplateList) > 0 { + if len(tempFormItemTemplateList) != len(formItemTemplateList) { + err = fmt.Errorf("itemGroupName:%s has exisit", param.ItemGroupName) + return } - return err - }) + for _, tempFormItemTemplate := range tempFormItemTemplateList { + if formItemTemplateMap[tempFormItemTemplate.Id] == nil { + err = fmt.Errorf("itemGroupName:%s has exisit", param.ItemGroupName) + return + } + } + } + if len(formItemTemplateList) > 0 { + // 更新模板 + for _, formItemTemplate := range formItemTemplateList { + formItemTemplate.ItemGroupName = param.ItemGroupName + formItemTemplate.ItemGroupRule = param.ItemGroupRule + formItemTemplate.ItemGroupType = param.ItemGroupType + err = s.formItemTemplateDao.Update(nil, formItemTemplate) + if err != nil { + return err + } + } + } else { + // 新增自定义组,同时给一个初始化假数据(后续更新模板组时候删除掉) + addFormItemTemplate = &models.FormItemTemplateTable{Id: guid.CreateGuid(), Name: defaultCustomFormItemName, ItemGroup: guid.CreateGuid(), ItemGroupName: param.ItemGroupName, + ItemGroupType: param.ItemGroupType, ItemGroupRule: param.ItemGroupRule, FormTemplate: param.FormTemplateId} + _, err = s.formItemTemplateDao.Add(nil, addFormItemTemplate) + } return } diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index a9cd8ff8..d975dcd0 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -141,6 +141,14 @@ func (s FormTemplateService) GetDataFormTemplate(requestTemplateId string) (resu if strings.TrimSpace(requestTemplate.ProcDefId) != "" { associationWorkflow = true } + // 新增数据表单 + if requestTemplate.DataFormTemplate == "" { + err = s.CreateDataFormTemplate(models.DataFormTemplateDto{}, requestTemplateId) + if err != nil { + return + } + requestTemplate, _ = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) + } result = &models.DataFormTemplateDto{DataFormTemplateId: requestTemplate.DataFormTemplate, Groups: make([]*models.FormTemplateGroupDto, 0), AssociationWorkflow: associationWorkflow} result.Groups, err = s.getFormTemplateGroups(requestTemplate.DataFormTemplate) return @@ -173,6 +181,9 @@ func (s FormTemplateService) getFormTemplateGroups(formTemplateId string) (group for itemGroup, formItemTemplateArr := range itemGroupMap { for _, formItemTemplate := range formItemTemplateList { if itemGroup == formItemTemplate.ItemGroup { + if formItemTemplate.ItemGroupType == string(models.FormItemGroupTypeCustom) && formItemTemplate.Name == defaultCustomFormItemName { + continue + } formItemTemplateArr = append(formItemTemplateArr, formItemTemplate) } } @@ -435,7 +446,3 @@ func (s FormTemplateService) GetDataFormConfig(formTemplateId, itemGroupName, us } return } - -func (s FormTemplateService) CopyDataFormTemplateItemGroup(formTemplateId, itemGroupName string) { - -} From 49b9c2d28419a50fc91855e7bb490ba1fac22f21 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Thu, 22 Feb 2024 19:54:57 +0800 Subject: [PATCH 043/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E3=80=81=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E8=A1=A8=E5=8D=95=E7=BB=84=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dao/form_item_template_group_dao.go | 51 +++++++++++++++++++ taskman-server/models/form_item_template.go | 37 ++++++++++++++ .../models/form_item_template_group.go | 13 +++++ 3 files changed, 101 insertions(+) create mode 100644 taskman-server/dao/form_item_template_group_dao.go create mode 100644 taskman-server/models/form_item_template_group.go diff --git a/taskman-server/dao/form_item_template_group_dao.go b/taskman-server/dao/form_item_template_group_dao.go new file mode 100644 index 00000000..41d7e470 --- /dev/null +++ b/taskman-server/dao/form_item_template_group_dao.go @@ -0,0 +1,51 @@ +package dao + +import ( + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "xorm.io/xorm" +) + +type FormItemTemplateGroupDao struct { + DB *xorm.Engine +} + +func (d FormItemTemplateGroupDao) Add(session *xorm.Session, formItemTemplate *models.FormItemTemplateGroupTable) (affected int64, err error) { + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + affected, err = session.Insert(formItemTemplate) + // 打印日志 + logExecuteSql(session, "FormItemTemplateGroupDao", "Add", formItemTemplate, affected, err) + return +} + +func (d FormItemTemplateGroupDao) Update(session *xorm.Session, formItemTemplateGroup *models.FormItemTemplateGroupTable) (err error) { + var affected int64 + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + if formItemTemplateGroup.Id == "" { + return + } + affected, err = session.ID(formItemTemplateGroup.Id).Update(formItemTemplateGroup) + // 打印日志 + logExecuteSql(session, "FormItemTemplateDao", "Update", formItemTemplateGroup, affected, err) + return +} + +func (d FormItemTemplateGroupDao) Get(formItemTemplateGroupId string) (*models.FormItemTemplateTable, error) { + var formItemTemplate *models.FormItemTemplateTable + var found bool + var err error + formItemTemplate = &models.FormItemTemplateTable{} + found, err = d.DB.ID(formItemTemplateGroupId).Get(formItemTemplate) + if err != nil { + return nil, err + } + if found { + return formItemTemplate, nil + } + return nil, nil +} diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index b4eb4c08..a1788ddb 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -37,6 +37,43 @@ type FormItemTemplateTable struct { Active bool `json:"active" xorm:"-"` // 是否选中状态 } +type FormItemTemplateDto struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + ItemGroup string `json:"itemGroup"` + ItemGroupType string `json:"itemGroupType"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 + ItemGroupName string `json:"itemGroupName"` + ItemGroupSort int `json:"ItemGroupSort"` // item_group 排序 + ItemGroupRule string `json:"itemGroupRule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 + FormTemplate string `json:"formTemplate"` + DefaultValue string `json:"defaultValue"` + Sort int `json:"sort"` + PackageName string `json:"packageName"` + Entity string `json:"entity"` + AttrDefId string `json:"attrDefId"` + AttrDefName string `json:"attrDefName"` + AttrDefDataType string `json:"attrDefDataType"` + ElementType string `json:"elementType"` + Title string `json:"title"` + Width int `json:"width"` + RefPackageName string `json:"refPackageName"` + RefEntity string `json:"refEntity"` + DataOptions string `json:"dataOptions"` + Required string `json:"required"` + Regular string `json:"regular"` + IsEdit string `json:"isEdit"` + IsView string `json:"isView"` + IsOutput string `json:"isOutput"` + InDisplayName string `json:"inDisplayName"` + IsRefInside string `json:"isRefInside"` + Multiple string `json:"multiple"` + DefaultClear string `json:"defaultClear"` + CopyId string `json:"copyId"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 + SelectList []*EntityDataObj `json:"selectList"` + Active bool `json:"active"` // 是否选中状态 +} + func (FormItemTemplateTable) TableName() string { return "form_item_template" } diff --git a/taskman-server/models/form_item_template_group.go b/taskman-server/models/form_item_template_group.go new file mode 100644 index 00000000..3d4ace1d --- /dev/null +++ b/taskman-server/models/form_item_template_group.go @@ -0,0 +1,13 @@ +package models + +type FormItemTemplateGroupTable struct { + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + ItemGroup string `json:"itemGroup" xorm:"item_group"` + ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 + ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` + ItemGroupSort int `json:"ItemGroupSort" xorm:"item_group_sort"` // item_group 排序 + ItemGroupRule string `json:"itemGroupRule" xorm:"item_group_rule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 + FormTemplate string `json:"formTemplate" xorm:"form_template"` +} From dbe8450acfdd3b8e894ea344c75cb85754fbe3f3 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Thu, 22 Feb 2024 21:39:35 +0800 Subject: [PATCH 044/618] =?UTF-8?q?=E5=AE=A1=E6=89=B9=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=A2=9E/=E6=94=B9/=E5=88=97=E8=A1=A8=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/const.go | 31 +++ .../service/approval_template_service.go | 195 +++++++++++++++++- 2 files changed, 225 insertions(+), 1 deletion(-) diff --git a/taskman-server/models/const.go b/taskman-server/models/const.go index 88b71d01..011e7cb3 100644 --- a/taskman-server/models/const.go +++ b/taskman-server/models/const.go @@ -89,3 +89,34 @@ const ( FormItemElementTypeSelect FormItemElementType = "select" FormItemElementTypeCalculate FormItemElementType = "calculate" //计算类型 ) + +// ApprovalTemplateRoleType 审批模板 分配方式 +type ApprovalTemplateRoleType string + +const ( + ApprovalTemplateRoleTypeCustom ApprovalTemplateRoleType = "custom" // 单人自定义 + ApprovalTemplateRoleTypeAny ApprovalTemplateRoleType = "any" // 协同 + ApprovalTemplateRoleTypeAll ApprovalTemplateRoleType = "all" // 并行 + ApprovalTemplateRoleTypeAdmin ApprovalTemplateRoleType = "admin" // 提交人角色管理员 + ApprovalTemplateRoleTypeAuto ApprovalTemplateRoleType = "auto" // 自动通过 +) + +// ApprovalTemplateRoleRoleType 审批处理模板 角色设置方式 +type ApprovalTemplateRoleRoleType string + +const ( + ApprovalTemplateRoleRoleTypeTemplate ApprovalTemplateRoleRoleType = "template" // 模板指定 + ApprovalTemplateRoleRoleTypeCustom ApprovalTemplateRoleRoleType = "custom" // 提交人指定 +) + +// ApprovalTemplateRoleHandlerType 审批处理模板 人员设置方式 +type ApprovalTemplateRoleHandlerType string + +const ( + ApprovalTemplateRoleHandlerTypeTemplate ApprovalTemplateRoleHandlerType = "template" // 模板指定 + ApprovalTemplateRoleHandlerTypeTemplateSuggest ApprovalTemplateRoleHandlerType = "template_suggest" // 模板建议 + ApprovalTemplateRoleHandlerTypeCustom ApprovalTemplateRoleHandlerType = "custom" // 提交人指定 + ApprovalTemplateRoleHandlerTypeCustomSuggest ApprovalTemplateRoleHandlerType = "custom_suggest" // 提交人建议 + ApprovalTemplateRoleHandlerTypeSystem ApprovalTemplateRoleHandlerType = "system" // 组内系统分配 + ApprovalTemplateRoleHandlerTypeClaim ApprovalTemplateRoleHandlerType = "claim" // 组内主动认领 +) diff --git a/taskman-server/service/approval_template_service.go b/taskman-server/service/approval_template_service.go index 300f460e..ef46bef1 100644 --- a/taskman-server/service/approval_template_service.go +++ b/taskman-server/service/approval_template_service.go @@ -1,6 +1,12 @@ package service import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" ) @@ -11,11 +17,144 @@ type ApprovalTemplateService struct { } func (s *ApprovalTemplateService) CreateApprovalTemplate(param *models.ApprovalTemplateCreateParam) (*models.ApprovalTemplateCreateResponse, error) { - result := &models.ApprovalTemplateCreateResponse{} + actions := []*dao.ExecAction{} + // 查询现有审批模板列表 + var approvalTemplates []*models.ApprovalTemplateTable + err := s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE request_template = ? ORDER BY sort", param.RequestTemplate).Find(&approvalTemplates) + if err != nil { + return nil, err + } + // 插入新审批模板 + nowTime := time.Now().Format(models.DateTimeFormat) + newApprovalTemplate := &models.ApprovalTemplateTable{ + Id: guid.CreateGuid(), + Sort: param.Sort, + RequestTemplate: param.RequestTemplate, + Name: param.Name, + RoleType: string(models.ApprovalTemplateRoleTypeCustom), + CreatedTime: nowTime, + UpdatedTime: nowTime, + } + action := &dao.ExecAction{Sql: "INSERT INTO approval_template (id,sort,request_template,name,expire_day,role_type,created_time,updated_time) VALUES (?,?,?,?,?,?,?,?)"} + action.Param = []interface{}{newApprovalTemplate.Id, newApprovalTemplate.Sort, newApprovalTemplate.RequestTemplate, newApprovalTemplate.Name, newApprovalTemplate.ExpireDay, newApprovalTemplate.RoleType, newApprovalTemplate.CreatedTime, newApprovalTemplate.UpdatedTime} + actions = append(actions, action) + // 插入新审批处理模板 + newApprovalTemplateRole := &models.ApprovalTemplateRoleTable{ + Id: guid.CreateGuid(), + Sort: 1, + ApprovalTemplate: newApprovalTemplate.Id, + RoleType: string(models.ApprovalTemplateRoleRoleTypeTemplate), + HandlerType: string(models.ApprovalTemplateRoleHandlerTypeTemplate), + } + action = &dao.ExecAction{Sql: "INSERT INTO approval_template_role (id,sort,approval_template,role_type,handler_type) VALUES (?,?,?,?,?)"} + action.Param = []interface{}{newApprovalTemplateRole.Id, newApprovalTemplateRole.Sort, newApprovalTemplateRole.ApprovalTemplate, newApprovalTemplateRole.RoleType, newApprovalTemplateRole.HandlerType} + actions = append(actions, action) + // 如果不是尾插,则需更新现有数据的序号 + if param.Sort != len(approvalTemplates)+1 { + for i := param.Sort; i < len(approvalTemplates)+1; i++ { + t := approvalTemplates[i-1] + t.Sort += 1 + t.UpdatedTime = nowTime + action = &dao.ExecAction{Sql: "UPDATE approval_template SET sort = ?, update_time = ? WHERE id = ?"} + action.Param = []interface{}{t.Sort, t.UpdatedTime, t.Id} + actions = append(actions, action) + } + tmp := append(approvalTemplates[:param.Sort-1], newApprovalTemplate) + approvalTemplates = append(tmp, approvalTemplates[param.Sort-1:]...) + } + // 执行事务 + err = dao.Transaction(actions) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.ApprovalTemplateCreateResponse{ + Id: newApprovalTemplate.Id, + Sort: newApprovalTemplate.Sort, + RequestTemplate: newApprovalTemplate.RequestTemplate, + Name: newApprovalTemplate.Name, + Ids: make([]*models.ApprovalTemplateIdObj, len(approvalTemplates)), + } + for i, approvalTemplate := range approvalTemplates { + result.Ids[i] = &models.ApprovalTemplateIdObj{ + Id: approvalTemplate.Id, + Sort: approvalTemplate.Sort, + Name: approvalTemplate.Name, + } + } return result, nil } func (s *ApprovalTemplateService) UpdateApprovalTemplate(param *models.ApprovalTemplateDto) error { + actions := []*dao.ExecAction{} + // 查询现有审批模板 + var approvalTemplates []*models.ApprovalTemplateTable + err := s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE id = ?", param.Id).Find(&approvalTemplates) + if err != nil { + return err + } + if len(approvalTemplates) == 0 { + return errors.New("no approval_template record found") + } + approvalTemplate := approvalTemplates[0] + // 校验参数 + if approvalTemplate.Sort != param.Sort || approvalTemplate.RequestTemplate != param.RequestTemplate { + return errors.New("param sort or requestTemplate wrong") + } + for _, roleObj := range param.RoleObjs { + if roleObj.RoleType != string(models.ApprovalTemplateRoleRoleTypeTemplate) && + (roleObj.HandlerType == string(models.ApprovalTemplateRoleHandlerTypeTemplate) || roleObj.HandlerType == string(models.ApprovalTemplateRoleHandlerTypeTemplateSuggest)) { + return fmt.Errorf("roleType %s not match handlerType %s", roleObj.RoleType, roleObj.HandlerType) + } + if roleObj.RoleType != string(models.ApprovalTemplateRoleRoleTypeTemplate) && roleObj.Role != "" { + return fmt.Errorf("roleType %s not match role %s", roleObj.RoleType, roleObj.Role) + } + if roleObj.HandlerType != string(models.ApprovalTemplateRoleHandlerTypeTemplate) && roleObj.HandlerType != string(models.ApprovalTemplateRoleHandlerTypeTemplateSuggest) && roleObj.Handler != "" { + return fmt.Errorf("handlerType %s not match handler %s", roleObj.HandlerType, roleObj.Handler) + } + } + // 更新现有审批模板 + nowTime := time.Now().Format(models.DateTimeFormat) + action := &dao.ExecAction{Sql: "UPDATE approval_template SET name = ?, expire_day = ?, description = ?, role_type = ?, update_time = ? WHERE id = ?"} + action.Param = []interface{}{param.Name, param.ExpireDay, param.Description, param.RoleType, nowTime, param.Id} + actions = append(actions, action) + // 增删改现有审批处理模板 + if param.RoleType == string(models.ApprovalTemplateRoleTypeAdmin) || param.RoleType == string(models.ApprovalTemplateRoleTypeAuto) { + action = &dao.ExecAction{Sql: "DELETE FROM approval_template_role WHERE approval_template = ?"} + action.Param = []interface{}{param.Id} + actions = append(actions, action) + } else { + // 查询现有审批处理模板 + var approvalTemplateRoles []*models.ApprovalTemplateRoleTable + err = s.approvalTemplateRoleDao.DB.SQL("SELECT * FROM approval_template_role WHERE approval_template = ? ORDER BY sort", param.Id).Find(&approvalTemplateRoles) + if err != nil { + return err + } + // 对比增删改 + for i, approvalTemplateRole := range approvalTemplateRoles { + if i < len(param.RoleObjs) { + roleObj := param.RoleObjs[i] + action = &dao.ExecAction{Sql: "UPDATE approval_template_role SET role_type = ?, handler_type = ?, role = ?, handler = ? WHERE id = ?"} + action.Param = []interface{}{roleObj.RoleType, roleObj.HandlerType, roleObj.Role, roleObj.Handler, approvalTemplateRole.Id} + actions = append(actions, action) + } else { + action = &dao.ExecAction{Sql: "DELETE FROM approval_template_role WHERE id = ?"} + action.Param = []interface{}{approvalTemplateRole.Id} + actions = append(actions, action) + } + } + for sort := len(approvalTemplateRoles) + 1; sort <= len(param.RoleObjs); sort++ { + roleObj := param.RoleObjs[sort-1] + action = &dao.ExecAction{Sql: "INSERT INTO approval_template_role (id,sort,approval_template,role_type,handler_type,role,handler) VALUES (?,?,?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), sort, param.Id, roleObj.RoleType, roleObj.HandlerType, roleObj.Role, roleObj.Handler} + actions = append(actions, action) + } + } + // 执行事务 + err = dao.Transaction(actions) + if err != nil { + return err + } return nil } @@ -36,5 +175,59 @@ func (s *ApprovalTemplateService) ListApprovalTemplateIds(requestTemplateId stri func (s *ApprovalTemplateService) ListApprovalTemplate(requestTemplateId string) ([]*models.ApprovalTemplateDto, error) { result := []*models.ApprovalTemplateDto{} + // 查询现有审批模板列表 + var approvalTemplates []*models.ApprovalTemplateTable + err := s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE request_template = ? ORDER BY sort", requestTemplateId).Find(&approvalTemplates) + if err != nil { + return nil, err + } + if len(approvalTemplates) == 0 { + return result, nil + } + // 汇总审批模板列表 + approvalTemplateIds := make([]string, len(approvalTemplates)) + for i, approvalTemplate := range approvalTemplates { + approvalTemplateIds[i] = approvalTemplate.Id + } + // 查询现有审批处理模板列表 + var approvalTemplateRoles []*models.ApprovalTemplateRoleTable + err = s.approvalTemplateRoleDao.DB.SQL("SELECT * FROM approval_template_role WHERE approval_template IN ('" + strings.Join(approvalTemplateIds, "','") + "') ORDER BY approval_template, sort").Find(&approvalTemplateRoles) + if err != nil { + return nil, err + } + // 汇总审批处理模板列表 + approvalTemplateRoleMap := make(map[string][]*models.ApprovalTemplateRoleTable) + approvalTemplateId := "" + for _, approvalTemplateRole := range approvalTemplateRoles { + if approvalTemplateId != approvalTemplateRole.ApprovalTemplate { + approvalTemplateId = approvalTemplateRole.ApprovalTemplate + approvalTemplateRoleMap[approvalTemplateId] = make([]*models.ApprovalTemplateRoleTable, 0) + } + approvalTemplateRoleMap[approvalTemplateId] = append(approvalTemplateRoleMap[approvalTemplateId], approvalTemplateRole) + } + // 构造返回结果 + result = make([]*models.ApprovalTemplateDto, len(approvalTemplates)) + for i, approvalTemplate := range approvalTemplates { + result[i] = &models.ApprovalTemplateDto{ + Id: approvalTemplate.Id, + Sort: approvalTemplate.Sort, + RequestTemplate: approvalTemplate.RequestTemplate, + Name: approvalTemplate.Name, + ExpireDay: approvalTemplate.ExpireDay, + Description: approvalTemplate.Description, + RoleType: approvalTemplate.RoleType, + } + if roleObjs, ok := approvalTemplateRoleMap[approvalTemplate.Id]; ok { + result[i].RoleObjs = make([]*models.ApprovalTemplateRoleDto, len(roleObjs)) + for j, roleObj := range roleObjs { + result[i].RoleObjs[j] = &models.ApprovalTemplateRoleDto{ + RoleType: roleObj.RoleType, + HandlerType: roleObj.HandlerType, + Role: roleObj.Role, + Handler: roleObj.Handler, + } + } + } + } return result, nil } From 259147a4446865de9ad94de3d0161d93f8fbe2f3 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Thu, 22 Feb 2024 22:30:58 +0800 Subject: [PATCH 045/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E8=B0=83=E6=95=B4,=E6=B7=BB=E5=8A=A0form=5Fitem=5Ftemplate=5Fg?= =?UTF-8?q?roup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/form/form_template.go | 30 ++-- taskman-server/dao/form_item_template_dao.go | 69 +++++++- .../dao/form_item_template_group_dao.go | 25 ++- taskman-server/models/form_item_template.go | 93 +++++++++- .../models/form_item_template_group.go | 7 +- taskman-server/models/form_template.go | 48 ++--- taskman-server/models/task_template.go | 40 ++--- .../service/form_item_template_service.go | 166 ++++++++---------- .../service/form_template_service.go | 108 ++++++------ taskman-server/service/service.go | 3 +- .../service/task_template_service.go | 14 +- 11 files changed, 382 insertions(+), 221 deletions(-) diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index f4091b79..e18a6db2 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -141,13 +141,15 @@ func GetDataFormTemplateItemGroupConfig(c *gin.Context) { var configureDto *models.FormTemplateGroupConfigureDto var err error formTemplateId := c.Query("form-template-id") - itemGroupName := c.Query("item-group-name") + entity := c.Query("entity") + formType := c.Query("form-type") + itemGroupId := c.Query("item-group-id") requestTemplateId := c.Query("request-template-id") - if itemGroupName == "" || requestTemplateId == "" || formTemplateId == "" { - middleware.ReturnParamEmptyError(c, "request-template-id or item-group-name or form-template-id") + if requestTemplateId == "" || formTemplateId == "" { + middleware.ReturnParamEmptyError(c, "request-template-id or item-group-id or form-template-id") return } - configureDto, err = service.GetFormTemplateService().GetDataFormConfig(formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + configureDto, err = service.GetFormTemplateService().GetDataFormConfig(formTemplateId, itemGroupId, formType, entity, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -160,13 +162,13 @@ func GetFormTemplateItemGroupConfig(c *gin.Context) { var configureDto *models.FormTemplateGroupConfigureDto var err error formTemplateId := c.Query("form-template-id") - itemGroupName := c.Query("item-group-name") + itemGroupId := c.Query("item-group-id") requestTemplateId := c.Query("request-template-id") - if itemGroupName == "" || formTemplateId == "" || requestTemplateId == "" { + if itemGroupId == "" || formTemplateId == "" || requestTemplateId == "" { middleware.ReturnParamEmptyError(c, "request-template-id or item-group-name or form-template-id") return } - configureDto, err = service.GetFormTemplateService().GetFormConfig(requestTemplateId, formTemplateId, itemGroupName, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + configureDto, err = service.GetFormTemplateService().GetFormConfig(requestTemplateId, formTemplateId, itemGroupId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -247,12 +249,12 @@ func SortFormTemplateItemGroup(c *gin.Context) { // DeleteFormTemplateItemGroup 删除表单组 func DeleteFormTemplateItemGroup(c *gin.Context) { formTemplateId := c.Query("form-template-id") - itemGroupName := c.Query("item-group-name") - if formTemplateId == "" || itemGroupName == "" { - middleware.ReturnParamEmptyError(c, "form-template-id or item-group-name") + itemGroupId := c.Query("item-group-id") + if formTemplateId == "" || itemGroupId == "" { + middleware.ReturnParamEmptyError(c, "form-template-id or item-group-id") return } - err := service.GetFormItemTemplateService().DeleteFormTemplateItemGroup(formTemplateId, itemGroupName) + err := service.GetFormItemTemplateService().DeleteFormTemplateItemGroup(formTemplateId, itemGroupId) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -263,12 +265,12 @@ func DeleteFormTemplateItemGroup(c *gin.Context) { // CopyDataFormTemplateItemGroup 数据表单模板组copy func CopyDataFormTemplateItemGroup(c *gin.Context) { formTemplateId := c.Query("form-template-id") - itemGroupName := c.Query("item-group-name") - if formTemplateId == "" || itemGroupName == "" { + itemGroupId := c.Query("item-group-id") + if formTemplateId == "" || itemGroupId == "" { middleware.ReturnParamEmptyError(c, "form-template-id or item-group-name") return } - err := service.GetFormItemTemplateService().CopyDataFormTemplateItemGroup(formTemplateId, itemGroupName) + err := service.GetFormItemTemplateService().CopyDataFormTemplateItemGroup(formTemplateId, itemGroupId) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/dao/form_item_template_dao.go b/taskman-server/dao/form_item_template_dao.go index 21ac8311..2b0165e9 100644 --- a/taskman-server/dao/form_item_template_dao.go +++ b/taskman-server/dao/form_item_template_dao.go @@ -50,12 +50,29 @@ func (d FormItemTemplateDao) Get(formItemTemplateId string) (*models.FormItemTem return nil, nil } -func (d FormItemTemplateDao) QueryByFormTemplate(formTemplate string) (formItemTemplate []*models.FormItemTemplateTable, err error) { - formItemTemplate = []*models.FormItemTemplateTable{} +func (d FormItemTemplateDao) QueryByFormTemplate(formTemplate string) (formItemTemplateDtoList []*models.FormItemTemplateDto, err error) { + var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateGroup *models.FormItemTemplateGroupTable + formItemTemplateDtoList = []*models.FormItemTemplateDto{} if formTemplate == "" { return } - err = d.DB.Where("form_template = ?", formTemplate).Find(&formItemTemplate) + err = d.DB.Where("form_template = ?", formTemplate).Find(&formItemTemplateList) + if err != nil { + return + } + if len(formItemTemplateList) > 0 { + err = d.DB.Where("id = ?", formItemTemplateList[0].ItemGroupId).Find(&formItemTemplateGroup) + if err != nil { + return + } + } + for _, formItemTemplate := range formItemTemplateList { + dto := models.ConvertFormItemTemplateModel2Dto(formItemTemplate, formItemTemplateGroup) + if dto != nil { + formItemTemplateDtoList = append(formItemTemplateDtoList, dto) + } + } return } @@ -65,6 +82,52 @@ func (d FormItemTemplateDao) QueryByFormTemplateAndItemGroupName(formTemplate, i return } +func (d FormItemTemplateDao) QueryDtoByFormTemplateAndItemGroupName(formTemplate, itemGroupName string) (formItemTemplateDtoList []*models.FormItemTemplateDto, err error) { + var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateGroup *models.FormItemTemplateGroupTable + formItemTemplateDtoList = []*models.FormItemTemplateDto{} + err = d.DB.Where("form_template = ? and item_group_name = ?", formTemplate, itemGroupName).Find(&formItemTemplateList) + if len(formItemTemplateList) > 0 { + err = d.DB.Where("id = ?", formItemTemplateList[0].ItemGroupId).Find(&formItemTemplateList) + if err != nil { + return + } + } + for _, formItemTemplate := range formItemTemplateList { + dto := models.ConvertFormItemTemplateModel2Dto(formItemTemplate, formItemTemplateGroup) + if dto != nil { + formItemTemplateDtoList = append(formItemTemplateDtoList, dto) + } + } + return +} + +func (d FormItemTemplateDao) QueryByFormTemplateAndItemGroupId(formTemplate, itemGroupId string) (formItemTemplate []*models.FormItemTemplateTable, err error) { + formItemTemplate = []*models.FormItemTemplateTable{} + err = d.DB.Where("form_template = ? and item_group_id = ?", formTemplate, itemGroupId).Find(&formItemTemplate) + return +} + +func (d FormItemTemplateDao) QueryDtoByFormTemplateAndItemGroupId(formTemplate, itemGroupId string) (formItemTemplateDtoList []*models.FormItemTemplateDto, err error) { + var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateGroup *models.FormItemTemplateGroupTable + formItemTemplateDtoList = []*models.FormItemTemplateDto{} + err = d.DB.Where("form_template = ? and item_group_id = ?", formTemplate, itemGroupId).Find(&formItemTemplateList) + if len(formItemTemplateList) > 0 { + err = d.DB.Where("id = ?", formItemTemplateList[0].ItemGroupId).Find(&formItemTemplateList) + if err != nil { + return + } + } + for _, formItemTemplate := range formItemTemplateList { + dto := models.ConvertFormItemTemplateModel2Dto(formItemTemplate, formItemTemplateGroup) + if dto != nil { + formItemTemplateDtoList = append(formItemTemplateDtoList, dto) + } + } + return +} + func (d FormItemTemplateDao) QueryByFormTemplateAndItemGroup(formTemplate, itemGroup string) (formItemTemplate []*models.FormItemTemplateTable, err error) { formItemTemplate = []*models.FormItemTemplateTable{} err = d.DB.Where("form_template = ? and item_group = ?", formTemplate, itemGroup).Find(&formItemTemplate) diff --git a/taskman-server/dao/form_item_template_group_dao.go b/taskman-server/dao/form_item_template_group_dao.go index 41d7e470..812967f7 100644 --- a/taskman-server/dao/form_item_template_group_dao.go +++ b/taskman-server/dao/form_item_template_group_dao.go @@ -35,17 +35,32 @@ func (d FormItemTemplateGroupDao) Update(session *xorm.Session, formItemTemplate return } -func (d FormItemTemplateGroupDao) Get(formItemTemplateGroupId string) (*models.FormItemTemplateTable, error) { - var formItemTemplate *models.FormItemTemplateTable +func (d FormItemTemplateGroupDao) Get(formItemTemplateGroupId string) (*models.FormItemTemplateGroupTable, error) { + var formItemTemplateGroup *models.FormItemTemplateGroupTable var found bool var err error - formItemTemplate = &models.FormItemTemplateTable{} - found, err = d.DB.ID(formItemTemplateGroupId).Get(formItemTemplate) + formItemTemplateGroup = &models.FormItemTemplateGroupTable{} + found, err = d.DB.ID(formItemTemplateGroupId).Get(formItemTemplateGroup) if err != nil { return nil, err } if found { - return formItemTemplate, nil + return formItemTemplateGroup, nil } return nil, nil } + +func (d FormItemTemplateGroupDao) DeleteByIdOrCopyId(session *xorm.Session, id string) (err error) { + var affected int64 + if session == nil { + session = d.DB.NewSession() + defer session.Close() + } + if id == "" { + return + } + affected, err = session.Where("id = ? or copy_id = ?", id, id).Delete(&models.FormItemTemplateGroupTable{}) + // 打印日志 + logExecuteSql(session, "FormItemTemplateGroupDao", "DeleteByIdOrCopyId", id, affected, err) + return +} diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index a1788ddb..32769353 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -4,11 +4,9 @@ type FormItemTemplateTable struct { Id string `json:"id" xorm:"'id' pk" primary-key:"id"` Name string `json:"name" xorm:"name"` Description string `json:"description" xorm:"description"` + ItemGroupId string `json:"itemGroupId" xorm:"item_group_id"` ItemGroup string `json:"itemGroup" xorm:"item_group"` - ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` - ItemGroupSort int `json:"ItemGroupSort" xorm:"item_group_sort"` // item_group 排序 - ItemGroupRule string `json:"itemGroupRule" xorm:"item_group_rule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 FormTemplate string `json:"formTemplate" xorm:"form_template"` DefaultValue string `json:"defaultValue" xorm:"default_value"` Sort int `json:"sort" xorm:"sort"` @@ -41,6 +39,7 @@ type FormItemTemplateDto struct { Id string `json:"id"` Name string `json:"name"` Description string `json:"description"` + ItemGroupId string `json:"itemGroupId"` ItemGroup string `json:"itemGroup"` ItemGroupType string `json:"itemGroupType"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName"` @@ -78,17 +77,17 @@ func (FormItemTemplateTable) TableName() string { return "form_item_template" } -type FormItemTemplateTableSort []*FormItemTemplateTable +type FormItemTemplateDtoSort []*FormItemTemplateDto -func (s FormItemTemplateTableSort) Len() int { +func (s FormItemTemplateDtoSort) Len() int { return len(s) } -func (s FormItemTemplateTableSort) Swap(i, j int) { +func (s FormItemTemplateDtoSort) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s FormItemTemplateTableSort) Less(i, j int) bool { +func (s FormItemTemplateDtoSort) Less(i, j int) bool { if s[i].Sort < s[j].Sort { return true } @@ -102,3 +101,83 @@ func ConvertFormItemTemplateList2Map(formItemTemplateList []*FormItemTemplateTab } return hashMap } + +func ConvertFormItemTemplateDto2Model(dto *FormItemTemplateDto) *FormItemTemplateTable { + return &FormItemTemplateTable{ + Id: dto.Id, + Name: dto.Name, + Description: dto.Description, + ItemGroupId: dto.ItemGroupId, + ItemGroup: dto.ItemGroup, + ItemGroupName: dto.ItemGroupName, + FormTemplate: dto.FormTemplate, + DefaultValue: dto.DefaultValue, + Sort: dto.Sort, + PackageName: dto.PackageName, + Entity: dto.Entity, + AttrDefId: dto.AttrDefId, + AttrDefName: dto.AttrDefName, + AttrDefDataType: dto.AttrDefDataType, + ElementType: dto.ElementType, + Title: dto.Title, + Width: dto.Width, + RefPackageName: dto.RefPackageName, + RefEntity: dto.RefEntity, + DataOptions: dto.DataOptions, + Required: dto.Required, + Regular: dto.Regular, + IsEdit: dto.IsEdit, + IsView: dto.IsView, + IsOutput: dto.IsOutput, + InDisplayName: dto.InDisplayName, + IsRefInside: dto.IsRefInside, + Multiple: dto.Multiple, + DefaultClear: dto.DefaultClear, + CopyId: dto.CopyId, + SelectList: dto.SelectList, + Active: dto.Active, + } +} + +func ConvertFormItemTemplateModel2Dto(model *FormItemTemplateTable, itemGroup *FormItemTemplateGroupTable) *FormItemTemplateDto { + dto := &FormItemTemplateDto{ + Id: model.Id, + Name: model.Name, + Description: model.Description, + ItemGroupId: model.ItemGroupId, + ItemGroup: model.ItemGroup, + ItemGroupName: model.ItemGroupName, + FormTemplate: model.FormTemplate, + DefaultValue: model.DefaultValue, + Sort: model.Sort, + PackageName: model.PackageName, + Entity: model.Entity, + AttrDefId: model.AttrDefId, + AttrDefName: model.AttrDefName, + AttrDefDataType: model.AttrDefDataType, + ElementType: model.ElementType, + Title: model.Title, + Width: model.Width, + RefPackageName: model.RefPackageName, + RefEntity: model.RefEntity, + DataOptions: model.DataOptions, + Required: model.Required, + Regular: model.Regular, + IsEdit: model.IsEdit, + IsView: model.IsView, + IsOutput: model.IsOutput, + InDisplayName: model.InDisplayName, + IsRefInside: model.IsRefInside, + Multiple: model.Multiple, + DefaultClear: model.DefaultClear, + CopyId: model.CopyId, + SelectList: model.SelectList, + Active: model.Active, + } + if itemGroup != nil { + dto.ItemGroupType = itemGroup.ItemGroupType + dto.ItemGroupRule = itemGroup.ItemGroupRule + dto.ItemGroupSort = itemGroup.ItemGroupSort + } + return dto +} diff --git a/taskman-server/models/form_item_template_group.go b/taskman-server/models/form_item_template_group.go index 3d4ace1d..44415e88 100644 --- a/taskman-server/models/form_item_template_group.go +++ b/taskman-server/models/form_item_template_group.go @@ -2,12 +2,15 @@ package models type FormItemTemplateGroupTable struct { Id string `json:"id" xorm:"'id' pk" primary-key:"id"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` ItemGroup string `json:"itemGroup" xorm:"item_group"` ItemGroupType string `json:"itemGroupType" xorm:"item_group_type"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` ItemGroupSort int `json:"ItemGroupSort" xorm:"item_group_sort"` // item_group 排序 ItemGroupRule string `json:"itemGroupRule" xorm:"item_group_rule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 FormTemplate string `json:"formTemplate" xorm:"form_template"` + CopyId string `json:"copyId" xorm:"copy_id"` // 复制Id +} + +func (FormItemTemplateGroupTable) TableName() string { + return "form_item_template_group" } diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index 9806c9ae..226a5f79 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -18,14 +18,14 @@ func (FormTemplateTable) TableName() string { } type FormTemplateDto struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - ExpireDay int `json:"expireDay"` - UpdatedBy string `json:"updatedBy"` - UpdatedTime string `json:"updatedTime"` - NowTime string `json:"-"` - Items []*FormItemTemplateTable `json:"items"` + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + ExpireDay int `json:"expireDay"` + UpdatedBy string `json:"updatedBy"` + UpdatedTime string `json:"updatedTime"` + NowTime string `json:"-"` + Items []*FormItemTemplateDto `json:"items"` } // DataFormTemplateDto 全局表单模板 dto @@ -44,38 +44,41 @@ type SimpleFormTemplateDto struct { // FormTemplateGroupDto 表单模板组dto type FormTemplateGroupDto struct { - ItemGroup string `json:"itemGroup"` - ItemGroupType string `json:"itemGroupType"` // 表单组类型:workflow 编排数据,optional 自选,custom 自定义 - ItemGroupName string `json:"itemGroupName"` - ItemGroupSort int `json:"itemGroupSort"` // 组排序 - Items []*FormItemTemplateTable `json:"items"` // 表单项 + ItemGroupId string `json:"itemGroupId"` //表单组ID + ItemGroup string `json:"itemGroup"` + ItemGroupType string `json:"itemGroupType"` // 表单组类型:workflow 编排数据,optional 自选,custom 自定义 + ItemGroupName string `json:"itemGroupName"` + ItemGroupSort int `json:"itemGroupSort"` // 组排序 + Items []*FormItemTemplateDto `json:"items"` // 表单项 } // FormTemplateGroupConfigureDto 表单组配置在dto type FormTemplateGroupConfigureDto struct { RequestTemplateId string `json:"requestTemplateId"` // 模板Id FormTemplateId string `json:"formTemplateId"` // 表单模板ID + ItemGroupId string `json:"itemGroupId"` ItemGroup string `json:"itemGroup"` ItemGroupType string `json:"itemGroupType"` // 表单组类型:workflow 编排数据,optional 自选,custom 自定义 ItemGroupName string `json:"itemGroupName"` ItemGroupRule string `json:"itemGroupRule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 ItemGroupSort int `json:"itemGroupSort"` // 表单组排序 SystemItems []*ProcEntityAttributeObj `json:"systemItems"` // 系统表单项 - CustomItems []*FormItemTemplateTable `json:"customItems"` // 自定义表单项 + CustomItems []*FormItemTemplateDto `json:"customItems"` // 自定义表单项 } // FormTemplateGroupCustomDataDto 表单组自定义数据dto type FormTemplateGroupCustomDataDto struct { - RequestTemplateId string `json:"requestTemplateId"` // 模板Id - FormTemplateId string `json:"formTemplateId"` // 表单模板ID - Items []*FormItemTemplateTable `json:"items"` // 表单项 + RequestTemplateId string `json:"requestTemplateId"` // 模板Id + FormTemplateId string `json:"formTemplateId"` // 表单模板ID + ItemGroupId string `json:"itemGroupId"` + Items []*FormItemTemplateDto `json:"items"` // 表单项 } // FormTemplateGroupSortDto 表单组排序dto type FormTemplateGroupSortDto struct { RequestTemplateId string `json:"requestTemplateId"` // 模板Id FormTemplateId string `json:"formTemplateId"` // 表单模板ID - ItemGroupNameSort []string `json:"itemGroupNameSort"` // 排序 + ItemGroupIdSort []string `json:"itemGroupIdSort"` // 排序 } type TaskFormItemQueryObj struct { @@ -103,7 +106,7 @@ func CovertFormTemplateDto2Model(dto FormTemplateDto) *FormTemplateTable { } func ConvertDataFormTemplate2FormTemplateDto(dto DataFormTemplateDto) FormTemplateDto { - var items = make([]*FormItemTemplateTable, 0) + var items = make([]*FormItemTemplateDto, 0) if len(dto.Groups) > 0 { for _, group := range dto.Groups { if group != nil && len(group.Items) > 0 { @@ -125,7 +128,7 @@ func ConvertDataFormTemplate2FormTemplateDto(dto DataFormTemplateDto) FormTempla } } -func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfigureDto, workflowEntityAttribute *ProcEntityAttributeObj) *FormItemTemplateTable { +func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfigureDto, workflowEntityAttribute *ProcEntityAttributeObj, newItemGroupId string) *FormItemTemplateTable { var elementType = string(FormItemElementTypeInput) if workflowEntityAttribute.DataType == "ref" { elementType = string(FormItemElementTypeSelect) @@ -134,11 +137,9 @@ func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfi Id: guid.CreateGuid(), Name: workflowEntityAttribute.Name, Description: workflowEntityAttribute.Description, + ItemGroupId: newItemGroupId, ItemGroup: param.ItemGroup, - ItemGroupType: param.ItemGroupType, ItemGroupName: param.ItemGroupName, - ItemGroupSort: param.ItemGroupSort, - ItemGroupRule: param.ItemGroupRule, FormTemplate: param.FormTemplateId, Sort: 0, PackageName: workflowEntityAttribute.EntityPackage, @@ -163,6 +164,7 @@ func ConvertProcEntityAttributeObj2FormItemTemplate(param FormTemplateGroupConfi DefaultClear: "no", CopyId: "", SelectList: nil, + Active: false, } } diff --git a/taskman-server/models/task_template.go b/taskman-server/models/task_template.go index 1ca43722..4241a04b 100644 --- a/taskman-server/models/task_template.go +++ b/taskman-server/models/task_template.go @@ -39,26 +39,26 @@ type TaskTemplateRoleTable struct { } type TaskTemplateDto struct { - Id string `json:"id"` - Type string `json:"type"` - NodeId string `json:"nodeId"` - NodeDefId string `json:"nodeDefId"` - NodeDefName string `json:"nodeDefName"` - Name string `json:"name"` - Description string `json:"description"` - ExpireDay int `json:"expireDay"` - Handler string `json:"handler"` - UpdatedTime string `json:"updatedTime"` - UpdatedBy string `json:"updatedBy"` - MGMTRoles []string `json:"mgmtRoles"` - USERoles []string `json:"useRoles"` - MGMTRoleObjs []*RoleTable `json:"mgmtRoleObjs"` - USERoleObjs []*RoleTable `json:"useRoleObjs"` - Items []*FormItemTemplateTable `json:"items"` - RequestTemplateId string `json:"requestTemplateId"` - Sort int `json:"sort"` - RoleType string `json:"roleType"` - RoleObjs []*TaskTemplateRoleDto `json:"roleObjs"` + Id string `json:"id"` + Type string `json:"type"` + NodeId string `json:"nodeId"` + NodeDefId string `json:"nodeDefId"` + NodeDefName string `json:"nodeDefName"` + Name string `json:"name"` + Description string `json:"description"` + ExpireDay int `json:"expireDay"` + Handler string `json:"handler"` + UpdatedTime string `json:"updatedTime"` + UpdatedBy string `json:"updatedBy"` + MGMTRoles []string `json:"mgmtRoles"` + USERoles []string `json:"useRoles"` + MGMTRoleObjs []*RoleTable `json:"mgmtRoleObjs"` + USERoleObjs []*RoleTable `json:"useRoleObjs"` + Items []*FormItemTemplateDto `json:"items"` + RequestTemplateId string `json:"requestTemplateId"` + Sort int `json:"sort"` + RoleType string `json:"roleType"` + RoleObjs []*TaskTemplateRoleDto `json:"roleObjs"` } type TaskTemplateRoleDto struct { diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 6d061211..0b3e39d5 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -1,8 +1,6 @@ package service import ( - "fmt" - "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" @@ -12,44 +10,54 @@ import ( const defaultCustomFormItemName = "taskman-custom-form" type FormItemTemplateService struct { - formItemTemplateDao dao.FormItemTemplateDao + formItemTemplateDao dao.FormItemTemplateDao + formItemTemplateGroupDao dao.FormItemTemplateGroupDao } func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models.FormTemplateGroupConfigureDto) (err error) { var formItemTemplateList []*models.FormItemTemplateTable var insertItems, updateItems, deleteItems []*models.FormItemTemplateTable + var updateItemGroup *models.FormItemTemplateGroupTable + var newItemGroupId string var systemItemExist, customItemExist bool var existMap = make(map[string]bool) if len(param.SystemItems) == 0 { param.SystemItems = []*models.ProcEntityAttributeObj{} } if len(param.CustomItems) == 0 { - param.CustomItems = []*models.FormItemTemplateTable{} - } - // 自定义类型 单独处理 - if param.ItemGroupType == string(models.FormItemGroupTypeCustom) { - return s.UpdateFormTemplateCustomItemGroupConfig(param) + param.CustomItems = []*models.FormItemTemplateDto{} } // 1. 查询表单组是否存在,不存在则新增 - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(param.FormTemplateId, param.ItemGroupName) + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(param.FormTemplateId, param.ItemGroupId) if err != nil { return } // 新增数据 if len(formItemTemplateList) == 0 { + newItemGroupId = guid.CreateGuid() if len(param.SystemItems) > 0 { for _, systemItem := range param.SystemItems { - insertItems = append(insertItems, models.ConvertProcEntityAttributeObj2FormItemTemplate(param, systemItem)) + insertItems = append(insertItems, models.ConvertProcEntityAttributeObj2FormItemTemplate(param, systemItem, newItemGroupId)) } } if len(param.CustomItems) > 0 { for _, customItem := range param.CustomItems { customItem.FormTemplate = param.FormTemplateId customItem.ElementType = string(models.FormItemElementTypeCalculate) - insertItems = append(insertItems, customItem) + insertItems = append(insertItems, models.ConvertFormItemTemplateDto2Model(customItem)) } } } else { + updateItemGroup, err = s.formItemTemplateGroupDao.Get(param.ItemGroupId) + if err != nil { + return + } + if updateItemGroup != nil { + updateItemGroup.ItemGroupName = param.ItemGroupName + updateItemGroup.ItemGroup = param.ItemGroup + updateItemGroup.ItemGroupRule = param.ItemGroupRule + updateItemGroup.ItemGroupType = param.ItemGroupType + } for _, systemItem := range param.SystemItems { systemItemExist = false existMap[systemItem.Id] = true @@ -60,7 +68,7 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. } } if !systemItemExist { - insertItems = append(insertItems, models.ConvertProcEntityAttributeObj2FormItemTemplate(param, systemItem)) + insertItems = append(insertItems, models.ConvertProcEntityAttributeObj2FormItemTemplate(param, systemItem, param.ItemGroupId)) } } for _, customItem := range param.CustomItems { @@ -69,13 +77,13 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. for _, formItemTemplate := range formItemTemplateList { if customItem.Id == formItemTemplate.Id { customItemExist = true - updateItems = append(updateItems, customItem) + updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(customItem)) break } } if !customItemExist { customItem.FormTemplate = param.FormTemplateId - insertItems = append(insertItems, customItem) + insertItems = append(insertItems, models.ConvertFormItemTemplateDto2Model(customItem)) } } for _, formItemTemplate := range formItemTemplateList { @@ -83,91 +91,57 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. deleteItems = append(deleteItems, formItemTemplate) } } + if param.ItemGroupType == string(models.FormItemGroupTypeCustom) { + + } } - if len(insertItems) > 0 || len(updateItems) > 0 || len(deleteItems) > 0 { - err = transaction(func(session *xorm.Session) error { - if len(insertItems) > 0 { - for _, item := range insertItems { - _, err = s.formItemTemplateDao.Add(session, item) - if err != nil { - return err - } - } - } - if len(updateItems) > 0 { - for _, item := range updateItems { - err = s.formItemTemplateDao.Update(session, item) - if err != nil { - return err - } - } - } - if len(deleteItems) > 0 { - for _, item := range deleteItems { - err = s.formItemTemplateDao.Delete(session, item.Id) - if err != nil { - return err - } + err = transaction(func(session *xorm.Session) error { + if newItemGroupId != "" { + _, err = s.formItemTemplateGroupDao.Add(session, &models.FormItemTemplateGroupTable{ + Id: newItemGroupId, + ItemGroup: param.ItemGroup, + ItemGroupType: param.ItemGroupType, + ItemGroupName: param.ItemGroupName, + ItemGroupSort: param.ItemGroupSort, + ItemGroupRule: param.ItemGroupRule, + FormTemplate: param.FormTemplateId, + }) + } + if updateItemGroup != nil { + err = s.formItemTemplateGroupDao.Update(session, updateItemGroup) + } + if len(insertItems) > 0 { + for _, item := range insertItems { + _, err = s.formItemTemplateDao.Add(session, item) + if err != nil { + return err } } - return err - }) - } - return -} - -func (s FormItemTemplateService) UpdateFormTemplateCustomItemGroupConfig(param models.FormTemplateGroupConfigureDto) (err error) { - var formItemTemplateList, tempFormItemTemplateList []*models.FormItemTemplateTable - var addFormItemTemplate *models.FormItemTemplateTable - // 1. 查询表单组是否存在,不存在则新增 - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroup(param.FormTemplateId, param.ItemGroup) - if err != nil { - return - } - if len(formItemTemplateList) == 0 { - formItemTemplateList = []*models.FormItemTemplateTable{} - } - formItemTemplateMap := models.ConvertFormItemTemplateList2Map(formItemTemplateList) - tempFormItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(param.FormTemplateId, param.ItemGroupName) - if err != nil { - return - } - - if len(tempFormItemTemplateList) > 0 { - if len(tempFormItemTemplateList) != len(formItemTemplateList) { - err = fmt.Errorf("itemGroupName:%s has exisit", param.ItemGroupName) - return } - for _, tempFormItemTemplate := range tempFormItemTemplateList { - if formItemTemplateMap[tempFormItemTemplate.Id] == nil { - err = fmt.Errorf("itemGroupName:%s has exisit", param.ItemGroupName) - return + if len(updateItems) > 0 { + for _, item := range updateItems { + err = s.formItemTemplateDao.Update(session, item) + if err != nil { + return err + } } } - } - if len(formItemTemplateList) > 0 { - // 更新模板 - for _, formItemTemplate := range formItemTemplateList { - formItemTemplate.ItemGroupName = param.ItemGroupName - formItemTemplate.ItemGroupRule = param.ItemGroupRule - formItemTemplate.ItemGroupType = param.ItemGroupType - err = s.formItemTemplateDao.Update(nil, formItemTemplate) - if err != nil { - return err + if len(deleteItems) > 0 { + for _, item := range deleteItems { + err = s.formItemTemplateDao.Delete(session, item.Id) + if err != nil { + return err + } } } - } else { - // 新增自定义组,同时给一个初始化假数据(后续更新模板组时候删除掉) - addFormItemTemplate = &models.FormItemTemplateTable{Id: guid.CreateGuid(), Name: defaultCustomFormItemName, ItemGroup: guid.CreateGuid(), ItemGroupName: param.ItemGroupName, - ItemGroupType: param.ItemGroupType, ItemGroupRule: param.ItemGroupRule, FormTemplate: param.FormTemplateId} - _, err = s.formItemTemplateDao.Add(nil, addFormItemTemplate) - } + return err + }) return } -func (s FormItemTemplateService) DeleteFormTemplateItemGroup(formTemplateId, itemGroupName string) (err error) { +func (s FormItemTemplateService) DeleteFormTemplateItemGroup(formTemplateId, itemGroupId string) (err error) { var formItemTemplateList []*models.FormItemTemplateTable - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(formTemplateId, itemGroupId) if err != nil { return err } @@ -178,6 +152,10 @@ func (s FormItemTemplateService) DeleteFormTemplateItemGroup(formTemplateId, ite if err != nil { return err } + err = s.formItemTemplateGroupDao.DeleteByIdOrCopyId(session, itemGroupId) + if err != nil { + return err + } } return nil }) @@ -193,9 +171,9 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroup(param models.FormTe if item.Id == "" { item.Id = guid.CreateGuid() item.FormTemplate = param.FormTemplateId - s.formItemTemplateDao.Add(session, item) + s.formItemTemplateDao.Add(session, models.ConvertFormItemTemplateDto2Model(item)) } else { - err = s.formItemTemplateDao.Update(session, item) + err = s.formItemTemplateDao.Update(session, models.ConvertFormItemTemplateDto2Model(item)) } if err != nil { return err @@ -208,9 +186,9 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroup(param models.FormTe } func (s FormItemTemplateService) SortFormTemplateItemGroup(param models.FormTemplateGroupSortDto) (err error) { - var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateList []*models.FormItemTemplateDto var formItemTemplateGroupSortMap = make(map[string]int) - formItemTemplateGroupSortMap = s.buildFormTemplateGroupSortMap(param.ItemGroupNameSort) + formItemTemplateGroupSortMap = s.buildFormTemplateGroupSortMap(param.ItemGroupIdSort) formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplate(param.FormTemplateId) if err != nil { return @@ -219,7 +197,7 @@ func (s FormItemTemplateService) SortFormTemplateItemGroup(param models.FormTemp err = transaction(func(session *xorm.Session) error { for _, formItemTemplate := range formItemTemplateList { formItemTemplate.Sort = formItemTemplateGroupSortMap[formItemTemplate.ItemGroupName] - err = s.formItemTemplateDao.Update(session, formItemTemplate) + err = s.formItemTemplateDao.Update(session, models.ConvertFormItemTemplateDto2Model(formItemTemplate)) if err != nil { return err } @@ -230,10 +208,10 @@ func (s FormItemTemplateService) SortFormTemplateItemGroup(param models.FormTemp return } -func (s FormItemTemplateService) CopyDataFormTemplateItemGroup(formTemplateId, itemGroupName string) (err error) { +func (s FormItemTemplateService) CopyDataFormTemplateItemGroup(formTemplateId, itemGroupId string) (err error) { var formItemTemplateList []*models.FormItemTemplateTable // 1. 查询表单组是否存在,不存在则新增 - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(formTemplateId, itemGroupId) if err != nil { return } diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index d975dcd0..bb9fa52c 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -33,7 +33,7 @@ func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplate for i, item := range formTemplateDto.Items { item.Id = itemIds[i] item.FormTemplate = newId - _, err = s.formItemTemplateDao.Add(session, item) + _, err = s.formItemTemplateDao.Add(session, models.ConvertFormItemTemplateDto2Model(item)) if err != nil { return } @@ -42,7 +42,7 @@ func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplate } func (s FormTemplateService) UpdateFormTemplate(session *xorm.Session, formTemplateDto models.FormTemplateDto) (err error) { - var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateList []*models.FormItemTemplateDto formTemplateDto.NowTime = time.Now().Format(models.DateTimeFormat) newItemGuidList := guid.CreateGuidList(len(formTemplateDto.Items)) formTemplateTable := &models.FormTemplateTable{ @@ -65,12 +65,12 @@ func (s FormTemplateService) UpdateFormTemplate(session *xorm.Session, formTempl for i, inputItem := range formTemplateDto.Items { if inputItem.Id == "" { inputItem.Id = newItemGuidList[i] - _, err = s.formItemTemplateDao.Add(session, inputItem) + _, err = s.formItemTemplateDao.Add(session, models.ConvertFormItemTemplateDto2Model(inputItem)) if err != nil { return } } else { - err = s.formItemTemplateDao.Update(session, inputItem) + err = s.formItemTemplateDao.Update(session, models.ConvertFormItemTemplateDto2Model(inputItem)) if err != nil { return } @@ -100,7 +100,7 @@ func (s FormTemplateService) UpdateFormTemplate(session *xorm.Session, formTempl func (s FormTemplateService) GetRequestFormTemplate(requestTemplateId string) (result *models.FormTemplateDto, err error) { var requestTemplate *models.RequestTemplateTable var formTemplate *models.FormTemplateTable - result = &models.FormTemplateDto{Items: []*models.FormItemTemplateTable{}} + result = &models.FormTemplateDto{Items: []*models.FormItemTemplateDto{}} requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) if err != nil { return @@ -161,8 +161,8 @@ func (s FormTemplateService) GetFormTemplate(formTemplateId string) (result *mod } func (s FormTemplateService) getFormTemplateGroups(formTemplateId string) (groups []*models.FormTemplateGroupDto, err error) { - var formItemTemplateList []*models.FormItemTemplateTable - var itemGroupMap = make(map[string][]*models.FormItemTemplateTable) + var formItemTemplateList []*models.FormItemTemplateDto + var itemGroupMap = make(map[string][]*models.FormItemTemplateDto) var itemGroupType, itemGroupName string var itemGroupSort int groups = []*models.FormTemplateGroupDto{} @@ -175,7 +175,7 @@ func (s FormTemplateService) getFormTemplateGroups(formTemplateId string) (group } for _, formItemTemplate := range formItemTemplateList { if _, ok := itemGroupMap[formItemTemplate.ItemGroup]; !ok { - itemGroupMap[formItemTemplate.ItemGroup] = make([]*models.FormItemTemplateTable, 0) + itemGroupMap[formItemTemplate.ItemGroup] = make([]*models.FormItemTemplateDto, 0) } } for itemGroup, formItemTemplateArr := range itemGroupMap { @@ -203,7 +203,7 @@ func (s FormTemplateService) getFormTemplateGroups(formTemplateId string) (group // 设置排序,保证前端展示数据顺序一致 for _, FormTemplateGroupDto := range groups { if len(FormTemplateGroupDto.Items) > 0 { - sort.Sort(models.FormItemTemplateTableSort(FormTemplateGroupDto.Items)) + sort.Sort(models.FormItemTemplateDtoSort(FormTemplateGroupDto.Items)) } } sort.Sort(models.FormTemplateGroupDtoSort(groups)) @@ -213,7 +213,7 @@ func (s FormTemplateService) getFormTemplateGroups(formTemplateId string) (group func (s FormTemplateService) GetDataFormTemplateItemGroups(requestTemplateId string) (entityList []string, err error) { var itemGroupNameMap = make(map[string]bool) var requestTemplate *models.RequestTemplateTable - var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateList []*models.FormItemTemplateDto entityList = []string{} requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) if err != nil { @@ -336,10 +336,10 @@ func (s FormTemplateService) CreateDataFormTemplate(formTemplateDto models.DataF } // GetFormConfig 获取配置表单,数据基于数据表单数据 -func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { +func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, itemGroupId, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { var requestTemplate *models.RequestTemplateTable var dataFormConfigureDto *models.FormTemplateGroupConfigureDto - var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateList []*models.FormItemTemplateDto var existAttrMap = make(map[string]bool) var existCustomItemsMap = make(map[string]string) requestTemplate, err = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) @@ -354,9 +354,9 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it err = fmt.Errorf("requestTemplate:%s DataFormTemplate is empty", requestTemplate.Id) return } - configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateTable{}} + configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateDto{}} // 1.先查询用户配置数据 - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) + formItemTemplateList, err = s.formItemTemplateDao.QueryDtoByFormTemplateAndItemGroupId(formTemplateId, itemGroupId) if err != nil { return } @@ -369,7 +369,7 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it } } // 2. 查询数据表单 - dataFormConfigureDto, err = s.GetDataFormConfig(requestTemplate.DataFormTemplate, itemGroupName, userToken, language) + dataFormConfigureDto, err = s.GetDataFormConfig(requestTemplate.DataFormTemplate, itemGroupId, "", "", userToken, language) if err != nil { return } @@ -398,50 +398,58 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it } // GetDataFormConfig 获取数据表单配置 -func (s FormTemplateService) GetDataFormConfig(formTemplateId, itemGroupName, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { - var formItemTemplate []*models.FormItemTemplateTable +func (s FormTemplateService) GetDataFormConfig(formTemplateId, itemGroupId, formType, entity, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { + var formItemTemplateList []*models.FormItemTemplateDto var entitiesList []*models.ExpressionEntities - var entity *models.ExpressionEntities + var expressEntity *models.ExpressionEntities var existAttrMap = make(map[string]bool) - configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateTable{}} + configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateDto{}} // 1.先查询用户配置数据 - formItemTemplate, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupName(formTemplateId, itemGroupName) - if err != nil { - return - } - if len(formItemTemplate) > 0 { - configureDto.ItemGroup = formItemTemplate[0].ItemGroup - configureDto.ItemGroupName = formItemTemplate[0].ItemGroupName - configureDto.ItemGroupType = formItemTemplate[0].ItemGroupType - configureDto.ItemGroupRule = formItemTemplate[0].ItemGroupRule - for _, formItem := range formItemTemplate { - if formItem.ItemGroupType == string(models.FormItemGroupTypeCustom) { - configureDto.CustomItems = append(configureDto.CustomItems, formItem) - } else { - existAttrMap[formItem.AttrDefId] = true + if itemGroupId != "" { + formItemTemplateList, err = s.formItemTemplateDao.QueryDtoByFormTemplateAndItemGroupId(formTemplateId, itemGroupId) + if err != nil { + return + } + if len(formItemTemplateList) > 0 { + configureDto.ItemGroup = formItemTemplateList[0].ItemGroup + configureDto.ItemGroupName = formItemTemplateList[0].ItemGroupName + configureDto.ItemGroupType = formItemTemplateList[0].ItemGroupType + configureDto.ItemGroupRule = formItemTemplateList[0].ItemGroupRule + for _, formItem := range formItemTemplateList { + if formItem.ItemGroupType == string(models.FormItemGroupTypeCustom) { + configureDto.CustomItems = append(configureDto.CustomItems, formItem) + } else { + existAttrMap[formItem.AttrDefId] = true + } + } + // 自定义表单组的 entity 为空 + if configureDto.ItemGroupType != string(models.FormItemGroupTypeCustom) { + entity = configureDto.ItemGroupName } } } // 2.查询entity 属性集合 - entitiesList, err = rpc.QueryEntityAttributes(models.QueryExpressionDataParam{DataModelExpression: itemGroupName}, userToken, language) - if err != nil { - return - } - if len(entitiesList) > 0 && len(entitiesList[0].Attributes) > 0 { - entity = entitiesList[0] - if configureDto.ItemGroup == "" { - configureDto.ItemGroup = itemGroupName - configureDto.ItemGroupName = itemGroupName - configureDto.ItemGroupType = string(models.FormItemGroupTypeOptional) + if entity != "" { + entitiesList, err = rpc.QueryEntityAttributes(models.QueryExpressionDataParam{DataModelExpression: entity}, userToken, language) + if err != nil { + return } - for _, attribute := range entitiesList[0].Attributes { - attribute.Id = fmt.Sprintf("%s:%s:%s", entitiesList[0].PackageName, entitiesList[0].EntityName, attribute.Name) - attribute.EntityName = entity.EntityName - attribute.EntityPackage = entity.PackageName - if existAttrMap[attribute.Id] { - attribute.Active = true + if len(entitiesList) > 0 && len(entitiesList[0].Attributes) > 0 { + expressEntity = entitiesList[0] + if configureDto.ItemGroup == "" { + configureDto.ItemGroup = entity + configureDto.ItemGroupName = entity + configureDto.ItemGroupType = formType + } + for _, attribute := range entitiesList[0].Attributes { + attribute.Id = fmt.Sprintf("%s:%s:%s", entitiesList[0].PackageName, entitiesList[0].EntityName, attribute.Name) + attribute.EntityName = expressEntity.EntityName + attribute.EntityPackage = expressEntity.PackageName + if existAttrMap[attribute.Id] { + attribute.Active = true + } + configureDto.SystemItems = append(configureDto.SystemItems, attribute) } - configureDto.SystemItems = append(configureDto.SystemItems, attribute) } } return diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index e6c71fa6..0198cbaa 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -69,6 +69,7 @@ func New() (err error) { approvalTemplateRoleDao := dao.ApprovalTemplateRoleDao{DB: engine} approvalDao := dao.ApprovalDao{DB: engine} approvalRoleDao := dao.ApprovalRoleDao{DB: engine} + formItemTemplateGroupDao := dao.FormItemTemplateGroupDao{DB: engine} // 初始化Service collectTemplateService = CollectTemplateService{collectTemplateDao: collectTemplateDao} requestService = RequestService{requestDao: requestDao} @@ -83,7 +84,7 @@ func New() (err error) { requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao, operationLogDao: operationLogDao, requestTemplateRoleDao: requestTemplateRoleDao} requestTemplateGroupService = RequestTemplateGroupService{requestTemplateGroupDao: requestTemplateGroupDao} formTemplateService = FormTemplateService{formTemplateDao: formTemplateDao, formItemTemplateDao: formItemTemplateDao, formDao: formDao} - formItemTemplateService = FormItemTemplateService{formItemTemplateDao: formItemTemplateDao} + formItemTemplateService = FormItemTemplateService{formItemTemplateDao: formItemTemplateDao, formItemTemplateGroupDao: formItemTemplateGroupDao} roleService = RoleService{} approvalTemplateService = &ApprovalTemplateService{approvalTemplateDao: approvalTemplateDao, approvalTemplateRoleDao: approvalTemplateRoleDao} approvalService = &ApprovalService{approvalDao: approvalDao, approvalRoleDao: approvalRoleDao} diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index ded8b751..179f0703 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -15,7 +15,7 @@ type TaskTemplateService struct { } func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models.TaskTemplateDto, err error) { - result = models.TaskTemplateDto{} + result = models.TaskTemplateDto{Items: []*models.FormItemTemplateDto{}} taskTemplate, getTaskErr := getSimpleTaskTemplate("", requestTemplateId, proNodeId, nodeId) if getTaskErr != nil { log.Logger.Warn("GetTaskTemplate warning", log.Error(getTaskErr)) @@ -46,8 +46,18 @@ func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models result.UpdatedTime = formTemplateTable[0].UpdatedTime result.UpdatedBy = formTemplateTable[0].UpdatedBy var formItemTemplate []*models.FormItemTemplateTable + var formItemTemplateGroupList []*models.FormItemTemplateGroupTable + var formItemTemplateGroup *models.FormItemTemplateGroupTable dao.X.SQL("select * from form_item_template where form_template=?", taskTemplate.FormTemplate).Find(&formItemTemplate) - result.Items = formItemTemplate + if len(formItemTemplate) > 0 { + dao.X.SQL("select * from form_item_template_group where id=?", formItemTemplate[0].Id).Find(&formItemTemplateGroup) + if len(formItemTemplateGroupList) > 0 { + formItemTemplateGroup = formItemTemplateGroupList[0] + } + for _, formItem := range formItemTemplate { + result.Items = append(result.Items, models.ConvertFormItemTemplateModel2Dto(formItem, formItemTemplateGroup)) + } + } roleMap, _ := getRoleMap() var taskRoleTable []*models.TaskTemplateRoleTable dao.X.SQL("select `role`,role_type from task_template_role where task_template=?", taskTemplate.Id).Find(&taskRoleTable) From 1a62c1284c53cf31c96793666d662e3725915138 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 23 Feb 2024 01:08:20 +0800 Subject: [PATCH 046/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E8=B0=83=E6=95=B4,=E6=B7=BB=E5=8A=A0form=5Fitem=5Ftemplate=5Fg?= =?UTF-8?q?roup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/form/form_template.go | 7 - taskman-server/dao/form_item_template_dao.go | 24 +-- .../dao/form_item_template_group_dao.go | 9 ++ taskman-server/models/form_item_template.go | 26 ++- .../models/form_item_template_group.go | 1 + taskman-server/models/form_template.go | 11 +- .../service/form_item_template_service.go | 149 ++++++++++++------ .../service/form_template_service.go | 49 ++---- taskman-server/service/service.go | 2 +- .../service/task_template_service.go | 10 +- 10 files changed, 165 insertions(+), 123 deletions(-) diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index e18a6db2..3ff0c7ac 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -288,12 +288,5 @@ func validateFormTemplateItemGroupConfigParam(param models.FormTemplateGroupConf if param.ItemGroupType == "" || param.ItemGroupName == "" || param.ItemGroupRule == "" { return fmt.Errorf("param ItemGroup is empty") } - if len(param.CustomItems) > 0 { - for _, item := range param.CustomItems { - if item.ItemGroup != param.ItemGroup || item.ItemGroupName != param.ItemGroupName || item.ItemGroupType != param.ItemGroupType || item.ItemGroupRule != param.ItemGroupRule { - return fmt.Errorf("param CustomItems Id:%s is invalid", item.Id) - } - } - } return nil } diff --git a/taskman-server/dao/form_item_template_dao.go b/taskman-server/dao/form_item_template_dao.go index 2b0165e9..6a0df3e5 100644 --- a/taskman-server/dao/form_item_template_dao.go +++ b/taskman-server/dao/form_item_template_dao.go @@ -52,7 +52,7 @@ func (d FormItemTemplateDao) Get(formItemTemplateId string) (*models.FormItemTem func (d FormItemTemplateDao) QueryByFormTemplate(formTemplate string) (formItemTemplateDtoList []*models.FormItemTemplateDto, err error) { var formItemTemplateList []*models.FormItemTemplateTable - var formItemTemplateGroup *models.FormItemTemplateGroupTable + var formItemTemplateGroup models.FormItemTemplateGroupTable formItemTemplateDtoList = []*models.FormItemTemplateDto{} if formTemplate == "" { return @@ -61,8 +61,8 @@ func (d FormItemTemplateDao) QueryByFormTemplate(formTemplate string) (formItemT if err != nil { return } - if len(formItemTemplateList) > 0 { - err = d.DB.Where("id = ?", formItemTemplateList[0].ItemGroupId).Find(&formItemTemplateGroup) + if len(formItemTemplateList) > 0 && formItemTemplateList[0].ItemGroupId != "" { + _, err = d.DB.ID(formItemTemplateList[0].ItemGroupId).Get(&formItemTemplateGroup) if err != nil { return } @@ -84,11 +84,14 @@ func (d FormItemTemplateDao) QueryByFormTemplateAndItemGroupName(formTemplate, i func (d FormItemTemplateDao) QueryDtoByFormTemplateAndItemGroupName(formTemplate, itemGroupName string) (formItemTemplateDtoList []*models.FormItemTemplateDto, err error) { var formItemTemplateList []*models.FormItemTemplateTable - var formItemTemplateGroup *models.FormItemTemplateGroupTable + var formItemTemplateGroup models.FormItemTemplateGroupTable formItemTemplateDtoList = []*models.FormItemTemplateDto{} + if formTemplate == "" { + return + } err = d.DB.Where("form_template = ? and item_group_name = ?", formTemplate, itemGroupName).Find(&formItemTemplateList) - if len(formItemTemplateList) > 0 { - err = d.DB.Where("id = ?", formItemTemplateList[0].ItemGroupId).Find(&formItemTemplateList) + if len(formItemTemplateList) > 0 && formItemTemplateList[0].ItemGroupId != "" { + _, err = d.DB.ID(formItemTemplateList[0].ItemGroupId).Get(&formItemTemplateGroup) if err != nil { return } @@ -110,11 +113,14 @@ func (d FormItemTemplateDao) QueryByFormTemplateAndItemGroupId(formTemplate, ite func (d FormItemTemplateDao) QueryDtoByFormTemplateAndItemGroupId(formTemplate, itemGroupId string) (formItemTemplateDtoList []*models.FormItemTemplateDto, err error) { var formItemTemplateList []*models.FormItemTemplateTable - var formItemTemplateGroup *models.FormItemTemplateGroupTable + var formItemTemplateGroup models.FormItemTemplateGroupTable formItemTemplateDtoList = []*models.FormItemTemplateDto{} + if formTemplate == "" { + return + } err = d.DB.Where("form_template = ? and item_group_id = ?", formTemplate, itemGroupId).Find(&formItemTemplateList) - if len(formItemTemplateList) > 0 { - err = d.DB.Where("id = ?", formItemTemplateList[0].ItemGroupId).Find(&formItemTemplateList) + if len(formItemTemplateList) > 0 && formItemTemplateList[0].ItemGroupId != "" { + _, err = d.DB.ID(formItemTemplateList[0].ItemGroupId).Get(&formItemTemplateGroup) if err != nil { return } diff --git a/taskman-server/dao/form_item_template_group_dao.go b/taskman-server/dao/form_item_template_group_dao.go index 812967f7..288677a4 100644 --- a/taskman-server/dao/form_item_template_group_dao.go +++ b/taskman-server/dao/form_item_template_group_dao.go @@ -50,6 +50,15 @@ func (d FormItemTemplateGroupDao) Get(formItemTemplateGroupId string) (*models.F return nil, nil } +func (d FormItemTemplateGroupDao) QueryFormTemplate(formTemplated string) (formItemTemplateGroupList []*models.FormItemTemplateGroupTable, err error) { + formItemTemplateGroupList = []*models.FormItemTemplateGroupTable{} + err = d.DB.Where("form_template = ?", formTemplated).Find(&formItemTemplateGroupList) + if err != nil { + return + } + return +} + func (d FormItemTemplateGroupDao) DeleteByIdOrCopyId(session *xorm.Session, id string) (err error) { var affected int64 if session == nil { diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index 32769353..a37e784e 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -94,14 +94,6 @@ func (s FormItemTemplateDtoSort) Less(i, j int) bool { return false } -func ConvertFormItemTemplateList2Map(formItemTemplateList []*FormItemTemplateTable) map[string]*FormItemTemplateTable { - hashMap := make(map[string]*FormItemTemplateTable) - for _, table := range formItemTemplateList { - hashMap[table.Id] = table - } - return hashMap -} - func ConvertFormItemTemplateDto2Model(dto *FormItemTemplateDto) *FormItemTemplateTable { return &FormItemTemplateTable{ Id: dto.Id, @@ -139,7 +131,7 @@ func ConvertFormItemTemplateDto2Model(dto *FormItemTemplateDto) *FormItemTemplat } } -func ConvertFormItemTemplateModel2Dto(model *FormItemTemplateTable, itemGroup *FormItemTemplateGroupTable) *FormItemTemplateDto { +func ConvertFormItemTemplateModel2Dto(model *FormItemTemplateTable, itemGroup FormItemTemplateGroupTable) *FormItemTemplateDto { dto := &FormItemTemplateDto{ Id: model.Id, Name: model.Name, @@ -174,10 +166,16 @@ func ConvertFormItemTemplateModel2Dto(model *FormItemTemplateTable, itemGroup *F SelectList: model.SelectList, Active: model.Active, } - if itemGroup != nil { - dto.ItemGroupType = itemGroup.ItemGroupType - dto.ItemGroupRule = itemGroup.ItemGroupRule - dto.ItemGroupSort = itemGroup.ItemGroupSort - } + dto.ItemGroupType = itemGroup.ItemGroupType + dto.ItemGroupRule = itemGroup.ItemGroupRule + dto.ItemGroupSort = itemGroup.ItemGroupSort return dto } + +func ConvertFormItemTemplateModelList2Dto(tableList []*FormItemTemplateTable, itemGroup *FormItemTemplateGroupTable) []*FormItemTemplateDto { + var dtoList []*FormItemTemplateDto + for _, model := range tableList { + dtoList = append(dtoList, ConvertFormItemTemplateModel2Dto(model, *itemGroup)) + } + return dtoList +} diff --git a/taskman-server/models/form_item_template_group.go b/taskman-server/models/form_item_template_group.go index 44415e88..3ff9754e 100644 --- a/taskman-server/models/form_item_template_group.go +++ b/taskman-server/models/form_item_template_group.go @@ -9,6 +9,7 @@ type FormItemTemplateGroupTable struct { ItemGroupRule string `json:"itemGroupRule" xorm:"item_group_rule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 FormTemplate string `json:"formTemplate" xorm:"form_template"` CopyId string `json:"copyId" xorm:"copy_id"` // 复制Id + CreatedTime string `json:"createdTime" xorm:"created_time"` } func (FormItemTemplateGroupTable) TableName() string { diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index 226a5f79..a72956d3 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -119,12 +119,11 @@ func ConvertDataFormTemplate2FormTemplateDto(dto DataFormTemplateDto) FormTempla } } return FormTemplateDto{ - Id: dto.DataFormTemplateId, - Name: "globalFormTemplate", - Description: "", - ExpireDay: 0, - UpdatedBy: dto.UpdatedBy, - Items: items, + Id: dto.DataFormTemplateId, + Name: "global_form_template", + ExpireDay: 0, + UpdatedBy: dto.UpdatedBy, + Items: items, } } diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 0b3e39d5..0c2e411d 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -4,20 +4,19 @@ import ( "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "time" "xorm.io/xorm" ) -const defaultCustomFormItemName = "taskman-custom-form" - type FormItemTemplateService struct { formItemTemplateDao dao.FormItemTemplateDao formItemTemplateGroupDao dao.FormItemTemplateGroupDao } func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models.FormTemplateGroupConfigureDto) (err error) { - var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateGroup *models.FormItemTemplateGroupTable var insertItems, updateItems, deleteItems []*models.FormItemTemplateTable - var updateItemGroup *models.FormItemTemplateGroupTable + var formItemTemplateList []*models.FormItemTemplateTable var newItemGroupId string var systemItemExist, customItemExist bool var existMap = make(map[string]bool) @@ -28,12 +27,12 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. param.CustomItems = []*models.FormItemTemplateDto{} } // 1. 查询表单组是否存在,不存在则新增 - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(param.FormTemplateId, param.ItemGroupId) + formItemTemplateGroup, err = s.formItemTemplateGroupDao.Get(param.ItemGroupId) if err != nil { return } // 新增数据 - if len(formItemTemplateList) == 0 { + if formItemTemplateGroup == nil { newItemGroupId = guid.CreateGuid() if len(param.SystemItems) > 0 { for _, systemItem := range param.SystemItems { @@ -42,22 +41,26 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. } if len(param.CustomItems) > 0 { for _, customItem := range param.CustomItems { + customItem.Id = guid.CreateGuid() + customItem.ItemGroupId = newItemGroupId customItem.FormTemplate = param.FormTemplateId + customItem.ItemGroup = param.ItemGroup + customItem.ItemGroupName = param.ItemGroupName customItem.ElementType = string(models.FormItemElementTypeCalculate) insertItems = append(insertItems, models.ConvertFormItemTemplateDto2Model(customItem)) } } } else { - updateItemGroup, err = s.formItemTemplateGroupDao.Get(param.ItemGroupId) + // 直接更新表单组 + formItemTemplateGroup.ItemGroupName = param.ItemGroupName + formItemTemplateGroup.ItemGroup = param.ItemGroup + formItemTemplateGroup.ItemGroupRule = param.ItemGroupRule + formItemTemplateGroup.ItemGroupType = param.ItemGroupType + + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(param.FormTemplateId, param.ItemGroupId) if err != nil { return } - if updateItemGroup != nil { - updateItemGroup.ItemGroupName = param.ItemGroupName - updateItemGroup.ItemGroup = param.ItemGroup - updateItemGroup.ItemGroupRule = param.ItemGroupRule - updateItemGroup.ItemGroupType = param.ItemGroupType - } for _, systemItem := range param.SystemItems { systemItemExist = false existMap[systemItem.Id] = true @@ -73,16 +76,25 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. } for _, customItem := range param.CustomItems { customItemExist = false - existMap[customItem.Id] = true - for _, formItemTemplate := range formItemTemplateList { - if customItem.Id == formItemTemplate.Id { - customItemExist = true - updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(customItem)) - break + if customItem.Id != "" { + existMap[customItem.Id] = true + for _, formItemTemplate := range formItemTemplateList { + if customItem.Id == formItemTemplate.Id { + customItemExist = true + if customItem.ItemGroupId == "" { + customItem.ItemGroupId = param.ItemGroupId + } + updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(customItem)) + break + } } } if !customItemExist { + customItem.Id = guid.CreateGuid() customItem.FormTemplate = param.FormTemplateId + if customItem.ItemGroupId == "" { + customItem.ItemGroupId = param.ItemGroupId + } insertItems = append(insertItems, models.ConvertFormItemTemplateDto2Model(customItem)) } } @@ -91,9 +103,6 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. deleteItems = append(deleteItems, formItemTemplate) } } - if param.ItemGroupType == string(models.FormItemGroupTypeCustom) { - - } } err = transaction(func(session *xorm.Session) error { if newItemGroupId != "" { @@ -105,10 +114,11 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. ItemGroupSort: param.ItemGroupSort, ItemGroupRule: param.ItemGroupRule, FormTemplate: param.FormTemplateId, + CreatedTime: time.Now().Format(models.DateTimeFormat), }) } - if updateItemGroup != nil { - err = s.formItemTemplateGroupDao.Update(session, updateItemGroup) + if formItemTemplateGroup != nil { + err = s.formItemTemplateGroupDao.Update(session, formItemTemplateGroup) } if len(insertItems) > 0 { for _, item := range insertItems { @@ -145,43 +155,90 @@ func (s FormItemTemplateService) DeleteFormTemplateItemGroup(formTemplateId, ite if err != nil { return err } - if len(formItemTemplateList) > 0 { - err = transaction(func(session *xorm.Session) error { + err = transaction(func(session *xorm.Session) error { + if len(formItemTemplateList) > 0 { for _, formItemTemplate := range formItemTemplateList { err = s.formItemTemplateDao.DeleteByIdOrCopyId(session, formItemTemplate.Id) if err != nil { return err } - err = s.formItemTemplateGroupDao.DeleteByIdOrCopyId(session, itemGroupId) - if err != nil { - return err - } } - return nil - }) - } + } + err = s.formItemTemplateGroupDao.DeleteByIdOrCopyId(session, itemGroupId) + if err != nil { + return err + } + return nil + }) return } func (s FormItemTemplateService) UpdateFormTemplateItemGroup(param models.FormTemplateGroupCustomDataDto) (err error) { - if len(param.Items) > 0 { - err = transaction(func(session *xorm.Session) error { - for _, item := range param.Items { - // Id 为空新增 - if item.Id == "" { - item.Id = guid.CreateGuid() - item.FormTemplate = param.FormTemplateId - s.formItemTemplateDao.Add(session, models.ConvertFormItemTemplateDto2Model(item)) - } else { - err = s.formItemTemplateDao.Update(session, models.ConvertFormItemTemplateDto2Model(item)) + var formItemTemplateList []*models.FormItemTemplateTable + var insertItems, updateItems, deleteItems []*models.FormItemTemplateTable + var exist bool + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(param.FormTemplateId, param.ItemGroupId) + if err != nil { + return + } + if len(formItemTemplateList) == 0 { + formItemTemplateList = []*models.FormItemTemplateTable{} + } + + if len(param.Items) == 0 { + param.Items = []*models.FormItemTemplateDto{} + } + for _, item := range param.Items { + // Id 为空新增 + if item.Id == "" { + item.Id = guid.CreateGuid() + item.FormTemplate = param.FormTemplateId + item.ItemGroupId = param.ItemGroupId + insertItems = append(insertItems, models.ConvertFormItemTemplateDto2Model(item)) + } else { + item.FormTemplate = param.FormTemplateId + item.ItemGroupId = param.ItemGroupId + updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(item)) + } + } + for _, formItemTemplate := range formItemTemplateList { + exist = false + for _, item := range param.Items { + if item.Id == formItemTemplate.Id { + exist = true + } + } + if !exist { + deleteItems = append(deleteItems, formItemTemplate) + } + } + err = transaction(func(session *xorm.Session) error { + if len(insertItems) > 0 { + for _, item := range insertItems { + _, err = s.formItemTemplateDao.Add(session, item) + if err != nil { + return err + } + } + } + if len(updateItems) > 0 { + for _, item := range updateItems { + err = s.formItemTemplateDao.Update(session, item) + if err != nil { + return err } + } + } + if len(deleteItems) > 0 { + for _, item := range deleteItems { + err = s.formItemTemplateDao.Delete(session, item.Id) if err != nil { return err } } - return err - }) - } + } + return err + }) return } diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index bb9fa52c..bd43b62c 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -14,9 +14,10 @@ import ( ) type FormTemplateService struct { - formTemplateDao dao.FormTemplateDao - formItemTemplateDao dao.FormItemTemplateDao - formDao dao.FormDao + formTemplateDao dao.FormTemplateDao + formItemTemplateDao dao.FormItemTemplateDao + formItemTemplateGroupDao dao.FormItemTemplateGroupDao + formDao dao.FormDao } func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplateDto models.FormTemplateDto) (newId string, err error) { @@ -161,43 +162,25 @@ func (s FormTemplateService) GetFormTemplate(formTemplateId string) (result *mod } func (s FormTemplateService) getFormTemplateGroups(formTemplateId string) (groups []*models.FormTemplateGroupDto, err error) { - var formItemTemplateList []*models.FormItemTemplateDto - var itemGroupMap = make(map[string][]*models.FormItemTemplateDto) - var itemGroupType, itemGroupName string - var itemGroupSort int + var formItemTemplateGroupList []*models.FormItemTemplateGroupTable + var formItemTemplateList []*models.FormItemTemplateTable groups = []*models.FormTemplateGroupDto{} - formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplate(formTemplateId) + formItemTemplateGroupList, err = s.formItemTemplateGroupDao.QueryFormTemplate(formTemplateId) if err != nil { return } - if len(formItemTemplateList) == 0 { + if len(formItemTemplateGroupList) == 0 { return } - for _, formItemTemplate := range formItemTemplateList { - if _, ok := itemGroupMap[formItemTemplate.ItemGroup]; !ok { - itemGroupMap[formItemTemplate.ItemGroup] = make([]*models.FormItemTemplateDto, 0) - } - } - for itemGroup, formItemTemplateArr := range itemGroupMap { - for _, formItemTemplate := range formItemTemplateList { - if itemGroup == formItemTemplate.ItemGroup { - if formItemTemplate.ItemGroupType == string(models.FormItemGroupTypeCustom) && formItemTemplate.Name == defaultCustomFormItemName { - continue - } - formItemTemplateArr = append(formItemTemplateArr, formItemTemplate) - } - } - if len(formItemTemplateArr) > 0 { - itemGroupType = formItemTemplateArr[0].ItemGroupType - itemGroupName = formItemTemplateArr[0].ItemGroupName - itemGroupSort = formItemTemplateArr[0].ItemGroupSort - } + for _, group := range formItemTemplateGroupList { + formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(formTemplateId, group.Id) groups = append(groups, &models.FormTemplateGroupDto{ - ItemGroup: itemGroup, - ItemGroupType: itemGroupType, - ItemGroupName: itemGroupName, - ItemGroupSort: itemGroupSort, - Items: formItemTemplateArr, + ItemGroupId: group.Id, + ItemGroup: group.ItemGroup, + ItemGroupType: group.ItemGroupType, + ItemGroupName: group.ItemGroupName, + ItemGroupSort: group.ItemGroupSort, + Items: models.ConvertFormItemTemplateModelList2Dto(formItemTemplateList, group), }) } // 设置排序,保证前端展示数据顺序一致 diff --git a/taskman-server/service/service.go b/taskman-server/service/service.go index 0198cbaa..27486a43 100644 --- a/taskman-server/service/service.go +++ b/taskman-server/service/service.go @@ -83,7 +83,7 @@ func New() (err error) { formService = FormService{formDao: formDao, formItemDao: formItemDao} requestTemplateService = RequestTemplateService{requestTemplateDao: requestTemplateDao, operationLogDao: operationLogDao, requestTemplateRoleDao: requestTemplateRoleDao} requestTemplateGroupService = RequestTemplateGroupService{requestTemplateGroupDao: requestTemplateGroupDao} - formTemplateService = FormTemplateService{formTemplateDao: formTemplateDao, formItemTemplateDao: formItemTemplateDao, formDao: formDao} + formTemplateService = FormTemplateService{formTemplateDao: formTemplateDao, formItemTemplateDao: formItemTemplateDao, formDao: formDao, formItemTemplateGroupDao: formItemTemplateGroupDao} formItemTemplateService = FormItemTemplateService{formItemTemplateDao: formItemTemplateDao, formItemTemplateGroupDao: formItemTemplateGroupDao} roleService = RoleService{} approvalTemplateService = &ApprovalTemplateService{approvalTemplateDao: approvalTemplateDao, approvalTemplateRoleDao: approvalTemplateRoleDao} diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 179f0703..511222df 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -46,14 +46,10 @@ func GetTaskTemplate(requestTemplateId, proNodeId, nodeId string) (result models result.UpdatedTime = formTemplateTable[0].UpdatedTime result.UpdatedBy = formTemplateTable[0].UpdatedBy var formItemTemplate []*models.FormItemTemplateTable - var formItemTemplateGroupList []*models.FormItemTemplateGroupTable - var formItemTemplateGroup *models.FormItemTemplateGroupTable + var formItemTemplateGroup models.FormItemTemplateGroupTable dao.X.SQL("select * from form_item_template where form_template=?", taskTemplate.FormTemplate).Find(&formItemTemplate) - if len(formItemTemplate) > 0 { - dao.X.SQL("select * from form_item_template_group where id=?", formItemTemplate[0].Id).Find(&formItemTemplateGroup) - if len(formItemTemplateGroupList) > 0 { - formItemTemplateGroup = formItemTemplateGroupList[0] - } + if len(formItemTemplate) > 0 && formItemTemplate[0].ItemGroupId != "" { + dao.X.SQL("select * from form_item_template_group where id=?", formItemTemplate[0].ItemGroupId).Get(&formItemTemplateGroup) for _, formItem := range formItemTemplate { result.Items = append(result.Items, models.ConvertFormItemTemplateModel2Dto(formItem, formItemTemplateGroup)) } From ffb128e0e129f680e17cf6a51c74b8d5517e577d Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 23 Feb 2024 01:37:21 +0800 Subject: [PATCH 047/618] =?UTF-8?q?=E4=BF=A1=E6=81=AF=E8=A1=A8=E5=8D=95?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/form_template_service.go | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index bd43b62c..d5c0c342 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -21,6 +21,7 @@ type FormTemplateService struct { } func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplateDto models.FormTemplateDto) (newId string, err error) { + var groupId string newId = guid.CreateGuid() itemIds := guid.CreateGuidList(len(formTemplateDto.Items)) formTemplateDto.NowTime = time.Now().Format(models.DateTimeFormat) @@ -30,6 +31,14 @@ func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplate if err != nil { return } + // 新建 item_group + if len(formTemplateDto.Items) > 0 && formTemplateDto.Items[0].ItemGroupId == "" { + groupId = guid.CreateGuid() + _, err = s.formItemTemplateGroupDao.Add(session, &models.FormItemTemplateGroupTable{Id: groupId, ItemGroupName: "message-form", FormTemplate: newId}) + if err != nil { + return + } + } // 添加模板项 for i, item := range formTemplateDto.Items { item.Id = itemIds[i] @@ -230,10 +239,10 @@ func (s FormTemplateService) CreateRequestFormTemplate(formTemplateDto models.Fo if requestTemplate == nil { return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param id is invalid")) } - // 请求模板的处理不是当前用户,不允许操作 - if requestTemplate.Handler != formTemplateDto.UpdatedBy { - return exterror.New().DataPermissionDeny - } + /* // 请求模板的处理不是当前用户,不允许操作 + if requestTemplate.Handler != formTemplateDto.UpdatedBy { + return exterror.New().DataPermissionDeny + }*/ err = transactionWithoutForeignCheck(func(session *xorm.Session) error { // 添加表单模板 formTemplateDto.Id, err = s.AddFormTemplate(session, formTemplateDto) @@ -262,9 +271,9 @@ func (s FormTemplateService) UpdateRequestFormTemplate(formTemplateDto models.Fo return exterror.Catch(exterror.New().RequestParamValidateError, fmt.Errorf("param id is invalid")) } // 请求模板的处理不是当前用户,不允许操作 - if requestTemplate.Handler != formTemplateDto.UpdatedBy { + /*if requestTemplate.Handler != formTemplateDto.UpdatedBy { return exterror.New().DataPermissionDeny - } + }*/ formTemplate, err = s.formTemplateDao.Get(formTemplateDto.Id) if err != nil { return From f56fb1b7f85006946fc7ab1146ede6fc7d38a503 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Fri, 23 Feb 2024 10:06:22 +0800 Subject: [PATCH 048/618] =?UTF-8?q?=E5=AE=A1=E6=89=B9=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=88=9B=E5=BB=BAbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/approval_template_service.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/taskman-server/service/approval_template_service.go b/taskman-server/service/approval_template_service.go index ef46bef1..2c8d1173 100644 --- a/taskman-server/service/approval_template_service.go +++ b/taskman-server/service/approval_template_service.go @@ -24,6 +24,10 @@ func (s *ApprovalTemplateService) CreateApprovalTemplate(param *models.ApprovalT if err != nil { return nil, err } + // 校验参数 + if param.Sort <= 0 || param.Sort > len(approvalTemplates)+1 { + return nil, errors.New("param sort out of range") + } // 插入新审批模板 nowTime := time.Now().Format(models.DateTimeFormat) newApprovalTemplate := &models.ApprovalTemplateTable{ @@ -61,6 +65,8 @@ func (s *ApprovalTemplateService) CreateApprovalTemplate(param *models.ApprovalT } tmp := append(approvalTemplates[:param.Sort-1], newApprovalTemplate) approvalTemplates = append(tmp, approvalTemplates[param.Sort-1:]...) + } else { + approvalTemplates = append(approvalTemplates, newApprovalTemplate) } // 执行事务 err = dao.Transaction(actions) From 185f1bef93a6d5013339a430424f4352e3216317 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Fri, 23 Feb 2024 10:37:33 +0800 Subject: [PATCH 049/618] =?UTF-8?q?=E5=AE=A1=E6=89=B9=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=88=9B=E5=BB=BAbug=20updated=5Ftime?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/approval_template_service.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/taskman-server/service/approval_template_service.go b/taskman-server/service/approval_template_service.go index 2c8d1173..7bb64f60 100644 --- a/taskman-server/service/approval_template_service.go +++ b/taskman-server/service/approval_template_service.go @@ -59,7 +59,7 @@ func (s *ApprovalTemplateService) CreateApprovalTemplate(param *models.ApprovalT t := approvalTemplates[i-1] t.Sort += 1 t.UpdatedTime = nowTime - action = &dao.ExecAction{Sql: "UPDATE approval_template SET sort = ?, update_time = ? WHERE id = ?"} + action = &dao.ExecAction{Sql: "UPDATE approval_template SET sort = ?, updated_time = ? WHERE id = ?"} action.Param = []interface{}{t.Sort, t.UpdatedTime, t.Id} actions = append(actions, action) } @@ -121,7 +121,7 @@ func (s *ApprovalTemplateService) UpdateApprovalTemplate(param *models.ApprovalT } // 更新现有审批模板 nowTime := time.Now().Format(models.DateTimeFormat) - action := &dao.ExecAction{Sql: "UPDATE approval_template SET name = ?, expire_day = ?, description = ?, role_type = ?, update_time = ? WHERE id = ?"} + action := &dao.ExecAction{Sql: "UPDATE approval_template SET name = ?, expire_day = ?, description = ?, role_type = ?, updated_time = ? WHERE id = ?"} action.Param = []interface{}{param.Name, param.ExpireDay, param.Description, param.RoleType, nowTime, param.Id} actions = append(actions, action) // 增删改现有审批处理模板 From 4e601bf164dcfedf02f0852b6eb2d8492fd18bb2 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Fri, 23 Feb 2024 12:05:55 +0800 Subject: [PATCH 050/618] =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=A2=9E/=E6=94=B9/=E5=88=97=E8=A1=A8=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/const.go | 36 ++++ .../service/task_template_service.go | 204 +++++++++++++++++- 2 files changed, 238 insertions(+), 2 deletions(-) diff --git a/taskman-server/models/const.go b/taskman-server/models/const.go index 011e7cb3..3540815a 100644 --- a/taskman-server/models/const.go +++ b/taskman-server/models/const.go @@ -120,3 +120,39 @@ const ( ApprovalTemplateRoleHandlerTypeSystem ApprovalTemplateRoleHandlerType = "system" // 组内系统分配 ApprovalTemplateRoleHandlerTypeClaim ApprovalTemplateRoleHandlerType = "claim" // 组内主动认领 ) + +// TaskTemplateType 任务模板 类型 +type TaskTemplateType string + +const ( + TaskTemplateTypeProc TaskTemplateType = "proc" // 编排 + TaskTemplateTypeCustom TaskTemplateType = "custom" // 自定义 +) + +// TaskTemplateRoleType 任务模板 分配方式 +type TaskTemplateRoleType string + +const ( + TaskTemplateRoleTypeCustom TaskTemplateRoleType = "custom" // 单人自定义 + TaskTemplateRoleTypeAdmin TaskTemplateRoleType = "admin" // 提交人角色管理员 +) + +// TaskTemplateRoleRoleType 任务处理模板 角色设置方式 +type TaskTemplateRoleRoleType string + +const ( + TaskTemplateRoleRoleTypeTemplate TaskTemplateRoleRoleType = "template" // 模板指定 + TaskTemplateRoleRoleTypeCustom TaskTemplateRoleRoleType = "custom" // 提交人指定 +) + +// TaskTemplateRoleHandlerType 任务处理模板 人员设置方式 +type TaskTemplateRoleHandlerType string + +const ( + TaskTemplateRoleHandlerTypeTemplate TaskTemplateRoleHandlerType = "template" // 模板指定 + TaskTemplateRoleHandlerTypeTemplateSuggest TaskTemplateRoleHandlerType = "template_suggest" // 模板建议 + TaskTemplateRoleHandlerTypeCustom TaskTemplateRoleHandlerType = "custom" // 提交人指定 + TaskTemplateRoleHandlerTypeCustomSuggest TaskTemplateRoleHandlerType = "custom_suggest" // 提交人建议 + TaskTemplateRoleHandlerTypeSystem TaskTemplateRoleHandlerType = "system" // 组内系统分配 + TaskTemplateRoleHandlerTypeClaim TaskTemplateRoleHandlerType = "claim" // 组内主动认领 +) diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 511222df..4539b740 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -1,12 +1,15 @@ package service import ( + "errors" "fmt" + "strings" + "time" + "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" - "time" ) type TaskTemplateService struct { @@ -248,11 +251,153 @@ func GetTaskTemplateMapByRequestTemplate(requestTemplate string) (taskTemplateMa } func (s TaskTemplateService) CreateCustomTaskTemplate(param *models.CustomTaskTemplateCreateParam) (*models.CustomTaskTemplateCreateResponse, error) { - result := &models.CustomTaskTemplateCreateResponse{} + actions := []*dao.ExecAction{} + // 查询现有任务模板列表 + var taskTemplates []*models.TaskTemplateTable + err := s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE request_template = ? ORDER BY sort", param.RequestTemplate).Find(&taskTemplates) + if err != nil { + return nil, err + } + // 校验参数 + if param.Sort <= 0 || param.Sort > len(taskTemplates)+1 { + return nil, errors.New("param sort out of range") + } + // 插入新任务模板 + nowTime := time.Now().Format(models.DateTimeFormat) + newTaskTemplate := &models.TaskTemplateTable{ + Id: guid.CreateGuid(), + Type: string(models.TaskTemplateTypeCustom), + Sort: param.Sort, + RequestTemplate: param.RequestTemplate, + Name: param.Name, + RoleType: string(models.TaskTemplateRoleTypeCustom), + CreatedTime: nowTime, + UpdatedTime: nowTime, + } + action := &dao.ExecAction{Sql: "INSERT INTO task_template (id,type,sort,request_template,name,expire_day,role_type,created_time,updated_time) VALUES (?,?,?,?,?,?,?,?,?)"} + action.Param = []interface{}{newTaskTemplate.Id, newTaskTemplate.Type, newTaskTemplate.Sort, newTaskTemplate.RequestTemplate, newTaskTemplate.Name, newTaskTemplate.ExpireDay, newTaskTemplate.RoleType, newTaskTemplate.CreatedTime, newTaskTemplate.UpdatedTime} + actions = append(actions, action) + // 插入新任务处理模板 + newTaskTemplateRole := &models.TaskTemplateRoleTable{ + Id: guid.CreateGuid(), + TaskTemplate: newTaskTemplate.Id, + CustomRoleType: string(models.TaskTemplateRoleRoleTypeTemplate), + HandlerType: string(models.TaskTemplateRoleHandlerTypeTemplate), + } + action = &dao.ExecAction{Sql: "INSERT INTO task_template_role (id,task_template,custom_role_type,handler_type) VALUES (?,?,?,?)"} + action.Param = []interface{}{newTaskTemplateRole.Id, newTaskTemplateRole.TaskTemplate, newTaskTemplateRole.CustomRoleType, newTaskTemplateRole.HandlerType} + actions = append(actions, action) + // 如果不是尾插,则需更新现有数据的序号 + if param.Sort != len(taskTemplates)+1 { + for i := param.Sort; i < len(taskTemplates)+1; i++ { + t := taskTemplates[i-1] + t.Sort += 1 + t.UpdatedTime = nowTime + action = &dao.ExecAction{Sql: "UPDATE task_template SET sort = ?, updated_time = ? WHERE id = ?"} + action.Param = []interface{}{t.Sort, t.UpdatedTime, t.Id} + actions = append(actions, action) + } + tmp := append(taskTemplates[:param.Sort-1], newTaskTemplate) + taskTemplates = append(tmp, taskTemplates[param.Sort-1:]...) + } else { + taskTemplates = append(taskTemplates, newTaskTemplate) + } + // 执行事务 + err = dao.Transaction(actions) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.CustomTaskTemplateCreateResponse{ + Id: newTaskTemplate.Id, + Sort: newTaskTemplate.Sort, + RequestTemplate: newTaskTemplate.RequestTemplate, + Name: newTaskTemplate.Name, + Ids: make([]*models.CustomTaskTemplateIdObj, len(taskTemplates)), + } + for i, taskTemplate := range taskTemplates { + result.Ids[i] = &models.CustomTaskTemplateIdObj{ + Id: taskTemplate.Id, + Sort: taskTemplate.Sort, + Name: taskTemplate.Name, + } + } return result, nil } func (s TaskTemplateService) UpdateCustomTaskTemplate(param *models.TaskTemplateDto) error { + actions := []*dao.ExecAction{} + // 查询现有任务模板 + var taskTemplates []*models.TaskTemplateTable + err := s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE id = ?", param.Id).Find(&taskTemplates) + if err != nil { + return err + } + if len(taskTemplates) == 0 { + return errors.New("no task_template record found") + } + taskTemplate := taskTemplates[0] + // 校验参数 + if param.Type != string(models.TaskTemplateTypeCustom) { + return errors.New("param type wrong") + } + if taskTemplate.Type != param.Type || taskTemplate.Sort != param.Sort || taskTemplate.RequestTemplate != param.RequestTemplateId { + return errors.New("param type or sort or requestTemplate wrong") + } + for _, roleObj := range param.RoleObjs { + if roleObj.RoleType != string(models.TaskTemplateRoleRoleTypeTemplate) && + (roleObj.HandlerType == string(models.TaskTemplateRoleHandlerTypeTemplate) || roleObj.HandlerType == string(models.TaskTemplateRoleHandlerTypeTemplateSuggest)) { + return fmt.Errorf("roleType %s not match handlerType %s", roleObj.RoleType, roleObj.HandlerType) + } + if roleObj.RoleType != string(models.TaskTemplateRoleRoleTypeTemplate) && roleObj.Role != "" { + return fmt.Errorf("roleType %s not match role %s", roleObj.RoleType, roleObj.Role) + } + if roleObj.HandlerType != string(models.TaskTemplateRoleHandlerTypeTemplate) && roleObj.HandlerType != string(models.TaskTemplateRoleHandlerTypeTemplateSuggest) && roleObj.Handler != "" { + return fmt.Errorf("handlerType %s not match handler %s", roleObj.HandlerType, roleObj.Handler) + } + } + // 更新现有任务模板 + nowTime := time.Now().Format(models.DateTimeFormat) + action := &dao.ExecAction{Sql: "UPDATE task_template SET name = ?, expire_day = ?, description = ?, role_type = ?, updated_time = ? WHERE id = ?"} + action.Param = []interface{}{param.Name, param.ExpireDay, param.Description, param.RoleType, nowTime, param.Id} + actions = append(actions, action) + // 增删改现有任务处理模板 + if param.RoleType == string(models.TaskTemplateRoleTypeAdmin) { + action = &dao.ExecAction{Sql: "DELETE FROM task_template_role WHERE task_template = ?"} + action.Param = []interface{}{param.Id} + actions = append(actions, action) + } else { + // 查询现有任务处理模板 + var taskTemplateRoles []*models.TaskTemplateRoleTable + err = s.taskTemplateRoleDao.DB.SQL("SELECT * FROM task_template_role WHERE task_template = ?", param.Id).Find(&taskTemplateRoles) + if err != nil { + return err + } + // 对比增删改 + for i, taskTemplateRole := range taskTemplateRoles { + if i < len(param.RoleObjs) { + roleObj := param.RoleObjs[i] + action = &dao.ExecAction{Sql: "UPDATE task_template_role SET custom_role_type = ?, handler_type = ?, custom_role = ?, handler = ? WHERE id = ?"} + action.Param = []interface{}{roleObj.RoleType, roleObj.HandlerType, roleObj.Role, roleObj.Handler, taskTemplateRole.Id} + actions = append(actions, action) + } else { + action = &dao.ExecAction{Sql: "DELETE FROM task_template_role WHERE id = ?"} + action.Param = []interface{}{taskTemplateRole.Id} + actions = append(actions, action) + } + } + for sort := len(taskTemplateRoles) + 1; sort <= len(param.RoleObjs); sort++ { + roleObj := param.RoleObjs[sort-1] + action = &dao.ExecAction{Sql: "INSERT INTO task_template_role (id,task_template,custom_role_type,handler_type,custom_role,handler) VALUES (?,?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), param.Id, roleObj.RoleType, roleObj.HandlerType, roleObj.Role, roleObj.Handler} + actions = append(actions, action) + } + } + // 执行事务 + err = dao.Transaction(actions) + if err != nil { + return err + } return nil } @@ -273,5 +418,60 @@ func (s TaskTemplateService) ListCustomTaskTemplateIds(requestTemplateId string) func (s TaskTemplateService) ListCustomTaskTemplate(requestTemplateId string) ([]*models.TaskTemplateDto, error) { result := []*models.TaskTemplateDto{} + // 查询现有任务模板列表 + var taskTemplates []*models.TaskTemplateTable + err := s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE request_template = ? ORDER BY sort", requestTemplateId).Find(&taskTemplates) + if err != nil { + return nil, err + } + if len(taskTemplates) == 0 { + return result, nil + } + // 汇总任务模板列表 + taskTemplateIds := make([]string, len(taskTemplates)) + for i, taskTemplate := range taskTemplates { + taskTemplateIds[i] = taskTemplate.Id + } + // 查询现有任务处理模板列表 + var taskTemplateRoles []*models.TaskTemplateRoleTable + err = s.taskTemplateRoleDao.DB.SQL("SELECT * FROM task_template_role WHERE task_template IN ('" + strings.Join(taskTemplateIds, "','") + "') ORDER BY task_template").Find(&taskTemplateRoles) + if err != nil { + return nil, err + } + // 汇总任务处理模板列表 + taskTemplateRoleMap := make(map[string][]*models.TaskTemplateRoleTable) + taskTemplateId := "" + for _, taskTemplateRole := range taskTemplateRoles { + if taskTemplateId != taskTemplateRole.TaskTemplate { + taskTemplateId = taskTemplateRole.TaskTemplate + taskTemplateRoleMap[taskTemplateId] = make([]*models.TaskTemplateRoleTable, 0) + } + taskTemplateRoleMap[taskTemplateId] = append(taskTemplateRoleMap[taskTemplateId], taskTemplateRole) + } + // 构造返回结果 + result = make([]*models.TaskTemplateDto, len(taskTemplates)) + for i, taskTemplate := range taskTemplates { + result[i] = &models.TaskTemplateDto{ + Id: taskTemplate.Id, + Type: taskTemplate.Type, + Sort: taskTemplate.Sort, + RequestTemplateId: taskTemplate.RequestTemplate, + Name: taskTemplate.Name, + ExpireDay: taskTemplate.ExpireDay, + Description: taskTemplate.Description, + RoleType: taskTemplate.RoleType, + } + if roleObjs, ok := taskTemplateRoleMap[taskTemplate.Id]; ok { + result[i].RoleObjs = make([]*models.TaskTemplateRoleDto, len(roleObjs)) + for j, roleObj := range roleObjs { + result[i].RoleObjs[j] = &models.TaskTemplateRoleDto{ + RoleType: roleObj.CustomRoleType, + HandlerType: roleObj.HandlerType, + Role: roleObj.CustomRole, + Handler: roleObj.Handler, + } + } + } + } return result, nil } From eda0a598ee150ed2babb0a524703e18f26feb004 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 23 Feb 2024 13:08:59 +0800 Subject: [PATCH 051/618] =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E8=A1=A8?= =?UTF-8?q?=E5=8D=95=E7=BB=84=E6=9F=A5=E8=AF=A2=E9=80=BB=E8=BE=91=E8=B0=83?= =?UTF-8?q?=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/form_template_service.go | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index d5c0c342..929c017e 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -34,7 +34,7 @@ func (s FormTemplateService) AddFormTemplate(session *xorm.Session, formTemplate // 新建 item_group if len(formTemplateDto.Items) > 0 && formTemplateDto.Items[0].ItemGroupId == "" { groupId = guid.CreateGuid() - _, err = s.formItemTemplateGroupDao.Add(session, &models.FormItemTemplateGroupTable{Id: groupId, ItemGroupName: "message-form", FormTemplate: newId}) + _, err = s.formItemTemplateGroupDao.Add(session, &models.FormItemTemplateGroupTable{Id: groupId, ItemGroupName: "message-form", FormTemplate: newId, CreatedTime: time.Now().Format(models.DateTimeFormat)}) if err != nil { return } @@ -395,18 +395,26 @@ func (s FormTemplateService) GetDataFormConfig(formTemplateId, itemGroupId, form var entitiesList []*models.ExpressionEntities var expressEntity *models.ExpressionEntities var existAttrMap = make(map[string]bool) - configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateDto{}} + var formItemTemplateGroup *models.FormItemTemplateGroupTable + configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, ItemGroupId: itemGroupId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateDto{}} // 1.先查询用户配置数据 if itemGroupId != "" { formItemTemplateList, err = s.formItemTemplateDao.QueryDtoByFormTemplateAndItemGroupId(formTemplateId, itemGroupId) if err != nil { return } + // 查询表单组 + formItemTemplateGroup, err = s.formItemTemplateGroupDao.Get(itemGroupId) + if err != nil { + return + } + if formItemTemplateGroup != nil { + configureDto.ItemGroup = formItemTemplateGroup.ItemGroup + configureDto.ItemGroupName = formItemTemplateGroup.ItemGroupName + configureDto.ItemGroupType = formItemTemplateGroup.ItemGroupType + configureDto.ItemGroupRule = formItemTemplateGroup.ItemGroupRule + } if len(formItemTemplateList) > 0 { - configureDto.ItemGroup = formItemTemplateList[0].ItemGroup - configureDto.ItemGroupName = formItemTemplateList[0].ItemGroupName - configureDto.ItemGroupType = formItemTemplateList[0].ItemGroupType - configureDto.ItemGroupRule = formItemTemplateList[0].ItemGroupRule for _, formItem := range formItemTemplateList { if formItem.ItemGroupType == string(models.FormItemGroupTypeCustom) { configureDto.CustomItems = append(configureDto.CustomItems, formItem) From 290570b71a3f5d792a9c9bf458431dc04ef8abf5 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 23 Feb 2024 14:42:32 +0800 Subject: [PATCH 052/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=8E=92=E5=BA=8F?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/v1/form/form_template.go | 2 +- taskman-server/dao/request_template_dao.go | 4 ++-- taskman-server/models/request_template.go | 3 +++ .../service/form_item_template_service.go | 20 ++++++++++++++++++- .../service/form_template_service.go | 8 +++++--- .../service/request_template_service.go | 4 ++-- 6 files changed, 32 insertions(+), 9 deletions(-) diff --git a/taskman-server/api/v1/form/form_template.go b/taskman-server/api/v1/form/form_template.go index 3ff0c7ac..dd874eff 100644 --- a/taskman-server/api/v1/form/form_template.go +++ b/taskman-server/api/v1/form/form_template.go @@ -149,7 +149,7 @@ func GetDataFormTemplateItemGroupConfig(c *gin.Context) { middleware.ReturnParamEmptyError(c, "request-template-id or item-group-id or form-template-id") return } - configureDto, err = service.GetFormTemplateService().GetDataFormConfig(formTemplateId, itemGroupId, formType, entity, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + configureDto, err = service.GetFormTemplateService().GetDataFormConfig(requestTemplateId, formTemplateId, itemGroupId, formType, entity, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/dao/request_template_dao.go b/taskman-server/dao/request_template_dao.go index e3af4efc..0d8f7e33 100644 --- a/taskman-server/dao/request_template_dao.go +++ b/taskman-server/dao/request_template_dao.go @@ -31,10 +31,10 @@ func (d RequestTemplateDao) AddBasicInfo(session *xorm.Session, template *models } result, err = session.Exec("insert into request_template(id,`group`,name,description,tags,package_name,entity_name,proc_def_key,proc_def_id,"+ "proc_def_name,expire_day,handler,created_by,created_time,updated_by,updated_time,type,operator_obj_type,parent_id,approve_by,pending_switch,"+ - "pending_role,pending_handler,confirm_switch,confirm_expire_day,rollback_desc) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", template.Id, + "pending_role,pending_handler,confirm_switch,confirm_expire_day,rollback_desc,pending_expire_day) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", template.Id, template.Group, template.Name, template.Description, template.Tags, template.PackageName, template.EntityName, template.ProcDefKey, template.ProcDefId, template.ProcDefName, template.ExpireDay, template.Handler, template.CreatedBy, template.CreatedTime, template.UpdatedBy, template.UpdatedTime, template.Type, template.OperatorObjType, - template.Id, template.ApproveBy, template.PendingSwitch, template.PendingRole, template.PendingHandler, template.ConfirmSwitch, template.ConfirmExpireDay, template.RollbackDesc) + template.Id, template.ApproveBy, template.PendingSwitch, template.PendingRole, template.PendingHandler, template.ConfirmSwitch, template.ConfirmExpireDay, template.RollbackDesc, template.PendingExpireDay) if err != nil { return } diff --git a/taskman-server/models/request_template.go b/taskman-server/models/request_template.go index 513672bf..c8a5d30c 100644 --- a/taskman-server/models/request_template.go +++ b/taskman-server/models/request_template.go @@ -35,6 +35,7 @@ type RequestTemplateTable struct { ApproveBy string `json:"approveBy" xorm:"approve_by"` // 模板发布审批人 PendingSwitch bool `json:"pendingSwitch" xorm:"pending_switch"` // 是否加入确认定版流程 PendingRole string `json:"pendingRole" xorm:"pending_role"` // 定版角色 + PendingExpireDay int `json:"pendingExpireDay" xorm:"pending_expire_day"` // 定版时效 PendingHandler string `json:"pendingHandler" xorm:"pending_handler"` // 定版处理人 ConfirmSwitch bool `json:"confirmSwitch" xorm:"confirm_switch"` // 是否加入确认流程 ConfirmExpireDay int `json:"confirmExpireDay" xorm:"confirm_expire_day"` // 确认过期时间 @@ -208,12 +209,14 @@ func ConvertRequestTemplateUpdateParam2RequestTemplate(param RequestTemplateUpda UpdatedTime: nowTime, ExpireDay: param.ExpireDay, Handler: param.Handler, + DelFlag: 0, Type: param.Type, OperatorObjType: param.OperatorObjType, ParentId: param.Id, ApproveBy: param.ApproveBy, PendingSwitch: param.PendingSwitch, PendingRole: param.PendingRole, + PendingExpireDay: param.PendingExpireDay, PendingHandler: param.PendingHandler, ConfirmSwitch: param.ConfirmSwitch, ConfirmExpireDay: param.ConfirmExpireDay, diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 0c2e411d..197f941a 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -2,6 +2,7 @@ package service import ( "github.com/WeBankPartners/go-common-lib/guid" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "time" @@ -111,7 +112,7 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. ItemGroup: param.ItemGroup, ItemGroupType: param.ItemGroupType, ItemGroupName: param.ItemGroupName, - ItemGroupSort: param.ItemGroupSort, + ItemGroupSort: s.CalcItemGroupSort(param.FormTemplateId), ItemGroupRule: param.ItemGroupRule, FormTemplate: param.FormTemplateId, CreatedTime: time.Now().Format(models.DateTimeFormat), @@ -149,6 +150,23 @@ func (s FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models. return } +func (s FormItemTemplateService) CalcItemGroupSort(formTemplateId string) int { + var max = 0 + list, err := s.formItemTemplateGroupDao.QueryFormTemplate(formTemplateId) + if err != nil { + log.Logger.Error("CalcItemGroupSort err", log.Error(err)) + return 0 + } + if len(list) > 0 { + for _, group := range list { + if group.ItemGroupSort >= max { + max = group.ItemGroupSort + } + } + } + return max + 1 +} + func (s FormItemTemplateService) DeleteFormTemplateItemGroup(formTemplateId, itemGroupId string) (err error) { var formItemTemplateList []*models.FormItemTemplateTable formItemTemplateList, err = s.formItemTemplateDao.QueryByFormTemplateAndItemGroupId(formTemplateId, itemGroupId) diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index 929c017e..67d79977 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -361,7 +361,7 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it } } // 2. 查询数据表单 - dataFormConfigureDto, err = s.GetDataFormConfig(requestTemplate.DataFormTemplate, itemGroupId, "", "", userToken, language) + dataFormConfigureDto, err = s.GetDataFormConfig(requestTemplateId, requestTemplate.DataFormTemplate, itemGroupId, "", "", userToken, language) if err != nil { return } @@ -390,13 +390,13 @@ func (s FormTemplateService) GetFormConfig(requestTemplateId, formTemplateId, it } // GetDataFormConfig 获取数据表单配置 -func (s FormTemplateService) GetDataFormConfig(formTemplateId, itemGroupId, formType, entity, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { +func (s FormTemplateService) GetDataFormConfig(requestTemplateId, formTemplateId, itemGroupId, formType, entity, userToken, language string) (configureDto *models.FormTemplateGroupConfigureDto, err error) { var formItemTemplateList []*models.FormItemTemplateDto var entitiesList []*models.ExpressionEntities var expressEntity *models.ExpressionEntities var existAttrMap = make(map[string]bool) var formItemTemplateGroup *models.FormItemTemplateGroupTable - configureDto = &models.FormTemplateGroupConfigureDto{FormTemplateId: formTemplateId, ItemGroupId: itemGroupId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateDto{}} + configureDto = &models.FormTemplateGroupConfigureDto{RequestTemplateId: requestTemplateId, FormTemplateId: formTemplateId, SystemItems: []*models.ProcEntityAttributeObj{}, CustomItems: []*models.FormItemTemplateDto{}} // 1.先查询用户配置数据 if itemGroupId != "" { formItemTemplateList, err = s.formItemTemplateDao.QueryDtoByFormTemplateAndItemGroupId(formTemplateId, itemGroupId) @@ -409,10 +409,12 @@ func (s FormTemplateService) GetDataFormConfig(formTemplateId, itemGroupId, form return } if formItemTemplateGroup != nil { + configureDto.ItemGroupId = itemGroupId configureDto.ItemGroup = formItemTemplateGroup.ItemGroup configureDto.ItemGroupName = formItemTemplateGroup.ItemGroupName configureDto.ItemGroupType = formItemTemplateGroup.ItemGroupType configureDto.ItemGroupRule = formItemTemplateGroup.ItemGroupRule + configureDto.ItemGroupSort = formItemTemplateGroup.ItemGroupSort } if len(formItemTemplateList) > 0 { for _, formItem := range formItemTemplateList { diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 0b6234d8..99e9ca7f 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -392,10 +392,10 @@ func (s RequestTemplateService) UpdateRequestTemplate(param *models.RequestTempl result = models.RequestTemplateQueryObj{RequestTemplateTable: param.RequestTemplateTable, MGMTRoles: []*models.RoleTable{}, USERoles: []*models.RoleTable{}} updateAction := dao.ExecAction{Sql: "update request_template set status='created',`group`=?,name=?,description=?,tags=?,package_name=?,entity_name=?," + "proc_def_key=?,proc_def_id=?,proc_def_name=?,expire_day=?,handler=?,updated_by=?,updated_time=?,type=?,operator_obj_type=?,approve_by=?,pending_switch=?," + - "pending_role=?,pending_handler=?,confirm_switch=?,confirm_expire_day=? where id=?"} + "pending_role=?,pending_handler=?,confirm_switch=?,confirm_expire_day=?,pending_expire_day=? where id=?"} updateAction.Param = []interface{}{param.Group, param.Name, param.Description, param.Tags, param.PackageName, param.EntityName, param.ProcDefKey, param.ProcDefId, param.ProcDefName, param.ExpireDay, param.Handler, param.UpdatedBy, nowTime, param.Type, param.OperatorObjType, param.ApproveBy, - param.PendingSwitch, param.PendingRole, param.PendingHandler, param.ConfirmSwitch, param.ConfirmExpireDay, param.Id} + param.PendingSwitch, param.PendingRole, param.PendingHandler, param.ConfirmSwitch, param.ConfirmExpireDay, param.PendingExpireDay, param.Id} actions = append(actions, &updateAction) actions = append(actions, &dao.ExecAction{Sql: "delete from request_template_role where request_template=?", Param: []interface{}{param.Id}}) for _, v := range param.MGMTRoles { From 1d279b8e84b3d379acce4924bc868d421c09422b Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Fri, 23 Feb 2024 15:00:56 +0800 Subject: [PATCH 053/618] =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=8E=92=E5=BA=8F?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/form_template.go | 4 ++-- taskman-server/service/form_template_service.go | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/taskman-server/models/form_template.go b/taskman-server/models/form_template.go index a72956d3..62c4caf9 100644 --- a/taskman-server/models/form_template.go +++ b/taskman-server/models/form_template.go @@ -30,7 +30,7 @@ type FormTemplateDto struct { // DataFormTemplateDto 全局表单模板 dto type DataFormTemplateDto struct { - DataFormTemplateId string `json:"dataFormTemplateId"` // 数据表单模板ID + FormTemplateId string `json:"formTemplateId"` // 数据表单模板ID AssociationWorkflow bool `json:"associationWorkflow"` // 是否关联编排 UpdatedBy string `json:"updatedBy"` // 更新人 Groups []*FormTemplateGroupDto `json:"groups"` @@ -119,7 +119,7 @@ func ConvertDataFormTemplate2FormTemplateDto(dto DataFormTemplateDto) FormTempla } } return FormTemplateDto{ - Id: dto.DataFormTemplateId, + Id: dto.FormTemplateId, Name: "global_form_template", ExpireDay: 0, UpdatedBy: dto.UpdatedBy, diff --git a/taskman-server/service/form_template_service.go b/taskman-server/service/form_template_service.go index 67d79977..46668c9b 100644 --- a/taskman-server/service/form_template_service.go +++ b/taskman-server/service/form_template_service.go @@ -159,7 +159,7 @@ func (s FormTemplateService) GetDataFormTemplate(requestTemplateId string) (resu } requestTemplate, _ = GetRequestTemplateService().GetRequestTemplate(requestTemplateId) } - result = &models.DataFormTemplateDto{DataFormTemplateId: requestTemplate.DataFormTemplate, Groups: make([]*models.FormTemplateGroupDto, 0), AssociationWorkflow: associationWorkflow} + result = &models.DataFormTemplateDto{FormTemplateId: requestTemplate.DataFormTemplate, Groups: make([]*models.FormTemplateGroupDto, 0), AssociationWorkflow: associationWorkflow} result.Groups, err = s.getFormTemplateGroups(requestTemplate.DataFormTemplate) return } @@ -313,12 +313,12 @@ func (s FormTemplateService) CreateDataFormTemplate(formTemplateDto models.DataF } err = transactionWithoutForeignCheck(func(session *xorm.Session) error { // 添加表单模板 - formTemplateDto.DataFormTemplateId, err = s.AddFormTemplate(session, models.ConvertDataFormTemplate2FormTemplateDto(formTemplateDto)) + formTemplateDto.FormTemplateId, err = s.AddFormTemplate(session, models.ConvertDataFormTemplate2FormTemplateDto(formTemplateDto)) if err != nil { return err } // 更新模板 - err = GetRequestTemplateService().UpdateRequestTemplateDataForm(session, requestTemplateId, formTemplateDto.DataFormTemplateId, formTemplateDto.UpdatedBy) + err = GetRequestTemplateService().UpdateRequestTemplateDataForm(session, requestTemplateId, formTemplateDto.FormTemplateId, formTemplateDto.UpdatedBy) if err != nil { return err } From c237f7dbfc36a0740b77085d0ab2bf78869c9eb6 Mon Sep 17 00:00:00 2001 From: pobu168 <244202969@qq.com> Date: Fri, 23 Feb 2024 16:20:14 +0800 Subject: [PATCH 054/618] add: data from --- taskman-ui/src/api/server.js | 12 + taskman-ui/src/locale/i18n/en-US.json | 4 +- taskman-ui/src/locale/i18n/zh-CN.json | 6 +- .../src/pages/temp-management/basic-info.vue | 22 +- .../src/pages/temp-management/index.vue | 25 +- .../temp-management/request-form copy.vue | 814 ++++++++++++++++++ .../request-form-data-custom.vue | 143 +++ .../request-form-data-optional.vue | 383 ++++++++ .../request-form-data-workflow.vue | 182 ++++ .../temp-management/request-form-data.vue | 795 +++++++++++++++++ .../temp-management/request-form-msg copy.vue | 814 ++++++++++++++++++ .../temp-management/request-form-msg.vue | 625 ++++++++++++++ .../pages/temp-management/request-form.vue | 799 +---------------- 13 files changed, 3825 insertions(+), 799 deletions(-) create mode 100644 taskman-ui/src/pages/temp-management/request-form copy.vue create mode 100644 taskman-ui/src/pages/temp-management/request-form-data-custom.vue create mode 100644 taskman-ui/src/pages/temp-management/request-form-data-optional.vue create mode 100644 taskman-ui/src/pages/temp-management/request-form-data-workflow.vue create mode 100644 taskman-ui/src/pages/temp-management/request-form-data.vue create mode 100644 taskman-ui/src/pages/temp-management/request-form-msg copy.vue create mode 100644 taskman-ui/src/pages/temp-management/request-form-msg.vue diff --git a/taskman-ui/src/api/server.js b/taskman-ui/src/api/server.js index 1c9b560f..c890ed21 100755 --- a/taskman-ui/src/api/server.js +++ b/taskman-ui/src/api/server.js @@ -146,3 +146,15 @@ export const getNodeContextByNodeId = (instanceId, nodeId) => req.post(`/taskman/api/v1/request/workflow/task_node/${instanceId}/${nodeId}`) export const getAllDataModels = () => req.get(`/platform/v1/models`) +// 获取可添加表单组 +export const getEntityByTemplateId = tmpId => req.get(`/taskman/api/v1/request-template/${tmpId}/entity`) + +export const getRequestDataForm = tmpId => req.get(`/taskman/api/v1/request-form-template/${tmpId}/data-form`) +export const saveRequestGroupForm = data => req.post(`/taskman/api/v1/form-template/item-group-config`, data) +export const deleteRequestGroupForm = (tmpId, formTemplateId) => + req.delete(`/taskman/api/v1/form-template/item-group?item-group-id=${tmpId}&form-template-id=${formTemplateId}`) +export const saveRequestGroupCustomForm = data => req.post(`/taskman/api/v1/form-template/item-group`, data) +export const getRequestGroupForm = (tmpId, formTemplateId, itemGroupId) => + req.get( + `/taskman/api/v1/data-form-template/item-group-config?request-template-id=${tmpId}&form-template-id=${formTemplateId}&item-group-id=${itemGroupId}` + ) diff --git a/taskman-ui/src/locale/i18n/en-US.json b/taskman-ui/src/locale/i18n/en-US.json index 870c76e7..b227a868 100755 --- a/taskman-ui/src/locale/i18n/en-US.json +++ b/taskman-ui/src/locale/i18n/en-US.json @@ -148,6 +148,9 @@ "status_inProgress_timeouted": "InProgress(Timeouted)", "status_faulted": "Faulted", "status_draft": "Draft", + "abandon": "Abandon", + "confirm_discarding_changes": "Confirm Discarding Changes", + "params_edit_confirm": "The data changes, if you choose to give up, the changed information will not be saved!", "tw_yes": "yes", "tw_no": "no", "tw_default_empty": "Default clear", @@ -207,7 +210,6 @@ "tw_use_template": "Using Template", "tw_request_des": "Request Description", "tw_upload_10_error": "File Upload Failed: Please ensure the file size is below 10MB and try again.", - "tw_handle_history": "Processing Record", "tw_submit_request": "Submit", "tw_submit_approval": "Submit Approval", diff --git a/taskman-ui/src/locale/i18n/zh-CN.json b/taskman-ui/src/locale/i18n/zh-CN.json index c8bf37f9..95e1fc84 100755 --- a/taskman-ui/src/locale/i18n/zh-CN.json +++ b/taskman-ui/src/locale/i18n/zh-CN.json @@ -42,7 +42,7 @@ "form_settings": "表单填写", "input_items": "输入项", "output_items": "输出项", - "custom_form": "自定义表单", + "custom_form": "自定义表单项", "general_attributes": "通用属性", "field_name": "字段名", "display_name": "显示名", @@ -148,6 +148,9 @@ "status_inProgress_timeouted": "节点超时", "status_faulted": "自动退出", "status_draft": "草稿", + "abandon": "放弃", + "confirm_discarding_changes": "确认放弃改动", + "params_edit_confirm": "数据发生变化,选择放弃则变化信息不会被保存!", "tw_yes": "是", "tw_no": "否", "tw_default_empty": "默认清空", @@ -207,7 +210,6 @@ "tw_use_template": "使用模板", "tw_request_des": "请求描述", "tw_upload_10_error": "文件上传失败,请上传大小小于10M的文件", - "tw_handle_history": "处理历史", "tw_submit_request": "提交请求", "tw_submit_approval": "提交审批", diff --git a/taskman-ui/src/pages/temp-management/basic-info.vue b/taskman-ui/src/pages/temp-management/basic-info.vue index 34595e56..bf42dce7 100644 --- a/taskman-ui/src/pages/temp-management/basic-info.vue +++ b/taskman-ui/src/pages/temp-management/basic-info.vue @@ -3,7 +3,6 @@ - {{ isParmasChanged }}
@@ -175,6 +174,15 @@ }} + + + + * +
@@ -225,7 +233,7 @@ -
+
@@ -262,6 +270,7 @@ export default { pendingSwitch: false, // 定版节点 pendingRole: '', // 定版角色 pendingHandler: '', // 定版处理人 + pendingExpireDay: 1, // 定版节点时效 procDefId: '', confirmSwitch: false, // 结束确认节点 confirmExpireDay: 1 // 确认过期时间 @@ -297,9 +306,7 @@ export default { this.isParmasChanged = false this.getGroupOptions() this.getManagementRoles() - // this.getHandlerRoles() this.getUserRoles() - this.getPendingHandlerRoles() this.getProcess() this.getTemplateData() }, @@ -373,9 +380,10 @@ export default { this.basicInfo = templateData this.basicInfo.mgmtRoles = templateData.mgmtRoles[0].id this.basicInfo.useRoles = templateData.useRoles.map(role => role.id) - + this.showFlow = templateData.procDefId !== '' this.getTags() this.getHandlerRoles() + this.getPendingHandlerRoles() } } }, @@ -391,11 +399,11 @@ export default { this.createTemp() }, onCancel: () => { - console.log('next') + this.$emit('gotoNextStep', this.requestTemplateId || this.basicInfo.id) } }) } else { - console.log('next') + this.$emit('gotoNextStep', this.requestTemplateId || this.basicInfo.id) } }, // 获取模版组信息 diff --git a/taskman-ui/src/pages/temp-management/index.vue b/taskman-ui/src/pages/temp-management/index.vue index 5b064774..31e9b12f 100644 --- a/taskman-ui/src/pages/temp-management/index.vue +++ b/taskman-ui/src/pages/temp-management/index.vue @@ -9,9 +9,6 @@ {{ $t('basic_information_settings') }} - - {{ $t('form_item_selection') }} - {{ $t('request_form_settings') }} @@ -32,27 +29,21 @@
- - +
+ + diff --git a/taskman-ui/src/pages/temp-management/request-form-data-custom.vue b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue new file mode 100644 index 00000000..19128f06 --- /dev/null +++ b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue @@ -0,0 +1,143 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/request-form-data-optional.vue b/taskman-ui/src/pages/temp-management/request-form-data-optional.vue new file mode 100644 index 00000000..bb410c52 --- /dev/null +++ b/taskman-ui/src/pages/temp-management/request-form-data-optional.vue @@ -0,0 +1,383 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue new file mode 100644 index 00000000..4b75faf9 --- /dev/null +++ b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue @@ -0,0 +1,182 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue new file mode 100644 index 00000000..115f5751 --- /dev/null +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -0,0 +1,795 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/request-form-msg copy.vue b/taskman-ui/src/pages/temp-management/request-form-msg copy.vue new file mode 100644 index 00000000..54e09231 --- /dev/null +++ b/taskman-ui/src/pages/temp-management/request-form-msg copy.vue @@ -0,0 +1,814 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/request-form-msg.vue b/taskman-ui/src/pages/temp-management/request-form-msg.vue new file mode 100644 index 00000000..51dd81df --- /dev/null +++ b/taskman-ui/src/pages/temp-management/request-form-msg.vue @@ -0,0 +1,625 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/request-form.vue b/taskman-ui/src/pages/temp-management/request-form.vue index 54e09231..26f0fd06 100644 --- a/taskman-ui/src/pages/temp-management/request-form.vue +++ b/taskman-ui/src/pages/temp-management/request-form.vue @@ -1,789 +1,48 @@ From bd8a04efc3882daab354d8f282706b728ea4f5a9 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Fri, 23 Feb 2024 16:54:44 +0800 Subject: [PATCH 055/618] =?UTF-8?q?=E5=AE=A1=E6=89=B9/=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=88=9B=E5=BB=BAbug=20=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/approval_template_service.go | 7 +++++-- taskman-server/service/task_template_service.go | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/taskman-server/service/approval_template_service.go b/taskman-server/service/approval_template_service.go index 7bb64f60..8290d336 100644 --- a/taskman-server/service/approval_template_service.go +++ b/taskman-server/service/approval_template_service.go @@ -63,8 +63,11 @@ func (s *ApprovalTemplateService) CreateApprovalTemplate(param *models.ApprovalT action.Param = []interface{}{t.Sort, t.UpdatedTime, t.Id} actions = append(actions, action) } - tmp := append(approvalTemplates[:param.Sort-1], newApprovalTemplate) - approvalTemplates = append(tmp, approvalTemplates[param.Sort-1:]...) + tmp := make([]*models.ApprovalTemplateTable, len(approvalTemplates)+1) + copy(tmp, approvalTemplates[:param.Sort-1]) + tmp[param.Sort-1] = newApprovalTemplate + copy(tmp[param.Sort:], approvalTemplates[:param.Sort-1]) + approvalTemplates = tmp } else { approvalTemplates = append(approvalTemplates, newApprovalTemplate) } diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 4539b740..e01dab71 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -297,8 +297,11 @@ func (s TaskTemplateService) CreateCustomTaskTemplate(param *models.CustomTaskTe action.Param = []interface{}{t.Sort, t.UpdatedTime, t.Id} actions = append(actions, action) } - tmp := append(taskTemplates[:param.Sort-1], newTaskTemplate) - taskTemplates = append(tmp, taskTemplates[param.Sort-1:]...) + tmp := make([]*models.TaskTemplateTable, len(taskTemplates)+1) + copy(tmp, taskTemplates[:param.Sort-1]) + tmp[param.Sort-1] = newTaskTemplate + copy(tmp[param.Sort:], taskTemplates[:param.Sort-1]) + taskTemplates = tmp } else { taskTemplates = append(taskTemplates, newTaskTemplate) } From 3388e8a4039fe7764b50b27aa6c648cbaa96fad7 Mon Sep 17 00:00:00 2001 From: pobu168 <244202969@qq.com> Date: Fri, 23 Feb 2024 18:06:43 +0800 Subject: [PATCH 056/618] update: data form --- taskman-ui/src/api/server.js | 4 +- .../request-form-data-custom.vue | 4 +- .../request-form-data-workflow.vue | 96 ++++++++++++++----- .../temp-management/request-form-data.vue | 43 ++++++++- 4 files changed, 113 insertions(+), 34 deletions(-) diff --git a/taskman-ui/src/api/server.js b/taskman-ui/src/api/server.js index c890ed21..5f94811f 100755 --- a/taskman-ui/src/api/server.js +++ b/taskman-ui/src/api/server.js @@ -154,7 +154,7 @@ export const saveRequestGroupForm = data => req.post(`/taskman/api/v1/form-templ export const deleteRequestGroupForm = (tmpId, formTemplateId) => req.delete(`/taskman/api/v1/form-template/item-group?item-group-id=${tmpId}&form-template-id=${formTemplateId}`) export const saveRequestGroupCustomForm = data => req.post(`/taskman/api/v1/form-template/item-group`, data) -export const getRequestGroupForm = (tmpId, formTemplateId, itemGroupId) => +export const getRequestGroupForm = params => req.get( - `/taskman/api/v1/data-form-template/item-group-config?request-template-id=${tmpId}&form-template-id=${formTemplateId}&item-group-id=${itemGroupId}` + `/taskman/api/v1/data-form-template/item-group-config?entity=${params.entity}&form-type=${params.formType}&request-template-id=${params.requestTemplateId}&form-template-id=${params.formTemplateId}&item-group-id=${params.itemGroupId}` ) diff --git a/taskman-ui/src/pages/temp-management/request-form-data-custom.vue b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue index 19128f06..794a15d2 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data-custom.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue @@ -50,8 +50,8 @@ export default { itemGroupName: '', // 组名称 itemGroupSort: -1, // 组顺序 itemGroupRule: 'new', // 新增一行 - systemItems: [], - customItems: [] + systemItems: [], // 预制表单字段 + customItems: [] // 自定义分析字段 } } }, diff --git a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue index 4b75faf9..ec52c4c1 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue @@ -3,7 +3,9 @@
- + @@ -18,6 +20,13 @@ * 预制表单字段 +
+ + + {{ system.description }} + + +
自定义分析字段 字段名称 @@ -62,6 +71,16 @@ export default { { label: '输入新数据', value: 'new' }, { label: '选择已有数据', value: 'exist' } ], + groupStyle: { + workflow: { + border: '1px solid #ba89f8', + color: '#ba89f8' + }, + optional: { + border: '1px solid #81b337', + color: '#81b337' + } + }, defaultItem: { // 自定义分析字段信息 active: false, @@ -111,29 +130,35 @@ export default { } } }, - props: ['requestTemplateId'], methods: { - loadPage (params, formTemplateId) { + async loadPage (params) { + await this.getRequestGroupForm(params) if (params.isAdd) { - this.group.requestTemplateId = params.requestTemplateId - this.group.formTemplateId = params.formTemplateId - this.group.itemGroupName = params.itemGroup - this.group.itemGroupType = params.itemGroupType - this.group.itemGroup = params.itemGroup - this.group.itemGroupName = params.itemGroup + // this.group = {} + // this.group.requestTemplateId = params.requestTemplateId + // this.group.formTemplateId = params.formTemplateId + // this.group.itemGroupName = params.itemGroup + // this.group.itemGroupType = params.itemGroupType + // this.group.itemGroup = params.itemGroup this.group.itemGroupSort = params.itemGroupSort - this.openFormConfig = true + this.group.itemGroupRule = 'new' + // this.group.systemItems = [] + // this.group.customItems = [] } - this.getRequestGroupForm() + console.log(55, this.group) + this.openFormConfig = true }, - async getRequestGroupForm () { - const { statusCode, data } = await getRequestGroupForm( - this.requestTemplateId, - '65d7106743737270', - this.group.itemGroupName - ) + async getRequestGroupForm (params) { + console.log(66, params) + const { statusCode, data } = await getRequestGroupForm({ + formTemplateId: params.formTemplateId, + requestTemplateId: params.requestTemplateId, + entity: params.itemGroup, + formType: params.itemGroupType, + itemGroupId: params.itemGroupId + }) if (statusCode === 'OK') { - console.log(22, data) + this.group = data } }, paramsChanged () { @@ -148,16 +173,37 @@ export default { return res }, async saveGroupDrawer () { - let params = { - formTemplateId: '', - groups: [this.group] - } - const { statusCode, data } = await saveRequestGroupForm(this.requestTemplateId, params) + let finalData = JSON.parse(JSON.stringify(this.group)) + finalData.systemItems = finalData.systemItems.filter(system => system.active === true) + const { statusCode } = await saveRequestGroupForm(finalData) if (statusCode === 'OK') { - console.log(data) + this.$Notice.success({ + title: this.$t('successful'), + desc: this.$t('successful') + }) + this.openFormConfig = false + this.$emit('reloadParentPage') + } + }, + cancelGroupDrawer () { + if (this.isParmasChanged) { + this.$Modal.confirm({ + title: `${this.$t('confirm_discarding_changes')}`, + content: `${this.group.itemGroupName}:${this.$t('params_edit_confirm')}`, + 'z-index': 1000000, + okText: this.$t('save'), + cancelText: this.$t('abandon'), + onOk: async () => { + this.saveGroupDrawer() + }, + onCancel: () => { + this.openFormConfig = false + } + }) + } else { + this.openFormConfig = false } }, - cancelGroupDrawer () {}, deleteCustomItem (itemIndex) {}, addCustomItem () { let tmpItem = JSON.parse(JSON.stringify(this.defaultItem)) diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index 115f5751..f48128f0 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -51,7 +51,7 @@ > @@ -298,11 +298,15 @@ - +
@@ -506,7 +510,21 @@ export default { itemGroupIndex: -1, attrIndex: -1 }, - allEntityList: [] + allEntityList: [], + groupStyle: { + custom: { + border: '1px solid #dd6da6', + color: '#dd6da6' + }, + workflow: { + border: '1px solid #ba89f8', + color: '#ba89f8' + }, + optional: { + border: '1px solid #81b337', + color: '#81b337' + } + } } }, props: ['requestTemplateId'], @@ -578,6 +596,7 @@ export default { isAdd: true, itemGroupType: this.itemGroupType, itemGroup: this.itemGroup, + itemGroupId: '', itemGroupSort: this.dataFormInfo.groups.length + 1 } this.$refs.requestFormDataCustomRef.loadPage(params) @@ -589,13 +608,14 @@ export default { } }) this.$nextTick(() => { - if (this.itemGroupType === 'workflow') { + if (['workflow', 'optional'].includes(this.itemGroupType)) { let params = { requestTemplateId: this.requestTemplateId, formTemplateId: this.dataFormInfo.formTemplateId, isAdd: true, itemGroupType: this.itemGroupType, itemGroup: this.itemGroup, + itemGroupId: '', itemGroupSort: this.dataFormInfo.groups.length + 1 } this.$refs.requestFormDataWorkflowRef.loadPage(params) @@ -670,6 +690,19 @@ export default { } this.$refs.requestFormDataCustomRef.loadPage(params) } + if (['workflow', 'optional'].includes(groupItem.itemGroupType)) { + this.itemGroupType = groupItem.itemGroupType + let params = { + requestTemplateId: this.requestTemplateId, + formTemplateId: this.dataFormInfo.formTemplateId, + isAdd: false, + itemGroupName: groupItem.itemGroupName, + itemGroupType: groupItem.itemGroupType, + itemGroupId: groupItem.itemGroupId, + itemGroup: groupItem.itemGroup + } + this.$refs.requestFormDataWorkflowRef.loadPage(params) + } }, // 获取wecmdb下拉类型entity值 async getAllDataModels () { From 4fbf7e3fe831f232ad1814f6a770d855e0dded1d Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Fri, 23 Feb 2024 19:42:13 +0800 Subject: [PATCH 057/618] =?UTF-8?q?=E5=AE=A1=E6=89=B9/=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=88=9B=E5=BB=BAbug=20crash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/approval_template_service.go | 2 +- taskman-server/service/task_template_service.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/taskman-server/service/approval_template_service.go b/taskman-server/service/approval_template_service.go index 8290d336..293b77f8 100644 --- a/taskman-server/service/approval_template_service.go +++ b/taskman-server/service/approval_template_service.go @@ -66,7 +66,7 @@ func (s *ApprovalTemplateService) CreateApprovalTemplate(param *models.ApprovalT tmp := make([]*models.ApprovalTemplateTable, len(approvalTemplates)+1) copy(tmp, approvalTemplates[:param.Sort-1]) tmp[param.Sort-1] = newApprovalTemplate - copy(tmp[param.Sort:], approvalTemplates[:param.Sort-1]) + copy(tmp[param.Sort:], approvalTemplates[param.Sort-1:]) approvalTemplates = tmp } else { approvalTemplates = append(approvalTemplates, newApprovalTemplate) diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index e01dab71..9e3aa563 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -300,7 +300,7 @@ func (s TaskTemplateService) CreateCustomTaskTemplate(param *models.CustomTaskTe tmp := make([]*models.TaskTemplateTable, len(taskTemplates)+1) copy(tmp, taskTemplates[:param.Sort-1]) tmp[param.Sort-1] = newTaskTemplate - copy(tmp[param.Sort:], taskTemplates[:param.Sort-1]) + copy(tmp[param.Sort:], taskTemplates[param.Sort-1:]) taskTemplates = tmp } else { taskTemplates = append(taskTemplates, newTaskTemplate) From 03d8af3a7a56007551d398e1788423de3765e0b0 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Sat, 24 Feb 2024 23:28:46 +0800 Subject: [PATCH 058/618] =?UTF-8?q?=E5=AE=A1=E6=89=B9/=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=20=E6=8E=A5=E5=8F=A3=E5=BC=80=E5=8F=91=E5=AE=8C=E6=9C=AA?= =?UTF-8?q?=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 4 +- .../api/v1/approval/approval_template.go | 4 +- taskman-server/api/v1/task/task_template.go | 10 +- taskman-server/models/const.go | 9 + taskman-server/models/task.go | 1 + taskman-server/service/approval_service.go | 271 ++++++++++++++++- .../service/approval_template_service.go | 135 ++++++++- taskman-server/service/task_service.go | 285 +++++++++++++++++- .../service/task_template_service.go | 147 ++++++++- 9 files changed, 834 insertions(+), 32 deletions(-) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index d1de61cf..78ae796a 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -79,7 +79,7 @@ func init() { &handlerFuncObj{Url: "/approval-template", Method: "DELETE", HandlerFunc: approval.DeleteApprovalTemplate}, &handlerFuncObj{Url: "/approval-template/:requestTemplateId/:id", Method: "GET", HandlerFunc: approval.GetApprovalTemplate}, &handlerFuncObj{Url: "/approval-template/:requestTemplateId/ids", Method: "GET", HandlerFunc: approval.ListApprovalTemplateIds}, - &handlerFuncObj{Url: "/approval-template/:requestTemplateId", Method: "GET", HandlerFunc: approval.ListApprovalTemplate}, + &handlerFuncObj{Url: "/approval-template/:requestTemplateId", Method: "GET", HandlerFunc: approval.ListApprovalTemplates}, &handlerFuncObj{Url: "/task-template/:requestTemplateId/:proNodeId", Method: "GET", HandlerFunc: task.GetTaskTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplateId", Method: "POST", HandlerFunc: task.UpdateTaskTemplate}, @@ -88,7 +88,7 @@ func init() { &handlerFuncObj{Url: "/task-template/custom", Method: "DELETE", HandlerFunc: task.DeleteCustomTaskTemplate}, &handlerFuncObj{Url: "/task-template/custom/:requestTemplateId/:id", Method: "GET", HandlerFunc: task.GetCustomTaskTemplate}, &handlerFuncObj{Url: "/task-template/custom/:requestTemplateId/ids", Method: "GET", HandlerFunc: task.ListCustomTaskTemplateIds}, - &handlerFuncObj{Url: "/task-template/custom/:requestTemplateId", Method: "GET", HandlerFunc: task.ListCustomTaskTemplate}, + &handlerFuncObj{Url: "/task-template/custom/:requestTemplateId", Method: "GET", HandlerFunc: task.ListTaskTemplates}, &handlerFuncObj{Url: "/user/template/collect", Method: "POST", HandlerFunc: collect.AddTemplateCollect}, &handlerFuncObj{Url: "/user/template/collect/:templateId", Method: "DELETE", HandlerFunc: collect.CancelTemplateCollect}, diff --git a/taskman-server/api/v1/approval/approval_template.go b/taskman-server/api/v1/approval/approval_template.go index 97238648..418632b6 100644 --- a/taskman-server/api/v1/approval/approval_template.go +++ b/taskman-server/api/v1/approval/approval_template.go @@ -83,9 +83,9 @@ func ListApprovalTemplateIds(c *gin.Context) { } // 审批模板列表 -func ListApprovalTemplate(c *gin.Context) { +func ListApprovalTemplates(c *gin.Context) { requestTemplateId := c.Param("requestTemplateId") - result, err := service.GetApprovalTemplateService().ListApprovalTemplate(requestTemplateId) + result, err := service.GetApprovalTemplateService().ListApprovalTemplates(requestTemplateId) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/api/v1/task/task_template.go b/taskman-server/api/v1/task/task_template.go index 8a7b21ef..74f257ef 100644 --- a/taskman-server/api/v1/task/task_template.go +++ b/taskman-server/api/v1/task/task_template.go @@ -97,7 +97,7 @@ func UpdateCustomTaskTemplate(c *gin.Context) { middleware.ReturnParamValidateError(c, err) return } - err := service.GetTaskTemplateService().UpdateCustomTaskTemplate(¶m) + err := service.GetTaskTemplateService().UpdateTaskTemplate(¶m) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -120,11 +120,11 @@ func DeleteCustomTaskTemplate(c *gin.Context) { middleware.ReturnData(c, result) } -// 读取自定义任务模板 +// 读取任务模板 func GetCustomTaskTemplate(c *gin.Context) { requestTemplateId := c.Param("requestTemplateId") id := c.Param("id") - result, err := service.GetTaskTemplateService().GetCustomTaskTemplate(id) + result, err := service.GetTaskTemplateService().GetTaskTemplate(id) if err != nil { middleware.ReturnServerHandleError(c, err) return @@ -149,9 +149,9 @@ func ListCustomTaskTemplateIds(c *gin.Context) { } // 任务模板列表 -func ListCustomTaskTemplate(c *gin.Context) { +func ListTaskTemplates(c *gin.Context) { requestTemplateId := c.Param("requestTemplateId") - result, err := service.GetTaskTemplateService().ListCustomTaskTemplate(requestTemplateId) + result, err := service.GetTaskTemplateService().ListTaskTemplates(requestTemplateId) if err != nil { middleware.ReturnServerHandleError(c, err) return diff --git a/taskman-server/models/const.go b/taskman-server/models/const.go index 3540815a..15055fbf 100644 --- a/taskman-server/models/const.go +++ b/taskman-server/models/const.go @@ -121,6 +121,15 @@ const ( ApprovalTemplateRoleHandlerTypeClaim ApprovalTemplateRoleHandlerType = "claim" // 组内主动认领 ) +// ApprovalRoleApprove 审批处理 是否同意 +type ApprovalRoleApprove string + +const ( + ApprovalRoleApproveInit ApprovalRoleApprove = "init" // 未处理 + ApprovalRoleApproveApprove ApprovalRoleApprove = "approve" // 同意 + ApprovalRoleApproveDeny ApprovalRoleApprove = "deny" // 拒绝 +) + // TaskTemplateType 任务模板 类型 type TaskTemplateType string diff --git a/taskman-server/models/task.go b/taskman-server/models/task.go index 84916dbe..fbbf2d73 100644 --- a/taskman-server/models/task.go +++ b/taskman-server/models/task.go @@ -54,6 +54,7 @@ type TaskRoleTable struct { type TaskDto struct { Id string `json:"id"` + Type string `json:"type"` Sort int `json:"sort"` TaskTemplate string `json:"taskTemplate"` Request string `json:"request" xorm:"request"` diff --git a/taskman-server/service/approval_service.go b/taskman-server/service/approval_service.go index 90a4f866..53ba21c8 100644 --- a/taskman-server/service/approval_service.go +++ b/taskman-server/service/approval_service.go @@ -1,6 +1,10 @@ package service import ( + "errors" + "strings" + + "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" ) @@ -11,21 +15,282 @@ type ApprovalService struct { } func (s *ApprovalService) CreateApprovals(param []*models.ApprovalDto) ([]*dao.ExecAction, error) { + if len(param) == 0 { + return nil, nil + } actions := []*dao.ExecAction{} + // 校验参数 + approvalTemplateId := param[0].ApprovalTemplate + requestId := param[0].Request + for _, approval := range param { + if approval.ApprovalTemplate != approvalTemplateId { + return nil, errors.New("param approvalTemplate not the same") + } + if approval.Request != requestId { + return nil, errors.New("param request not the same") + } + if len(approval.RoleObjs) == 0 { + continue + } + approvalTemplateRoleId := approval.RoleObjs[0].ApprovalTemplateRole + for _, roleObj := range approval.RoleObjs { + if roleObj.ApprovalTemplateRole != approvalTemplateRoleId { + return nil, errors.New("param approvalTemplateRole not the same") + } + } + // 查询现有审批处理模板 + var approvalTemplateRoles []*models.ApprovalTemplateRoleTable + err := GetApprovalTemplateService().approvalTemplateRoleDao.DB.SQL("SELECT * FROM approval_template_role WHERE id = ? AND approval_template = ?", approvalTemplateRoleId, approvalTemplateId).Find(&approvalTemplateRoles) + if err != nil { + return nil, err + } + if len(approvalTemplateRoles) == 0 { + return nil, errors.New("no approval_template_role record found") + } + } + // 查询现有审批模板 + var approvalTemplates []*models.ApprovalTemplateTable + err := GetApprovalTemplateService().approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE id = ?", approvalTemplateId).Find(&approvalTemplates) + if err != nil { + return nil, err + } + if len(approvalTemplates) == 0 { + return nil, errors.New("no approval_template record found") + } + // 查询现有审批列表 + var approvals []*models.ApprovalTable + err = s.approvalDao.DB.SQL("SELECT * FROM approval WHERE request = ? ORDER BY sort", requestId).Find(&approvals) + if err != nil { + return nil, err + } + if len(approvals) != 0 { + return nil, errors.New("approval record already exist") + } + // 插入数据 + for i, approval := range param { + approval.Id = guid.CreateGuid() + approval.Sort = i + 1 + // 插入审批 + action := &dao.ExecAction{Sql: "INSERT INTO approval (id,sort,approval_template,request) VALUES (?,?,?,?)"} + action.Param = []interface{}{approval.Id, approval.Sort, approval.ApprovalTemplate, approval.Request} + actions = append(actions, action) + // 插入审批处理 + for j, roleObj := range approval.RoleObjs { + action := &dao.ExecAction{Sql: "INSERT INTO approval_role (id,sort,approval_template_role,approval,role,handler,approve) VALUES (?,?,?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), j + 1, roleObj.ApprovalTemplateRole, approval.Id, roleObj.Role, roleObj.Handler, string(models.ApprovalRoleApproveInit)} + actions = append(actions, action) + } + } return actions, nil } func (s *ApprovalService) UpdateApprovals(param []*models.ApprovalDto) ([]*dao.ExecAction, error) { + if len(param) == 0 { + return nil, nil + } actions := []*dao.ExecAction{} + // 校验参数 + approvalTemplateId := param[0].ApprovalTemplate + requestId := param[0].Request + for i, approval := range param { + if approval.ApprovalTemplate != approvalTemplateId { + return nil, errors.New("param approvalTemplate not the same") + } + if approval.Request != requestId { + return nil, errors.New("param request not the same") + } + if approval.Sort != i+1 { + return nil, errors.New("param sort wrong") + } + if len(approval.RoleObjs) == 0 { + continue + } + approvalTemplateRoleId := approval.RoleObjs[0].ApprovalTemplateRole + for _, roleObj := range approval.RoleObjs { + if roleObj.ApprovalTemplateRole != approvalTemplateRoleId { + return nil, errors.New("param approvalTemplateRole not the same") + } + } + // 查询现有审批处理模板 + var approvalTemplateRoles []*models.ApprovalTemplateRoleTable + err := GetApprovalTemplateService().approvalTemplateRoleDao.DB.SQL("SELECT * FROM approval_template_role WHERE id = ? AND approval_template = ?", approvalTemplateRoleId, approvalTemplateId).Find(&approvalTemplateRoles) + if err != nil { + return nil, err + } + if len(approvalTemplateRoles) == 0 { + return nil, errors.New("no approval_template_role record found") + } + } + // 查询现有审批模板 + var approvalTemplates []*models.ApprovalTemplateTable + err := GetApprovalTemplateService().approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE id = ?", approvalTemplateId).Find(&approvalTemplates) + if err != nil { + return nil, err + } + if len(approvalTemplates) == 0 { + return nil, errors.New("no approval_template record found") + } + // 查询现有审批列表 + var approvals []*models.ApprovalTable + err = s.approvalDao.DB.SQL("SELECT * FROM approval WHERE request = ? AND approval_template = ? ORDER BY sort", requestId, approvalTemplateId).Find(&approvals) + if err != nil { + return nil, err + } + // 汇总审批列表 + approvalIds := make([]string, len(approvals)) + for i, approval := range approvals { + approvalIds[i] = approval.Id + } + // 查询现有审批处理列表 + var approvalRoles []*models.ApprovalRoleTable + err = s.approvalRoleDao.DB.SQL("SELECT * FROM approval_role WHERE approval IN ('" + strings.Join(approvalIds, "','") + "') ORDER BY approval, sort").Find(&approvalRoles) + if err != nil { + return nil, err + } + // 汇总审批处理列表 + approvalRoleMap := make(map[string][]*models.ApprovalRoleTable) + approvalId := "" + for _, approvalRole := range approvalRoles { + if approvalId != approvalRole.Approval { + approvalId = approvalRole.Approval + approvalRoleMap[approvalId] = make([]*models.ApprovalRoleTable, 0) + } + approvalRoleMap[approvalId] = append(approvalRoleMap[approvalId], approvalRole) + } + // 对比请求和现有数据 + for _, approval := range param { + if approval.Id == "" { + approval.Id = guid.CreateGuid() + } + approvalRoles, ok := approvalRoleMap[approval.Id] + if !ok { + // 插入审批 + action := &dao.ExecAction{Sql: "INSERT INTO approval (id,sort,approval_template,request) VALUES (?,?,?,?)"} + action.Param = []interface{}{approval.Id, approval.Sort, approval.ApprovalTemplate, approval.Request} + actions = append(actions, action) + // 插入审批处理 + for j, roleObj := range approval.RoleObjs { + action := &dao.ExecAction{Sql: "INSERT INTO approval_role (id,sort,approval_template_role,approval,role,handler,approve) VALUES (?,?,?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), j + 1, roleObj.ApprovalTemplateRole, approval.Id, roleObj.Role, roleObj.Handler, string(models.ApprovalRoleApproveInit)} + actions = append(actions, action) + } + } else { + // 更新审批 + action := &dao.ExecAction{Sql: "UPDATE approval SET sort = ? WHERE id = ?"} + action.Param = []interface{}{approval.Sort, approval.Id} + actions = append(actions, action) + // 增删改审批处理 + for j, approvalRole := range approvalRoles { + if j < len(approval.RoleObjs) { + roleObj := approval.RoleObjs[j] + action = &dao.ExecAction{Sql: "UPDATE approval_role SET role = ?, handler = ?, approve = ? WHERE id = ?"} + action.Param = []interface{}{roleObj.Role, roleObj.Handler, roleObj.Approve, approvalRole.Id} + actions = append(actions, action) + } else { + action = &dao.ExecAction{Sql: "DELETE FROM approval_role WHERE id = ?"} + action.Param = []interface{}{approvalRole.Id} + actions = append(actions, action) + } + } + for sort := len(approvalRoles) + 1; sort <= len(approval.RoleObjs); sort++ { + roleObj := approval.RoleObjs[sort-1] + action = &dao.ExecAction{Sql: "INSERT INTO approval_role (id,sort,approval_template_role,approval,role,handler,approve) VALUES (?,?,?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), sort, roleObj.ApprovalTemplateRole, approval.Id, roleObj.Role, roleObj.Handler, string(models.ApprovalRoleApproveInit)} + actions = append(actions, action) + } + // 处理完,从审批处理列表删除 + delete(approvalRoleMap, approval.Id) + } + } + // 删除剩余的审批和审批处理 + for approvalId := range approvalRoleMap { + action := &dao.ExecAction{Sql: "DELETE FROM approval_role WHERE approval = ?"} + action.Param = []interface{}{approvalId} + actions = append(actions, action) + + action = &dao.ExecAction{Sql: "DELETE FROM approval WHERE id = ?"} + action.Param = []interface{}{approvalId} + actions = append(actions, action) + } return actions, nil } -func (s *ApprovalService) DeleteApprovals(param []*models.ApprovalDto) ([]*dao.ExecAction, error) { +func (s *ApprovalService) DeleteApprovals(requestId string) ([]*dao.ExecAction, error) { actions := []*dao.ExecAction{} + // 查询现有审批列表 + var approvals []*models.ApprovalTable + err := s.approvalDao.DB.SQL("SELECT * FROM approval WHERE request = ? ORDER BY sort", requestId).Find(&approvals) + if err != nil { + return nil, err + } + if len(approvals) == 0 { + return nil, nil + } + // 汇总审批列表 + approvalIds := make([]string, len(approvals)) + for i, approval := range approvals { + approvalIds[i] = approval.Id + } + // 删除现有审批处理列表 + action := &dao.ExecAction{Sql: "DELETE FROM approval_role WHERE approval IN ('" + strings.Join(approvalIds, "','") + "')"} + actions = append(actions, action) + // 删除现有审批列表 + action = &dao.ExecAction{Sql: "DELETE FROM approval WHERE id IN ('" + strings.Join(approvalIds, "','") + "')"} + actions = append(actions, action) return actions, nil } -func (s *ApprovalService) ListApproval(requestId string) ([]*models.ApprovalDto, error) { - result := []*models.ApprovalDto{} +func (s *ApprovalService) ListApprovals(requestId string) ([]*models.ApprovalDto, error) { + // 查询现有审批列表 + var approvals []*models.ApprovalTable + err := s.approvalDao.DB.SQL("SELECT * FROM approval WHERE request = ? ORDER BY sort", requestId).Find(&approvals) + if err != nil { + return nil, err + } + if len(approvals) == 0 { + return nil, nil + } + // 汇总审批列表 + approvalIds := make([]string, len(approvals)) + for i, approval := range approvals { + approvalIds[i] = approval.Id + } + // 查询现有审批处理列表 + var approvalRoles []*models.ApprovalRoleTable + err = s.approvalRoleDao.DB.SQL("SELECT * FROM approval_role WHERE approval IN ('" + strings.Join(approvalIds, "','") + "') ORDER BY approval, sort").Find(&approvalRoles) + if err != nil { + return nil, err + } + // 汇总审批处理列表 + approvalRoleMap := make(map[string][]*models.ApprovalRoleTable) + approvalId := "" + for _, approvalRole := range approvalRoles { + if approvalId != approvalRole.Approval { + approvalId = approvalRole.Approval + approvalRoleMap[approvalId] = make([]*models.ApprovalRoleTable, 0) + } + approvalRoleMap[approvalId] = append(approvalRoleMap[approvalId], approvalRole) + } + // 构造返回结果 + result := make([]*models.ApprovalDto, len(approvals)) + for i, approval := range approvals { + result[i] = &models.ApprovalDto{ + Id: approval.Id, + Sort: approval.Sort, + ApprovalTemplate: approval.ApprovalTemplate, + Request: approval.Request, + } + if roleObjs, ok := approvalRoleMap[approval.Id]; ok { + result[i].RoleObjs = make([]*models.ApprovalRoleDto, len(roleObjs)) + for j, roleObj := range roleObjs { + result[i].RoleObjs[j] = &models.ApprovalRoleDto{ + ApprovalTemplateRole: roleObj.ApprovalTemplateRole, + Role: roleObj.Role, + Handler: roleObj.Handler, + Approve: roleObj.Approve, + } + } + } + } return result, nil } diff --git a/taskman-server/service/approval_template_service.go b/taskman-server/service/approval_template_service.go index 293b77f8..cea40f1f 100644 --- a/taskman-server/service/approval_template_service.go +++ b/taskman-server/service/approval_template_service.go @@ -168,21 +168,123 @@ func (s *ApprovalTemplateService) UpdateApprovalTemplate(param *models.ApprovalT } func (s *ApprovalTemplateService) DeleteApprovalTemplate(id string) (*models.ApprovalTemplateDeleteResponse, error) { - result := &models.ApprovalTemplateDeleteResponse{} + actions := []*dao.ExecAction{} + // 查询现有审批模板 + var approvalTemplates []*models.ApprovalTemplateTable + err := s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE id = ?", id).Find(&approvalTemplates) + if err != nil { + return nil, err + } + if len(approvalTemplates) == 0 { + return nil, errors.New("no approval_template record found") + } + approvalTemplate := approvalTemplates[0] + // 删除现有审批处理模板 + action := &dao.ExecAction{Sql: "DELETE FROM approval_template_role WHERE approval_template = ?"} + action.Param = []interface{}{id} + actions = append(actions, action) + // 删除现有审批模板 + action = &dao.ExecAction{Sql: "DELETE FROM approval_template WHERE id = ?"} + action.Param = []interface{}{id} + actions = append(actions, action) + // 查询剩余审批模板列表 + approvalTemplates = nil + err = s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE request_template = ? AND id != ? ORDER BY sort", approvalTemplate.RequestTemplate, id).Find(&approvalTemplates) + if err != nil { + return nil, err + } + // 如果不是尾删,则需更新现有数据的序号 + if approvalTemplate.Sort != len(approvalTemplates)+1 { + nowTime := time.Now().Format(models.DateTimeFormat) + for i := approvalTemplate.Sort; i < len(approvalTemplates)+1; i++ { + t := approvalTemplates[i-1] + t.Sort = i + t.UpdatedTime = nowTime + action = &dao.ExecAction{Sql: "UPDATE approval_template SET sort = ?, updated_time = ? WHERE id = ?"} + action.Param = []interface{}{t.Sort, t.UpdatedTime, t.Id} + actions = append(actions, action) + } + } + // 执行事务 + err = dao.Transaction(actions) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.ApprovalTemplateDeleteResponse{ + Ids: make([]*models.ApprovalTemplateIdObj, len(approvalTemplates)), + } + for i, approvalTemplate := range approvalTemplates { + result.Ids[i] = &models.ApprovalTemplateIdObj{ + Id: approvalTemplate.Id, + Sort: approvalTemplate.Sort, + Name: approvalTemplate.Name, + } + } return result, nil } func (s *ApprovalTemplateService) GetApprovalTemplate(id string) (*models.ApprovalTemplateDto, error) { - result := &models.ApprovalTemplateDto{} + // 查询现有审批模板 + var approvalTemplates []*models.ApprovalTemplateTable + err := s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE id = ?", id).Find(&approvalTemplates) + if err != nil { + return nil, err + } + if len(approvalTemplates) == 0 { + return nil, errors.New("no approval_template record found") + } + approvalTemplate := approvalTemplates[0] + // 查询现有审批处理模板 + var approvalTemplateRoles []*models.ApprovalTemplateRoleTable + err = s.approvalTemplateRoleDao.DB.SQL("SELECT * FROM approval_template_role WHERE approval_template = ? ORDER BY sort", id).Find(&approvalTemplateRoles) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.ApprovalTemplateDto{ + Id: approvalTemplate.Id, + Sort: approvalTemplate.Sort, + RequestTemplate: approvalTemplate.RequestTemplate, + Name: approvalTemplate.Name, + ExpireDay: approvalTemplate.ExpireDay, + Description: approvalTemplate.Description, + RoleType: approvalTemplate.RoleType, + RoleObjs: make([]*models.ApprovalTemplateRoleDto, len(approvalTemplateRoles)), + } + for i, approvalTemplateRole := range approvalTemplateRoles { + result.RoleObjs[i] = &models.ApprovalTemplateRoleDto{ + RoleType: approvalTemplateRole.RoleType, + HandlerType: approvalTemplateRole.HandlerType, + Role: approvalTemplateRole.Role, + Handler: approvalTemplateRole.Handler, + } + } return result, nil } func (s *ApprovalTemplateService) ListApprovalTemplateIds(requestTemplateId string) (*models.ApprovalTemplateListIdsResponse, error) { - result := &models.ApprovalTemplateListIdsResponse{} + // 查询现有审批模板列表 + var approvalTemplates []*models.ApprovalTemplateTable + err := s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE request_template = ? ORDER BY sort", requestTemplateId).Find(&approvalTemplates) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.ApprovalTemplateListIdsResponse{ + Ids: make([]*models.ApprovalTemplateIdObj, len(approvalTemplates)), + } + for i, approvalTemplate := range approvalTemplates { + result.Ids[i] = &models.ApprovalTemplateIdObj{ + Id: approvalTemplate.Id, + Sort: approvalTemplate.Sort, + Name: approvalTemplate.Name, + } + } return result, nil } -func (s *ApprovalTemplateService) ListApprovalTemplate(requestTemplateId string) ([]*models.ApprovalTemplateDto, error) { +func (s *ApprovalTemplateService) ListApprovalTemplates(requestTemplateId string) ([]*models.ApprovalTemplateDto, error) { result := []*models.ApprovalTemplateDto{} // 查询现有审批模板列表 var approvalTemplates []*models.ApprovalTemplateTable @@ -240,3 +342,28 @@ func (s *ApprovalTemplateService) ListApprovalTemplate(requestTemplateId string) } return result, nil } + +func (s *ApprovalTemplateService) DeleteApprovalTemplates(requestTemplateId string) ([]*dao.ExecAction, error) { + // 查询现有审批模板列表 + var approvalTemplates []*models.ApprovalTemplateTable + err := s.approvalTemplateDao.DB.SQL("SELECT * FROM approval_template WHERE request_template = ? ORDER BY sort", requestTemplateId).Find(&approvalTemplates) + if err != nil { + return nil, err + } + if len(approvalTemplates) == 0 { + return nil, nil + } + // 汇总审批模板列表 + approvalTemplateIds := make([]string, len(approvalTemplates)) + for i, approvalTemplate := range approvalTemplates { + approvalTemplateIds[i] = approvalTemplate.Id + } + actions := []*dao.ExecAction{} + // 删除现有审批处理模板 + action := &dao.ExecAction{Sql: "DELETE FROM approval_template_role WHERE approval_template IN ('" + strings.Join(approvalTemplateIds, "','") + "')"} + actions = append(actions, action) + // 删除现有审批模板 + action = &dao.ExecAction{Sql: "DELETE FROM approval_template WHERE id IN ('" + strings.Join(approvalTemplateIds, "','") + "')"} + actions = append(actions, action) + return actions, nil +} diff --git a/taskman-server/service/task_service.go b/taskman-server/service/task_service.go index 592f34fc..34044bfd 100644 --- a/taskman-server/service/task_service.go +++ b/taskman-server/service/task_service.go @@ -2,7 +2,12 @@ package service import ( "encoding/json" + "errors" "fmt" + "strconv" + "strings" + "time" + "github.com/WeBankPartners/go-common-lib/guid" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" @@ -10,13 +15,10 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/rpc" - "strconv" - "strings" - "time" ) type TaskService struct { - taskDao dao.TaskDao + taskDao dao.TaskDao taskRoleDao dao.TaskRoleDao } @@ -851,21 +853,290 @@ func GetSimpleTask(taskId string) (task models.TaskTable, err error) { } func (s TaskService) CreateTasks(param []*models.TaskDto) ([]*dao.ExecAction, error) { + if len(param) == 0 { + return nil, nil + } actions := []*dao.ExecAction{} + // 校验参数 + taskTemplateId := param[0].TaskTemplate + requestId := param[0].Request + taskType := param[0].Type + for _, task := range param { + if task.TaskTemplate != taskTemplateId { + return nil, errors.New("param taskTemplate not the same") + } + if task.Request != requestId { + return nil, errors.New("param request not the same") + } + if task.Type != taskType { + return nil, errors.New("param type not the same") + } + if len(task.RoleObjs) == 0 { + continue + } + taskTemplateRoleId := task.RoleObjs[0].TaskTemplateRole + for _, roleObj := range task.RoleObjs { + if roleObj.TaskTemplateRole != taskTemplateRoleId { + return nil, errors.New("param taskTemplateRole not the same") + } + } + // 查询现有任务处理模板 + var taskTemplateRoles []*models.TaskTemplateRoleTable + err := GetTaskTemplateService().taskTemplateRoleDao.DB.SQL("SELECT * FROM task_template_role WHERE id = ? AND task_template = ?", taskTemplateRoleId, taskTemplateId).Find(&taskTemplateRoles) + if err != nil { + return nil, err + } + if len(taskTemplateRoles) == 0 { + return nil, errors.New("no task_template_role record found") + } + } + // 查询现有任务模板 + var taskTemplates []*models.TaskTemplateTable + err := GetTaskTemplateService().taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE id = ?", taskTemplateId).Find(&taskTemplates) + if err != nil { + return nil, err + } + if len(taskTemplates) == 0 { + return nil, errors.New("no task_template record found") + } + // 查询现有任务列表 + var tasks []*models.TaskTable + err = s.taskDao.DB.SQL("SELECT * FROM task WHERE request = ? ORDER BY sort", requestId).Find(&tasks) + if err != nil { + return nil, err + } + if len(tasks) != 0 { + return nil, errors.New("task record already exist") + } + // 插入数据 + for i, task := range param { + task.Id = guid.CreateGuid() + task.Sort = i + 1 + // 插入任务 + action := &dao.ExecAction{Sql: "INSERT INTO task (id,type,sort,task_template,request) VALUES (?,?,?,?,?)"} + action.Param = []interface{}{task.Id, task.Type, task.Sort, task.TaskTemplate, task.Request} + actions = append(actions, action) + // 插入任务处理 + for _, roleObj := range task.RoleObjs { + action := &dao.ExecAction{Sql: "INSERT INTO task_role (id,task_template_role,task,role,handler) VALUES (?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), roleObj.TaskTemplateRole, task.Id, roleObj.Role, roleObj.Handler} + actions = append(actions, action) + } + } return actions, nil } func (s TaskService) UpdateTasks(param []*models.TaskDto) ([]*dao.ExecAction, error) { + if len(param) == 0 { + return nil, nil + } actions := []*dao.ExecAction{} + // 校验参数 + taskTemplateId := param[0].TaskTemplate + requestId := param[0].Request + taskType := param[0].Type + for i, task := range param { + if task.TaskTemplate != taskTemplateId { + return nil, errors.New("param taskTemplate not the same") + } + if task.Request != requestId { + return nil, errors.New("param request not the same") + } + if task.Type != taskType { + return nil, errors.New("param type not the same") + } + if task.Sort != i+1 { + return nil, errors.New("param sort wrong") + } + if len(task.RoleObjs) == 0 { + continue + } + taskTemplateRoleId := task.RoleObjs[0].TaskTemplateRole + for _, roleObj := range task.RoleObjs { + if roleObj.TaskTemplateRole != taskTemplateRoleId { + return nil, errors.New("param taskTemplateRole not the same") + } + } + // 查询现有任务处理模板 + var taskTemplateRoles []*models.TaskTemplateRoleTable + err := GetTaskTemplateService().taskTemplateRoleDao.DB.SQL("SELECT * FROM task_template_role WHERE id = ? AND task_template = ?", taskTemplateRoleId, taskTemplateId).Find(&taskTemplateRoles) + if err != nil { + return nil, err + } + if len(taskTemplateRoles) == 0 { + return nil, errors.New("no task_template_role record found") + } + } + // 查询现有任务模板 + var taskTemplates []*models.TaskTemplateTable + err := GetTaskTemplateService().taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE id = ?", taskTemplateId).Find(&taskTemplates) + if err != nil { + return nil, err + } + if len(taskTemplates) == 0 { + return nil, errors.New("no task_template record found") + } + // 查询现有任务列表 + var tasks []*models.TaskTable + err = s.taskDao.DB.SQL("SELECT * FROM task WHERE request = ? AND task_template = ? ORDER BY sort", requestId, taskTemplateId).Find(&tasks) + if err != nil { + return nil, err + } + // 汇总任务列表 + taskIds := make([]string, len(tasks)) + for i, task := range tasks { + taskIds[i] = task.Id + } + // 查询现有任务处理列表 + var taskRoles []*models.TaskRoleTable + err = s.taskRoleDao.DB.SQL("SELECT * FROM task_role WHERE task IN ('" + strings.Join(taskIds, "','") + "') ORDER BY task").Find(&taskRoles) + if err != nil { + return nil, err + } + // 汇总任务处理列表 + taskRoleMap := make(map[string][]*models.TaskRoleTable) + taskId := "" + for _, taskRole := range taskRoles { + if taskId != taskRole.Task { + taskId = taskRole.Task + taskRoleMap[taskId] = make([]*models.TaskRoleTable, 0) + } + taskRoleMap[taskId] = append(taskRoleMap[taskId], taskRole) + } + // 对比请求和现有数据 + for _, task := range param { + if task.Id == "" { + task.Id = guid.CreateGuid() + } + taskRoles, ok := taskRoleMap[task.Id] + if !ok { + // 插入任务 + action := &dao.ExecAction{Sql: "INSERT INTO task (id,type,sort,task_template,request) VALUES (?,?,?,?,?)"} + action.Param = []interface{}{task.Id, task.Type, task.Sort, task.TaskTemplate, task.Request} + actions = append(actions, action) + // 插入任务处理 + for _, roleObj := range task.RoleObjs { + action := &dao.ExecAction{Sql: "INSERT INTO task_role (id,task_template_role,task,role,handler) VALUES (?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), roleObj.TaskTemplateRole, task.Id, roleObj.Role, roleObj.Handler} + actions = append(actions, action) + } + } else { + // 更新任务 + action := &dao.ExecAction{Sql: "UPDATE task SET sort = ? WHERE id = ?"} + action.Param = []interface{}{task.Sort, task.Id} + actions = append(actions, action) + // 增删改任务处理 + for j, taskRole := range taskRoles { + if j < len(task.RoleObjs) { + roleObj := task.RoleObjs[j] + action = &dao.ExecAction{Sql: "UPDATE task_role SET role = ?, handler = ? WHERE id = ?"} + action.Param = []interface{}{roleObj.Role, roleObj.Handler, taskRole.Id} + actions = append(actions, action) + } else { + action = &dao.ExecAction{Sql: "DELETE FROM task_role WHERE id = ?"} + action.Param = []interface{}{taskRole.Id} + actions = append(actions, action) + } + } + for sort := len(taskRoles) + 1; sort <= len(task.RoleObjs); sort++ { + roleObj := task.RoleObjs[sort-1] + action = &dao.ExecAction{Sql: "INSERT INTO task_role (id,task_template_role,task,role,handler) VALUES (?,?,?,?,?)"} + action.Param = []interface{}{guid.CreateGuid(), roleObj.TaskTemplateRole, task.Id, roleObj.Role, roleObj.Handler} + actions = append(actions, action) + } + // 处理完,从任务处理列表删除 + delete(taskRoleMap, task.Id) + } + } + // 删除剩余的任务和任务处理 + for taskId := range taskRoleMap { + action := &dao.ExecAction{Sql: "DELETE FROM task_role WHERE task = ?"} + action.Param = []interface{}{taskId} + actions = append(actions, action) + + action = &dao.ExecAction{Sql: "DELETE FROM task WHERE id = ?"} + action.Param = []interface{}{taskId} + actions = append(actions, action) + } return actions, nil } -func (s TaskService) DeleteTasks(param []*models.TaskDto) ([]*dao.ExecAction, error) { +func (s TaskService) DeleteTasks(requestId string) ([]*dao.ExecAction, error) { actions := []*dao.ExecAction{} + // 查询现有任务列表 + var tasks []*models.TaskTable + err := s.taskDao.DB.SQL("SELECT * FROM task WHERE request = ? ORDER BY sort", requestId).Find(&tasks) + if err != nil { + return nil, err + } + if len(tasks) == 0 { + return nil, nil + } + // 汇总任务列表 + taskIds := make([]string, len(tasks)) + for i, task := range tasks { + taskIds[i] = task.Id + } + // 删除现有任务处理列表 + action := &dao.ExecAction{Sql: "DELETE FROM task_role WHERE task IN ('" + strings.Join(taskIds, "','") + "')"} + actions = append(actions, action) + // 删除现有任务列表 + action = &dao.ExecAction{Sql: "DELETE FROM task WHERE id IN ('" + strings.Join(taskIds, "','") + "')"} + actions = append(actions, action) return actions, nil } -func (s TaskService) ListTask(requestId string) ([]*models.TaskDto, error) { - result := []*models.TaskDto{} +func (s TaskService) ListTasks(requestId string) ([]*models.TaskDto, error) { + // 查询现有任务列表 + var tasks []*models.TaskTable + err := s.taskDao.DB.SQL("SELECT * FROM task WHERE request = ? ORDER BY sort", requestId).Find(&tasks) + if err != nil { + return nil, err + } + if len(tasks) == 0 { + return nil, nil + } + // 汇总任务列表 + taskIds := make([]string, len(tasks)) + for i, task := range tasks { + taskIds[i] = task.Id + } + // 查询现有任务处理列表 + var taskRoles []*models.TaskRoleTable + err = s.taskRoleDao.DB.SQL("SELECT * FROM task_role WHERE task IN ('" + strings.Join(taskIds, "','") + "') ORDER BY task").Find(&taskRoles) + if err != nil { + return nil, err + } + // 汇总任务处理列表 + taskRoleMap := make(map[string][]*models.TaskRoleTable) + taskId := "" + for _, taskRole := range taskRoles { + if taskId != taskRole.Task { + taskId = taskRole.Task + taskRoleMap[taskId] = make([]*models.TaskRoleTable, 0) + } + taskRoleMap[taskId] = append(taskRoleMap[taskId], taskRole) + } + // 构造返回结果 + result := make([]*models.TaskDto, len(tasks)) + for i, task := range tasks { + result[i] = &models.TaskDto{ + Id: task.Id, + Type: task.Type, + Sort: task.Sort, + TaskTemplate: task.TaskTemplate, + Request: task.Request, + } + if roleObjs, ok := taskRoleMap[task.Id]; ok { + result[i].RoleObjs = make([]*models.TaskRoleDto, len(roleObjs)) + for j, roleObj := range roleObjs { + result[i].RoleObjs[j] = &models.TaskRoleDto{ + TaskTemplateRole: roleObj.TaskTemplateRole, + Role: roleObj.Role, + Handler: roleObj.Handler, + } + } + } + } return result, nil } diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 9e3aa563..be53b42a 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -328,7 +328,7 @@ func (s TaskTemplateService) CreateCustomTaskTemplate(param *models.CustomTaskTe return result, nil } -func (s TaskTemplateService) UpdateCustomTaskTemplate(param *models.TaskTemplateDto) error { +func (s TaskTemplateService) UpdateTaskTemplate(param *models.TaskTemplateDto) error { actions := []*dao.ExecAction{} // 查询现有任务模板 var taskTemplates []*models.TaskTemplateTable @@ -341,9 +341,6 @@ func (s TaskTemplateService) UpdateCustomTaskTemplate(param *models.TaskTemplate } taskTemplate := taskTemplates[0] // 校验参数 - if param.Type != string(models.TaskTemplateTypeCustom) { - return errors.New("param type wrong") - } if taskTemplate.Type != param.Type || taskTemplate.Sort != param.Sort || taskTemplate.RequestTemplate != param.RequestTemplateId { return errors.New("param type or sort or requestTemplate wrong") } @@ -405,21 +402,128 @@ func (s TaskTemplateService) UpdateCustomTaskTemplate(param *models.TaskTemplate } func (s TaskTemplateService) DeleteCustomTaskTemplate(id string) (*models.CustomTaskTemplateDeleteResponse, error) { - result := &models.CustomTaskTemplateDeleteResponse{} + actions := []*dao.ExecAction{} + // 查询现有任务模板 + var taskTemplates []*models.TaskTemplateTable + err := s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE id = ?", id).Find(&taskTemplates) + if err != nil { + return nil, err + } + if len(taskTemplates) == 0 { + return nil, errors.New("no task_template record found") + } + taskTemplate := taskTemplates[0] + // 校验参数 + if taskTemplate.Type != string(models.TaskTemplateTypeCustom) { + return nil, errors.New("type wrong") + } + // 删除现有任务处理模板 + action := &dao.ExecAction{Sql: "DELETE FROM task_template_role WHERE task_template = ?"} + action.Param = []interface{}{id} + actions = append(actions, action) + // 删除现有任务模板 + action = &dao.ExecAction{Sql: "DELETE FROM task_template WHERE id = ?"} + action.Param = []interface{}{id} + actions = append(actions, action) + // 查询剩余任务模板列表 + taskTemplates = nil + err = s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE request_template = ? AND id != ? ORDER BY sort", taskTemplate.RequestTemplate, id).Find(&taskTemplates) + if err != nil { + return nil, err + } + // 如果不是尾删,则需更新现有数据的序号 + if taskTemplate.Sort != len(taskTemplates)+1 { + nowTime := time.Now().Format(models.DateTimeFormat) + for i := taskTemplate.Sort; i < len(taskTemplates)+1; i++ { + t := taskTemplates[i-1] + t.Sort = i + t.UpdatedTime = nowTime + action = &dao.ExecAction{Sql: "UPDATE task_template SET sort = ?, updated_time = ? WHERE id = ?"} + action.Param = []interface{}{t.Sort, t.UpdatedTime, t.Id} + actions = append(actions, action) + } + } + // 执行事务 + err = dao.Transaction(actions) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.CustomTaskTemplateDeleteResponse{ + Ids: make([]*models.CustomTaskTemplateIdObj, len(taskTemplates)), + } + for i, taskTemplate := range taskTemplates { + result.Ids[i] = &models.CustomTaskTemplateIdObj{ + Id: taskTemplate.Id, + Sort: taskTemplate.Sort, + Name: taskTemplate.Name, + } + } return result, nil } -func (s TaskTemplateService) GetCustomTaskTemplate(id string) (*models.TaskTemplateDto, error) { - result := &models.TaskTemplateDto{} +func (s TaskTemplateService) GetTaskTemplate(id string) (*models.TaskTemplateDto, error) { + // 查询现有任务模板 + var taskTemplates []*models.TaskTemplateTable + err := s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE id = ?", id).Find(&taskTemplates) + if err != nil { + return nil, err + } + if len(taskTemplates) == 0 { + return nil, errors.New("no task_template record found") + } + taskTemplate := taskTemplates[0] + // 查询现有任务处理模板 + var taskTemplateRoles []*models.TaskTemplateRoleTable + err = s.taskTemplateRoleDao.DB.SQL("SELECT * FROM task_template_role WHERE task_template = ? ORDER BY sort", id).Find(&taskTemplateRoles) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.TaskTemplateDto{ + Id: taskTemplate.Id, + Type: taskTemplate.Type, + Sort: taskTemplate.Sort, + RequestTemplateId: taskTemplate.RequestTemplate, + Name: taskTemplate.Name, + ExpireDay: taskTemplate.ExpireDay, + Description: taskTemplate.Description, + RoleType: taskTemplate.RoleType, + RoleObjs: make([]*models.TaskTemplateRoleDto, len(taskTemplateRoles)), + } + for i, taskTemplateRole := range taskTemplateRoles { + result.RoleObjs[i] = &models.TaskTemplateRoleDto{ + RoleType: taskTemplateRole.CustomRoleType, + HandlerType: taskTemplateRole.HandlerType, + Role: taskTemplateRole.CustomRole, + Handler: taskTemplateRole.Handler, + } + } return result, nil } func (s TaskTemplateService) ListCustomTaskTemplateIds(requestTemplateId string) (*models.CustomTaskTemplateListIdsResponse, error) { - result := &models.CustomTaskTemplateListIdsResponse{} + // 查询现有任务模板列表 + var taskTemplates []*models.TaskTemplateTable + err := s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE request_template = ? AND type = ? ORDER BY sort", requestTemplateId, string(models.TaskTemplateTypeCustom)).Find(&taskTemplates) + if err != nil { + return nil, err + } + // 构造返回结果 + result := &models.CustomTaskTemplateListIdsResponse{ + Ids: make([]*models.CustomTaskTemplateIdObj, len(taskTemplates)), + } + for i, taskTemplate := range taskTemplates { + result.Ids[i] = &models.CustomTaskTemplateIdObj{ + Id: taskTemplate.Id, + Sort: taskTemplate.Sort, + Name: taskTemplate.Name, + } + } return result, nil } -func (s TaskTemplateService) ListCustomTaskTemplate(requestTemplateId string) ([]*models.TaskTemplateDto, error) { +func (s TaskTemplateService) ListTaskTemplates(requestTemplateId string) ([]*models.TaskTemplateDto, error) { result := []*models.TaskTemplateDto{} // 查询现有任务模板列表 var taskTemplates []*models.TaskTemplateTable @@ -478,3 +582,28 @@ func (s TaskTemplateService) ListCustomTaskTemplate(requestTemplateId string) ([ } return result, nil } + +func (s *TaskTemplateService) DeleteTaskTemplates(requestTemplateId string) ([]*dao.ExecAction, error) { + // 查询现有任务模板列表 + var taskTemplates []*models.TaskTemplateTable + err := s.taskTemplateDao.DB.SQL("SELECT * FROM task_template WHERE request_template = ? ORDER BY sort", requestTemplateId).Find(&taskTemplates) + if err != nil { + return nil, err + } + if len(taskTemplates) == 0 { + return nil, nil + } + // 汇总任务模板列表 + taskTemplateIds := make([]string, len(taskTemplates)) + for i, taskTemplate := range taskTemplates { + taskTemplateIds[i] = taskTemplate.Id + } + actions := []*dao.ExecAction{} + // 删除现有任务处理模板 + action := &dao.ExecAction{Sql: "DELETE FROM task_template_role WHERE task_template IN ('" + strings.Join(taskTemplateIds, "','") + "')"} + actions = append(actions, action) + // 删除现有任务模板 + action = &dao.ExecAction{Sql: "DELETE FROM task_template WHERE id IN ('" + strings.Join(taskTemplateIds, "','") + "')"} + actions = append(actions, action) + return actions, nil +} From 7d849ee22c18a9b197f8a2607666f21d9de7bd80 Mon Sep 17 00:00:00 2001 From: pobu168 <244202969@qq.com> Date: Mon, 26 Feb 2024 10:28:35 +0800 Subject: [PATCH 059/618] update: custom data mgmt --- .../temp-management/request-form-data-custom.vue | 12 +++++++----- .../src/pages/temp-management/request-form-data.vue | 6 ++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/taskman-ui/src/pages/temp-management/request-form-data-custom.vue b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue index 794a15d2..e42e37b3 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data-custom.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue @@ -71,11 +71,13 @@ export default { this.group.customItems = [] this.openFormConfig = true } else { - const { statusCode, data } = await getRequestGroupForm( - params.requestTemplateId, - params.formTemplateId, - params.itemGroupId - ) + const { statusCode, data } = await getRequestGroupForm({ + formTemplateId: params.formTemplateId, + requestTemplateId: params.requestTemplateId, + entity: params.itemGroup, + formType: params.itemGroupType, + itemGroupId: params.itemGroupId + }) if (statusCode === 'OK') { this.group = data this.group.requestTemplateId = params.requestTemplateId diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index f48128f0..e4cb8c8b 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -46,6 +46,7 @@ type="primary" size="small" ghost + shape="circle" style="position: relative;left: 16px;bottom: 16px;" icon="md-create" > @@ -60,6 +61,7 @@ type="error" size="small" ghost + shape="circle" icon="md-trash" style="position: relative;right: 16px;bottom: 16px;" > @@ -68,7 +70,6 @@
- {{ isParmasChanged }} - - diff --git a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue index ec52c4c1..14490899 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue @@ -130,6 +130,7 @@ export default { } } }, + props: ['module'], methods: { async loadPage (params) { await this.getRequestGroupForm(params) @@ -155,7 +156,8 @@ export default { requestTemplateId: params.requestTemplateId, entity: params.itemGroup, formType: params.itemGroupType, - itemGroupId: params.itemGroupId + itemGroupId: params.itemGroupId, + module: this.module }) if (statusCode === 'OK') { this.group = data diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index fbd2ac6f..b0e3b4e0 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -299,6 +299,7 @@ @@ -306,6 +307,7 @@
@@ -322,7 +324,6 @@ import { import draggable from 'vuedraggable' import RequestFormDataCustom from './request-form-data-custom.vue' import RequestFormDataWorkflow from './request-form-data-workflow.vue' -import RequestFormDataOptional from './request-form-data-optional.vue' let idGlobal = 18 export default { name: 'form-select', @@ -533,7 +534,9 @@ export default { }, methods: { async loadPage (requestTemplateId) { - this.requestTemplateId = requestTemplateId + if (requestTemplateId) { + this.requestTemplateId = requestTemplateId + } this.isParmasChanged = false const { statusCode, data } = await getRequestDataForm(this.requestTemplateId) if (statusCode === 'OK') { @@ -619,6 +622,7 @@ export default { itemGroupId: '', itemGroupSort: this.dataFormInfo.groups.length + 1 } + console.log(34, params) this.$refs.requestFormDataWorkflowRef.loadPage(params) } }) @@ -777,8 +781,7 @@ export default { components: { draggable, RequestFormDataCustom, - RequestFormDataWorkflow, - RequestFormDataOptional + RequestFormDataWorkflow } } From dfdf3e01c8a6efe1b26a31da30e0d8373e1665a1 Mon Sep 17 00:00:00 2001 From: wanghao7717 <792974788@qq.com> Date: Tue, 27 Feb 2024 21:14:48 +0800 Subject: [PATCH 073/618] =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0=E8=81=94?= =?UTF-8?q?=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-ui/src/api/server.js | 4 + .../src/pages/components/limit-select.vue | 27 +- taskman-ui/src/pages/template.vue | 62 ++- .../workbench/components/base-progress.vue | 282 ++++++++++ .../workbench/components/custom-form.vue | 207 +++++++ .../pages/workbench/components/data-card.vue | 26 +- .../components/entity-table copy.vue | 502 +++++++++++++++++ .../workbench/components/entity-table.vue | 507 +++++++++-------- .../components/flow/dynamic-flow.vue | 2 +- taskman-ui/src/pages/workbench/index.vue | 36 +- .../publish/components/base-create.vue | 526 +++++++++++++----- .../publish/components/base-detail.vue | 168 ++---- 12 files changed, 1781 insertions(+), 568 deletions(-) create mode 100644 taskman-ui/src/pages/workbench/components/base-progress.vue create mode 100644 taskman-ui/src/pages/workbench/components/custom-form.vue create mode 100644 taskman-ui/src/pages/workbench/components/entity-table copy.vue diff --git a/taskman-ui/src/api/server.js b/taskman-ui/src/api/server.js index e8162274..5c7cdabe 100755 --- a/taskman-ui/src/api/server.js +++ b/taskman-ui/src/api/server.js @@ -142,6 +142,10 @@ export const startRequestNew = (requestId, data) => req.post(`/taskman/api/v2/re // 定版暂存新接口 export const saveRequestNew = (requestId, type, data) => req.post(`/taskman/api/v2/request-data/save/${requestId}/bing/${type}`, data) +// 审批模板配置 +export const getApprovalConfig = (templateId) => req.get(`/taskman/api/v1/approval-template/${templateId}`) +// 任务模板配置 +export const getTaskConfig = (templateId) => req.get(`/taskman/api/v1/task-template/custom/${templateId}`) // 查询流程图 export const getFlowByTemplateId = templateId => req.get(`/taskman/api/v1/request/process/definitions/${templateId}`) diff --git a/taskman-ui/src/pages/components/limit-select.vue b/taskman-ui/src/pages/components/limit-select.vue index 19a18916..68a015b9 100644 --- a/taskman-ui/src/pages/components/limit-select.vue +++ b/taskman-ui/src/pages/components/limit-select.vue @@ -1,17 +1,16 @@ - diff --git a/taskman-ui/src/pages/temp-management/basic-info.vue b/taskman-ui/src/pages/temp-management/basic-info.vue index 283fe63d..fa729905 100644 --- a/taskman-ui/src/pages/temp-management/basic-info.vue +++ b/taskman-ui/src/pages/temp-management/basic-info.vue @@ -6,23 +6,22 @@
- 1
- 模版信息 + 1.模版信息
- + * {{ $t('name') }}{{ $t('can_not_be_empty') }} - * @@ -31,7 +30,7 @@ > - @@ -45,7 +44,7 @@ @on-open-change="getTags" filterable allow-create - style="width: 90%" + style="width: 95%;" @on-change="paramsChanged" @on-create="handleCreate" > @@ -58,7 +57,7 @@ - @@ -131,9 +130,8 @@
- 2
- 模版配置 + 2.模版配置
@@ -152,7 +150,7 @@
- @@ -164,7 +162,7 @@ v-model="basicInfo.pendingHandler" @on-open-change="getPendingHandlerRoles" filterable - style="width: 90%" + style="width: 95%;" > - @@ -193,7 +191,7 @@ @@ -197,7 +197,7 @@ +
@@ -429,7 +430,8 @@ import { getApprovalNodeGroups, deleteRequestGroupForm, getAllDataModels, - saveRequestGroupCustomForm + saveRequestGroupCustomForm, + submitTemplate } from '@/api/server.js' let idGlobal = 118 export default { @@ -444,7 +446,7 @@ export default { id: '', sort: 1, requestTemplate: '', - name: '审批1', + name: '任务1', expireDay: 1, description: '', roleType: '', @@ -588,7 +590,7 @@ export default { name: 'datePicker', title: 'datePicker', elementType: 'datePicker', - abc: 'datePicker', + type: 'datetime', defaultValue: '', defaultClear: 'no', // tag: '', @@ -818,7 +820,8 @@ export default { editNode (node) { let params = { requestTemplateId: this.requestTemplateId, - id: node.id + id: node.id, + procDefId: this.procDefId } this.nextNodeInfo = node const res = this.preApprovalNodeChange(2) @@ -858,7 +861,8 @@ export default { this.cancelGroup() let params = { requestTemplateId: this.requestTemplateId, - id: this.nextNodeInfo.id + id: this.nextNodeInfo.id, + procDefId: this.procDefId } this.activeEditingNode = this.nextNodeInfo this.$refs.approvalFormNodeRef.loadPage(params) @@ -1163,6 +1167,32 @@ export default { res = this.procDefId === '' ? 'background:#b886f8;' : 'background:#cba43f;' } return res + }, + async submitTemplate () { + this.$Modal.confirm({ + title: `${this.$t('submit_for_review')}`, + content: `${this.$t('submit_for_review_tip')}`, + 'z-index': 1000000, + okText: this.$t('confirm'), + cancelText: this.$t('cancel'), + onOk: async () => { + let data = { + requestTemplateId: this.requestTemplateId, + status: 'created', + targetStatus: 'pending', + reason: '{}' + } + const { statusCode } = await submitTemplate(data) + if (statusCode === 'OK') { + this.$Notice.success({ + title: this.$t('successful'), + desc: this.$t('successful') + }) + this.$router.push({ path: '/taskman/template-mgmt' }) + } + }, + onCancel: () => {} + }) } }, components: { From c237a2dcbafaddd4ec8d20aabd883f5078516e7a Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Mon, 11 Mar 2024 14:33:06 +0800 Subject: [PATCH 247/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E8=AE=A1=E7=AE=97?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E6=B7=BB=E5=8A=A0routineExpression=E5=AD=98?= =?UTF-8?q?=E5=82=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/form_item_template.go | 258 ++++++++++---------- 1 file changed, 131 insertions(+), 127 deletions(-) diff --git a/taskman-server/models/form_item_template.go b/taskman-server/models/form_item_template.go index f7c8415c..87a55f3c 100644 --- a/taskman-server/models/form_item_template.go +++ b/taskman-server/models/form_item_template.go @@ -1,74 +1,76 @@ package models type FormItemTemplateTable struct { - Id string `json:"id" xorm:"'id' pk" primary-key:"id"` - Name string `json:"name" xorm:"name"` - Description string `json:"description" xorm:"description"` - ItemGroup string `json:"itemGroup" xorm:"item_group"` - ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` - FormTemplate string `json:"formTemplate" xorm:"form_template"` - DefaultValue string `json:"defaultValue" xorm:"default_value"` - Sort int `json:"sort" xorm:"sort"` - PackageName string `json:"packageName" xorm:"package_name"` - Entity string `json:"entity" xorm:"entity"` - AttrDefId string `json:"attrDefId" xorm:"attr_def_id"` - AttrDefName string `json:"attrDefName" xorm:"attr_def_name"` - AttrDefDataType string `json:"attrDefDataType" xorm:"attr_def_data_type"` - ElementType string `json:"elementType" xorm:"element_type"` - Title string `json:"title" xorm:"title"` - Width int `json:"width" xorm:"width"` - RefPackageName string `json:"refPackageName" xorm:"ref_package_name"` - RefEntity string `json:"refEntity" xorm:"ref_entity"` - DataOptions string `json:"dataOptions" xorm:"data_options"` - Required string `json:"required" xorm:"required"` - Regular string `json:"regular" xorm:"regular"` - IsEdit string `json:"isEdit" xorm:"is_edit"` - IsView string `json:"isView" xorm:"is_view"` - IsOutput string `json:"isOutput" xorm:"is_output"` - InDisplayName string `json:"inDisplayName" xorm:"in_display_name"` - IsRefInside string `json:"isRefInside" xorm:"is_ref_inside"` - Multiple string `json:"multiple" xorm:"multiple"` - DefaultClear string `json:"defaultClear" xorm:"default_clear"` - RefId string `json:"refId" xorm:"ref_id"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 - SelectList []*EntityDataObj `json:"selectList" xorm:"-"` - Active bool `json:"active" xorm:"-"` // 是否选中状态 + Id string `json:"id" xorm:"'id' pk" primary-key:"id"` + Name string `json:"name" xorm:"name"` + Description string `json:"description" xorm:"description"` + ItemGroup string `json:"itemGroup" xorm:"item_group"` + ItemGroupName string `json:"itemGroupName" xorm:"item_group_name"` + FormTemplate string `json:"formTemplate" xorm:"form_template"` + DefaultValue string `json:"defaultValue" xorm:"default_value"` + Sort int `json:"sort" xorm:"sort"` + PackageName string `json:"packageName" xorm:"package_name"` + Entity string `json:"entity" xorm:"entity"` + AttrDefId string `json:"attrDefId" xorm:"attr_def_id"` + AttrDefName string `json:"attrDefName" xorm:"attr_def_name"` + AttrDefDataType string `json:"attrDefDataType" xorm:"attr_def_data_type"` + ElementType string `json:"elementType" xorm:"element_type"` + Title string `json:"title" xorm:"title"` + Width int `json:"width" xorm:"width"` + RefPackageName string `json:"refPackageName" xorm:"ref_package_name"` + RefEntity string `json:"refEntity" xorm:"ref_entity"` + DataOptions string `json:"dataOptions" xorm:"data_options"` + Required string `json:"required" xorm:"required"` + Regular string `json:"regular" xorm:"regular"` + IsEdit string `json:"isEdit" xorm:"is_edit"` + IsView string `json:"isView" xorm:"is_view"` + IsOutput string `json:"isOutput" xorm:"is_output"` + InDisplayName string `json:"inDisplayName" xorm:"in_display_name"` + IsRefInside string `json:"isRefInside" xorm:"is_ref_inside"` + Multiple string `json:"multiple" xorm:"multiple"` + DefaultClear string `json:"defaultClear" xorm:"default_clear"` + RefId string `json:"refId" xorm:"ref_id"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 + RoutineExpression string `json:"routineExpression" xorm:"routine_expression"` //计算表达式 + SelectList []*EntityDataObj `json:"selectList" xorm:"-"` + Active bool `json:"active" xorm:"-"` // 是否选中状态 } type FormItemTemplateDto struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - FormTemplate string `json:"itemGroupId"` - ItemGroup string `json:"itemGroup"` - ItemGroupType string `json:"itemGroupType"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 - ItemGroupName string `json:"itemGroupName"` - ItemGroupSort int `json:"ItemGroupSort"` // item_group 排序 - ItemGroupRule string `json:"itemGroupRule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 - DefaultValue string `json:"defaultValue"` - Sort int `json:"sort"` - PackageName string `json:"packageName"` - Entity string `json:"entity"` - AttrDefId string `json:"attrDefId"` - AttrDefName string `json:"attrDefName"` - AttrDefDataType string `json:"attrDefDataType"` - ElementType string `json:"elementType"` - Title string `json:"title"` - Width int `json:"width"` - RefPackageName string `json:"refPackageName"` - RefEntity string `json:"refEntity"` - DataOptions string `json:"dataOptions"` - Required string `json:"required"` - Regular string `json:"regular"` - IsEdit string `json:"isEdit"` - IsView string `json:"isView"` - IsOutput string `json:"isOutput"` - InDisplayName string `json:"inDisplayName"` - IsRefInside string `json:"isRefInside"` - Multiple string `json:"multiple"` - DefaultClear string `json:"defaultClear"` - RefId string `json:"copyId"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 - SelectList []*EntityDataObj `json:"selectList"` - Active bool `json:"active"` // 是否选中状态 + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + FormTemplate string `json:"itemGroupId"` + ItemGroup string `json:"itemGroup"` + ItemGroupType string `json:"itemGroupType"` //表单组类型:workflow 编排数据,optional 自选,custom 自定义 + ItemGroupName string `json:"itemGroupName"` + ItemGroupSort int `json:"ItemGroupSort"` // item_group 排序 + ItemGroupRule string `json:"itemGroupRule"` // item_group_rule 新增一行规则,new 输入新数据,exist 选择已有数据 + DefaultValue string `json:"defaultValue"` + Sort int `json:"sort"` + PackageName string `json:"packageName"` + Entity string `json:"entity"` + AttrDefId string `json:"attrDefId"` + AttrDefName string `json:"attrDefName"` + AttrDefDataType string `json:"attrDefDataType"` + ElementType string `json:"elementType"` + Title string `json:"title"` + Width int `json:"width"` + RefPackageName string `json:"refPackageName"` + RefEntity string `json:"refEntity"` + DataOptions string `json:"dataOptions"` + Required string `json:"required"` + Regular string `json:"regular"` + IsEdit string `json:"isEdit"` + IsView string `json:"isView"` + IsOutput string `json:"isOutput"` + InDisplayName string `json:"inDisplayName"` + IsRefInside string `json:"isRefInside"` + Multiple string `json:"multiple"` + DefaultClear string `json:"defaultClear"` + RefId string `json:"copyId"` //复制数据表单ID,数据表单删除该表单项时,需要删除审批表单,任务表单对应数据项 + RoutineExpression string `json:"routineExpression"` //计算表达式 + SelectList []*EntityDataObj `json:"selectList"` + Active bool `json:"active"` // 是否选中状态 } func (FormItemTemplateTable) TableName() string { @@ -94,73 +96,75 @@ func (s FormItemTemplateDtoSort) Less(i, j int) bool { func ConvertFormItemTemplateDto2Model(dto *FormItemTemplateDto) *FormItemTemplateTable { return &FormItemTemplateTable{ - Id: dto.Id, - Name: dto.Name, - Description: dto.Description, - FormTemplate: dto.FormTemplate, - ItemGroup: dto.ItemGroup, - ItemGroupName: dto.ItemGroupName, - DefaultValue: dto.DefaultValue, - Sort: dto.Sort, - PackageName: dto.PackageName, - Entity: dto.Entity, - AttrDefId: dto.AttrDefId, - AttrDefName: dto.AttrDefName, - AttrDefDataType: dto.AttrDefDataType, - ElementType: dto.ElementType, - Title: dto.Title, - Width: dto.Width, - RefPackageName: dto.RefPackageName, - RefEntity: dto.RefEntity, - DataOptions: dto.DataOptions, - Required: dto.Required, - Regular: dto.Regular, - IsEdit: dto.IsEdit, - IsView: dto.IsView, - IsOutput: dto.IsOutput, - InDisplayName: dto.InDisplayName, - IsRefInside: dto.IsRefInside, - Multiple: dto.Multiple, - DefaultClear: dto.DefaultClear, - RefId: dto.RefId, - SelectList: dto.SelectList, - Active: dto.Active, + Id: dto.Id, + Name: dto.Name, + Description: dto.Description, + FormTemplate: dto.FormTemplate, + ItemGroup: dto.ItemGroup, + ItemGroupName: dto.ItemGroupName, + DefaultValue: dto.DefaultValue, + Sort: dto.Sort, + PackageName: dto.PackageName, + Entity: dto.Entity, + AttrDefId: dto.AttrDefId, + AttrDefName: dto.AttrDefName, + AttrDefDataType: dto.AttrDefDataType, + ElementType: dto.ElementType, + Title: dto.Title, + Width: dto.Width, + RefPackageName: dto.RefPackageName, + RefEntity: dto.RefEntity, + DataOptions: dto.DataOptions, + Required: dto.Required, + Regular: dto.Regular, + IsEdit: dto.IsEdit, + IsView: dto.IsView, + IsOutput: dto.IsOutput, + InDisplayName: dto.InDisplayName, + IsRefInside: dto.IsRefInside, + Multiple: dto.Multiple, + DefaultClear: dto.DefaultClear, + RefId: dto.RefId, + SelectList: dto.SelectList, + Active: dto.Active, + RoutineExpression: dto.RoutineExpression, } } func ConvertFormItemTemplateModel2Dto(model *FormItemTemplateTable, itemGroup FormTemplateTable) *FormItemTemplateDto { dto := &FormItemTemplateDto{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - ItemGroup: model.ItemGroup, - ItemGroupName: model.ItemGroupName, - FormTemplate: model.FormTemplate, - DefaultValue: model.DefaultValue, - Sort: model.Sort, - PackageName: model.PackageName, - Entity: model.Entity, - AttrDefId: model.AttrDefId, - AttrDefName: model.AttrDefName, - AttrDefDataType: model.AttrDefDataType, - ElementType: model.ElementType, - Title: model.Title, - Width: model.Width, - RefPackageName: model.RefPackageName, - RefEntity: model.RefEntity, - DataOptions: model.DataOptions, - Required: model.Required, - Regular: model.Regular, - IsEdit: model.IsEdit, - IsView: model.IsView, - IsOutput: model.IsOutput, - InDisplayName: model.InDisplayName, - IsRefInside: model.IsRefInside, - Multiple: model.Multiple, - DefaultClear: model.DefaultClear, - RefId: model.RefId, - SelectList: model.SelectList, - Active: model.Active, + Id: model.Id, + Name: model.Name, + Description: model.Description, + ItemGroup: model.ItemGroup, + ItemGroupName: model.ItemGroupName, + FormTemplate: model.FormTemplate, + DefaultValue: model.DefaultValue, + Sort: model.Sort, + PackageName: model.PackageName, + Entity: model.Entity, + AttrDefId: model.AttrDefId, + AttrDefName: model.AttrDefName, + AttrDefDataType: model.AttrDefDataType, + ElementType: model.ElementType, + Title: model.Title, + Width: model.Width, + RefPackageName: model.RefPackageName, + RefEntity: model.RefEntity, + DataOptions: model.DataOptions, + Required: model.Required, + Regular: model.Regular, + IsEdit: model.IsEdit, + IsView: model.IsView, + IsOutput: model.IsOutput, + InDisplayName: model.InDisplayName, + IsRefInside: model.IsRefInside, + Multiple: model.Multiple, + DefaultClear: model.DefaultClear, + RefId: model.RefId, + SelectList: model.SelectList, + Active: model.Active, + RoutineExpression: model.RoutineExpression, } dto.ItemGroupType = itemGroup.ItemGroupType dto.ItemGroupRule = itemGroup.ItemGroupRule From 49501730511a29aa8f7b73d2c9bb0cec73ab66be Mon Sep 17 00:00:00 2001 From: zgyzgyhero <894526647@qq.com> Date: Mon, 11 Mar 2024 15:27:34 +0800 Subject: [PATCH 248/618] add expression data query api --- taskman-server/api/api.go | 1 + taskman-server/api/v1/request/request.go | 21 ++++++++++++++ taskman-server/models/data_model.go | 11 ++++++++ taskman-server/rpc/proc_def_rpc.go | 28 +++++++++++++++++++ .../service/form_item_template_service.go | 5 ++++ 5 files changed, 66 insertions(+) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 5ad3d404..57790a97 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -104,6 +104,7 @@ func init() { &handlerFuncObj{Url: "/request-data/get/:requestId/:cacheType", Method: "GET", HandlerFunc: request.GetRequestCache}, &handlerFuncObj{Url: "/request-status/:requestId/:status", Method: "POST", HandlerFunc: request.UpdateRequestStatus}, &handlerFuncObj{Url: "/request-data/reference/query/:formItemTemplateId/:requestId/:attrName", Method: "POST", HandlerFunc: request.GetReferenceData}, + &handlerFuncObj{Url: "/request-data/entity/expression/query/:formItemTemplateId/:rootDataId", Method: "GET", HandlerFunc: request.GetExpressionItemData}, &handlerFuncObj{Url: "/user/platform/count", Method: "GET", HandlerFunc: request.CountPlatform}, &handlerFuncObj{Url: "/user/platform/filter-item", Method: "POST", HandlerFunc: request.FilterItem}, diff --git a/taskman-server/api/v1/request/request.go b/taskman-server/api/v1/request/request.go index 43716c35..57d67200 100644 --- a/taskman-server/api/v1/request/request.go +++ b/taskman-server/api/v1/request/request.go @@ -6,6 +6,7 @@ import ( "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/exterror" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" + "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/rpc" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/service" "github.com/gin-gonic/gin" "io/ioutil" @@ -524,3 +525,23 @@ func GetRequestProgress(c *gin.Context) { } middleware.ReturnData(c, rowData) } + +func GetExpressionItemData(c *gin.Context) { + formItemTemplateId := c.Param("formItemTemplateId") + rootDataId := c.Param("rootDataId") + formItemTemplateRow, err := service.GetFormItemTemplateService().GetFormItemTemplate(formItemTemplateId) + if err != nil { + middleware.ReturnError(c, err) + return + } + if formItemTemplateRow.RoutineExpression == "" { + middleware.ReturnError(c, fmt.Errorf("expression is empty")) + return + } + result, queryErr := rpc.QueryEntityExpressionData(formItemTemplateRow.RoutineExpression, rootDataId, c.GetHeader("Authorization")) + if queryErr != nil { + middleware.ReturnError(c, queryErr) + } else { + middleware.ReturnData(c, result) + } +} diff --git a/taskman-server/models/data_model.go b/taskman-server/models/data_model.go index 6d480230..1893e378 100644 --- a/taskman-server/models/data_model.go +++ b/taskman-server/models/data_model.go @@ -151,3 +151,14 @@ type ProcEntity struct { DisplayName string `json:"displayName"` Attributes []*ProcEntityAttributeObj `json:"attributes"` } + +type PluginQueryExpressionDataParam struct { + DataModelExpression string `json:"dataModelExpression" binding:"required"` + RootDataId string `json:"rootDataId" binding:"required"` + Token string `json:"token"` +} + +type PluginQueryExpressionDataResponse struct { + HttpResponseMeta + Data []map[string]interface{} `json:"data"` +} diff --git a/taskman-server/rpc/proc_def_rpc.go b/taskman-server/rpc/proc_def_rpc.go index 595357de..9404050e 100644 --- a/taskman-server/rpc/proc_def_rpc.go +++ b/taskman-server/rpc/proc_def_rpc.go @@ -37,6 +37,8 @@ const ( pathQueryEntityModel = "/platform/v1/models/package/%s/entity/%s" // pathSyncWorkflowUseRole pathSyncWorkflowUseRole = "/platform/v1/public/process/definitions/syncUseRole" + // pathQueryEntityExpressionData 查询表达式数据 + pathQueryEntityExpressionData = "/platform/v1/process/public/data-model/dme/integrated-query" ) // QueryProcessDefinitionList 查询当前角色编排列表,并且根据属主角色进行过滤 @@ -348,3 +350,29 @@ func SyncWorkflowUseRole(param models.SyncUseRoleParam, userToken, language stri } return } + +func QueryEntityExpressionData(expression, rootDataId, userToken string) (result []map[string]interface{}, err error) { + param := models.PluginQueryExpressionDataParam{ + DataModelExpression: expression, + RootDataId: rootDataId, + Token: userToken, + } + var response models.PluginQueryExpressionDataResponse + var byteArr []byte + postBytes, _ := json.Marshal(param) + byteArr, err = HttpPost(models.Config.Wecube.BaseUrl+pathQueryEntityExpressionData, userToken, "", postBytes) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } else { + result = response.Data + } + return +} diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 15d0a787..29df0280 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -314,3 +314,8 @@ func (s *FormItemTemplateService) CopyDataFormTemplateItemGroup(requestTemplateI }) return } + +func (s *FormItemTemplateService) GetFormItemTemplate(formItemTemplateId string) (result *models.FormItemTemplateTable, err error) { + result, err = s.formItemTemplateDao.Get(formItemTemplateId) + return +} From d271da5ad4411815bf20fd89d612121fac4c4860 Mon Sep 17 00:00:00 2001 From: zhanglin9833 Date: Mon, 11 Mar 2024 15:28:51 +0800 Subject: [PATCH 249/618] update NotifyTaskMail --- taskman-server/api/v1/task/task.go | 2 +- taskman-server/api/v2/request/request.go | 2 +- taskman-server/service/cron.go | 15 ++++++++++++--- taskman-server/service/task_service.go | 8 +++++++- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/taskman-server/api/v1/task/task.go b/taskman-server/api/v1/task/task.go index 97ad5676..c27017a6 100644 --- a/taskman-server/api/v1/task/task.go +++ b/taskman-server/api/v1/task/task.go @@ -49,7 +49,7 @@ func CreateTask(c *gin.Context) { output.ErrorMessage = tmpErr.Error() err = tmpErr } else { - notifyErr := service.NotifyTaskMail(taskId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + notifyErr := service.NotifyTaskMail(taskId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), "", "") if notifyErr != nil { log.Logger.Error("Notify task mail fail", log.Error(notifyErr)) } diff --git a/taskman-server/api/v2/request/request.go b/taskman-server/api/v2/request/request.go index b2bff9e6..acc282d6 100644 --- a/taskman-server/api/v2/request/request.go +++ b/taskman-server/api/v2/request/request.go @@ -232,7 +232,7 @@ func PluginCreateRequest(c *gin.Context) { output.ErrorMessage = tmpErr.Error() err = tmpErr } else { - notifyErr := service.NotifyTaskMail(taskId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader)) + notifyErr := service.NotifyTaskMail(taskId, c.GetHeader("Authorization"), c.GetHeader(middleware.AcceptLanguageHeader), "", "") if notifyErr != nil { log.Logger.Error("Notify task mail fail", log.Error(notifyErr)) } diff --git a/taskman-server/service/cron.go b/taskman-server/service/cron.go index 886409ea..671aec21 100644 --- a/taskman-server/service/cron.go +++ b/taskman-server/service/cron.go @@ -1,6 +1,7 @@ package service import ( + "fmt" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/common/log" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/dao" "github.com/WeBankPartners/wecube-plugins-taskman/taskman-server/models" @@ -32,13 +33,21 @@ func notifyAction() { return } for _, v := range taskTable { - if v.NotifyCount >= 1 { + if v.NotifyCount >= 2 { continue } tmpExpireObj := models.ExpireObj{ReportTime: v.CreatedTime, ExpireTime: v.ExpireTime, NowTime: time.Now().Format(models.DateTimeFormat)} calcExpireObj(&tmpExpireObj) - if tmpExpireObj.Percent > 75 { - tmpErr := NotifyTaskMail(v.Id, models.CoreToken.GetCoreToken(), "") + if ((tmpExpireObj.Percent >= 75) && (v.NotifyCount == 0)) || ((tmpExpireObj.Percent >= 100) && (v.NotifyCount < 2)) { + mailSubject := "【任务超时提醒】" + mailContent := "" + if (tmpExpireObj.Percent >= 75) && (v.NotifyCount == 0) { + mailContent = fmt.Sprintf("分配给您的任务[请求:%s-任务:%s]快过期了,有效期到%s,请点击链接处理", v.Request, v.Name, v.ExpireTime) + } else { + mailContent = fmt.Sprintf("分配给您的任务[请求:%s-任务:%s]已过期,请点击链接尽快处理", v.Request, v.Name) + } + + tmpErr := NotifyTaskMail(v.Id, models.CoreToken.GetCoreToken(), "", mailSubject, mailContent) if tmpErr != nil { log.Logger.Error("notify task mail fail", log.String("taskId", v.Id), log.Error(tmpErr)) } else { diff --git a/taskman-server/service/task_service.go b/taskman-server/service/task_service.go index 22262977..2ba0f445 100644 --- a/taskman-server/service/task_service.go +++ b/taskman-server/service/task_service.go @@ -1270,7 +1270,7 @@ func buildTaskOperation(taskObj *models.TaskListObj, operator string) { } } -func NotifyTaskMail(taskId, userToken, language string) error { +func NotifyTaskMail(taskId, userToken, language, mailSubject, mailContent string) error { if !models.MailEnable { return nil } @@ -1302,6 +1302,12 @@ func NotifyTaskMail(taskId, userToken, language string) error { var subject, content string subject = fmt.Sprintf("Taskman task [%s] %s[%s]", models.PriorityLevelMap[taskTable[0].Emergency], taskTable[0].Name, taskTable[0].Request) content = fmt.Sprintf("Taskman task \nID:%s \nPriority:%s \nName:%s \nRequest:%s \nDescription:%s \nReporter:%s \nCreateTime:%s \n", taskTable[0].Id, models.PriorityLevelMap[taskTable[0].Emergency], taskTable[0].Name, taskTable[0].Request, taskTable[0].Description, taskTable[0].Reporter, taskTable[0].CreatedTime) + if mailSubject != "" { + subject = mailSubject + } + if mailContent != "" { + content = mailContent + } err := models.MailSender.Send(subject, content, mailList) if err != nil { return fmt.Errorf("send notify email fail:%s ", err.Error()) From a5482afa638abf75659ed0d5594e328425cb0fe0 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Mon, 11 Mar 2024 15:36:27 +0800 Subject: [PATCH 250/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BFbug=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/dao/form_item_template_dao.go | 5 +++++ taskman-server/dao/task_dao.go | 4 ++-- taskman-server/dao/task_handle_dao.go | 8 ++++---- taskman-server/dao/task_handle_template_dao.go | 8 ++++---- taskman-server/dao/task_template_dao.go | 4 ++-- .../service/form_item_template_service.go | 14 ++++++++++++-- taskman-server/service/request_template_service.go | 11 +++++++++++ 7 files changed, 40 insertions(+), 14 deletions(-) diff --git a/taskman-server/dao/form_item_template_dao.go b/taskman-server/dao/form_item_template_dao.go index 86812fc5..7020e024 100644 --- a/taskman-server/dao/form_item_template_dao.go +++ b/taskman-server/dao/form_item_template_dao.go @@ -126,3 +126,8 @@ func (d *FormItemTemplateDao) DeleteByFormTemplate(session *xorm.Session, formTe logExecuteSql(session, "FormItemTemplateDao", "DeleteByFormTemplate", formTemplate, affected, err) return } + +func (d *FormItemTemplateDao) QueryByRefId(refId string) (formItemTemplateList []*models.FormItemTemplateTable, err error) { + err = d.DB.Where("ref_id = ?", refId).Find(&formItemTemplateList) + return +} diff --git a/taskman-server/dao/task_dao.go b/taskman-server/dao/task_dao.go index 66784499..f2c4d098 100644 --- a/taskman-server/dao/task_dao.go +++ b/taskman-server/dao/task_dao.go @@ -39,7 +39,7 @@ func (d *TaskDao) Delete(session *xorm.Session, id string) (err error) { session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.ID(id).Delete(&models.TaskTable{}) + _, err = session.ID(id).Delete(&models.TaskTable{}) return } @@ -51,7 +51,7 @@ func (d *TaskDao) Deletes(session *xorm.Session, ids []string) (err error) { if len(ids) == 0 { return } - _, err = d.DB.In("id", ids).Delete(&models.TaskTable{}) + _, err = session.In("id", ids).Delete(&models.TaskTable{}) return } diff --git a/taskman-server/dao/task_handle_dao.go b/taskman-server/dao/task_handle_dao.go index 22873d15..c0c0644e 100644 --- a/taskman-server/dao/task_handle_dao.go +++ b/taskman-server/dao/task_handle_dao.go @@ -39,7 +39,7 @@ func (d *TaskHandleDao) Delete(session *xorm.Session, id string) (err error) { session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.ID(id).Delete(&models.TaskHandleTable{}) + _, err = session.ID(id).Delete(&models.TaskHandleTable{}) return } @@ -51,7 +51,7 @@ func (d *TaskHandleDao) Deletes(session *xorm.Session, ids []string) (err error) if len(ids) == 0 { return } - _, err = d.DB.In("id", ids).Delete(&models.TaskHandleTable{}) + _, err = session.In("id", ids).Delete(&models.TaskHandleTable{}) return } @@ -60,7 +60,7 @@ func (d *TaskHandleDao) DeleteByTask(session *xorm.Session, taskId string) (err session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.Where("task=?", taskId).Delete(&models.TaskHandleTable{}) + _, err = session.Where("task=?", taskId).Delete(&models.TaskHandleTable{}) return } @@ -72,7 +72,7 @@ func (d *TaskHandleDao) DeleteByTasks(session *xorm.Session, taskIds []string) ( if len(taskIds) == 0 { return } - _, err = d.DB.In("task", taskIds).Delete(&models.TaskHandleTable{}) + _, err = session.In("task", taskIds).Delete(&models.TaskHandleTable{}) return } diff --git a/taskman-server/dao/task_handle_template_dao.go b/taskman-server/dao/task_handle_template_dao.go index 94dd1f53..17fd1796 100644 --- a/taskman-server/dao/task_handle_template_dao.go +++ b/taskman-server/dao/task_handle_template_dao.go @@ -43,7 +43,7 @@ func (d *TaskHandleTemplateDao) Delete(session *xorm.Session, id string) (err er session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.ID(id).Delete(&models.TaskHandleTemplateTable{}) + _, err = session.ID(id).Delete(&models.TaskHandleTemplateTable{}) return } @@ -55,7 +55,7 @@ func (d *TaskHandleTemplateDao) Deletes(session *xorm.Session, ids []string) (er if len(ids) == 0 { return } - _, err = d.DB.In("id", ids).Delete(&models.TaskHandleTemplateTable{}) + _, err = session.In("id", ids).Delete(&models.TaskHandleTemplateTable{}) return } @@ -64,7 +64,7 @@ func (d *TaskHandleTemplateDao) DeleteByTaskTemplate(session *xorm.Session, task session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.Where("task_template=?", taskTemplateId).Delete(&models.TaskHandleTemplateTable{}) + _, err = session.Where("task_template=?", taskTemplateId).Delete(&models.TaskHandleTemplateTable{}) return } @@ -76,7 +76,7 @@ func (d *TaskHandleTemplateDao) DeleteByTaskTemplates(session *xorm.Session, tas if len(taskTemplateIds) == 0 { return } - _, err = d.DB.In("task_template", taskTemplateIds).Delete(&models.TaskHandleTemplateTable{}) + _, err = session.In("task_template", taskTemplateIds).Delete(&models.TaskHandleTemplateTable{}) return } diff --git a/taskman-server/dao/task_template_dao.go b/taskman-server/dao/task_template_dao.go index 1b325044..514b66b9 100644 --- a/taskman-server/dao/task_template_dao.go +++ b/taskman-server/dao/task_template_dao.go @@ -39,7 +39,7 @@ func (d *TaskTemplateDao) Delete(session *xorm.Session, id string) (err error) { session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.ID(id).Delete(&models.TaskTemplateTable{}) + _, err = session.ID(id).Delete(&models.TaskTemplateTable{}) return } @@ -48,7 +48,7 @@ func (d *TaskTemplateDao) Deletes(session *xorm.Session, ids []string) (err erro session = d.DB.NewSession() defer session.Close() } - _, err = d.DB.In("id", ids).Delete(&models.TaskTemplateTable{}) + _, err = session.In("id", ids).Delete(&models.TaskTemplateTable{}) return } diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 15d0a787..28586257 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -18,7 +18,7 @@ type FormItemTemplateService struct { func (s *FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models.FormTemplateGroupConfigureDto) (err error) { var formTemplate *models.FormTemplateTable var insertItems, updateItems, deleteItems []*models.FormItemTemplateTable - var formItemTemplateList []*models.FormItemTemplateTable + var formItemTemplateList, refFormItemTemplateList []*models.FormItemTemplateTable var newItemGroupId string var systemItemExist, customItemExist bool var existMap = make(map[string]bool) @@ -96,6 +96,7 @@ func (s *FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models for _, customItem := range param.CustomItems { customItemExist = false if customItem.Id != "" { + refFormItemTemplateList = []*models.FormItemTemplateTable{} existMap[customItem.Id] = true for _, formItemTemplate := range formItemTemplateList { if customItem.Id == formItemTemplate.Id { @@ -103,6 +104,15 @@ func (s *FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models if customItem.FormTemplate == "" { customItem.FormTemplate = param.FormTemplateId } + // 查询 refId指向当前ID的数据 + refFormItemTemplateList, _ = s.formItemTemplateDao.QueryByRefId(customItem.Id) + if len(refFormItemTemplateList) > 0 { + for _, refFormItemTemplate := range refFormItemTemplateList { + // 主要更新 routineExpression 值 + refFormItemTemplate.RoutineExpression = customItem.RoutineExpression + updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(refFormItemTemplate)) + } + } updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(customItem)) break } @@ -167,7 +177,7 @@ func (s *FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models } if len(deleteItems) > 0 { for _, item := range deleteItems { - err = s.formItemTemplateDao.Delete(session, item.Id) + err = s.formItemTemplateDao.DeleteByIdOrRefId(session, item.Id) if err != nil { return err } diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index a7528ead..4c6cd930 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -531,6 +531,17 @@ func (s *RequestTemplateService) UpdateRequestTemplate(param *models.RequestTemp } // 编排处理,(1)新增了编排 (2)编排节点名称有更新 (3)删除编排 if requestTemplate.ProcDefId == "" && param.ProcDefId != "" { + // 先删除已有任务 + for _, taskTemplate := range implementTaskTemplateList { + deleteTaskTemplateActions = []*dao.ExecAction{} + deleteTaskTemplateActions, err = GetTaskTemplateService().deleteProcTaskTemplateSql(param.Id, taskTemplate.Id) + if err != nil { + return + } + if len(deleteTaskTemplateActions) > 0 { + actions = append(actions, deleteTaskTemplateActions...) + } + } // 新增编排 insertTaskTemplateActions, err = GetTaskTemplateService().createProcTaskTemplatesSql(param.ProcDefId, param.Id, userToken, language, "system") if err != nil { From fb966617e6004949c32047b43b26f3fdaedc61b9 Mon Sep 17 00:00:00 2001 From: prog-hjj Date: Mon, 11 Mar 2024 15:36:45 +0800 Subject: [PATCH 251/618] =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=8E=BB=E6=8E=89=E6=97=A0=E7=94=A8=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/task_template_service.go | 249 ++---------------- 1 file changed, 22 insertions(+), 227 deletions(-) diff --git a/taskman-server/service/task_template_service.go b/taskman-server/service/task_template_service.go index 99a026ab..0bf1863b 100644 --- a/taskman-server/service/task_template_service.go +++ b/taskman-server/service/task_template_service.go @@ -159,112 +159,6 @@ func (s *TaskTemplateService) checkHandleTemplates(param *models.TaskTemplateDto return nil } -func (s *TaskTemplateService) CreateProcTaskTemplate(param *models.TaskTemplateDto, userToken, language, operator string) (*models.TaskTemplateDto, error) { - // 校验参数 - if param.Type != string(models.TaskTypeImplement) { - return nil, fmt.Errorf("param type wrong: %s", param.Type) - } - if param.NodeDefId == "" { - return nil, errors.New("param empty") - } - if err := s.checkHandleTemplates(param); err != nil { - return nil, err - } - // 查询请求模板 - requestTemplate, err := GetRequestTemplateService().GetRequestTemplate(param.RequestTemplate) - if err != nil { - return nil, err - } - if requestTemplate == nil { - return nil, errors.New("no request_template record found") - } - if requestTemplate.ProcDefId == "" { - return nil, fmt.Errorf("param requestTemplate not type proc") - } - // 查询现有任务模板 - taskTemplate, err := s.taskTemplateDao.GetProc(param.RequestTemplate, param.NodeDefId) - if err != nil { - return nil, err - } - if taskTemplate != nil { - return nil, errors.New("task_template record already exist") - } - // 查询编排任务节点 - nodeList, err := s.getProcTaskTemplateNodes(requestTemplate.ProcDefId, userToken, language) - if err != nil { - return nil, err - } - sort := 0 - for i, node := range nodeList { - if node.NodeDefId == param.NodeDefId { - sort = i + 1 - if node.NodeId != param.NodeId || node.NodeName != param.NodeDefName { - return nil, fmt.Errorf("param nodeId %q or nodeName %q wrong", param.NodeId, param.NodeDefName) - } - break - } - } - if param.Sort <= 0 || sort != param.Sort { - return nil, fmt.Errorf("param sort %d or nodeDefId %s wrong", param.Sort, param.NodeDefId) - } - // 插入新任务模板 - nowTime := time.Now().Format(models.DateTimeFormat) - newTaskTemplate := &models.TaskTemplateTable{ - Id: fmt.Sprintf("ts_%s", guid.CreateGuid()), - Type: param.Type, - Sort: param.Sort, - RequestTemplate: param.RequestTemplate, - Name: param.Name, - Description: param.Description, - NodeId: param.NodeId, - NodeDefId: param.NodeDefId, - NodeName: param.NodeDefName, - ExpireDay: param.ExpireDay, - CreatedBy: operator, - CreatedTime: nowTime, - UpdatedBy: operator, - UpdatedTime: nowTime, - HandleMode: param.HandleMode, - } - // 插入新任务处理模板 - newTaskHandleTemplates := make([]*models.TaskHandleTemplateTable, len(param.HandleTemplates)) - for i, handleTemplate := range param.HandleTemplates { - newTaskHandleTemplates[i] = &models.TaskHandleTemplateTable{ - Id: guid.CreateGuid(), - Sort: i + 1, - TaskTemplate: newTaskTemplate.Id, - Assign: handleTemplate.Assign, - HandlerType: handleTemplate.HandlerType, - Role: handleTemplate.Role, - Handler: handleTemplate.Handler, - HandleMode: param.HandleMode, - } - } - // 执行事务 - err = transaction(func(session *xorm.Session) error { - _, err := s.taskTemplateDao.Add(session, newTaskTemplate) - if err != nil { - return err - } - for _, newTaskHandleTemplate := range newTaskHandleTemplates { - _, err = s.taskHandleTemplateDao.Add(session, newTaskHandleTemplate) - if err != nil { - return err - } - } - return nil - }) - if err != nil { - return nil, err - } - // 构造返回结果 - result, err := s.genTaskTemplateDto(newTaskTemplate.Id) - if err != nil { - return nil, err - } - return result, nil -} - func (s *TaskTemplateService) createProcTaskTemplates(session *xorm.Session, procDefId, requestTemplateId, userToken, language, operator string) (err error) { var nodeList []*models.ProcNodeObj // 查询编排任务节点 @@ -656,63 +550,19 @@ func (s *TaskTemplateService) ListTaskTemplateIds(requestTemplateId, typ, userTo return nil, errors.New("no request_template record found") } result := &models.TaskTemplateListIdsResponse{Type: typ, ProcDefId: requestTemplate.ProcDefId} - if requestTemplate.ProcDefId != "" && typ == string(models.TaskTypeImplement) { - // 编排任务 - // 查询任务节点 - nodeList, err := s.getProcTaskTemplateNodes(requestTemplate.ProcDefId, userToken, language) - if err != nil { - return nil, err - } - // 查询任务模板列表 - taskTemplates, err := s.taskTemplateDao.QueryByRequestTemplateAndType(requestTemplateId, typ) - if err != nil { - return nil, err - } - // 构造返回结果 - result.Ids = make([]*models.TaskTemplateIdObj, len(nodeList)) - taskTemplateIdx := 0 - for i, node := range nodeList { - if taskTemplateIdx < len(taskTemplates) { - taskTemplate := taskTemplates[taskTemplateIdx] - if node.NodeDefId == taskTemplate.NodeDefId { - result.Ids[i] = &models.TaskTemplateIdObj{ - Id: taskTemplate.Id, - Sort: taskTemplate.Sort, - Name: taskTemplate.Name, - NodeDefId: taskTemplate.NodeDefId, - } - taskTemplateIdx++ - } else { - result.Ids[i] = &models.TaskTemplateIdObj{ - Sort: i + 1, - Name: node.NodeName, - NodeDefId: node.NodeDefId, - } - } - } else { - result.Ids[i] = &models.TaskTemplateIdObj{ - Sort: i + 1, - Name: node.NodeName, - NodeDefId: node.NodeDefId, - } - } - } - } else { - // 其他类型 - // 查询任务模板列表 - taskTemplates, err := s.taskTemplateDao.QueryByRequestTemplateAndType(requestTemplateId, typ) - if err != nil { - return nil, err - } - // 构造返回结果 - result.Ids = make([]*models.TaskTemplateIdObj, len(taskTemplates)) - for i, taskTemplate := range taskTemplates { - result.Ids[i] = &models.TaskTemplateIdObj{ - Id: taskTemplate.Id, - Sort: taskTemplate.Sort, - Name: taskTemplate.Name, - NodeDefId: taskTemplate.NodeDefId, - } + // 查询任务模板列表 + taskTemplates, err := s.taskTemplateDao.QueryByRequestTemplateAndType(requestTemplateId, typ) + if err != nil { + return nil, err + } + // 构造返回结果 + result.Ids = make([]*models.TaskTemplateIdObj, len(taskTemplates)) + for i, taskTemplate := range taskTemplates { + result.Ids[i] = &models.TaskTemplateIdObj{ + Id: taskTemplate.Id, + Sort: taskTemplate.Sort, + Name: taskTemplate.Name, + NodeDefId: taskTemplate.NodeDefId, } } return result, nil @@ -728,53 +578,18 @@ func (s *TaskTemplateService) ListTaskTemplates(requestTemplateId, typ, userToke return nil, errors.New("no request_template record found") } var result []*models.TaskTemplateDto - if requestTemplate.ProcDefId != "" && typ == string(models.TaskTypeImplement) { - // 编排任务 - // 查询任务节点 - nodeList, err := s.getProcTaskTemplateNodes(requestTemplate.ProcDefId, userToken, language) - if err != nil { - return nil, err - } - // 查询任务模板列表 - taskTemplates, err := s.taskTemplateDao.QueryByRequestTemplateAndType(requestTemplateId, typ) - if err != nil { - return nil, err - } - // 构造返回结果 - result = make([]*models.TaskTemplateDto, len(nodeList)) - taskTemplateIdx := 0 - for i, node := range nodeList { - if taskTemplateIdx < len(taskTemplates) { - taskTemplate := taskTemplates[taskTemplateIdx] - if node.NodeDefId == taskTemplate.NodeDefId { - dto, err := s.genTaskTemplateDto(taskTemplate.Id) - if err != nil { - return nil, err - } - result[i] = dto - taskTemplateIdx++ - } else { - result[i] = s.genProcTaskTemplateDto(node, requestTemplateId, i+1) - } - } else { - result[i] = s.genProcTaskTemplateDto(node, requestTemplateId, i+1) - } - } - } else { - // 其他类型 - // 查询任务模板列表 - taskTemplates, err := s.taskTemplateDao.QueryByRequestTemplateAndType(requestTemplateId, typ) + // 查询任务模板列表 + taskTemplates, err := s.taskTemplateDao.QueryByRequestTemplateAndType(requestTemplateId, typ) + if err != nil { + return nil, err + } + // 构造返回结果 + result = make([]*models.TaskTemplateDto, len(taskTemplates)) + for i, taskTemplate := range taskTemplates { + result[i], err = s.genTaskTemplateDto(taskTemplate.Id) if err != nil { return nil, err } - // 构造返回结果 - result = make([]*models.TaskTemplateDto, len(taskTemplates)) - for i, taskTemplate := range taskTemplates { - result[i], err = s.genTaskTemplateDto(taskTemplate.Id) - if err != nil { - return nil, err - } - } } return result, nil } @@ -849,26 +664,6 @@ func (s *TaskTemplateService) genTaskTemplateDto(taskTemplateId string) (*models return result, nil } -func (s *TaskTemplateService) genProcTaskTemplateDto(node *models.ProcNodeObj, requestTemplateId string, sort int) *models.TaskTemplateDto { - return &models.TaskTemplateDto{ - Type: string(models.TaskTypeImplement), - NodeId: node.NodeId, - NodeDefId: node.NodeDefId, - NodeDefName: node.NodeName, - Name: node.NodeName, - ExpireDay: 1, - RequestTemplate: requestTemplateId, - Sort: sort, - HandleMode: string(models.TaskTemplateHandleModeCustom), - HandleTemplates: []*models.TaskHandleTemplateDto{ - { - Assign: string(models.TaskHandleTemplateAssignTypeCustom), - HandlerType: string(models.TaskHandleTemplateHandlerTypeCustom), - }, - }, - } -} - func (s *TaskTemplateService) genTaskTemplateIds(requestTemplateId, typ string) ([]*models.TaskTemplateIdObj, error) { taskTemplates, err := s.taskTemplateDao.QueryByRequestTemplateAndType(requestTemplateId, typ) if err != nil { From 6b25fdb3262453d07ef9c5e04fc19b3f8b75cf20 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Mon, 11 Mar 2024 15:38:31 +0800 Subject: [PATCH 252/618] =?UTF-8?q?=E6=A8=A1=E6=9D=BFbug=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/form_item_template_service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/taskman-server/service/form_item_template_service.go b/taskman-server/service/form_item_template_service.go index 1b93438c..dba86410 100644 --- a/taskman-server/service/form_item_template_service.go +++ b/taskman-server/service/form_item_template_service.go @@ -110,7 +110,7 @@ func (s *FormItemTemplateService) UpdateFormTemplateItemGroupConfig(param models for _, refFormItemTemplate := range refFormItemTemplateList { // 主要更新 routineExpression 值 refFormItemTemplate.RoutineExpression = customItem.RoutineExpression - updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(refFormItemTemplate)) + updateItems = append(updateItems, refFormItemTemplate) } } updateItems = append(updateItems, models.ConvertFormItemTemplateDto2Model(customItem)) From 6917d4d2c97b300f0fa30626f6a1dd3540c35ca9 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Mon, 11 Mar 2024 15:40:33 +0800 Subject: [PATCH 253/618] =?UTF-8?q?db=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wiki/db/init.sql | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/wiki/db/init.sql b/wiki/db/init.sql index 326c9893..9e17d21c 100644 --- a/wiki/db/init.sql +++ b/wiki/db/init.sql @@ -429,7 +429,7 @@ CREATE TABLE IF NOT EXISTS `form_template` ( `item_group_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '表单组名', `item_group_type` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '表单组类型:workflow 编排数据,optional 自选,custom 自定义,request 请求信息', `item_group_rule` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '新增一行规则', - `item_group_sort` tinyint(4) DEFAULT '0' COMMENT '排序', + `item_group_sort` tinyint(4) DEFAULT '1' COMMENT '排序', `ref_id` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '引用ID', `request_form_type` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '请求表单类型:message 信息表单 data 数据表单', `del_flag` tinyint(4) DEFAULT '0' COMMENT '是否删除', @@ -494,13 +494,14 @@ CREATE TABLE IF NOT EXISTS `task_handle` ( `handler` varchar(64) DEFAULT NULL, `handler_type` varchar(255) DEFAULT NULL, `handler_result` varchar(64) DEFAULT NULL, - `handler_status` varchar(64) DEFAULT NULL, + `handle_status` varchar(64) DEFAULT 'uncompleted', `parent_id` varchar(64) DEFAULT NULL, `created_time` datetime NULL, `updated_time` datetime NULL, `result_desc` text DEFAULT NULL, `change_reason` varchar(64) DEFAULT NULL, `sort` int DEFAULT '0', + `latest_flag` tinyint DEFAULT '1', PRIMARY KEY (`id`), CONSTRAINT `fore_task_handle_template` FOREIGN KEY (`task_handle_template`) REFERENCES `task_handle_template` (`id`), CONSTRAINT `fore_task_handle_task` FOREIGN KEY (`task`) REFERENCES `task` (`id`) @@ -518,4 +519,5 @@ alter table form_item add constraint fore_form_item_task_handle foreign key(task alter table attach_file add column task_handle varchar(64) default null COMMENT '任务处理'; alter table attach_file add constraint fore_attach_file_task_handle foreign key(task_handle) REFERENCES task_handle(id); +alter table form_item_template add column routine_expression text default null COMMENT '表单项计算表达式'; #@v1.0.5-end@; From 218f4f29a10369c079deff1cbbdd9462c76b24f6 Mon Sep 17 00:00:00 2001 From: wanghao7717 <792974788@qq.com> Date: Mon, 11 Mar 2024 15:41:30 +0800 Subject: [PATCH 254/618] =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0=E5=BD=93?= =?UTF-8?q?=E5=89=8D=E5=A4=84=E7=90=86=EF=BC=8C=E5=A4=84=E7=90=86=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E9=A1=B5=E9=9D=A2=E9=97=AE=E9=A2=98=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-ui/src/api/server.js | 2 +- taskman-ui/src/locale/i18n/en-US.json | 4 +- taskman-ui/src/locale/i18n/zh-CN.json | 4 +- .../src/pages/components/scroll-tag.vue | 45 ++++++++ taskman-ui/src/pages/template.vue | 1 + .../src/pages/workbench/collect-table.vue | 36 +++++-- taskman-ui/src/pages/workbench/column.js | 101 +++++------------- taskman-ui/src/pages/workbench/index.vue | 3 +- .../publish/components/base-create.vue | 2 +- .../workbench/publish/components/progress.vue | 63 +---------- taskman-ui/src/pages/workbench/search.js | 46 ++++---- 11 files changed, 135 insertions(+), 172 deletions(-) create mode 100644 taskman-ui/src/pages/components/scroll-tag.vue diff --git a/taskman-ui/src/api/server.js b/taskman-ui/src/api/server.js index 33213e2b..6f3a8588 100755 --- a/taskman-ui/src/api/server.js +++ b/taskman-ui/src/api/server.js @@ -133,7 +133,7 @@ export const recallRequest = id => req.post(`/taskman/api/v1/user/request/revoke // 新建发布-发布信息获取 export const getCreateInfo = params => req.post(`/taskman/api/v2/request`, params) // 新建发布-请求进度 -export const getProgressInfo = params => req.post(`/taskman/api/v1/request/progress`, params) +export const getProgressInfo = params => req.get(`/taskman/api/v1/request/progress`, params) // 新建发布-保存数据 export const savePublishData = (requestId, params) => req.post(`/taskman/api/v2/request-data/save/${requestId}/data/save`, params) diff --git a/taskman-ui/src/locale/i18n/en-US.json b/taskman-ui/src/locale/i18n/en-US.json index 8b64fafe..6482f299 100755 --- a/taskman-ui/src/locale/i18n/en-US.json +++ b/taskman-ui/src/locale/i18n/en-US.json @@ -280,8 +280,10 @@ "tw_expect_time": "Expected Completion", "tw_request_commit_time": "Request Submission", "tw_pending_handler": "Version Approval Handler", - "tw_task_tab": "Approval", + "tw_task_tab": "Task Approval", "tw_pending_tab": "Owner Approval", + "tw_confirm_tab": "Confirm", + "tw_approve_tab": "Approval", "tw_all_tab": "All", "tw_return_tab": "Returned", "tw_recall_tab": "Recalled", diff --git a/taskman-ui/src/locale/i18n/zh-CN.json b/taskman-ui/src/locale/i18n/zh-CN.json index cad19807..952dff6c 100755 --- a/taskman-ui/src/locale/i18n/zh-CN.json +++ b/taskman-ui/src/locale/i18n/zh-CN.json @@ -262,7 +262,7 @@ "tw_launch": "发起", "tw_request_id": "请求ID", "tw_returned_tips": "被退回", - "tw_progress": "进展", + "tw_progress": "请求进度", "tw_task_stay_time": "任务停留时长", "tw_request_stay_time": "请求停留时长", "tw_days": "日", @@ -282,6 +282,8 @@ "tw_pending_handler": "定版处理人", "tw_task_tab": "任务处理", "tw_pending_tab": "请求定版", + "tw_confirm_tab": "请求确认", + "tw_approve_tab": "审批", "tw_all_tab": "所有", "tw_return_tab": "被退回", "tw_recall_tab": "本人撤回", diff --git a/taskman-ui/src/pages/components/scroll-tag.vue b/taskman-ui/src/pages/components/scroll-tag.vue new file mode 100644 index 00000000..6df0a81c --- /dev/null +++ b/taskman-ui/src/pages/components/scroll-tag.vue @@ -0,0 +1,45 @@ + + + + + diff --git a/taskman-ui/src/pages/template.vue b/taskman-ui/src/pages/template.vue index da7e33bf..07d33110 100644 --- a/taskman-ui/src/pages/template.vue +++ b/taskman-ui/src/pages/template.vue @@ -370,6 +370,7 @@ export default { } }, mounted () { + this.status = this.$route.query.status || 'confirm' const accessToken = getCookie('accessToken') this.headers = { Authorization: 'Bearer ' + accessToken diff --git a/taskman-ui/src/pages/workbench/collect-table.vue b/taskman-ui/src/pages/workbench/collect-table.vue index 7f946174..6c939285 100644 --- a/taskman-ui/src/pages/workbench/collect-table.vue +++ b/taskman-ui/src/pages/workbench/collect-table.vue @@ -25,11 +25,13 @@ + + diff --git a/taskman-ui/src/pages/temp-management/task-form-node copy.vue b/taskman-ui/src/pages/temp-management/task-form-node copy.vue new file mode 100644 index 00000000..62f06bb2 --- /dev/null +++ b/taskman-ui/src/pages/temp-management/task-form-node copy.vue @@ -0,0 +1,426 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/task-form-node.vue b/taskman-ui/src/pages/temp-management/task-form-node.vue index 62f06bb2..663ba5a1 100644 --- a/taskman-ui/src/pages/temp-management/task-form-node.vue +++ b/taskman-ui/src/pages/temp-management/task-form-node.vue @@ -85,7 +85,7 @@ + + *
{{ $t('name') }}{{ $t('can_not_be_empty') }}
- * @@ -34,7 +35,7 @@
- * @@ -55,14 +56,14 @@ {{ roleObjIndex + 1 }} - -
diff --git a/taskman-ui/src/pages/temp-management/index.vue b/taskman-ui/src/pages/temp-management/index.vue index 3ea1c228..19561e21 100644 --- a/taskman-ui/src/pages/temp-management/index.vue +++ b/taskman-ui/src/pages/temp-management/index.vue @@ -97,7 +97,12 @@ export default { okText: this.$t('confirm'), cancelText: this.$t('cancel'), onOk: async () => { - this.$router.push({ path: '/taskman/template-mgmt' }) + this.$router.push({ + path: '/taskman/template-mgmt', + query: { + status: 'created' + } + }) }, onCancel: () => {} }) diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index b69c151f..81ba796c 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -304,13 +304,7 @@
- @@ -1010,6 +1004,9 @@ fieldset[disabled] .ivu-input { .ivu-select-disabled .ivu-select-selection { color: #757575 !important; } +.ivu-select-dropdown { + max-height: 300px !important; +} diff --git a/taskman-ui/src/pages/workbench/components/data-card.vue b/taskman-ui/src/pages/workbench/components/data-card.vue index 06151126..66985556 100644 --- a/taskman-ui/src/pages/workbench/components/data-card.vue +++ b/taskman-ui/src/pages/workbench/components/data-card.vue @@ -1,16 +1,36 @@ @@ -403,6 +414,7 @@ @@ -412,6 +424,7 @@ ref="requestFormDataWorkflowRef" :isCustomItemEditable="false" @reloadParentPage="reloadGroup" + :isCheck="isCheck" module="other" v-show="['workflow', 'optional'].includes(itemGroupType)" > @@ -726,7 +739,7 @@ export default { } } }, - props: ['requestTemplateId'], + props: ['isCheck', 'requestTemplateId'], mounted () { this.MODALHEIGHT = document.body.scrollHeight - 500 this.removeEmptyDataForm() @@ -1151,6 +1164,10 @@ export default { this.openPanel = '' }, async gotoNext () { + if (this.isCheck === 'Y') { + this.$emit('gotoStep', this.requestTemplateId, 'forward') + return + } const nodeStatus = this.$refs.approvalFormNodeRef.panalStatus() if (nodeStatus === 'canSave') { await this.$refs.approvalFormNodeRef.saveNode(3) @@ -1163,6 +1180,10 @@ export default { } }, gotoForward () { + if (this.isCheck === 'Y') { + this.$emit('gotoStep', this.requestTemplateId, 'backward') + return + } const nodeStatus = this.$refs.approvalFormNodeRef.panalStatus() if (nodeStatus === 'canSave') { this.$refs.approvalFormNodeRef.saveNode(3) diff --git a/taskman-ui/src/pages/temp-management/basic-info.vue b/taskman-ui/src/pages/temp-management/basic-info.vue index 69fee083..74ce64ef 100644 --- a/taskman-ui/src/pages/temp-management/basic-info.vue +++ b/taskman-ui/src/pages/temp-management/basic-info.vue @@ -233,20 +233,23 @@
- +
-
diff --git a/taskman-ui/src/pages/temp-management/index.vue b/taskman-ui/src/pages/temp-management/index.vue index 19561e21..6b57c8b0 100644 --- a/taskman-ui/src/pages/temp-management/index.vue +++ b/taskman-ui/src/pages/temp-management/index.vue @@ -4,7 +4,7 @@ $t('back_to_template') }} - + @@ -12,22 +12,33 @@ -
- - - - + + + +
@@ -37,7 +48,6 @@ import ApprovalForm from './approval-form' import RequestForm from './request-form' import BasicInfo from './basic-info' import TaskForm from './task-form' -import { submitTemplate } from '@/api/server.js' export default { name: '', data () { @@ -55,57 +65,35 @@ export default { this.currentStep = 0 }, methods: { - async submitTemplate () { - this.$Modal.confirm({ - title: `${this.$t('submit_for_review')}`, - content: `${this.$t('submit_for_review_tip')}`, - 'z-index': 1000000, - okText: this.$t('confirm'), - cancelText: this.$t('cancel'), - onOk: async () => { - let data = { - requestTemplateId: this.requestTemplateId, - status: 'created', - targetStatus: 'pending', - reason: '{}' + changeStep (val) { + this.currentStep = val + }, + backToTemplate () { + if (this.isCheck === 'Y') { + this.$router.push({ + path: '/taskman/template-mgmt', + query: { + status: 'pending' } - const { statusCode } = await submitTemplate(data) - if (statusCode === 'OK') { - this.$Notice.success({ - title: this.$t('successful'), - desc: this.$t('successful') - }) + }) + } else { + this.$Modal.confirm({ + title: `${this.$t('back_to_template')}`, + content: `${this.$t('back_to_template_tip')}`, + 'z-index': 1000000, + okText: this.$t('confirm'), + cancelText: this.$t('cancel'), + onOk: async () => { this.$router.push({ path: '/taskman/template-mgmt', query: { - status: 'pending' + status: 'created' } }) - } - }, - onCancel: () => {} - }) - }, - changeStep (val) { - this.currentStep = val - }, - backToTemplate () { - this.$Modal.confirm({ - title: `${this.$t('back_to_template')}`, - content: `${this.$t('back_to_template_tip')}`, - 'z-index': 1000000, - okText: this.$t('confirm'), - cancelText: this.$t('cancel'), - onOk: async () => { - this.$router.push({ - path: '/taskman/template-mgmt', - query: { - status: 'created' - } - }) - }, - onCancel: () => {} - }) + }, + onCancel: () => {} + }) + } }, gotoStep (tmpId, stepDirection) { this.requestTemplateId = tmpId diff --git a/taskman-ui/src/pages/temp-management/request-form-data-custom.vue b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue index 08a15ba3..92d7d653 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data-custom.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data-custom.vue @@ -21,9 +21,14 @@
@@ -55,7 +60,7 @@ export default { } } }, - props: ['requestTemplateId', 'module'], + props: ['isCheck', 'requestTemplateId', 'module'], methods: { async loadPage (params) { if (params.isAdd) { @@ -109,6 +114,10 @@ export default { } }, cancelGroupDrawer () { + if (this.isCheck === 'Y') { + this.openFormConfig = false + return + } if (this.isParmasChanged) { this.$Modal.confirm({ title: `${this.$t('confirm_discarding_changes')}`, diff --git a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue index 222137ee..76607489 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue @@ -82,9 +82,14 @@
@@ -171,7 +176,7 @@ export default { } } }, - props: ['module', 'isCustomItemEditable'], + props: ['isCheck', 'module', 'isCustomItemEditable'], methods: { // 自定义字段获取所有类型 async getAllDataModels () { @@ -232,6 +237,10 @@ export default { } }, cancelGroupDrawer () { + if (this.isCheck === 'Y') { + this.openFormConfig = false + return + } if (this.isParmasChanged) { this.$Modal.confirm({ title: `${this.$t('confirm_discarding_changes')}`, diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index 1cebe34e..ec96e602 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -63,10 +63,17 @@ {{ `${groupItem.itemGroupName}` }} - + + @@ -332,6 +341,7 @@ @@ -341,6 +351,7 @@ ref="requestFormDataWorkflowRef" :isCustomItemEditable="true" @reloadParentPage="isLoadLastGroup" + :isCheck="isCheck" module="data-form" v-show="['workflow', 'optional'].includes(itemGroupType)" > @@ -598,6 +609,7 @@ export default { nextGroupInfo: {} } }, + props: ['isCheck'], computed: { activeStyle () { return function (item) { @@ -987,9 +999,15 @@ export default { return this.isParmasChanged }, tabChange () { - this.saveGroup(3) + if (this.isCheck !== 'Y') { + this.saveGroup(3) + } }, gotoNext () { + if (this.isCheck === 'Y') { + this.$emit('gotoStep', this.requestTemplateId, 'forward') + return + } let finalData = JSON.parse(JSON.stringify(this.finalElement[0])) if (finalData.itemGroupId === '') { this.$emit('gotoStep', this.requestTemplateId, 'forward') @@ -998,6 +1016,10 @@ export default { } }, gotoForward () { + if (this.isCheck === 'Y') { + this.$emit('gotoStep', this.requestTemplateId, 'backward') + return + } let finalData = JSON.parse(JSON.stringify(this.finalElement[0])) if (finalData.itemGroupId === '') { this.$emit('gotoStep', this.requestTemplateId, 'backward') diff --git a/taskman-ui/src/pages/temp-management/request-form-msg.vue b/taskman-ui/src/pages/temp-management/request-form-msg.vue index c9334ff2..15f87f61 100644 --- a/taskman-ui/src/pages/temp-management/request-form-msg.vue +++ b/taskman-ui/src/pages/temp-management/request-form-msg.vue @@ -252,17 +252,20 @@
- +
- diff --git a/taskman-ui/src/pages/temp-management/request-form.vue b/taskman-ui/src/pages/temp-management/request-form.vue index 365d3e0e..0f831cb0 100644 --- a/taskman-ui/src/pages/temp-management/request-form.vue +++ b/taskman-ui/src/pages/temp-management/request-form.vue @@ -14,12 +14,14 @@ v-if="activeTab === 'msgForm'" @gotoStep="gotoStep" @changTab="changTab" + :isCheck="isCheck" ref="msgFormRef" > @@ -38,7 +40,7 @@ export default { activeTab: 'msgForm' } }, - props: ['requestTemplateId'], + props: ['isCheck', 'requestTemplateId'], mounted () { this.changTab(this.activeTab, true) }, @@ -48,19 +50,24 @@ export default { return } - const tabStatus = this.$refs[`${this.activeTab}Ref`].panalStatus() - if (tabStatus) { - this.$nextTick(() => { - this.$refs[`${this.activeTab}Ref`].tabChange() - }) - } else { + if (this.isCheck === 'Y') { this.activeTab = tabName this.$nextTick(() => { this.$refs[`${this.activeTab}Ref`].loadPage(this.requestTemplateId) }) + } else { + const tabStatus = this.$refs[`${this.activeTab}Ref`].panalStatus() + if (tabStatus) { + this.$nextTick(() => { + this.$refs[`${this.activeTab}Ref`].tabChange() + }) + } else { + this.activeTab = tabName + this.$nextTick(() => { + this.$refs[`${this.activeTab}Ref`].loadPage(this.requestTemplateId) + }) + } } - - this.$nextTick(() => {}) }, gotoStep (requestTemplateId, stepDirection) { this.$emit('gotoStep', requestTemplateId, stepDirection) diff --git a/taskman-ui/src/pages/temp-management/task-form-node.vue b/taskman-ui/src/pages/temp-management/task-form-node.vue index c0337a20..b8514b1b 100644 --- a/taskman-ui/src/pages/temp-management/task-form-node.vue +++ b/taskman-ui/src/pages/temp-management/task-form-node.vue @@ -122,7 +122,9 @@
- +
@@ -195,7 +197,7 @@ export default { deep: true } }, - props: ['nodeType'], + props: ['isCheck', 'nodeType'], methods: { loadPage (params) { this.procDefId = params.procDefId diff --git a/taskman-ui/src/pages/temp-management/task-form.vue b/taskman-ui/src/pages/temp-management/task-form.vue index ae230cf8..5beecea6 100644 --- a/taskman-ui/src/pages/temp-management/task-form.vue +++ b/taskman-ui/src/pages/temp-management/task-form.vue @@ -14,7 +14,7 @@ > {{ approval.name }}
+ @@ -418,6 +422,7 @@ @@ -427,6 +432,7 @@ ref="requestFormDataWorkflowRef" :isCustomItemEditable="false" @reloadParentPage="reloadGroup" + :isCheck="isCheck" module="other" v-show="['workflow', 'optional'].includes(itemGroupType)" > @@ -436,9 +442,14 @@ - + @@ -744,7 +755,7 @@ export default { } } }, - props: ['requestTemplateId'], + props: ['isCheck', 'requestTemplateId'], mounted () { this.MODALHEIGHT = document.body.scrollHeight - 500 this.removeEmptyDataForm() @@ -1173,6 +1184,10 @@ export default { this.openPanel = '' }, gotoForward () { + if (this.isCheck === 'Y') { + this.$emit('gotoStep', this.requestTemplateId, 'backward') + return + } // 有编排无数据 if (this.procDefId !== '' && this.approvalNodes.length === 0) { this.$emit('gotoStep', this.requestTemplateId, 'backward') From b26f3aea8750dc4ea0a8a8c874d31d6bf4e2069b Mon Sep 17 00:00:00 2001 From: zgyzgyhero <894526647@qq.com> Date: Wed, 13 Mar 2024 14:16:53 +0800 Subject: [PATCH 312/618] update get request form --- taskman-server/service/request_service_new.go | 1 + 1 file changed, 1 insertion(+) diff --git a/taskman-server/service/request_service_new.go b/taskman-server/service/request_service_new.go index 7bb213af..aabb2ae0 100644 --- a/taskman-server/service/request_service_new.go +++ b/taskman-server/service/request_service_new.go @@ -1324,6 +1324,7 @@ func getRequestForm(request *models.RequestTable, userToken, language string) (f } form.FormData = cacheObj.Data form.RootEntityId = cacheObj.RootEntityId + form.OperatorObj = cacheObj.EntityName } return } From 33fb00dc503fcb8c046b52d16c663436c726fc10 Mon Sep 17 00:00:00 2001 From: wanghao7717 <792974788@qq.com> Date: Wed, 13 Mar 2024 16:16:14 +0800 Subject: [PATCH 313/618] =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E8=BF=94=E5=9B=9E=E5=AE=9A=E4=BD=8D=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-ui/src/main-plugin.js | 16 +++++----- .../workbench/publish/components/progress.vue | 32 +++++++++++-------- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/taskman-ui/src/main-plugin.js b/taskman-ui/src/main-plugin.js index 010ff9e0..a2ea4c49 100755 --- a/taskman-ui/src/main-plugin.js +++ b/taskman-ui/src/main-plugin.js @@ -8,15 +8,15 @@ import enUS from '@/locale/i18n/en-US.json' import { ValidationProvider } from 'vee-validate' import './vee-validate-local-config' -import Dashboard from '@/pages/workbench/index.vue' +// import Dashboard from '@/pages/workbench/index.vue' window.component('ValidationProvider', ValidationProvider) -window.addHomepageComponent && - window.addHomepageComponent({ - name: () => { - return window.vm.$t('tw_workbench') - }, - component: Dashboard - }) +// window.addHomepageComponent && +// window.addHomepageComponent({ +// name: () => { +// return window.vm.$t('tw_workbench') +// }, +// component: Dashboard +// }) window.locale('zh-CN', zhCN) window.locale('en-US', enUS) diff --git a/taskman-ui/src/pages/workbench/publish/components/progress.vue b/taskman-ui/src/pages/workbench/publish/components/progress.vue index b48e20ca..3aaeaaed 100644 --- a/taskman-ui/src/pages/workbench/publish/components/progress.vue +++ b/taskman-ui/src/pages/workbench/publish/components/progress.vue @@ -40,7 +40,7 @@ -
+
审批进度: {{ approvalTypeName[i.approveType] || '' }}
- -
{{ i.handler }}
-
+
+ {{ j.role || '-' }} / + {{ handlerType[j.handlerType] || j.handler || '-' }} +
-
+
任务进度: {{ approvalTypeName[i.approveType] || '' }}
- -
{{ i.handler }}
-
+
+ {{ j.role || '-' }} / + {{ handlerType[j.handlerType] || j.handler || '-' }} +
@@ -139,6 +141,10 @@ export default { all: '并行', admin: '提交人角色管理员', auto: '自动通过' + }, + handlerType: { + system: '系统分配', + claim: '主动认领' } } }, @@ -258,12 +264,12 @@ export default { margin-right: 20px; } .mode { - font-size: 11px; - background: #2d8cf0; - color: #fff; - padding: 1px 5px; + font-size: 12px; + // background: #2d8cf0; + color: #2d8cf0; + // padding: 1px 5px; display: inline-block; - border-radius: 2px; + // border-radius: 2px; } .role { display: flex; From 1603aa87e645cbae0e095026b88168e10556f083 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 13 Mar 2024 16:31:22 +0800 Subject: [PATCH 314/618] =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/models/const.go | 14 ++ taskman-server/models/param.go | 6 +- taskman-server/models/request.go | 13 +- taskman-server/service/request_service_new.go | 192 ++++++++++-------- 4 files changed, 132 insertions(+), 93 deletions(-) diff --git a/taskman-server/models/const.go b/taskman-server/models/const.go index a3957a20..b69eee16 100644 --- a/taskman-server/models/const.go +++ b/taskman-server/models/const.go @@ -197,6 +197,20 @@ const ( SceneTypeChange SceneType = 5 // 变更 ) +type PlatTab string + +const ( + PlatTabRequest PlatTab = "Request" // 请求 + PlatTabRelease PlatTab = "Release" // 发布 + PlatTabProblem PlatTab = "Problem" // 问题 + PlatTabProblemEvent PlatTab = "Event" // 事件 + PlatTabProblemChange PlatTab = "Change" // 变更 + PlatTabProblemApprove PlatTab = "Approve" // 审批 + PlatTabProblemTask PlatTab = "Task" // 任务处理 + PlatTabProblemCheck PlatTab = "Check" // 请求定版 + PlatTabProblemConfirm PlatTab = "Confirm" // 请求确认 +) + // TaskExecStatus 任务执行状态 // 状态值:1 进行中 2.未开始 3.已完成 4.报错被拒绝了 type TaskExecStatus int diff --git a/taskman-server/models/param.go b/taskman-server/models/param.go index b1fa0bcf..2c85917b 100644 --- a/taskman-server/models/param.go +++ b/taskman-server/models/param.go @@ -67,9 +67,9 @@ type QueryCollectTemplateParam struct { } type CountPlatformParam struct { - Scene int `json:"scene"` //场景,0表示所有 - QueryTimeStart string `json:"queryTimeStart" ` // 查询时间 - QueryTimeEnd string `json:"queryTimeEnd" ` // + Tab string `json:"tab"` // 标签,取值有:pending 待处理,myPending 本人待处理,hasProcessed 已处理 submit 我提交的 draft 我的暂存, all表示查询所有 + QueryTimeStart string `json:"queryTimeStart" ` // 查询时间-开始 + QueryTimeEnd string `json:"queryTimeEnd" ` // 查询时间结束 } // AddCollectTemplateParam 添加收藏 diff --git a/taskman-server/models/request.go b/taskman-server/models/request.go index d387b71f..236787af 100644 --- a/taskman-server/models/request.go +++ b/taskman-server/models/request.go @@ -71,14 +71,11 @@ type CreateRequestDto struct { // PlatformData 工作台数据 type PlatformData struct { - Pending []int `json:"pending"` // 待处理 - PendingTask []int `json:"pendingTask"` // 待处理任务 - PendingApprove []int `json:"pendingApprove"` // 待处理审批 - PendingCheck []int `json:"pendingCheck"` // 待处理定版 - PendingConfirm []int `json:"pendingConfirm"` // 待处理请求确认 - HasProcessed []int `json:"hasProcessed"` // 已处理 - Submit []int `json:"submit"` // 我提交的 - Draft []int `json:"draft"` // 我暂存的 + MyPending map[string]int `json:"myPending"` // 本人待处理 + Pending map[string]int `json:"pending"` // 本组待处理 + HasProcessed map[string]int `json:"hasProcessed"` // 已处理 + Submit map[string]int `json:"submit"` // 我提交的 + Draft map[string]int `json:"draft"` // 我暂存的 } // PlatformDataObj 工作台返回数据 diff --git a/taskman-server/service/request_service_new.go b/taskman-server/service/request_service_new.go index 7bb213af..d0a240b1 100644 --- a/taskman-server/service/request_service_new.go +++ b/taskman-server/service/request_service_new.go @@ -31,8 +31,14 @@ const ( AutoNode = "autoNode" //自动节点 ) -// sceneTypeArr 场景数组 -var sceneTypeArr = []models.SceneType{models.SceneTypeRequest, models.SceneTypeRelease, models.SceneTypeProblem, models.SceneTypeEvent, models.SceneTypeChange} +// sceneTypeMap 场景数组 +var sceneTypeMap = map[models.PlatTab]models.SceneType{ + models.PlatTabRequest: models.SceneTypeRequest, + models.PlatTabRelease: models.SceneTypeRelease, + models.PlatTabProblem: models.SceneTypeProblem, + models.PlatTabProblemEvent: models.SceneTypeEvent, + models.PlatTabProblemChange: models.SceneTypeChange, +} func getTaskTypeByType(uiType int) models.TaskType { // 0 所有,1表示请求定版,2 任务处理,3 审批 4确认请求 @@ -51,21 +57,26 @@ func getTaskTypeByType(uiType int) models.TaskType { // GetPlatformCount 工作台数量统计 func GetPlatformCount(param models.CountPlatformParam, user string, userRoles []string) (platformData models.PlatformData, err error) { - var pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending, hasProcessed []int - if param.Scene == int(models.SceneTypeAll) { - pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending = GetPendingCountAll(param, user, userRoles) - } else { - pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending = GetPendingCountSingle(param, user, userRoles) - } - hasProcessed = GetHasProcessedCount(param, user) - platformData.Pending = pending - platformData.PendingTask = pendingTask - platformData.PendingApprove = pendingApprove - platformData.PendingCheck = pendingCheck - platformData.PendingConfirm = pendingConfirm - platformData.HasProcessed = hasProcessed - platformData.Submit = GetSubmitCount(param, user) - platformData.Draft = GetDraftCount(param, user) + switch param.Tab { + case "all": + platformData.Pending = GetPendingCount(param, userRoles) + platformData.MyPending = GetMyPendingCount(param, user, userRoles) + platformData.HasProcessed = GetHasProcessedCount(param, user) + platformData.Submit = GetSubmitCount(param, user) + platformData.Draft = GetDraftCount(param, user) + case "pending": + platformData.Pending = GetPendingCount(param, userRoles) + platformData.MyPending = GetMyPendingCount(param, user, userRoles) + case "myPending": + platformData.Pending = GetPendingCount(param, userRoles) + platformData.MyPending = GetMyPendingCount(param, user, userRoles) + case "hasProcessed": + platformData.HasProcessed = GetHasProcessedCount(param, user) + case "submit": + platformData.Submit = GetSubmitCount(param, user) + case "draft": + platformData.Draft = GetDraftCount(param, user) + } return } @@ -92,39 +103,75 @@ func UpdateRequestHandler(requestId, user string) (err error) { return } -// GetPendingCountAll 统计待处理,包括:请求、发布,以及下面的请求提交、任务、审批、请求定版、请求确认 -func GetPendingCountAll(param models.CountPlatformParam, user string, userRoles []string) (pendingTaskArr, pendingApproveArr, pendingCheckArr, pendingConfirmArr, pendingArr []int) { - var pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending []int - for _, scene := range sceneTypeArr { - param.Scene = int(scene) - pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending = GetPendingCountSingle(param, user, userRoles) - pendingTaskArr = append(pendingTaskArr, pendingTask...) - pendingApproveArr = append(pendingApproveArr, pendingApprove...) - pendingCheckArr = append(pendingCheckArr, pendingCheck...) - pendingConfirmArr = append(pendingConfirmArr, pendingConfirm...) - pendingArr = append(pendingArr, pending...) +// GetPendingCount 统计待处理,包括:请求、发布,以及下面的请求提交、任务、审批、请求定版、请求确认 +func GetPendingCount(param models.CountPlatformParam, userRoles []string) (resultMap map[string]int) { + var pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending int + resultMap = make(map[string]int) + for sceneName, sceneType := range sceneTypeMap { + pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending = GetPendingCountByScene(param, int(sceneType), userRoles) + resultMap[string(sceneName)] = pending + resultMap[string(sceneName)+string(models.PlatTabProblemApprove)] = pendingApprove + resultMap[string(sceneName)+string(models.PlatTabProblemTask)] = pendingTask + resultMap[string(sceneName)+string(models.PlatTabProblemCheck)] = pendingCheck + resultMap[string(sceneName)+string(models.PlatTabProblemConfirm)] = pendingConfirm } return } -func GetPendingCountSingle(param models.CountPlatformParam, user string, userRoles []string) (pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending []int) { +// GetMyPendingCount 统计本人待处理 +func GetMyPendingCount(param models.CountPlatformParam, user string, userRoles []string) (resultMap map[string]int) { + var pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending int + resultMap = make(map[string]int) + for sceneName, sceneType := range sceneTypeMap { + pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending = GetMyPendingCountByScene(param, int(sceneType), user, userRoles) + resultMap[string(sceneName)] = pending + resultMap[string(sceneName)+string(models.PlatTabProblemApprove)] = pendingApprove + resultMap[string(sceneName)+string(models.PlatTabProblemTask)] = pendingTask + resultMap[string(sceneName)+string(models.PlatTabProblemCheck)] = pendingCheck + resultMap[string(sceneName)+string(models.PlatTabProblemConfirm)] = pendingConfirm + } + return +} + +// GetPendingCountByScene 统计本组待处理,包括:请求、发布,以及下面的请求提交、任务、审批、请求定版、请求确认 +func GetPendingCountByScene(param models.CountPlatformParam, scene int, userRoles []string) (pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending int) { userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") - var pendingTaskParam, pendingApproveParam, pendingCheckParam, pendingConfirmParam, pendingParam []interface{} - var pTaskSQL, pendingApproveSQL, pendingCheckSQL, pendingConfirmSQL, pendingSQL string - pTaskSQL, pendingTaskParam = pendingMyTaskSQL(param.Scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeImplement) - pendingTask = append(pendingTask, dao.QueryCount(pTaskSQL, pendingTaskParam...)) + var pendingTaskParam, pendingApproveParam, pendingCheckParam, pendingConfirmParam []interface{} + var pTaskSQL, pendingApproveSQL, pendingCheckSQL, pendingConfirmSQL string + pTaskSQL, pendingTaskParam = pendingTaskSQL(scene, userRolesFilterSql, userRolesFilterParam, models.TaskTypeImplement) + pendingTask = dao.QueryCount(pTaskSQL, pendingTaskParam...) - pendingApproveSQL, pendingApproveParam = pendingMyTaskSQL(param.Scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeApprove) - pendingApprove = append(pendingApprove, dao.QueryCount(pendingApproveSQL, pendingApproveParam...)) + pendingApproveSQL, pendingApproveParam = pendingTaskSQL(scene, userRolesFilterSql, userRolesFilterParam, models.TaskTypeApprove) + pendingApprove = dao.QueryCount(pendingApproveSQL, pendingApproveParam...) - pendingCheckSQL, pendingCheckParam = pendingMyTaskSQL(param.Scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeCheck) - pendingCheck = append(pendingCheck, dao.QueryCount(pendingCheckSQL, pendingCheckParam...)) + pendingCheckSQL, pendingCheckParam = pendingTaskSQL(scene, userRolesFilterSql, userRolesFilterParam, models.TaskTypeCheck) + pendingCheck = dao.QueryCount(pendingCheckSQL, pendingCheckParam...) - pendingConfirmSQL, pendingConfirmParam = pendingMyTaskSQL(param.Scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeConfirm) - pendingConfirm = append(pendingConfirm, dao.QueryCount(pendingConfirmSQL, pendingConfirmParam...)) + pendingConfirmSQL, pendingConfirmParam = pendingTaskSQL(scene, userRolesFilterSql, userRolesFilterParam, models.TaskTypeConfirm) + pendingConfirm = dao.QueryCount(pendingConfirmSQL, pendingConfirmParam...) - pendingSQL, pendingParam = pendingTaskSQL(param.Scene, userRolesFilterSql, userRolesFilterParam, models.TaskTypeNone) - pending = append(pending, dao.QueryCount(pendingSQL, pendingParam...)) + pending = pendingTask + pendingApprove + pendingCheck + pendingConfirm + return +} + +// GetMyPendingCountByScene 根据场景查询我的待处理 +func GetMyPendingCountByScene(param models.CountPlatformParam, scene int, user string, userRoles []string) (pendingTask, pendingApprove, pendingCheck, pendingConfirm, pending int) { + userRolesFilterSql, userRolesFilterParam := dao.CreateListParams(userRoles, "") + var pendingTaskParam, pendingApproveParam, pendingCheckParam, pendingConfirmParam []interface{} + var pTaskSQL, pendingApproveSQL, pendingCheckSQL, pendingConfirmSQL string + pTaskSQL, pendingTaskParam = pendingMyTaskSQL(scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeImplement) + pendingTask = dao.QueryCount(pTaskSQL, pendingTaskParam...) + + pendingApproveSQL, pendingApproveParam = pendingMyTaskSQL(scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeApprove) + pendingApprove = dao.QueryCount(pendingApproveSQL, pendingApproveParam...) + + pendingCheckSQL, pendingCheckParam = pendingMyTaskSQL(scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeCheck) + pendingCheck = dao.QueryCount(pendingCheckSQL, pendingCheckParam...) + + pendingConfirmSQL, pendingConfirmParam = pendingMyTaskSQL(scene, user, userRolesFilterSql, userRolesFilterParam, models.TaskTypeConfirm) + pendingConfirm = dao.QueryCount(pendingConfirmSQL, pendingConfirmParam...) + + pending = pendingTask + pendingApprove + pendingCheck + pendingConfirm return } @@ -170,41 +217,27 @@ func hasProcessedTaskSQL(templateType int, user string, taskType models.TaskType } // GetHasProcessedCount 统计已处理,包括:(1)处理定版 (2) 任务已审批 -func GetHasProcessedCount(param models.CountPlatformParam, user string) (hasProcessed []int) { - var hasProcessedParam []interface{} - var hasProcessedSQL string - var tempHasProcessed int - if param.Scene == int(models.SceneTypeAll) { - for _, sceneType := range sceneTypeArr { - hasProcessedSQL, hasProcessedParam = hasProcessedTaskSQL(int(sceneType), user, models.TaskTypeNone) - tempHasProcessed = dao.QueryCount(hasProcessedSQL, hasProcessedParam...) - hasProcessed = append(hasProcessed, tempHasProcessed) - } - } else { - hasProcessedSQL, hasProcessedParam = hasProcessedTaskSQL(param.Scene, user, models.TaskTypeNone) - tempHasProcessed = dao.QueryCount(hasProcessedSQL, hasProcessedParam...) - hasProcessed = append(hasProcessed, tempHasProcessed) +func GetHasProcessedCount(param models.CountPlatformParam, user string) map[string]int { + var resultMap = make(map[string]int) + for sceneName, sceneType := range sceneTypeMap { + hasProcessedSQL, hasProcessedParam := hasProcessedTaskSQL(int(sceneType), user, models.TaskTypeNone) + resultMap[string(sceneName)] = dao.QueryCount(hasProcessedSQL, hasProcessedParam...) } - return + return resultMap } // GetSubmitCount 统计用户提交 -func GetSubmitCount(param models.CountPlatformParam, user string) (countArr []int) { - var tempCount int +func GetSubmitCount(param models.CountPlatformParam, user string) map[string]int { + var resultMap = make(map[string]int) var sql string var queryParam []interface{} - if param.Scene == int(models.SceneTypeAll) { - for _, sceneType := range sceneTypeArr { - sql, queryParam = submitSQL(0, int(sceneType), user) - tempCount = dao.QueryCount(sql, queryParam...) - countArr = append(countArr, tempCount) - } - } else { - sql, queryParam = submitSQL(0, param.Scene, user) - tempCount = dao.QueryCount(sql, queryParam...) - countArr = append(countArr, tempCount) + var count int + for sceneName, sceneType := range sceneTypeMap { + sql, queryParam = submitSQL(0, int(sceneType), user) + count = dao.QueryCount(sql, queryParam...) + resultMap[string(sceneName)] = count } - return + return resultMap } func submitSQL(rollback, templateType int, user string) (sql string, queryParam []interface{}) { @@ -224,22 +257,17 @@ func submitSQL(rollback, templateType int, user string) (sql string, queryParam } // GetDraftCount 统计用户暂存 -func GetDraftCount(param models.CountPlatformParam, user string) (countArr []int) { +func GetDraftCount(param models.CountPlatformParam, user string) map[string]int { + var resultMap = make(map[string]int) var sql string var queryParam []interface{} - var tempCount int - if param.Scene == int(models.SceneTypeAll) { - for _, sceneType := range sceneTypeArr { - sql, queryParam = draftSQL(int(sceneType), user) - tempCount = dao.QueryCount(sql, queryParam...) - countArr = append(countArr, tempCount) - } - } else { - sql, queryParam = draftSQL(param.Scene, user) - tempCount = dao.QueryCount(sql, queryParam...) - countArr = append(countArr, tempCount) + var count int + for sceneName, sceneType := range sceneTypeMap { + sql, queryParam = draftSQL(int(sceneType), user) + count = dao.QueryCount(sql, queryParam...) + resultMap[string(sceneName)] = count } - return + return resultMap } func draftSQL(templateType int, user string) (sql string, queryParam []interface{}) { From 25445578c21ef70c7e6ad1607e05f69ae8963288 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 13 Mar 2024 16:46:09 +0800 Subject: [PATCH 315/618] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=A8=A1=E7=89=88=E4=BB=BB=E5=8A=A1=E8=A1=A8=E5=8D=95=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/api/api.go | 1 + taskman-server/api/v1/task/task_template.go | 22 +++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index 4ed5bd7d..bf177ff5 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -78,6 +78,7 @@ func init() { &handlerFuncObj{Url: "/task-template/:requestTemplate", Method: "POST", HandlerFunc: task.CreateTaskTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplate/:id", Method: "PUT", HandlerFunc: task.UpdateTaskTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplate/:id", Method: "DELETE", HandlerFunc: task.DeleteTaskTemplate}, + &handlerFuncObj{Url: "/task-template/form-template/:requestTemplate/:id", Method: "DELETE", HandlerFunc: task.DeleteTaskTemplateFormTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplate/:id", Method: "GET", HandlerFunc: task.GetTaskTemplate}, &handlerFuncObj{Url: "/task-template/:requestTemplate/ids", Method: "GET", HandlerFunc: task.ListTaskTemplateIds}, &handlerFuncObj{Url: "/task-template/:requestTemplate", Method: "GET", HandlerFunc: task.ListTaskTemplates}, diff --git a/taskman-server/api/v1/task/task_template.go b/taskman-server/api/v1/task/task_template.go index ab59794b..d4b28ee8 100644 --- a/taskman-server/api/v1/task/task_template.go +++ b/taskman-server/api/v1/task/task_template.go @@ -111,6 +111,28 @@ func DeleteTaskTemplate(c *gin.Context) { middleware.ReturnData(c, result) } +func DeleteTaskTemplateFormTemplate(c *gin.Context) { + var result *models.SimpleFormTemplateDto + var err error + requestTemplateId := c.Param("requestTemplate") + id := c.Param("id") + result, err = service.GetFormTemplateService().GetFormTemplate(requestTemplateId, id) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + if result != nil && len(result.Groups) > 0 { + for _, group := range result.Groups { + err = service.GetFormTemplateService().DeleteFormTemplateItemGroup(group.ItemGroupId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + } + } + middleware.ReturnSuccess(c) +} + // 读取任务模板 func GetTaskTemplate(c *gin.Context) { requestTemplateId := c.Param("requestTemplate") From 63df353b8bfe108fd407741efc7b2302d4c32ccd Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 13 Mar 2024 17:52:25 +0800 Subject: [PATCH 316/618] =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0=E6=9F=A5?= =?UTF-8?q?=E7=9C=8B=E5=B7=B2=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91=E8=B0=83?= =?UTF-8?q?=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/request_service_new.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/taskman-server/service/request_service_new.go b/taskman-server/service/request_service_new.go index ea7ccde5..2e49ca28 100644 --- a/taskman-server/service/request_service_new.go +++ b/taskman-server/service/request_service_new.go @@ -207,10 +207,10 @@ func pendingMyTaskSQL(templateType int, user, userRolesFilterSql string, userRol func hasProcessedTaskSQL(templateType int, user string, taskType models.TaskType) (sql string, queryParam []interface{}) { queryParam = []interface{}{} if taskType == models.TaskTypeNone { - sql = "select * from (select t.id,t.request,t.template_type,t.name,t.type,t.created_time as task_created_time,th.updated_time as task_approval_time,t.updated_time,t.status,t.expire_time,th.role as task_handle_role,th.id as task_handle_id,th.handler as task_handler,t.del_flag,th.latest_flag,th.handle_status from task t right join task_handle th ON t.id = th.task) tha where del_flag = 0 and status = 'done' and template_type = ? and type != ? and task_handler =? and latest_flag = 1 " + sql = "select * from (select t.id,t.request,t.template_type,t.name,t.type,t.created_time as task_created_time,th.updated_time as task_approval_time,t.updated_time,t.status,t.expire_time,th.role as task_handle_role,th.id as task_handle_id,th.handler as task_handler,t.del_flag,th.latest_flag,th.handle_status from task t right join task_handle th ON t.id = th.task) tha where del_flag = 0 and handle_status = 'complete' and template_type = ? and type != ? and task_handler =? and latest_flag = 1 " queryParam = append([]interface{}{templateType, models.TaskTypeSubmit, user}) } else { - sql = "select * from (select t.id,t.request,t.template_type,t.name,t.type,t.created_time as task_created_time,th.updated_time as task_approval_time,t.updated_time,t.status,t.expire_time,th.role as task_handle_role,th.id as task_handle_id,th.handler as task_handler,t.del_flag,th.latest_flag,th.handle_status from task t right join task_handle th ON t.id = th.task) tha where del_flag = 0 and status = 'done' and template_type = ? and type = ? and task_handler =? and latest_flag = 1 " + sql = "select * from (select t.id,t.request,t.template_type,t.name,t.type,t.created_time as task_created_time,th.updated_time as task_approval_time,t.updated_time,t.status,t.expire_time,th.role as task_handle_role,th.id as task_handle_id,th.handler as task_handler,t.del_flag,th.latest_flag,th.handle_status from task t right join task_handle th ON t.id = th.task) tha where del_flag = 0 and handle_status = 'complete' and template_type = ? and type = ? and task_handler =? and latest_flag = 1 " queryParam = append([]interface{}{templateType, taskType, user}) } return From 349d36689ead1cd414af6341219a957c018d7fe8 Mon Sep 17 00:00:00 2001 From: zgyzgyhero <894526647@qq.com> Date: Wed, 13 Mar 2024 18:10:40 +0800 Subject: [PATCH 317/618] add request form data save --- taskman-server/api/api.go | 1 + taskman-server/api/v2/request/request.go | 25 +++++++++++++++++++++++ taskman-server/service/request_service.go | 7 +++++++ 3 files changed, 33 insertions(+) diff --git a/taskman-server/api/api.go b/taskman-server/api/api.go index bf177ff5..1e963363 100644 --- a/taskman-server/api/api.go +++ b/taskman-server/api/api.go @@ -156,6 +156,7 @@ func init() { &handlerFuncObj{Url: "/request-check/confirm/:requestId", Method: "POST", HandlerFunc: requestNew.CheckRequest}, // 确认定版 &handlerFuncObj{Url: "/request/history/:requestId", Method: "GET", HandlerFunc: requestNew.GetRequestHistory}, &handlerFuncObj{Url: "/plugin/request/create", Method: "POST", HandlerFunc: requestNew.PluginCreateRequest}, + &handlerFuncObj{Url: "/request-data/form/save/:requestId", Method: "POST", HandlerFunc: requestNew.SaveRequestFormData}, ) } diff --git a/taskman-server/api/v2/request/request.go b/taskman-server/api/v2/request/request.go index 5c67d3b0..213cdbee 100644 --- a/taskman-server/api/v2/request/request.go +++ b/taskman-server/api/v2/request/request.go @@ -285,3 +285,28 @@ func handlePluginRequestCreate(input *models.PluginRequestCreateParamObj, callRe } return } + +func SaveRequestFormData(c *gin.Context) { + requestId := c.Param("requestId") + user := middleware.GetRequestUser(c) + var param models.RequestPreDataTableObj + if err := c.ShouldBindJSON(¶m); err != nil { + middleware.ReturnParamValidateError(c, err) + return + } + request, err := service.GetSimpleRequest(requestId) + if err != nil { + middleware.ReturnServerHandleError(c, err) + return + } + if request.CreatedBy != user { + middleware.ReturnReportRequestNotPermissionError(c) + return + } + err = service.SaveRequestForm(requestId, user, ¶m) + if err != nil { + middleware.ReturnServerHandleError(c, err) + } else { + middleware.ReturnData(c, param) + } +} diff --git a/taskman-server/service/request_service.go b/taskman-server/service/request_service.go index 3b90cf54..932d9853 100644 --- a/taskman-server/service/request_service.go +++ b/taskman-server/service/request_service.go @@ -2422,3 +2422,10 @@ func getTaskFormItems(requestFormItems []*models.FormItemTable, taskForms []*mod } return } + +func SaveRequestForm(requestId, operator string, param *models.RequestPreDataTableObj) (err error) { + nowTime := time.Now().Format(models.DateTimeFormat) + actions := UpdateRequestFormItem(requestId, operator, nowTime, &models.RequestPreDataDto{Data: []*models.RequestPreDataTableObj{param}}) + err = dao.Transaction(actions) + return +} From 751edda0a1292b0109192bb00baf36a02a13a6b3 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Wed, 13 Mar 2024 18:20:05 +0800 Subject: [PATCH 318/618] =?UTF-8?q?=E5=AE=9A=E7=89=88=E9=80=80=E5=9B=9E?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/request_service.go | 34 +++++++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/taskman-server/service/request_service.go b/taskman-server/service/request_service.go index 3b90cf54..1156ba88 100644 --- a/taskman-server/service/request_service.go +++ b/taskman-server/service/request_service.go @@ -938,11 +938,39 @@ func UpdateRequestStatus(requestId, status, operator, userToken, language, descr // 请求定版, 根据模板配置开启是否确认定版 err = GetRequestService().CreateRequestCheck(request, operator, bindCache, userToken, language) } else if status == "Draft" { - /*if request.Handler != operator { + // 只有定版人才能处理 + var checkTask *models.TaskTable + var taskHandleList []*models.TaskHandleTable + var actions []*dao.ExecAction + checkTask, err = GetTaskService().GetLatestCheckTask(requestId) + if err != nil { + return err + } + if checkTask == nil { + err = fmt.Errorf("requestId:%s check task not exist", requestId) + return err + } + + taskHandleList, err = GetTaskHandleService().GetTaskHandleListByTaskId(checkTask.Id) + if err != nil { + return err + } + + if len(taskHandleList) == 0 { + err = fmt.Errorf("requestId:%s check task handler is empty", requestId) + return err + } + if taskHandleList[0].Handler != operator { err = exterror.New().UpdateRequestHandlerStatusError return err - }*/ - _, err = dao.X.Exec("update request set status=?,rollback_desc=?,updated_by=?,handler=?,updated_time=?,confirm_time=? where id=?", status, description, operator, operator, nowTime, nowTime, requestId) + } + // 更新处理人,拒绝 + actions = append(actions, &dao.ExecAction{Sql: "update task_handle set handle_result = ?,handle_status = ?,updated_time =? where id= ?", Param: []interface{}{models.TaskHandleResultTypeDeny, models.TaskHandleResultTypeComplete, nowTime, taskHandleList[0].Id}}) + // 更新任务到完成 + actions = append(actions, &dao.ExecAction{Sql: "update task set status = ?,task_result = ?,updated_by =?,updated_time =? where id = ?", Param: []interface{}{models.TaskStatusDone, models.TaskHandleResultTypeRedraw, operator, nowTime, checkTask.Id}}) + // 更新请求 + actions = append(actions, &dao.ExecAction{Sql: "update request set status=?,rollback_desc=?,updated_by=?,handler=?,updated_time=?,confirm_time=? where id=?", Param: []interface{}{status, description, operator, operator, nowTime, nowTime, requestId}}) + err = dao.Transaction(actions) } else { _, err = dao.X.Exec("update request set status=?,updated_by=?,updated_time=? where id=?", status, operator, nowTime, requestId) } From ed56989c6bf3fae66b31780db96b22600e785142 Mon Sep 17 00:00:00 2001 From: pobu168 <244202969@qq.com> Date: Wed, 13 Mar 2024 18:23:33 +0800 Subject: [PATCH 319/618] add: clear groups --- taskman-ui/src/api/server.js | 4 + .../temp-management/approval-form-node.vue | 21 +- .../pages/temp-management/approval-form.vue | 722 +++++++++--------- .../src/pages/temp-management/basic-info.vue | 40 +- .../pages/temp-management/task-form-node.vue | 22 +- .../src/pages/temp-management/task-form.vue | 716 ++++++++--------- 6 files changed, 795 insertions(+), 730 deletions(-) diff --git a/taskman-ui/src/api/server.js b/taskman-ui/src/api/server.js index 5f648e94..1ede1ff9 100755 --- a/taskman-ui/src/api/server.js +++ b/taskman-ui/src/api/server.js @@ -178,6 +178,10 @@ export const getRequestGroupForm = params => ) // 获取审批节点 export const getApprovalNode = (tmpId, type) => req.get(`/taskman/api/v1/task-template/${tmpId}/ids?type=${type}`) + +// 清空节点下的组 +export const deleteGroupsByNodeid = (tmpId, nodeId) => + req.delete(`/taskman/api/v1/task-template/form-template/${tmpId}/${nodeId}`) // 保存审批节点 export const addApprovalNode = data => req.post(`/taskman/api/v1/task-template/${data.requestTemplate}`, data) // 保存审批节点 diff --git a/taskman-ui/src/pages/temp-management/approval-form-node.vue b/taskman-ui/src/pages/temp-management/approval-form-node.vue index e91fc82e..fafc5294 100644 --- a/taskman-ui/src/pages/temp-management/approval-form-node.vue +++ b/taskman-ui/src/pages/temp-management/approval-form-node.vue @@ -121,7 +121,7 @@ icon="md-add" :disabled="isHandlerAddDisable" > - + 处理人设置存在重复数据,请修改
@@ -139,7 +139,13 @@ diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index 6833fff7..f087a10c 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -31,7 +31,7 @@
- 预览 + {{ $t('tw_preview') }}
{{ $t('root_entity') }} @@ -52,10 +52,10 @@ v-for="(groupItem, index) in dataFormInfo.groups" :key="index" :class="{ - radio: true, - custom: groupItem.itemGroupType === 'custom', - workflow: groupItem.itemGroupType === 'workflow', - optional: groupItem.itemGroupType === 'optional' + 'radio-group-radio': true, + 'radio-group-custom': groupItem.itemGroupType === 'custom', + 'radio-group-workflow': groupItem.itemGroupType === 'workflow', + 'radio-group-optional': groupItem.itemGroupType === 'optional' }" :style="activeStyle(groupItem)" > @@ -1103,27 +1103,28 @@ fieldset[disabled] .ivu-input { .radio-group { margin-bottom: 15px; - .radio { - padding: 5px 15px; - border-radius: 32px; - font-size: 12px; - cursor: pointer; - margin: 4px; - display: inline-block; - } - .custom { - border: 1px solid #b886f8; - color: #b886f8; - } - .workflow { - border: 1px solid #cba43f; - color: #cba43f; - } - .optional { - border: 1px solid #81b337; - color: #81b337; - } } +.radio-group-radio { + padding: 5px 15px; + border-radius: 32px; + font-size: 12px; + cursor: pointer; + margin: 4px; + display: inline-block; +} +.radio-group-custom { + border: 1px solid #b886f8; + color: #b886f8; +} +.radio-group-workflow { + border: 1px solid #cba43f; + color: #cba43f; +} +.radio-group-optional { + border: 1px solid #81b337; + color: #81b337; +} + .btn-footer-margin { margin: 0 6px; } diff --git a/taskman-ui/src/pages/temp-management/request-form-msg.vue b/taskman-ui/src/pages/temp-management/request-form-msg.vue index 7f6dc14d..31d13750 100644 --- a/taskman-ui/src/pages/temp-management/request-form-msg.vue +++ b/taskman-ui/src/pages/temp-management/request-form-msg.vue @@ -31,7 +31,7 @@
- 预览 + {{ $t('tw_preview') }}
{{ $t('请求信息') }} diff --git a/taskman-ui/src/pages/temp-management/task-form-node.vue b/taskman-ui/src/pages/temp-management/task-form-node.vue index 7481b3b8..be0ed12d 100644 --- a/taskman-ui/src/pages/temp-management/task-form-node.vue +++ b/taskman-ui/src/pages/temp-management/task-form-node.vue @@ -2,7 +2,7 @@
- 节点配置 + {{ $t('tw_node_configuration') }}
@@ -53,16 +53,16 @@ - 序号 + {{ $t('index') }} 角色设置方式 人员设置方式 - 角色 + {{ $t('manageRole') }} 人员 - + {{ roleObjIndex + 1 }} @@ -150,7 +150,7 @@ export default { id: '', sort: 1, requestTemplate: '', - name: '任务1', + name: `${this.$t('task')}1`, expireDay: 1, description: '', handleMode: 'custom', diff --git a/taskman-ui/src/pages/temp-management/task-form.vue b/taskman-ui/src/pages/temp-management/task-form.vue index d98235af..0e4a7924 100644 --- a/taskman-ui/src/pages/temp-management/task-form.vue +++ b/taskman-ui/src/pages/temp-management/task-form.vue @@ -97,7 +97,7 @@
- 预览 + {{ $t('tw_preview') }}
{{ $t('任务内容') }} @@ -110,10 +110,10 @@ v-for="(groupItem, index) in dataFormInfo.groups" :key="index" :class="{ - radio: true, - custom: groupItem.itemGroupType === 'custom', - workflow: groupItem.itemGroupType === 'workflow', - optional: groupItem.itemGroupType === 'optional' + 'radio-group-radio': true, + 'radio-group-custom': groupItem.itemGroupType === 'custom', + 'radio-group-workflow': groupItem.itemGroupType === 'workflow', + 'radio-group-optional': groupItem.itemGroupType === 'optional' }" :style="activeStyle(groupItem)" > @@ -241,9 +241,7 @@
- + - - - - -
暂未配置表单
+
+ + 信息表单 + + +
暂未配置表单
+ + 数据表单 + + + + + +
暂未配置表单
+
@@ -460,6 +464,10 @@ export default { color: #515a6e; font-weight: bold; } + .request-form { + width: calc(100% - 20px); + margin: 0 0 12px 16px; + } .no-data { padding-left: 20px; height: 60px; From af6de90cfbceb9b03863d534cc0a6816445160d9 Mon Sep 17 00:00:00 2001 From: wanghao7717 <792974788@qq.com> Date: Mon, 18 Mar 2024 12:18:42 +0800 Subject: [PATCH 409/618] =?UTF-8?q?=E5=B7=A5=E4=BD=9C=E5=8F=B0=E8=87=AA?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E8=AE=A1=E7=AE=97=E5=88=86=E6=9E=90=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E9=80=BB=E8=BE=91=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-ui/src/pages/workbench/components/entity-table.vue | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/taskman-ui/src/pages/workbench/components/entity-table.vue b/taskman-ui/src/pages/workbench/components/entity-table.vue index c3e91f01..33d0c135 100644 --- a/taskman-ui/src/pages/workbench/components/entity-table.vue +++ b/taskman-ui/src/pages/workbench/components/entity-table.vue @@ -284,7 +284,8 @@ export default { v.entityData[key] = '' // 后端可能返回'[]'这种数据 } } - if (!v.entityData[key] && v.addFlag) { + // 添加一行的数据,并且有cmdb数据id,调用接口获取 + if (!v.entityData[key] && v.addFlag && v.dataId) { const titleObj = data.title.find(t => t.name === key) this.getExpressionData(titleObj, v) } From c472ad9b8e64a639dcfbf45c6825e0d3b2dea4af Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Mon, 18 Mar 2024 13:47:32 +0800 Subject: [PATCH 410/618] =?UTF-8?q?=E5=AF=BC=E5=85=A5=E6=A8=A1=E7=89=88?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=92=8C=E5=B1=9E=E4=B8=BB=E8=A7=92=E8=89=B2?= =?UTF-8?q?=E9=87=87=E7=94=A8=E5=BD=93=E5=89=8D=E6=93=8D=E4=BD=9C=E4=BA=BA?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E7=AC=AC=E4=B8=80=E4=B8=AA=E8=A7=92=E8=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/rpc/user_role_rpc.go | 23 ++++++++++- .../service/request_template_service.go | 40 +++++++++++++++---- 2 files changed, 54 insertions(+), 9 deletions(-) diff --git a/taskman-server/rpc/user_role_rpc.go b/taskman-server/rpc/user_role_rpc.go index 86074f22..9e8c1f40 100644 --- a/taskman-server/rpc/user_role_rpc.go +++ b/taskman-server/rpc/user_role_rpc.go @@ -13,6 +13,8 @@ const ( pathRetrieveAllUser = "/platform/v1/users/retrieve" // pathRetrieveRoleUsers 查询角色用户列表 pathRetrieveRoleUsers = "/platform/v1/roles/%s/users" + // pathUserRoles 查询用户角色列表 + pathUserRoles = "/platform/v1/users/%s/roles" ) // QueryAllRoles 查询所有角色 @@ -71,7 +73,7 @@ func QueryAllUser(userToken, language string) (userMap map[string]*models.UserDt return } -// QueryRolesUsers 查询角色用户列表 +// QueryRolesUsers 查询用户角色列表 func QueryRolesUsers(roleId, userToken, language string) (list []*models.UserDto, err error) { var response models.QueryUserResponse byteArr, err := HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathRetrieveRoleUsers, roleId), userToken, language) @@ -89,3 +91,22 @@ func QueryRolesUsers(roleId, userToken, language string) (list []*models.UserDto list = response.Data return } + +// QueryUserRoles 查询用户角色列表 +func QueryUserRoles(user, userToken, language string) (list []*models.SimpleLocalRoleDto, err error) { + var response models.QueryRolesResponse + byteArr, err := HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathUserRoles, user), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + list = response.Data + return +} diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 467978b6..4b86949c 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -1285,11 +1285,11 @@ func (s *RequestTemplateService) RequestTemplateImport(input models.RequestTempl return } else { // 有重复数据,但是新导入模板版本最高,直接当成新建处理 - input = s.createNewImportTemplate(input, input.RequestTemplate.RecordId) + input = s.createNewImportTemplate(input, operator, input.RequestTemplate.RecordId, userToken, language) } } else { // 无名称重复数据,新建模板id以及模板关联表id都新建 - input = s.createNewImportTemplate(input, "") + input = s.createNewImportTemplate(input, operator, "", userToken, language) } } else { // 删除冲突模板数据 @@ -1310,7 +1310,7 @@ func (s *RequestTemplateService) RequestTemplateImport(input models.RequestTempl actions = append(actions, delActions...) } // 新建模板&模板相关表属性 - input = s.createNewImportTemplate(input, input.RequestTemplate.RecordId) + input = s.createNewImportTemplate(input, operator, input.RequestTemplate.RecordId, userToken, language) } if input.RequestTemplate.Id == "" { err = fmt.Errorf("RequestTemplate id illegal ") @@ -1416,17 +1416,36 @@ func (s *RequestTemplateService) RequestTemplateImport(input models.RequestTempl return } -func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTemplateExport, recordId string) models.RequestTemplateExport { +func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTemplateExport, operator, recordId, userToken, language string) models.RequestTemplateExport { var newTaskTemplateIdMap = make(map[string]string) var newFormTemplateIdMap = make(map[string]string) var newFormItemTemplateIdMap = make(map[string]string) var historyTemplateId = input.RequestTemplate.Id + var roleList []*models.SimpleLocalRoleDto + now := time.Now().Format(models.DateTimeFormat) input.RequestTemplate.Id = guid.CreateGuid() input.RequestTemplate.RecordId = recordId - // 修改模板角色中模板id,新建角色id - for _, requestTemplateRole := range input.RequestTemplateRole { - requestTemplateRole.Id = guid.CreateGuid() - requestTemplateRole.RequestTemplate = input.RequestTemplate.Id + input.RequestTemplate.CreatedBy = operator + input.RequestTemplate.CreatedTime = now + input.RequestTemplate.UpdatedBy = operator + input.RequestTemplate.UpdatedTime = now + // 模版导入,模版使用角色和属主角色取当前操作人角色 + roleList, _ = rpc.QueryUserRoles(operator, userToken, language) + if len(roleList) > 0 { + role := roleList[0].Name + input.RequestTemplateRole = make([]*models.RequestTemplateRoleTable, 0) + input.RequestTemplateRole = append(input.RequestTemplateRole, &models.RequestTemplateRoleTable{ + Id: guid.CreateGuid(), + RequestTemplate: input.RequestTemplate.Id, + Role: role, + RoleType: string(models.RolePermissionMGMT), + }) + input.RequestTemplateRole = append(input.RequestTemplateRole, &models.RequestTemplateRoleTable{ + Id: guid.CreateGuid(), + RequestTemplate: input.RequestTemplate.Id, + Role: role, + RoleType: string(models.RolePermissionUse), + }) } // 修改 taskTemplate中formTemplate,RequestTemplate,以及taskTemplateRole修改 for _, taskTemplate := range input.TaskTemplate { @@ -1436,6 +1455,10 @@ func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTem if taskTemplate.RequestTemplate == historyTemplateId { taskTemplate.RequestTemplate = input.RequestTemplate.Id } + taskTemplate.CreatedBy = operator + taskTemplate.UpdatedBy = operator + taskTemplate.CreatedTime = now + taskTemplate.UpdatedTime = now newTaskTemplateIdMap[historyTaskTemplateId] = taskTemplate.Id } for _, taskHandleTemplate := range input.TaskHandleTemplate { @@ -1449,6 +1472,7 @@ func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTem newFormTemplateIdMap[historyFormTemplateId] = formTemplate.Id formTemplate.RequestTemplate = input.RequestTemplate.Id formTemplate.TaskTemplate = newTaskTemplateIdMap[formTemplate.TaskTemplate] + formTemplate.CreatedTime = now } for _, formItemTemplate := range input.FormItemTemplate { historyFormItemTemplateId := formItemTemplate.Id From 20fa32835a55d97ee4bf3944abd14167bd7c4689 Mon Sep 17 00:00:00 2001 From: pobu168 <244202969@qq.com> Date: Mon, 18 Mar 2024 14:12:04 +0800 Subject: [PATCH 411/618] update: request form name --- taskman-ui/src/pages/temp-management/request-form-data.vue | 6 +++--- taskman-ui/src/pages/temp-management/request-form-msg.vue | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index c7b8c450..2a156fb3 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -34,7 +34,7 @@ {{ $t('tw_preview') }}
- {{ $t('root_entity') }} + {{ $t('tw_data_form') }}
@@ -324,7 +324,7 @@
- @@ -334,7 +334,7 @@
diff --git a/taskman-ui/src/pages/temp-management/request-form-msg.vue b/taskman-ui/src/pages/temp-management/request-form-msg.vue index f8fb4a32..8f5ff28b 100644 --- a/taskman-ui/src/pages/temp-management/request-form-msg.vue +++ b/taskman-ui/src/pages/temp-management/request-form-msg.vue @@ -34,7 +34,7 @@ {{ $t('tw_preview') }}
- {{ $t('tw_request_title') }} + {{ $t('tw_information_form') }}
@@ -446,7 +446,7 @@ export default { finalElement: [ { itemGroup: 'requestInfo', - itemGroupName: this.$t('tw_request_title'), + itemGroupName: this.$t('tw_information_form'), attrs: [] } ], From 98e84360c6251e8188b3b7e635a458407516b7d6 Mon Sep 17 00:00:00 2001 From: tangjiawei Date: Mon, 18 Mar 2024 14:39:56 +0800 Subject: [PATCH 412/618] =?UTF-8?q?=E5=AF=BC=E5=85=A5=E6=A8=A1=E7=89=88?= =?UTF-8?q?=E5=AE=A1=E6=89=B9=E5=92=8C=E4=BB=BB=E5=8A=A1=E4=B8=AD=E8=A7=92?= =?UTF-8?q?=E8=89=B2=E5=92=8C=E5=A4=84=E7=90=86=E4=BA=BA=E6=B8=85=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- taskman-server/service/request_template_service.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 4b86949c..fd2b1f85 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -1429,6 +1429,7 @@ func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTem input.RequestTemplate.CreatedTime = now input.RequestTemplate.UpdatedBy = operator input.RequestTemplate.UpdatedTime = now + input.RequestTemplate.Handler = operator // 模版导入,模版使用角色和属主角色取当前操作人角色 roleList, _ = rpc.QueryUserRoles(operator, userToken, language) if len(roleList) > 0 { @@ -1459,11 +1460,15 @@ func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTem taskTemplate.UpdatedBy = operator taskTemplate.CreatedTime = now taskTemplate.UpdatedTime = now + taskTemplate.Handler = "" newTaskTemplateIdMap[historyTaskTemplateId] = taskTemplate.Id } for _, taskHandleTemplate := range input.TaskHandleTemplate { taskHandleTemplate.Id = guid.CreateGuid() taskHandleTemplate.TaskTemplate = newTaskTemplateIdMap[taskHandleTemplate.TaskTemplate] + // 清空角色和处理人 + taskHandleTemplate.Handler = "" + taskHandleTemplate.Role = "" } // 修改 formTemplate for _, formTemplate := range input.FormTemplate { From 12505f75e6d04d87d4ee66345b0edc659aaaf708 Mon Sep 17 00:00:00 2001 From: pobu168 <244202969@qq.com> Date: Mon, 18 Mar 2024 14:50:20 +0800 Subject: [PATCH 413/618] update: request form name --- taskman-server/rpc/user_role_rpc.go | 23 ++++++- taskman-server/service/request_service_new.go | 4 ++ .../service/request_template_service.go | 40 +++++++++--- .../request-form-data-workflow.vue | 6 +- .../temp-management/request-form-data.vue | 7 ++- .../temp-management/request-form-msg.vue | 1 + taskman-ui/src/pages/workbench/column.js | 17 ++--- .../workbench/components/custom-form.vue | 9 ++- .../workbench/components/entity-table.vue | 5 +- .../publish/components/base-create.vue | 6 +- .../publish/components/base-detail.vue | 62 +++++++++++-------- 11 files changed, 123 insertions(+), 57 deletions(-) diff --git a/taskman-server/rpc/user_role_rpc.go b/taskman-server/rpc/user_role_rpc.go index 86074f22..9e8c1f40 100644 --- a/taskman-server/rpc/user_role_rpc.go +++ b/taskman-server/rpc/user_role_rpc.go @@ -13,6 +13,8 @@ const ( pathRetrieveAllUser = "/platform/v1/users/retrieve" // pathRetrieveRoleUsers 查询角色用户列表 pathRetrieveRoleUsers = "/platform/v1/roles/%s/users" + // pathUserRoles 查询用户角色列表 + pathUserRoles = "/platform/v1/users/%s/roles" ) // QueryAllRoles 查询所有角色 @@ -71,7 +73,7 @@ func QueryAllUser(userToken, language string) (userMap map[string]*models.UserDt return } -// QueryRolesUsers 查询角色用户列表 +// QueryRolesUsers 查询用户角色列表 func QueryRolesUsers(roleId, userToken, language string) (list []*models.UserDto, err error) { var response models.QueryUserResponse byteArr, err := HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathRetrieveRoleUsers, roleId), userToken, language) @@ -89,3 +91,22 @@ func QueryRolesUsers(roleId, userToken, language string) (list []*models.UserDto list = response.Data return } + +// QueryUserRoles 查询用户角色列表 +func QueryUserRoles(user, userToken, language string) (list []*models.SimpleLocalRoleDto, err error) { + var response models.QueryRolesResponse + byteArr, err := HttpGet(fmt.Sprintf(models.Config.Wecube.BaseUrl+pathUserRoles, user), userToken, language) + if err != nil { + return + } + err = json.Unmarshal(byteArr, &response) + if err != nil { + err = fmt.Errorf("Try to json unmarshal response body fail,%s ", err.Error()) + return + } + if response.Status != "OK" { + err = fmt.Errorf(response.Message) + } + list = response.Data + return +} diff --git a/taskman-server/service/request_service_new.go b/taskman-server/service/request_service_new.go index b511e725..d5be2b4c 100644 --- a/taskman-server/service/request_service_new.go +++ b/taskman-server/service/request_service_new.go @@ -670,6 +670,8 @@ func getPlatData(req models.PlatDataParam, newSQL, language string, page bool) ( } } platformDataObj.HandleRoleDisplay = strings.Join(newRoleDisplayArr, ",") + } else { + platformDataObj.HandleRoleDisplay = roleDisplayMap[platformDataObj.HandleRole] } if strings.Contains(platformDataObj.TaskHandleRole, ",") { var newRoleDisplayArr []string @@ -680,6 +682,8 @@ func getPlatData(req models.PlatDataParam, newSQL, language string, page bool) ( } } platformDataObj.TaskHandleRoleDisplay = strings.Join(newRoleDisplayArr, ",") + } else { + platformDataObj.TaskHandleRoleDisplay = roleDisplayMap[platformDataObj.TaskHandleRole] } } if len(actions) > 0 { diff --git a/taskman-server/service/request_template_service.go b/taskman-server/service/request_template_service.go index 467978b6..4b86949c 100644 --- a/taskman-server/service/request_template_service.go +++ b/taskman-server/service/request_template_service.go @@ -1285,11 +1285,11 @@ func (s *RequestTemplateService) RequestTemplateImport(input models.RequestTempl return } else { // 有重复数据,但是新导入模板版本最高,直接当成新建处理 - input = s.createNewImportTemplate(input, input.RequestTemplate.RecordId) + input = s.createNewImportTemplate(input, operator, input.RequestTemplate.RecordId, userToken, language) } } else { // 无名称重复数据,新建模板id以及模板关联表id都新建 - input = s.createNewImportTemplate(input, "") + input = s.createNewImportTemplate(input, operator, "", userToken, language) } } else { // 删除冲突模板数据 @@ -1310,7 +1310,7 @@ func (s *RequestTemplateService) RequestTemplateImport(input models.RequestTempl actions = append(actions, delActions...) } // 新建模板&模板相关表属性 - input = s.createNewImportTemplate(input, input.RequestTemplate.RecordId) + input = s.createNewImportTemplate(input, operator, input.RequestTemplate.RecordId, userToken, language) } if input.RequestTemplate.Id == "" { err = fmt.Errorf("RequestTemplate id illegal ") @@ -1416,17 +1416,36 @@ func (s *RequestTemplateService) RequestTemplateImport(input models.RequestTempl return } -func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTemplateExport, recordId string) models.RequestTemplateExport { +func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTemplateExport, operator, recordId, userToken, language string) models.RequestTemplateExport { var newTaskTemplateIdMap = make(map[string]string) var newFormTemplateIdMap = make(map[string]string) var newFormItemTemplateIdMap = make(map[string]string) var historyTemplateId = input.RequestTemplate.Id + var roleList []*models.SimpleLocalRoleDto + now := time.Now().Format(models.DateTimeFormat) input.RequestTemplate.Id = guid.CreateGuid() input.RequestTemplate.RecordId = recordId - // 修改模板角色中模板id,新建角色id - for _, requestTemplateRole := range input.RequestTemplateRole { - requestTemplateRole.Id = guid.CreateGuid() - requestTemplateRole.RequestTemplate = input.RequestTemplate.Id + input.RequestTemplate.CreatedBy = operator + input.RequestTemplate.CreatedTime = now + input.RequestTemplate.UpdatedBy = operator + input.RequestTemplate.UpdatedTime = now + // 模版导入,模版使用角色和属主角色取当前操作人角色 + roleList, _ = rpc.QueryUserRoles(operator, userToken, language) + if len(roleList) > 0 { + role := roleList[0].Name + input.RequestTemplateRole = make([]*models.RequestTemplateRoleTable, 0) + input.RequestTemplateRole = append(input.RequestTemplateRole, &models.RequestTemplateRoleTable{ + Id: guid.CreateGuid(), + RequestTemplate: input.RequestTemplate.Id, + Role: role, + RoleType: string(models.RolePermissionMGMT), + }) + input.RequestTemplateRole = append(input.RequestTemplateRole, &models.RequestTemplateRoleTable{ + Id: guid.CreateGuid(), + RequestTemplate: input.RequestTemplate.Id, + Role: role, + RoleType: string(models.RolePermissionUse), + }) } // 修改 taskTemplate中formTemplate,RequestTemplate,以及taskTemplateRole修改 for _, taskTemplate := range input.TaskTemplate { @@ -1436,6 +1455,10 @@ func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTem if taskTemplate.RequestTemplate == historyTemplateId { taskTemplate.RequestTemplate = input.RequestTemplate.Id } + taskTemplate.CreatedBy = operator + taskTemplate.UpdatedBy = operator + taskTemplate.CreatedTime = now + taskTemplate.UpdatedTime = now newTaskTemplateIdMap[historyTaskTemplateId] = taskTemplate.Id } for _, taskHandleTemplate := range input.TaskHandleTemplate { @@ -1449,6 +1472,7 @@ func (s *RequestTemplateService) createNewImportTemplate(input models.RequestTem newFormTemplateIdMap[historyFormTemplateId] = formTemplate.Id formTemplate.RequestTemplate = input.RequestTemplate.Id formTemplate.TaskTemplate = newTaskTemplateIdMap[formTemplate.TaskTemplate] + formTemplate.CreatedTime = now } for _, formItemTemplate := range input.FormItemTemplate { historyFormItemTemplateId := formItemTemplate.Id diff --git a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue index 4bf18a0c..a69fc518 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data-workflow.vue @@ -29,9 +29,9 @@
- {{ - system.description || system.name - }} + {{ system.description || system.name }}({{ system.name }})
diff --git a/taskman-ui/src/pages/temp-management/request-form-data.vue b/taskman-ui/src/pages/temp-management/request-form-data.vue index c7b8c450..2c8316a0 100644 --- a/taskman-ui/src/pages/temp-management/request-form-data.vue +++ b/taskman-ui/src/pages/temp-management/request-form-data.vue @@ -34,10 +34,11 @@ {{ $t('tw_preview') }}
- {{ $t('root_entity') }} + {{ $t('tw_request_title') }}
+ {{ $t('tw_data_form') }} {{ $t('tw_choose_object') }} @@ -324,7 +325,7 @@
- @@ -334,7 +335,7 @@
diff --git a/taskman-ui/src/pages/temp-management/request-form-msg.vue b/taskman-ui/src/pages/temp-management/request-form-msg.vue index f8fb4a32..94e5760d 100644 --- a/taskman-ui/src/pages/temp-management/request-form-msg.vue +++ b/taskman-ui/src/pages/temp-management/request-form-msg.vue @@ -38,6 +38,7 @@
+ {{ $t('tw_information_form') }}

^J3SC{O=CWxCY&tzNKiT7Ed?5&{U3B&KGl|Qi^kMOQv-cdv&|b# zHv+SZnT-wAe#7(YZP%L^B$3jDwEgJu(xPef1bPBj%~dC;>1=x8>E5aNpVdk9wEbN6 znfaFOK%PuQ9ON7bZ#)?~79(fcCXQqA`D`Z^Rgu8`diJp@{pdoRYN4v4B4!~qJ-xju zz9IuzeC7N8f2iUny2fVW&qlO$b@fXohTE2YkVtuxm^Lfs2*8}h`MmELTD7An)$top z>)iW4A+RHqf!yXsIQ;4yji&n6bje&nP9`W_hdwjbH)&I*Wh8ZLl=GX0)U9S4oXxg6 zZ{12VGBnnQ1(;YF+gRC~?6xwY(n4ZEb7U-Fc{#E{b-*pmQcv9y{)P@%LPCS`v-JaK zT8IV_uYiNZn#0rZdHL1O0GRqoE^pN`*{DwiyuB!#aE=KF62E}$cw>RQ+gAg zsYe&`UP`U3`0(qQqqLS-DIYLd2FV&Z7OZ9beu-$Fy5@4Pb z6%`PyADnHMZKoHEky+BJHLEtSH`ZHcVG(Ar7F!#4+W1&I9@$}i^N1`Z}+u zyi=Qw=EXF5SA_bhQsc@)(<>q}u&VxP-`GS?*T*03`fjmreyMNxr#i(*y+SY|FB7<- zD&PpDJk~K?2M(O7O=WZpM`W%ZI&sp{EfdLxXo|~@txkZj&oI8f*6T%cbPRVShlPZM z#D<5PS=s3u8DSG|fYF-ZZ2e%+oP!-UfH)X$UQIF%U!9HeWsmU-pG8@J7J`j}&tbIQ z+S<{5tvflT?#xdObSDT|o*GbB3%T4RuJ9Z)`NCCN zY)F{#>hap_GezrY3Wg~|+7OjT3*K0kle_;}|XMc1yy z$2TV>jf%nkGC}`HjgpA$0<@fqWrFW{_|MQg1>#9aGQhu16cF2;{t<%wz=60#_pdGA zQYR#Ex%{7)qSI_)Y)E7XEs7QyYn7N}a?r%~O%u#hSUOW(Tx@r5^^M)@>+4KfV_;-p zVn{O9vr4itNlJ3tZ*K0D7T_2{^9rMxxJSiC(=r>_v}kiWo1c=zEli*{@X2IqA-7<@ zh)L1fBhoDf*e-}C;vkz>3ah^5K?(!o;_$)KVhple11Wk?gIgQTKrF(Zh{Bw!Q8r!I#@`l`!c zi87)Hf^SQ-jfv!w_vWru=OAUhaDO0CSm46;%@k5IU0hBHAa`bPTpq*eA77VFTTbKCQR$>Gl|b{yVw~P=d z3=WBRgDu98<0@Q&37mDX67^AAcaqNd*F>^iooNO>OPEi{rzytxqraRR!ji z@2WTy5$7M1TD7Iz`+zDi=$U9%U8o5M@M-iZal% zBN^G5t}c6CZY*#!^&6N=h@@7dR~*C@GVH9bPHo@K{nFELN^ijCYQ;XLNq^q|ZAdG;UY> z7yj)T54L-~<*q85t>WG@_0-w!Jhz$v$g?NSA(AGJaSUK24kyaZS z6S~$92FY)>vopnp=HNBKo3o9wadS3{FW-IFWY1@M*ztZC8($6|w*Knyw!^q_A0}^K z!IJZ~BZSs>ypnPRAIOfU2cF#Hh|#6wKmeNXc@1bj)45FYd})7AS5Irj<+0)MEA7w9 z;{q!V>}vWvFx6ibxa-0DGgY52e!jR^{_xqK{ffq#$yyYxW&LtQHK|-9Rce$x@cTjM zVsxJwFf3HaI%mff*uFyUcxtuI#N~%=FvaJt-x9KELUuSilg6fj*J&1CW{2BnuUVa~ zA0BL%9gMpX8Ll=Ax4?^Au!Ef$QMo~EoNbc$Nl~_L25xBv_GzT`ULotq`@?tInERwf zoiN$oKqK$ZjHV}?E(|*%bajnAolvd5aPM9+n3u`K`BB*sZi$vHPg9I^zO3eV(s*6P z<+i>jqZzNp9O@`PkP+{HH1yM|R}Y{&^YZ&0!*?@g(2NA;Nu>f?BnFiT=PaItB|G;> z=ES5--_}esVNF_g15yalbVaU?7pNT%0zLHZS;BU$*E=+RI`!3C1&z7ahRpK z>^67a?SlKSP#s*HF&1pR*V64E>CHEd4hGng0vt#VHs(gbdaDuOOh^`MNzd=m!v+HE zD8L;$$e(PpUb_?ffUI4~m`-tb-)a3^iqFny*FrU2-4a9;t#C9k;pssL@;nVoIwGi% zl%lU(+t~fEGriI;9f>>E7xUsUD^%%M?jP^nG1C$8hyTo9fBntVmB%$*#^H@!>>f;H z12$xXjbIXJvXT&*vtSJZW&;HlM}#`=iGi$$h{MWFXAp=MA{BH%fgGiiL(Iz1C`GbE zR8Uu>r9t)Sdxr(_A z0$UfPC8dZcl(ZzN#zR9#%1#wA=?srh4F{cOwo4h4=Bf15d&YWG0|S{`x3a>Y$-p$H z8?=qwpyaoDb@T%dtae+y_h4!S*hBKvy(bTvOs2lsMYIgp4JZ;GI6d@13nO>8Ihnw( zet+?si)Wu)SGw-;xWjSUEtS>#FqvK15w)%B?&_#hKb82;|NZwLf4z06;@zoh7cU(u z1iob+KlIu0fm1$Rst>+3>tN^bI(ha%i^i8c-a}-fMQ_l@CS3MGm}FT zDxgbhRgF$nmkuAN^i~pCUW_u9hD{{YGkFvymndb|OOvE9c%U>C0voo@CbH`JYyqE7 z%S*2CEYRyKWO)@8%8G)#0=-IQsxhgJs9}m~dUI5UT_#zrsl2nc`@0bQVt8IBOba)c zwHV+~a<&1XMEP>;%lS3hn4{W`(k-Q>>(*@BxA}#2G0(>Pw?tJxaO$VvkN*7g?>|33 zG+_Va=g@QZm+}uBXc(M0^6J}fUmE&uMab~b(-&!1cwxpKmO9=0;@?UnC8JJmX1X`b%C`tvlhL}z%z@rEp7uuDZ7 zo<$$Gl;1khlF5Gfo?GK1HdUIjMwb_wuBu7T)bOZ~Tw`L;hv&=lkuZdzzQXkZ$$kOC z$n|O2%Od>He+ zohpx~R0@=t*jO32zFt~Z&u0-Un6P*$5f7P6p=*2yOmdP7kqd<;9*vs97ZN?`PQEOS z0NO0yRiEsu;4|cWb#%HxohH|zLm`Vc%A-{V6Hxle+s-{><48G?%;1a)tMU&70hT^} z43z$k2jSn}*#(yY^;73UVfY7*$tZ=!MTowV<%pH|F1s}$2=HwIR1x^e{OC0 z==YwU>9-rI4wb}6dk-~kZ7eEWud(0*sOyS8&; zc&>Ms5jMW7Hm9%#P*g$kGGWj%1|tX;-jz!ANJ3nPfAb)+rED@Y$q7btLenH^X(>V- zEmT0GS75%AEa3B4L{GN2CoO|U#ZW=`{o?SzFtIpHrVtzC^1KK|pFwX@mk(aXnP+7! z8oRT6vox9u^V{1bMypCAsl8zxw9* z$7fHUzH+7K`1Y^H9{#jzwEEgW|MluLNK{Q8PkB*QTBEsab^$1(E8@Ar7 zF7ND~xl@e5>WnXlzl~NL(oVkvRRz~ZbB}@73dU#flck&A*xUi>(3tHVTJ5%HgCE_p zCU?X3(x{_x4}NcSH*R!K8P!F3=#l2h#C*M{ zx4_$r=HM<%Wf?kF*Kfs@hPs9Xj83f#Uj=x8$lpTJ#r-uU-IhES#r%?&+mEGiN| zt>f3^g$h-n1)&8TPSG+lmm~r^)Pv#bL4iUxh0l~S$xNavmCW^^Q?sF=>cU~r1+FQc z$pWf`&vj)$Zr9h7%kbjyyr_JyVCyMF7E3_jQRyB8 zj#Nlbqthidz8Z-rNuuG1D3Jkv=)TmG>nRjAJBdiFFJqL&l9BV)ds0$(z-TEzZorgx z7evP@#6^4cM!8xXT`up_^_lAA>T&~6!2Y2d-|g7lT$nxS_JG^Ty$2t<*l=Rgqo+3H zLOc|rO3w!G>(Kfi-Wa@YyW_!9d=bQjhaD%6o~-`%D#l&gfW#eWKh)6NFol=@L@7@<{w?&jLA*2zBB*-$ey~||AJ@Q%<>a}Q@s8j`f z9XNn|0fEKl)t9lU0u~oyYAm8hJ(Ec!N{P7pJ`9dX6tFXtK$cK_m?SQbz~zH4D@mb+ z(geb?ydZairy$5PnZyesxeJ1}dMcFqt%|%%gDgxPW&rg-A(NS8261oi$c^K(0H*v# znwkzaVI1(Tu^wnQtSxyorg}@qzK(71aSKmY#xHE{S}18bdb1__e77nA1hADi`t7&u!?%Zj`)z6KO9|{!E|=v5EvO0AUu!;2abZ;J!%oR}qy-Fz*@Pb{W6cI&AVUi?h!Dy01 zDH`aA)9C3W&U(6VXAXTmQzFbGpwZ$*Lr2Q%{&4SSFbR(_st9-3y4p=1CYQ;>6nTIu z4Jz9=#|JL?9Y`Md;;Ge7J2T$Fm#b791N(tK;HhP91BF zIu_pAbk zS-S(1U)(zGyJgmX&TgtxtI-lx$z;Hv-Q9Ii5@oV@JcKS^Ave;6;RE;0b0zWp7#hEH zjt~*tg(&rK@%8g1Joz^3n4M9Yxc$keSe!`>p3!Pa!G>b%cH>%*z1Klykpcl7wEe`);MN3~k)xMMy( zc)oODzO*Z5Avf27F%E^};Dsq66dVdIW~+H;L%U^vW1@L~R^oe!AuC?lvGSKshgYCF zFK%3kt3F<3o|+wAdHc0R@csJS+}vybb~=ZLC&zmSdu^S%U9~!tl{$4@C?b#&Ghc#0 z&sdr_i-+9Yg9y41)rUl<`-;+bl6(S0bQcL-D9TyyD4&vr z18HC8cCGOr{p63cXECSTv1NXrzr!C9E!P3HfyYj@mUJmnqocY88qB*7Ou^dQ3lSX5 z2~#0p<~3XoNf<0nFyF8@6gHb18bcCS+SQkm{W{N#&)vK7<$LbAetUXwdUz#V-1U%g z`|qIqcXroxmm6yhIw?(H5HLGL2_)6*Vb5Nmm=IvvHZTh zvIp*49vybyeXHd!rrwo$R~X3Rtvv%6Xd9R~5_D|MT~TWHJVWZ?f+${KVeVR?mfl7 z-0piizZ~=@>l{q{-a9kXgPnVZ?u0l~8vB_cm1muL$X;%<88P>x(&_6|>FBla^}?JW zjy{0z?Lz|-6z9z#ijc=ZFx`bK(ulYaX(15n^VyhgBqed!n0;Y08H^n0!=q7^EQu5_ z2xU|VchTxuWs5P+J2o%Y9kC-EZ3%qEPIOqRTeL#av^ua!X=oAyyMZXj@hZu;S3cQv zSIdP*$4+gC(w1ob7fRwC{>Qc>Y0q6a)%EBCUe(Q~4t~*}xU;#c%C8;mR15m{K-aAA zCA`^aS&`Lvz4+c6{j0Ke?Hbc2 zd5&>-&X}SuLI$f=DBLqMV#B>-Gh&&sEEXY!$q|yXef@Sy0wmmJWQGQOp>!$R!wJxc z=yZG`0D;S)`vzpY?i7+Dd0bHtTObq&7+!2HE;|Dv2g%7n1VNb~7AZZ-S2(<|5t-HlSzI(7e0Zj5c*b;o$Y_mWDxVqO}v=Zv56rL1F*J)No^O?Ik0Y ze(0A~*2(gkBDL6PFdR<+tqZQs}x>hCBz5#V8BBqIu=AgDw{1J z2v})Mz9^K#$qrZ+8Q?34qz3u1T^NxJczcnb$d%3^Xeb^O3Q-^-5;+7egnCFkBC1va zgF$2D=yM8WLRyeOuY?;>gsJ6jXhALCyF4t_xd7Zm;N#xtgO4=zoE~W(Go?QA(Abx! z$DWFUf@pk8+@_lg59gLdJ#yjZrlx~y@4HK{?;0rF{dDvG#=`61Wi&VMPq2c3idWE> zXjy?9Uwr%Wg#F}QDRSE`paQtiioV&91f;A6gTZ$2xs!8tOLOD6EmIa~f>Odcl|C<1 zta(Ps$gHSvqn9aJK`8`2bhU&OK7~Z(feR~QQlxBbkEhZ2Nz-<6BeNs3G3Vy$=i=*u zP(X!NIFm>&i*@zlk6i_B}5 zZR&JE#YByX|9p=6t-B>8@SXF1-+OzW=l%GjZ_nKG^k2|+$3Tnji;p~X@k@L3;>FtP z?aCs$YYT7qR-a#f7e4K-xh|aY+*DT=>e;yQE*%fc`2JSKoTVw+fw3cr^jfAZCa^X6)+U@~PL)O)#Ma@_ zk-BMk#wIB@7&nPzav9!lP!c4N$Tum(0Rxg*x0UOz#uw6zVCQt=}b3M%P<#DO}=^wwQJyno{aG_O#npRTrR>&@&f{mYzm+QQUoCqb{!~0gC_;(m9y-x@ zGIj!GjuVlcW*yquNi=Ex;gtW~ptjZngsWi%$)zqL6%*92e@$1MtIBvKBE3Y}7+ zCirS2m?6;8KiP1<=>E3G@m7(8GE$-Vc;Yk$jo3gW>%@4ol@>5WAP5zW7CYKcf$jR< z`|n>?UHKmCHSVjQzSn*G@!O9)a(t@2_srzo4}?FYQq|1xam)5XR}N_pkn1CJBW!SX z$Jx2{vj7|eQZWVCec=mNd-J)np8?;hx)|;Fd~d5vQRQ}~W1iaHDOZ?gv(8@$``_O> z+M6~Hj`lmu;nOM2#2pE>O{(_DiMk@Xf=_1Lne}RlWv*C5R__yBoFl(Er)B; zb7iDNA{O(SR6=7=frD<8RuNSpOPt4%fF5O;4w1YtkEp3T-Ij3H&euS(7L6zf8iL(# z@AO0;=vcy;pLf~jPfhmT-G1uMjkmrRqpR}PYu~^2^N-&>c;>Hrx{n{ZxN>}E1yVoJ zUVAtyDpq!{?OxtL+}!y6@7vfqHXuWN=q(qLR~9l?rg96Ffhawi_GY7C8HPNQ2?lh& zbP1u<#`fl=3XLWxy?yCM_1<2^6LP@0)j1RmpmZk3MV3epGE?NKD71?S4#`((b*+fDY-!8hMZ_H9$>L@8byigVrD+5X!j{F_-7#D>IgePfb`w5sTcy0i;qQ zwtxrr#A$XaL@UI+TE}ZdI%S;)o{cGbI%aEGQdsR0v^71Mk!tV6Q1#~RNlL>SE?CkPMOhGRU+#i zf1)ma;=~ET6DRrnNN^|}% zzVo%_9w8BSG>juMktjF{u22BBu8OA$$^t=?P~-FYjP8DGM9kyFd_t*If+lmos_vKh zcy1F3B0pgjNM)ibC~K=ZgqSbm%k&n#$xBA+rS-7;L}NWVG7c!9u%gO#mI!9+)X`BL ztxI`yOgW^}v5=#$fQuONx!;(Ih{YDu>o2@H}ZlV-Ij@E;vLpK`idVg2^v{@m5g z%Kq8)&CM@DDF< zz7YUvOcFgup8*vH-XFIjuocFj%EaXw_;LfGSF4js(l8z&2sW7!iR#deX@-O{jd=s% z5XGy(ejT=U8&t%jo+xhkB31M->GbB=97sZi!qfs&w7q47ce%x`!c-=Au(zfRhs!RHISMnfN9|AvSh9QI zLgv9kqv*u;SC3WV8{1oz-QRv-KL7J@^S4_+EiNx_?e=*0;>}M8>c&ZZBx!ZKNrN!h zUlr6=Nn?DmSR*!wtsF(hs}>uR7>FPxs>mQuC2!)gLmdrLq0GW}TS%Y9q>fFitvqDA zb&wuB(a_WIgrm+F4iTY72jy^eOt#dr2H#G3pvxCFqjZ7d6?$>m&9fsJ@PRTu!|>G0 z5yR_OED&gcud96B-Tihi#@;=!vNQqN@kw(hV{U0~on^ju8*nWQxu*;Zxi=&W8*SlY zI28@iblhz2cbOF~nxb3`?SWt{)9xyJvfG=0bou>`neDAn@3hY`xVw3U zh$x;sp*kT|#mSzWAy6=glPW$J!<_^w+;MV~Po|N;)=2ak^!Y#Uo!dvFWbrwa9G{W~^2>PbSlv zFw_i6n;ENtE0kmQlTfLbgX_!H2o*+!+ejq&GB=QB5v8RLvsxS5+A!Fyrg6BgXFMFH zU1oD_2Oa_>rEN?qA5P^%-n@5g?B?phr9PGn$9AJY5EFSmy&iOE|&5hx!Mn#pR3Uv!a@LI&J zq%tWnka{am&*A6=$YGGjYr*d3Sw-X4NMtBtGVzjDiJAl2A4e#CMmP@VhMSHjs>7(a zfdOZ=4TBRCE(-4VD*z# zNh(HQII#jfxCV$lxmp3EqFpFWQeJ%0*)b-aH-jFBrw{!67eD=9C&%mW>RMmyLSDYx zGU~E7uF&UuYdh|S;_p39XKxz!cadt_e!P%;ys$X3Siq-{dv|Z`^R4UKlv5Y=z%1+@ zT=GtEO=+`E_iR4xW&D0Bn{tHE6v&R2E?+vlus*jxT%P;=8c3=`R_hG-OECfjW_3T= zPg;3$4PWj9S6>^G2@3&;uJJi?0}p3i9MniPY$iYC)9}bDkya|#i?t@ToG;`^)uxmI z_r0}0E>h|e=s%+8UN_JTpo+*G3h7{s9Xe-iEtO5{vi|YWHI_Q?EVjRYlif4BmPgLQ z>T!jYoavH1)lq^(R`gDUeRmf<6J}Q%sy+8#&5c}n90w1sFlQL~>ae)GKeyxYhIQVW zM5?;lHjhcXY#3p4MYAsa-w~oxgIO5BaN_eDxeR=1;b>>`X#JL;rw2bO&{FOs8Plo+ zQf{0b0zk%MrkFMoAZ0k}Ds99>YV=Jp#5QhU@|=Xv#ZCq6h2Y}~v{g#uI38C9Gd+1? zxC$ZScSMNwpty_b@C;hpXh@0M=J8`B9OfFjCdJSc8gY=zSpDkxRd9?B{(kH~FyAZa z!!CB+(RY0VCw3lF*H)a+s_dP(yBjiYQM>0QWGBDP}(GzkarYYh?rCjHA)TGl%*)e+wBj>RD%j*Ti5V^v7;VTf=%W*<20$3;%Gm3?J zlOzc}HNCV-5@Z{VVu{9@F&K@Sq!{pE=*Y_50dQfE$BVg|02I@OZaG4kq+6^}6Odaa z;N4*RBDFMvo&-k$qj$7n?r~y(mA!#SccmE@n(Z@r?@Sh0#npd5V}rQr{*_Z;0anYb zz`~^xqOu~w6uZvjY_q#uEr4TE@DPxe!51$Be#O$n3)lA2X5IF}@-CCWX`*d57l!%R z;Z1A22%siHc0@IfaJ7wULx_KQe-0;v-TgX#Eza%iPWOA+R(gyinvjheG#rglD}f(Z z3%R(^3`%2wi@24S(aVw?+yN%ORm_)T+8GQ&#w!ScAhd{^xTFlqd>kbqtJ4}S2Eu9) zHPqF&wY56f$(V^SokFQ1p{VxK9@-YxnE@;UGI@0sTW8mP9~wi;iw|FTcyS%OpWDha zB!GE}Lbj|Mt%P_5DQ1P#h&Nt)6 zYsY*Wlq$jrue!#I`b1^n@eAu%7ykc^KexUDqw85c*)LNf<(4b8e6%5CVw7xf)$xg> z*raWeD0qA$8NgeYsPr5XnuBhAl2m3C3Tu$i5M;Qi0Dw7Z4`kr zK!kKcI^5`V=&EaR--XjUGt{nXY&Is%i~`fK%C3X!7w)*w*N2}5O!7PSE8BU*qzLzm z9yTy#7d(}{$fQeYJThz@3r4@(_tSxYaOTE~*AMbuzc;R<<90e89S*r@q_1=~)la(+ zEhBjy1Z437yYMX*3+osDTd%;wtv-A1Szl&I4q(PF zEfa`Qs?cOepMfMn`inQ25X%Y`G9^c*!iZ|fOrsnrsy_+8CQ_?J^}@Qk`V&esWcS0T z?}tq7zBe1wRm3u|$%YjJCjVH|9;3N5W-KqF8E42=ZL`tE!E6Yj>*y#N ztOxrnIe#7d1ylY1H~-jeET0hs<)NYB3<->wMr?v`a!^22srWeQZiyRmb9_~VgtnxZ zBr{grX2{mH@*vO`$tGEHIO*o|2m&U-=gZ|nk@}=sWR#?o1kQS6Rr6_J>RN3;*PzMc zBv6-z;+amD_QO>FJ?>bWM}3RzT3*Lz%j-{%tx;YxlP(YX(_z*@+lpx_no6g!^|7(t zo9ve^!?7*w>ZZf~)w184&Fa9i)PaXVowqyB!=WO4s2U& z`}haeZNGrI%5t+oc4C7%nM}q<1xm<^LtwEd5X1$57p=~iK;qZCwI;ci-^7>mtuk&V z7AwRJG6fF0M#fVK|EZ!VJQA7~*Am03C)o*upc9*$){oeO`@BQBUy>GX__i|0_qxU@A z`VA0BaO}62r>6&Z{`>$Zf~e+$r#`s&q;ws83sR6>2q=JcnBErJd+5`V>8+qI`1Dl_ z*f{||eGb%Xgsqhn-L_CnHaWyFU0(N^YZFz~xnwL((xgBg6131ZdDYSl70^e|Z~^jp8?99- zf+o;bJW~dCD#F$h5hBYll9cI)w3yu^67@um1tC;_QQQT8bOYyu(^yQQB0NG5>GIQC zPle|QpnLVzPjSd)tqT9Q6S7TL@bj8eeFwdl;kI#8rmG>0H)Q1Re7XuZcm@DCo(4-) zj~klk^ma<#uG89G-MDeH1!KQC4FUD&;%Dp?JHEH)XYoB;e?Y|w1?$mx0Y#^vrX?fQ zqtl!*Xu9KTa-8C66UjQsg?C-g4=l?9&M7uW>frFAgi2F-(J;6HYLNs{iKeJYSgK9T zr8&iBscd$mg9nth#gMSt9-+@-G+Cmz;TXmYls`pZ%h~y@5ASUpD(BB{?BLwo)vkxQ z{~c{-YZvRC(#}XL4@2>2Yk4+Z{sKMp;mLPj;_rTIhz$nA<8XdJ8Bn^l9$qe|wKZ*M zr)Y?T(sp?YY4*jR&qA*K=dZv1_1Di2W9#AGANT_&9{xUB9FEa2D;Rn^D&PT(SI`_T zHwRsKZK@c>u2E#hT}PFfE5y=dJgz25lgiJefdM~=dr{z%JV;$?u5*CIL%bP=}=a;KtaNQrRra(og&9(q=AOpm(RTIf#V|n{_C_%XR z`Qbl*{R`#Sqn|GR{tGQ;5cB>T+WP@8eu3Yz{Y-O4xs;NQPnuA1Lh(UyLScZ?qQOwa z0OfT)Miyz3)77F%(O?+T_sbt};bLcGGDFtfT6E1_JCKFSmu+1pR;XDd5=H&d&L zcqs*s5a2dyVZHZYxI8*IJy?Eq=ZQC-1E+rZ%iS-ukIPsq*gLrU^_^YxnqS3XLR!)< zjR1|SRqICS?6Z$P`R0@BH~L$3q z7r*`S=bx`09o@e5+fP3}5N`eFyN@5e6>c8eKmBD|w2;NP$X{Zr8Rf50vTWwlF(xnB zU~CD#kkl#FQuRE*zI{lMvo@ut^-!PndX7}{r`J#6M}Toh_aw@% zzVPaE&mBGYI5a3vUHlztxc_+Y=--V$fsrJ4ep)WnisfZvYt#vXdL6<(I$bmisv-%D zO`uoOR%C@UY+)eKFGb^AnpTTNGuE`oLDW!r-t&??i;@h-`f`QGu5-`lG8y!gAF4DjR0kRMZr@qvaw;kP1C+&JGI({(3E~=Skg5 z+l(=;*n%2Mb_oflPMh5Ugn-#ZHkFOU3n9$0IjK`ACjmQXGaKY z?%etiQT62)UmxGRQG&TwtDS1Kj7Je+?8x+9Tn|rk2aOq>P6q)&38~61Dwp^k{;)O* zJ=(}&=JAcncCNjJ(q65f(`q%xA32bghorz0w{hKHeeRxVFYxE>7cMU^PoKb%W9!XO zzx>6szug{>Ay=llZ9bXL<5n}Vg22rXttxSvXdVs@JsIu-`&)a=O}WRIeOAR@%9G<+1wx4{g0&-FdHH#U3>@gCLH<8@TB09RkftxYpb7 zgIDWULwRX+jz;BNVN%KE_P6KPM-V9ew@y!C?>Of%_USGU4(@)t7#}T;76%6t*!x%C zo_~D6T#HeraN>K>sMl*-oJw9Jl>##`b(0Vj+6Kz2a*QWwb<7E~cH50c3rT{@>*z2{ z32KVryL8BNVwwp@Nlm_zVY8vZ1L{Yt?>iPhvCzC#^H$EvIreV`r@vof>p$LUVAe}( zRc^pi{mzbtG;F<&Q-1{M>mztD?S2ptRdBiZyc)p3N4K164UoBAV-P1rH}{BoW@BHh z?>!x^{mnW?=P8r9+^~Eg%OYF{;TkuWFQKb;arVbwf#tdjkW<{@?Ci&jPY)Kcq9CPa zi8c~5j`P4srf6N^lAK&Y=4Oz#>n16~hO(P#Mp>av%5BC-n+j!CKzD$++Cgh>D{SRyg&fsye_-o(ZbBW_DpxnJS7GpF$SF{| zz&pR#`Mrf_xe%OUVaRhCugtu>D?(az72qkNBO8GuRhQ;_Jm#T_Vou!KM1?a zH;}Z!WLJ~c)L#r2i_vl<24F1Ce|qEHJ70h}L_=G@-$DK{*N|?n=N{X{E8&lBJ-WO3 zc7N+JaZ7_veib;Hd!<&p;y7Zb-`^CsH|n_^dMTx2e32K}!R{H+()Oe}DPz-F6(zYjeEdl^$kpscN30$e0ZZPK^~6 z@a)21aOfL4MX8(_L);S?FwL1ODAyz!t>e1dmQB_~>PrhsC6$%3y`CZa_C!HYlj-O7 zYAlE_ZwklO3be)u*wn%}-%o%1;KOG>Z2-A%0LXTyqsAy0l}BQ~ysm9uspFZ7^7>Wa zeHf(y=5WzR>)Ya^b@3r>Tg-@&TneEb7&2$F?ztd$!MF?VcLq``uvZ}K%uAEWVm=8-l#|wg*Yin&Mq?daA$SEE=()TW4@=J343&{s#}A~& zy*URCu(wlNIhug%?Y9r#ci$gU9pz58+YW^{pz9 zZY7Gl;GH&iVC$Rv;W$jhii(&KuB2Fz&y3g&tlUOve}6yq{A99x#-A0erWN?hMH2=O zg_kWi7nUx&NYavwKpFn{`?E3K_GDfj$B9^)_GgwW@LW3S@j8*`p?5L~({!i&6CNl3^kx<8S0G8(+tSyD5tbJO3o%3)HK>lmIX^kWjQ-;rVwesJ@p$Sr{@hV z%UL!cL74`~C*M6EPMzbDgj5SI`8q~-Yfwf$(g(5i8s3lYzo*sj7eVH?MlH+Hq$^@) zd*oo-`?>u(n9pr7ThHw5Z{*P2WP%Epn7zzC5Z;-%!D0f7p9PDtbvTADbul*l1@8Dj zE)-0@?dyUfnZ7Rw7G&y#AMd$QQgta$p4f8CZO0-M4JEUU!c(!yH3x<+I|2h>i^i@+ zT+e_JA!ubN5*2xp(IpTWN=%_BHu1_N5*bj2HJ{AUNvCzfn5SV4{YFsr8h!9aD25!I zfB4~#A0Hq0!)~_Px`&X|Z(Q;EAl2AXsfM=t{^pKWeOj!C>WY@^^u6`|_KV`))4e(l zoXPPWB#C^*scndxn|pxwM7GNoC`rhyIlW%n_bssOiohEK|73h}B+H9yNnQ!8=FIYK zo}keY>bgwNx5m~$kldcsW?WTJx?IJkRLbNqx}i&OwhrqVOhDe|i*YVmk-PFtYQqtN zsRY(jN>>$BicC^0#8Ujk=sv>}1S`D~N#IXuUYX2&WNniMme+Dtojzn{%ex=k`gU=1 zQR7>UPNy^ywd*Sw{Q7IJq1_M*I#Iy;I$lq|TGcQKM%+U6w!B%@#Lj#)8cCyQB1ejQ z<0=pyA=MngBL?Tx_xBPKV@$?lO844|tEdJ#95GGokSom0@R^4q9CKkjwr$oX;+*Tc zV>Vjwe2Dv8zg|=2gE+Mq>V7e z9;mk4uf5ja-0EW(hSq3iOrGjA_@**rT$s~2i$z~T`8hdku`i&%`+tj|qYpaNs3l z(WE3PNLyzzqY|?w*-Yk(BnS+l;M+akgwiz&}U@7Q?QWT}=tit7$bRukmqULN90$RTVB`UY5qa*s9xR2McYi$hM&i~E4prOsJ0oRM5gWb! zQ1qOtr-hFfR2!YGRJDUlESQc&shUf?oQXV?%E61XsZ=(D>ZVuQ$Pl@DCYS3}x*&^y zJM3PD@dR`XFrEk5`Qga{R2*cIv7&83m>HB2c6}FJANu7&P#6pONbwbD9nxxEiI{Vl z7u+_vM)6UBJ0y}S?z#}|mG31xwKz`?j_4Pw@qY7=BM-ELyZUMi9&72RN?G;3QrPtGA&PU8d(y&|)MAk$G2 zF+6AH2b4AI>M=3~^(Xq~6nM;J3^NU4#U#yBf=#FbB(Efcep*U5Q{z;HsnF0&xILnB z)?9{Kai1NHY8`3R8_mzgH-jTopT219=YVIuvM81T@uNBb3_)2AacXTlA?|fHLt0Y| z|1&4To!7TSQ9~gohkvqr8{sUpST04Z3E?MSsjv)~;l%SE%AMB))~o3 z)-nhtN)A!?Ry~2|^dzmsd$qZg%T+p(S7n_lsLhc!!jPY^bej}wUO9s?{<#_gyfu@Ev4vb2#*4xizdX^%)ETV1Nvd5URB1~u=FVlvTqmOFeA;7=$78UE*t=saXJmvTiqJp-X$Z}_G!jXXl|a!J2(nN{ZxIp&$jvK3 z;@@(d1q$v<#(BRM?|Uh~`ugQ-WGQePH-yKC`)cBbLf^fISFq3S zKKb~=4-wF-xI`MU_3CgJsn2;9l{m9`KA?=uuAhGWvic(eA{ z4`~#gyc>2eEpbw8IVmg==ii33iFD+kj^Yg`d3-Q#vqmp}e0=(H_@SvDpK*!$c>nNz zh8t7-^2he~@1MVTzxd?-^ZK(-KF2L+K8nAEJ|jgTPi1$X!kb@bHU56T5I%#fe+YxN ze}fpf`?`4fVe`@)p0^vm(S?l*Nc1>rV;*pQAlqKjJ~}=cGdbp4pYt>NuH3f?lZb%J z3e^rg{5tCZRIa%~A{qg|47p`BCO^PkhIAV!b;IiESt99qq_zzp4`Fn9x+I zBp)J%|3%MQVoz1N9iH|?NGqt`pi0c2t2CyjE{`v@c}e;G;qcStx9#)OSMMG_e;41Y z_?!aJx8HvI?pG-IVfUZjEr6Gsqd(l;;u_Fv4Bvc%d&OsqmaXa)%H-@NTiLJc`h^yX z zdbo>>9#4yxG~&4x-VdcTG>^dWq?!z+~;V$UdQhi!-Wo9r-Q9N z|K=NP$SRHs1XK|(zomaMvVy;bXh;#`Js$4{{v)cqyEvoHw#p{)x^MRVunsPlEZ@E9 zFYA-s zxqI)E?-n7i@38^cgazBb&$zCSXoK*jpab>QT)(qU@V(=;y3OG+0&9J{2~IX|hm(b2=8MRE(@kPy}(F2o+qxmnupIO&6Evx6WT-~E0yI-hH7RWf#`y1iEx%+g9`5Vta1?`uUU<6zYuh;Qnw5~VD zto}61ZeB+&*%U>gNfbp$sFR6`JO#aXsdYq-Y3}n&yM7Z`+f`MUKW%@!ti^K@#UVJG zd$TJ@KTW}Cn>_EDB%=92g^=?#@x2(V?a{bJt(hvK8|l!YCqxG+o#*SOqq2n`8_C#^ z4;>_iYzXHdSUf-k8$u!~j`N(YNKKE$0v*5S<3qDRN2wL5&ft9CKeZ5|dgpws_GGhEoPujA;bY?P0 zZOf`I?(He@e!n3ifBW@f{vaML1N{f7;7 ziu|@ui+gm|85j+;48AnRtTg-zS3hK*!o#nYEite>Rtwt^)DZ}@i6V68*a|$x<0BDV zD99Y8)(Xb#X~LXVhQO?)v>;4*-(8}^o^>6rR$O+;d8kTBtvh(p(H(JvGlw~Q+*Kay zpAtnFE=CM*8YKNKKSM1g`nKiL#g(?2vVv4mCq_x7c0nPuP$rzfJkljq|3+{wMhA^0 zR+54ja3C)!jpGP@B~QasTGUH$-!1GOfnkM5gkiDct3lu5qBbToc(2G_zvfuP$7MHT zQDC6Q@vCKS!U)WAVxfGeDMElF6s5C>b!j347WJPp4L##x_sSWaw>=dHvAUeeFD*#TiIR&DsL3(3mJNkic0@xc9BCP=5XOSI@|Z z1-2^QC4PhylQ=sG`=)l0<~(4#4v;J3P}2B4BE;?U{%i)FwrpnE^-Z%oWV4$NIiZTU z&@wtp>ilk3@`85~6`Y0?Zo@sEqi*DS7+f@~s9 zSLGu2uvK=2-7Uk6C+y)qzQ5@}nSxFNpbL@RUBMO}ixH>Tg48uiC8|`jF%#p81veQ= zly8F*mhhd=&zr;g@K?8f6ts|?SNxE_iTB^x}tLrx2Nn-?w(nPdEFv24!tyhdyL9o1I!nP5lXY@qM1v-L~$JEeG z_gEYe#4cOvk*mm#6tEV-$5kf8Gr}8|&8DW=JexV2R|Vb!cDPn+3X3?BxQpllT}LDV z+xf^Wfy;6ygya(LzzK&mWm)UhroXh@SImMK3N5yWzKPQ`MGbS8&BTo6Rz~5lgYwP3 zP>uI|Pu>hxczy3zm2$9i6GdZV?d)bpgo`&X#p8bDD}0 zGTU)!Rx6#+Xk71_$RNwnhlSV=={@?IMdmQTOtGl-t#FA;TECjjU_ig5bOWOnLuO`C zj%@Ka>f1;(xnG*`nM#KjmTJ9pFG-Mur*HTBU@hl)*Qtn%p;f!C+%9rZU&pB36Qhl2 z0LQJX)=zBvsqfOOHWdCK0&~s`X4+a zNklAA1HZ9x1a~BoX4y*>(He=2KESRI_Bv zO}HKBfU|~1NdihUCL=0k#h8%77zwQrl12#Q{_^JW(F@;oETrH-dx|2%(abf%0mW$M zGF|6P(wX=rE%oc6iCWo`wr3Z;-66M`XrevpqH7eWmO5(k#L3x6m^)4qE*C@z)$WxF z%0pkfrh&q=*4oqy5W{FJ*Tii^Gl6glYr2S*)gb z^9Ehqju71?)@5)}Btw#%#!)6nZcY(!KRD?GZ)~^gd7CUxwP;W-tO|m(QahFo+olkj zGCI{=!nt%aBP6MsCK+r;c+dY7jhqT*g{sf9OXjP)LzZMNrU?AmOok{)4T)@`fHPF8 zYV+0-+aby<#Lh|0C>BfQ0=-t0E72ttv?2#Z$@KVo0|dptBKom z3v>mj3&VgIcXeKGY-ArdDSJIV?6g2^iZ%4%VmXac@YcUt}E&?3f9K0 z9+)o-D-v9cT(8O7OUS2Z&fvD?`w=rFIr0@!YQ~hj(km5AU#FD`-cHlR6pAJrN#1*} z+JZo77-Viz3k2%SVodA*pwF++VgEq~?8UHjvK%5n7q8GU0ev;L%(g%WLipA?Bw4Hw z!pm@GA_igJiefrmwn?8Scz<7YjdHFT1|^ZdRYzhwN$%s!nXaj>lhKTkP50uNKUz`_ z{!H?<8-jl>wpCP_2X@s7ul=1t+Qi0B*20g5GBHuRH11wN-58oBMIr))cUG#Uw0d2u z`zJ!pe1nb+_&;>0Hvlh~WdzNH0eT^D{vYW2)$6zE3=|&FC36;D4?#+8*sSR^P7~fI z_+~>o%D_4#@y?E_^IWw|AQ)}L3f4NP6D2L3qeA6L6wQ-zqvs;`)+V$kz6x8Nzljo= zEv2uGI;;Soslz8{ji84Uu~NA#lzD|%55#d5>;gTYRj>}wDOU84*TW3_sBf;>40#I~ zeT7~da9A(U$zqNWetQMS3!J~117wY-SdPGX#0VD#w?KEV(5ap*1y$hfA|6kHB|t8^ zG4Y)ejZa#pFmG#_pbj#j?K}x8xe!80F+=6mx!JS{8wgvIzf__p8koI;Ac8$$)sn5Q z8nhzwJn67xcq5pCi-oW~bd$9qEHyk7sC5pkkEH$=Ix_~CF$qSqKwr$*8pyF^0u!&$ zg?)uyup3^Oi(a8Kz1Yp`k#r2uCH}qtpo1J@C{ryF3?$__SN_~C#jYPJB?wb3!3>O9 s>SmKTFz#xX%2+j_#T4;&ea^-9Z+8#z7el$et^fc407*qoM6N<$f?|Tx;{X5v literal 0 HcmV?d00001 diff --git a/taskman-server/vendor/github.com/go-playground/locales/rules.go b/taskman-server/vendor/github.com/go-playground/locales/rules.go new file mode 100644 index 00000000..92029001 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/locales/rules.go @@ -0,0 +1,293 @@ +package locales + +import ( + "strconv" + "time" + + "github.com/go-playground/locales/currency" +) + +// // ErrBadNumberValue is returned when the number passed for +// // plural rule determination cannot be parsed +// type ErrBadNumberValue struct { +// NumberValue string +// InnerError error +// } + +// // Error returns ErrBadNumberValue error string +// func (e *ErrBadNumberValue) Error() string { +// return fmt.Sprintf("Invalid Number Value '%s' %s", e.NumberValue, e.InnerError) +// } + +// var _ error = new(ErrBadNumberValue) + +// PluralRule denotes the type of plural rules +type PluralRule int + +// PluralRule's +const ( + PluralRuleUnknown PluralRule = iota + PluralRuleZero // zero + PluralRuleOne // one - singular + PluralRuleTwo // two - dual + PluralRuleFew // few - paucal + PluralRuleMany // many - also used for fractions if they have a separate class + PluralRuleOther // other - required—general plural form—also used if the language only has a single form +) + +const ( + pluralsString = "UnknownZeroOneTwoFewManyOther" +) + +// Translator encapsulates an instance of a locale +// NOTE: some values are returned as a []byte just in case the caller +// wishes to add more and can help avoid allocations; otherwise just cast as string +type Translator interface { + + // The following Functions are for overriding, debugging or developing + // with a Translator Locale + + // Locale returns the string value of the translator + Locale() string + + // returns an array of cardinal plural rules associated + // with this translator + PluralsCardinal() []PluralRule + + // returns an array of ordinal plural rules associated + // with this translator + PluralsOrdinal() []PluralRule + + // returns an array of range plural rules associated + // with this translator + PluralsRange() []PluralRule + + // returns the cardinal PluralRule given 'num' and digits/precision of 'v' for locale + CardinalPluralRule(num float64, v uint64) PluralRule + + // returns the ordinal PluralRule given 'num' and digits/precision of 'v' for locale + OrdinalPluralRule(num float64, v uint64) PluralRule + + // returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for locale + RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) PluralRule + + // returns the locales abbreviated month given the 'month' provided + MonthAbbreviated(month time.Month) string + + // returns the locales abbreviated months + MonthsAbbreviated() []string + + // returns the locales narrow month given the 'month' provided + MonthNarrow(month time.Month) string + + // returns the locales narrow months + MonthsNarrow() []string + + // returns the locales wide month given the 'month' provided + MonthWide(month time.Month) string + + // returns the locales wide months + MonthsWide() []string + + // returns the locales abbreviated weekday given the 'weekday' provided + WeekdayAbbreviated(weekday time.Weekday) string + + // returns the locales abbreviated weekdays + WeekdaysAbbreviated() []string + + // returns the locales narrow weekday given the 'weekday' provided + WeekdayNarrow(weekday time.Weekday) string + + // WeekdaysNarrowreturns the locales narrow weekdays + WeekdaysNarrow() []string + + // returns the locales short weekday given the 'weekday' provided + WeekdayShort(weekday time.Weekday) string + + // returns the locales short weekdays + WeekdaysShort() []string + + // returns the locales wide weekday given the 'weekday' provided + WeekdayWide(weekday time.Weekday) string + + // returns the locales wide weekdays + WeekdaysWide() []string + + // The following Functions are common Formatting functionsfor the Translator's Locale + + // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' + FmtNumber(num float64, v uint64) string + + // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' + // NOTE: 'num' passed into FmtPercent is assumed to be in percent already + FmtPercent(num float64, v uint64) string + + // returns the currency representation of 'num' with digits/precision of 'v' for locale + FmtCurrency(num float64, v uint64, currency currency.Type) string + + // returns the currency representation of 'num' with digits/precision of 'v' for locale + // in accounting notation. + FmtAccounting(num float64, v uint64, currency currency.Type) string + + // returns the short date representation of 't' for locale + FmtDateShort(t time.Time) string + + // returns the medium date representation of 't' for locale + FmtDateMedium(t time.Time) string + + // returns the long date representation of 't' for locale + FmtDateLong(t time.Time) string + + // returns the full date representation of 't' for locale + FmtDateFull(t time.Time) string + + // returns the short time representation of 't' for locale + FmtTimeShort(t time.Time) string + + // returns the medium time representation of 't' for locale + FmtTimeMedium(t time.Time) string + + // returns the long time representation of 't' for locale + FmtTimeLong(t time.Time) string + + // returns the full time representation of 't' for locale + FmtTimeFull(t time.Time) string +} + +// String returns the string value of PluralRule +func (p PluralRule) String() string { + + switch p { + case PluralRuleZero: + return pluralsString[7:11] + case PluralRuleOne: + return pluralsString[11:14] + case PluralRuleTwo: + return pluralsString[14:17] + case PluralRuleFew: + return pluralsString[17:20] + case PluralRuleMany: + return pluralsString[20:24] + case PluralRuleOther: + return pluralsString[24:] + default: + return pluralsString[:7] + } +} + +// +// Precision Notes: +// +// must specify a precision >= 0, and here is why https://play.golang.org/p/LyL90U0Vyh +// +// v := float64(3.141) +// i := float64(int64(v)) +// +// fmt.Println(v - i) +// +// or +// +// s := strconv.FormatFloat(v-i, 'f', -1, 64) +// fmt.Println(s) +// +// these will not print what you'd expect: 0.14100000000000001 +// and so this library requires a precision to be specified, or +// inaccurate plural rules could be applied. +// +// +// +// n - absolute value of the source number (integer and decimals). +// i - integer digits of n. +// v - number of visible fraction digits in n, with trailing zeros. +// w - number of visible fraction digits in n, without trailing zeros. +// f - visible fractional digits in n, with trailing zeros. +// t - visible fractional digits in n, without trailing zeros. +// +// +// Func(num float64, v uint64) // v = digits/precision and prevents -1 as a special case as this can lead to very unexpected behaviour, see precision note's above. +// +// n := math.Abs(num) +// i := int64(n) +// v := v +// +// +// w := strconv.FormatFloat(num-float64(i), 'f', int(v), 64) // then parse backwards on string until no more zero's.... +// f := strconv.FormatFloat(n, 'f', int(v), 64) // then turn everything after decimal into an int64 +// t := strconv.FormatFloat(n, 'f', int(v), 64) // then parse backwards on string until no more zero's.... +// +// +// +// General Inclusion Rules +// - v will always be available inherently +// - all require n +// - w requires i +// + +// W returns the number of visible fraction digits in N, without trailing zeros. +func W(n float64, v uint64) (w int64) { + + s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) + + // with either be '0' or '0.xxxx', so if 1 then w will be zero + // otherwise need to parse + if len(s) != 1 { + + s = s[2:] + end := len(s) + 1 + + for i := end; i >= 0; i-- { + if s[i] != '0' { + end = i + 1 + break + } + } + + w = int64(len(s[:end])) + } + + return +} + +// F returns the visible fractional digits in N, with trailing zeros. +func F(n float64, v uint64) (f int64) { + + s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) + + // with either be '0' or '0.xxxx', so if 1 then f will be zero + // otherwise need to parse + if len(s) != 1 { + + // ignoring error, because it can't fail as we generated + // the string internally from a real number + f, _ = strconv.ParseInt(s[2:], 10, 64) + } + + return +} + +// T returns the visible fractional digits in N, without trailing zeros. +func T(n float64, v uint64) (t int64) { + + s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) + + // with either be '0' or '0.xxxx', so if 1 then t will be zero + // otherwise need to parse + if len(s) != 1 { + + s = s[2:] + end := len(s) + 1 + + for i := end; i >= 0; i-- { + if s[i] != '0' { + end = i + 1 + break + } + } + + // ignoring error, because it can't fail as we generated + // the string internally from a real number + t, _ = strconv.ParseInt(s[:end], 10, 64) + } + + return +} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/.gitignore b/taskman-server/vendor/github.com/go-playground/universal-translator/.gitignore new file mode 100644 index 00000000..bc4e07f3 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/universal-translator/.gitignore @@ -0,0 +1,25 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof +*.coverprofile \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/.travis.yml b/taskman-server/vendor/github.com/go-playground/universal-translator/.travis.yml new file mode 100644 index 00000000..39b8b923 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/universal-translator/.travis.yml @@ -0,0 +1,27 @@ +language: go +go: + - 1.13.4 + - tip +matrix: + allow_failures: + - go: tip + +notifications: + email: + recipients: dean.karn@gmail.com + on_success: change + on_failure: always + +before_install: + - go install github.com/mattn/goveralls + +# Only clone the most recent commit. +git: + depth: 1 + +script: + - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... + +after_success: | + [ $TRAVIS_GO_VERSION = 1.13.4 ] && + goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/LICENSE b/taskman-server/vendor/github.com/go-playground/universal-translator/LICENSE new file mode 100644 index 00000000..8d8aba15 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/universal-translator/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Go Playground + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/README.md b/taskman-server/vendor/github.com/go-playground/universal-translator/README.md new file mode 100644 index 00000000..071f33ab --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/universal-translator/README.md @@ -0,0 +1,89 @@ +## universal-translator +![Project status](https://img.shields.io/badge/version-0.17.0-green.svg) +[![Build Status](https://travis-ci.org/go-playground/universal-translator.svg?branch=master)](https://travis-ci.org/go-playground/universal-translator) +[![Coverage Status](https://coveralls.io/repos/github/go-playground/universal-translator/badge.svg)](https://coveralls.io/github/go-playground/universal-translator) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/universal-translator)](https://goreportcard.com/report/github.com/go-playground/universal-translator) +[![GoDoc](https://godoc.org/github.com/go-playground/universal-translator?status.svg)](https://godoc.org/github.com/go-playground/universal-translator) +![License](https://img.shields.io/dub/l/vibe-d.svg) +[![Gitter](https://badges.gitter.im/go-playground/universal-translator.svg)](https://gitter.im/go-playground/universal-translator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Universal Translator is an i18n Translator for Go/Golang using CLDR data + pluralization rules + +Why another i18n library? +-------------------------- +Because none of the plural rules seem to be correct out there, including the previous implementation of this package, +so I took it upon myself to create [locales](https://github.com/go-playground/locales) for everyone to use; this package +is a thin wrapper around [locales](https://github.com/go-playground/locales) in order to store and translate text for +use in your applications. + +Features +-------- +- [x] Rules generated from the [CLDR](http://cldr.unicode.org/index/downloads) data, v30.0.3 +- [x] Contains Cardinal, Ordinal and Range Plural Rules +- [x] Contains Month, Weekday and Timezone translations built in +- [x] Contains Date & Time formatting functions +- [x] Contains Number, Currency, Accounting and Percent formatting functions +- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) +- [x] Support loading translations from files +- [x] Exporting translations to file(s), mainly for getting them professionally translated +- [ ] Code Generation for translation files -> Go code.. i.e. after it has been professionally translated +- [ ] Tests for all languages, I need help with this, please see [here](https://github.com/go-playground/locales/issues/1) + +Installation +----------- + +Use go get + +```shell +go get github.com/go-playground/universal-translator +``` + +Usage & Documentation +------- + +Please see https://godoc.org/github.com/go-playground/universal-translator for usage docs + +##### Examples: + +- [Basic](https://github.com/go-playground/universal-translator/tree/master/_examples/basic) +- [Full - no files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-no-files) +- [Full - with files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-with-files) + +File formatting +-------------- +All types, Plain substitution, Cardinal, Ordinal and Range translations can all be contained withing the same file(s); +they are only separated for easy viewing. + +##### Examples: + +- [Formats](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) + +##### Basic Makeup +NOTE: not all fields are needed for all translation types, see [examples](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) +```json +{ + "locale": "en", + "key": "days-left", + "trans": "You have {0} day left.", + "type": "Cardinal", + "rule": "One", + "override": false +} +``` +|Field|Description| +|---|---| +|locale|The locale for which the translation is for.| +|key|The translation key that will be used to store and lookup each translation; normally it is a string or integer.| +|trans|The actual translation text.| +|type|The type of translation Cardinal, Ordinal, Range or "" for a plain substitution(not required to be defined if plain used)| +|rule|The plural rule for which the translation is for eg. One, Two, Few, Many or Other.(not required to be defined if plain used)| +|override|If you wish to override an existing translation that has already been registered, set this to 'true'. 99% of the time there is no need to define it.| + +Help With Tests +--------------- +To anyone interesting in helping or contributing, I sure could use some help creating tests for each language. +Please see issue [here](https://github.com/go-playground/locales/issues/1) for details. + +License +------ +Distributed under MIT License, please see license file in code for more details. diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/errors.go b/taskman-server/vendor/github.com/go-playground/universal-translator/errors.go new file mode 100644 index 00000000..38b163b6 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/universal-translator/errors.go @@ -0,0 +1,148 @@ +package ut + +import ( + "errors" + "fmt" + + "github.com/go-playground/locales" +) + +var ( + // ErrUnknowTranslation indicates the translation could not be found + ErrUnknowTranslation = errors.New("Unknown Translation") +) + +var _ error = new(ErrConflictingTranslation) +var _ error = new(ErrRangeTranslation) +var _ error = new(ErrOrdinalTranslation) +var _ error = new(ErrCardinalTranslation) +var _ error = new(ErrMissingPluralTranslation) +var _ error = new(ErrExistingTranslator) + +// ErrExistingTranslator is the error representing a conflicting translator +type ErrExistingTranslator struct { + locale string +} + +// Error returns ErrExistingTranslator's internal error text +func (e *ErrExistingTranslator) Error() string { + return fmt.Sprintf("error: conflicting translator for locale '%s'", e.locale) +} + +// ErrConflictingTranslation is the error representing a conflicting translation +type ErrConflictingTranslation struct { + locale string + key interface{} + rule locales.PluralRule + text string +} + +// Error returns ErrConflictingTranslation's internal error text +func (e *ErrConflictingTranslation) Error() string { + + if _, ok := e.key.(string); !ok { + return fmt.Sprintf("error: conflicting key '%#v' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) + } + + return fmt.Sprintf("error: conflicting key '%s' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) +} + +// ErrRangeTranslation is the error representing a range translation error +type ErrRangeTranslation struct { + text string +} + +// Error returns ErrRangeTranslation's internal error text +func (e *ErrRangeTranslation) Error() string { + return e.text +} + +// ErrOrdinalTranslation is the error representing an ordinal translation error +type ErrOrdinalTranslation struct { + text string +} + +// Error returns ErrOrdinalTranslation's internal error text +func (e *ErrOrdinalTranslation) Error() string { + return e.text +} + +// ErrCardinalTranslation is the error representing a cardinal translation error +type ErrCardinalTranslation struct { + text string +} + +// Error returns ErrCardinalTranslation's internal error text +func (e *ErrCardinalTranslation) Error() string { + return e.text +} + +// ErrMissingPluralTranslation is the error signifying a missing translation given +// the locales plural rules. +type ErrMissingPluralTranslation struct { + locale string + key interface{} + rule locales.PluralRule + translationType string +} + +// Error returns ErrMissingPluralTranslation's internal error text +func (e *ErrMissingPluralTranslation) Error() string { + + if _, ok := e.key.(string); !ok { + return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%#v' and locale '%s'", e.translationType, e.rule, e.key, e.locale) + } + + return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%s' and locale '%s'", e.translationType, e.rule, e.key, e.locale) +} + +// ErrMissingBracket is the error representing a missing bracket in a translation +// eg. This is a {0 <-- missing ending '}' +type ErrMissingBracket struct { + locale string + key interface{} + text string +} + +// Error returns ErrMissingBracket error message +func (e *ErrMissingBracket) Error() string { + return fmt.Sprintf("error: missing bracket '{}', in translation. locale: '%s' key: '%v' text: '%s'", e.locale, e.key, e.text) +} + +// ErrBadParamSyntax is the error representing a bad parameter definition in a translation +// eg. This is a {must-be-int} +type ErrBadParamSyntax struct { + locale string + param string + key interface{} + text string +} + +// Error returns ErrBadParamSyntax error message +func (e *ErrBadParamSyntax) Error() string { + return fmt.Sprintf("error: bad parameter syntax, missing parameter '%s' in translation. locale: '%s' key: '%v' text: '%s'", e.param, e.locale, e.key, e.text) +} + +// import/export errors + +// ErrMissingLocale is the error representing an expected locale that could +// not be found aka locale not registered with the UniversalTranslator Instance +type ErrMissingLocale struct { + locale string +} + +// Error returns ErrMissingLocale's internal error text +func (e *ErrMissingLocale) Error() string { + return fmt.Sprintf("error: locale '%s' not registered.", e.locale) +} + +// ErrBadPluralDefinition is the error representing an incorrect plural definition +// usually found within translations defined within files during the import process. +type ErrBadPluralDefinition struct { + tl translation +} + +// Error returns ErrBadPluralDefinition's internal error text +func (e *ErrBadPluralDefinition) Error() string { + return fmt.Sprintf("error: bad plural definition '%#v'", e.tl) +} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/import_export.go b/taskman-server/vendor/github.com/go-playground/universal-translator/import_export.go new file mode 100644 index 00000000..7bd76f26 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/universal-translator/import_export.go @@ -0,0 +1,274 @@ +package ut + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" + "path/filepath" + + "io" + + "github.com/go-playground/locales" +) + +type translation struct { + Locale string `json:"locale"` + Key interface{} `json:"key"` // either string or integer + Translation string `json:"trans"` + PluralType string `json:"type,omitempty"` + PluralRule string `json:"rule,omitempty"` + OverrideExisting bool `json:"override,omitempty"` +} + +const ( + cardinalType = "Cardinal" + ordinalType = "Ordinal" + rangeType = "Range" +) + +// ImportExportFormat is the format of the file import or export +type ImportExportFormat uint8 + +// supported Export Formats +const ( + FormatJSON ImportExportFormat = iota +) + +// Export writes the translations out to a file on disk. +// +// NOTE: this currently only works with string or int translations keys. +func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) error { + + _, err := os.Stat(dirname) + fmt.Println(dirname, err, os.IsNotExist(err)) + if err != nil { + + if !os.IsNotExist(err) { + return err + } + + if err = os.MkdirAll(dirname, 0744); err != nil { + return err + } + } + + // build up translations + var trans []translation + var b []byte + var ext string + + for _, locale := range t.translators { + + for k, v := range locale.(*translator).translations { + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k, + Translation: v.text, + }) + } + + for k, pluralTrans := range locale.(*translator).cardinalTanslations { + + for i, plural := range pluralTrans { + + // leave enough for all plural rules + // but not all are set for all languages. + if plural == nil { + continue + } + + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k.(string), + Translation: plural.text, + PluralType: cardinalType, + PluralRule: locales.PluralRule(i).String(), + }) + } + } + + for k, pluralTrans := range locale.(*translator).ordinalTanslations { + + for i, plural := range pluralTrans { + + // leave enough for all plural rules + // but not all are set for all languages. + if plural == nil { + continue + } + + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k.(string), + Translation: plural.text, + PluralType: ordinalType, + PluralRule: locales.PluralRule(i).String(), + }) + } + } + + for k, pluralTrans := range locale.(*translator).rangeTanslations { + + for i, plural := range pluralTrans { + + // leave enough for all plural rules + // but not all are set for all languages. + if plural == nil { + continue + } + + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k.(string), + Translation: plural.text, + PluralType: rangeType, + PluralRule: locales.PluralRule(i).String(), + }) + } + } + + switch format { + case FormatJSON: + b, err = json.MarshalIndent(trans, "", " ") + ext = ".json" + } + + if err != nil { + return err + } + + err = ioutil.WriteFile(filepath.Join(dirname, fmt.Sprintf("%s%s", locale.Locale(), ext)), b, 0644) + if err != nil { + return err + } + + trans = trans[0:0] + } + + return nil +} + +// Import reads the translations out of a file or directory on disk. +// +// NOTE: this currently only works with string or int translations keys. +func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilename string) error { + + fi, err := os.Stat(dirnameOrFilename) + if err != nil { + return err + } + + processFn := func(filename string) error { + + f, err := os.Open(filename) + if err != nil { + return err + } + defer f.Close() + + return t.ImportByReader(format, f) + } + + if !fi.IsDir() { + return processFn(dirnameOrFilename) + } + + // recursively go through directory + walker := func(path string, info os.FileInfo, err error) error { + + if info.IsDir() { + return nil + } + + switch format { + case FormatJSON: + // skip non JSON files + if filepath.Ext(info.Name()) != ".json" { + return nil + } + } + + return processFn(path) + } + + return filepath.Walk(dirnameOrFilename, walker) +} + +// ImportByReader imports the the translations found within the contents read from the supplied reader. +// +// NOTE: generally used when assets have been embedded into the binary and are already in memory. +func (t *UniversalTranslator) ImportByReader(format ImportExportFormat, reader io.Reader) error { + + b, err := ioutil.ReadAll(reader) + if err != nil { + return err + } + + var trans []translation + + switch format { + case FormatJSON: + err = json.Unmarshal(b, &trans) + } + + if err != nil { + return err + } + + for _, tl := range trans { + + locale, found := t.FindTranslator(tl.Locale) + if !found { + return &ErrMissingLocale{locale: tl.Locale} + } + + pr := stringToPR(tl.PluralRule) + + if pr == locales.PluralRuleUnknown { + + err = locale.Add(tl.Key, tl.Translation, tl.OverrideExisting) + if err != nil { + return err + } + + continue + } + + switch tl.PluralType { + case cardinalType: + err = locale.AddCardinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) + case ordinalType: + err = locale.AddOrdinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) + case rangeType: + err = locale.AddRange(tl.Key, tl.Translation, pr, tl.OverrideExisting) + default: + return &ErrBadPluralDefinition{tl: tl} + } + + if err != nil { + return err + } + } + + return nil +} + +func stringToPR(s string) locales.PluralRule { + + switch s { + case "One": + return locales.PluralRuleOne + case "Two": + return locales.PluralRuleTwo + case "Few": + return locales.PluralRuleFew + case "Many": + return locales.PluralRuleMany + case "Other": + return locales.PluralRuleOther + default: + return locales.PluralRuleUnknown + } + +} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/logo.png b/taskman-server/vendor/github.com/go-playground/universal-translator/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..a37aa8c0cd0f6e1b98e0be3eb2531ebc6ac6717b GIT binary patch literal 16598 zcmV(yK*U_<=i=1Q$^7;0v#+eDrK0%p z>%6(N%f`XBv#;pk-N3xJlaY`9`tZ@r#>d0H&B?^Dtf>F`_3`TEoSK)csHK;dl)1LD z{xUb9o}0zMyZALSjf{%1BqI0!{{5jc`1SO`zPq8KpwB5MBz`@`DJHxnB>jUjr=XpP zhJ*ceGX0V>qah&tt}xmxDK3XPA9F;SA|8N$duRs?{%JJ*T{HG>5AcL8I*&O1Ju^KN z1^!Yp@h&apFDzno38}29au*Y6VF#%(B=Pd^`t{{04g#CPRH8PEL>89OH1Y4=wM`?Y+cnsCD|dZGb#-yb zPbYsY6v#U#TTlf1)HKmxCR88|TWkfi;WgJmEa>U!iH1CPzc%zlFUrZIxOpL50SAW2 zHrkRe-Bv8!+}rP-U23*Bp`mB-jzz%dHuKoF($TRq)t%&MEAPFIet}u?$D-;-NTfd? zqGBFudL7@{$H>RCmXS~SDk-e2cr(q3b}2D4;I^fdk8wf@!NHcex`pmIGxX}ykX2Zk zP#l(MXu)GF(Pvk zb5n$3uu@QfLrR3XE#bH{zmF;My}ImfZ|eE@n0GU+i65iC#kVv_JUkHP6q^ z=b4$1KRnawHnN9;XOVD+dTcU@PWtQI+{V7)vVb@}2{~W|d768ob{*KawLyATCMyBY zhk?3y?SQh*YZ(!U#KDNg9qaM-(p?CZPE$X(8z(y`Rk002FaNkl8uC7fajE|-h>jHG2b9lbevz(KOfu`z+X2)PND2t1w1WGFmB z;BZ@Tf}w8eW!d6lVUNJlhe<3w@VLAr5!hqYo=(frj?qrXhNe@r$z?o#)_BC$c#6Tn zw%ibJSrePzu1EE-o7FRWE@Bmr=0#t-W8=a(6GTqoYvcqTWN@=@*0!nMye8HIu2(T+Ak@9J5Z~>D99iw*`m8V%yP8G^_lKA3_-39D4+I+C1zz z%PxAIjtxqC6rEeEoK;TYRK5moFT3e)S;c473ltAKvc{hCWlVc;gKFP7(_^pP+TQSQ zjTnnuLBc{Sdb7KSnYy{T8Mi%*-`7X=bnva_VNVf!d<1rL=-JH6uuGF1?^y5f9AB6q zotFt+&fvKN9wTt?2px9TxG)4b)AV}%MO>l#`PSCbhc8CH z(ahGS3jt5QrHGrvLqpybTd3aT!_Ma3C?0!8iS}-@N4$|3Vjk~Odfkur_B2j4Q=ai9 zwCdFE-MgodJ$v@--@hOJdcD5T)wQs^+~2>veB#83lSsEgpFKBQ8LAYfrz?!j@VGrK zfD?mhnuhu zc6A*>`uqE-yqo0c(WA$Y&khU>p!`akr_C16;qx9(K3}Q48GMs(2|#W(U+C>U+gs?p z^6}jBk0WP#6@}XUG1|MFxifa;Gu`Gf@{^8r3D0vJ&-0ExB2Qql!KaO@u%q%RuxCa- z=nDq{@3OWa?o`}pF?bNzz;Q^nz?4c2d1Yzhk<6eIWaeu#=B8Cm810v^Rke)+e)?h zH``r9!+0zn64TyHj(U9NCw8Ir?OU83bm-%VH;0Wb>dWQso<4o4T$akBA7WgT3iz&_ zN#||w+mrl%lwSPt^Vg61UR6`~YFWHi_l{!JcULueSU zuU#7-U!wAd^F!yiGqsgYce}fpeBa&ns10GwH=8Hj)>BVDk~}BH;~@vhCnx{=D_1_h z9(z4@+Q`0r`z}a*NhgoKotri}dCcg8TMu47d)M~vT^slBr56_$zkgrMPE@N|O(WZ! zsLQ%0YpP1+LKrd6^35*)GUSB5)MzwrJS8#U4D>#RSz-pt?c=lJXO zeSaQ*)aC{sacalkE(o<+>1c~WPfGnKtu-k`2YJOl(N%r)u4fVPB7smYkR!~c!2?5` z13>TVn~)3sx0VVE3qQ8?KZ&MxkE4I%0~`Az9FB(`>c8OVKkXPppkEAHPbYRdx2|$6 zf*j~H;Ex?orIrKyj}eYAQ%S`h#fdpw@Cz<58T?>}2zx?ZT|%y(T{~Xpi=gkZTF;#e z3F=$F{`}PNFa>wR$HyM5Ztd#os_vSakjh6}Iy<|C2zX8|>ielr&R9gEe{Fo0|8gK| zkY8VlfcpEtiRi!U(S93Z-L~--2kINT8Vb8(?fP;$%dGar++*t=TX-4CqacXL~rY1d|=Z=r( zT@Q{j(+PIADfOvY)=!t^b(wRg^=0R7n8aR zGu)okchJ@@r~V1+Ujz8JBY#ZBac;u{>vE*5fRzYXDa*3>N)mKP)O|L;_+)+@W$#W_ z1HCSw0BPQbdWUK^n3k3~2){GaaiQou{J~fvivE1qGekZm14C^s_>uYe_~`Zew$6dh z&dz2jY$hilM;G9l1sq4)7Rn-P`H|OEqLr&S14g)DnOR!8zA!U0bMNinM7RaVpGDl; zY-jGh@Wtt|F$}V_tG&EfzS=j}cU7%lLF4S~p35Z7OJBR(*!bOV-xB?PmY6P)N+eR& zm~-CP8no)@pwxKED3P8YEr^+%?8q=F+vn#4EnG5nUJd7iSCx$h8STYo>M5XqKb%>U znOOtZDR(?fN4Uox1Ub*XkD$wZHf)e>(EIqv@I>f+HsGnMd7^oAVqjvh1vQ|K6RZ%6 zS(agDR(SBQc^!rdmzN8vK88rJqp)LqgEnqF@z805HGQJ@1$%=?VI znx@@zXBFMuwRP&sqPpVZvLw6xjS9oC{Zv}oug2jiu%}ZIcF@Ph^RCBI+pC^=W&^+h zj2nbIz;VS1L`O&K^(`$vP;`|5u!wLu!{jbqrQrBbaLVo`2m4qAM6qoVHq>>S?SyR` z*c}LXS5Tn6g}o`iI4?0VQ5zK%Rio1xlm=zWuo0G1 z^py0Jec*;-d4*BepMTH?oH9ZSY$|#H{6GG`^dbW~(Tbd;`3i5jm;5kK&YSMhLvC&3 zHVlp9eiusn*^WX_1XErv-9)w42ysdA?Q+H zW2CX6=ZBNdm?l$Xli3vMR5s}}x+#0!T+v)!UV9=H(9Y8J_>rsU{BkbR#TC3Ak&M^yN+acyB-!s$e-Ut;vL8ySlm4a z;eC8dRw94`tf=X%Uv6%$8=aRI9J<1TIMbMW6^gFu(4jHQl%}SF=r%{bpn^hWvR;$u# z?d{>=gnV=2*2E~n{(eP81u1Vp-=CRI+4rUIi{BUTb=|}MLKVTK$?cJhCIQZa#yajY zS(}2N?bT>;%*x8uf2KJB_nPh{ry9GsF6g#rFPyoz{6b}Ux%JHA;^J%)xNpWt!c`tW z{u(CNPsL)vuD!{O6hY2%>I8qZSX5O>PtGWEy~`Lmb<%8B>Xe$#4z(JbN}bN!q|z#P z103ko^(ZQx!H{Jz7!K^;PuL-zok!n77@PpuN3`=QIJaXNJwN>xw8No`D|!K~UHql+Qv5HWo# zB}cT^)aaC12QmqJ`hK3=ZTlv`6W5{ViSOGfIrW*|Np9;)2Kq```l9tRy)3$O^iF?{ zPUxJ75m{!I-KK-QaAxVc*K(Nd4R;SXqMht4{NEVX+)5Xg*@A@Hq<~LB?(fg+E!|uH zU3PZ%u1f#x_XH9a#ZAHrAeO}~uDGbkZnqajX~LVrJ32BtOdr;k&6(!Li-vb=RcYZo z`qr(9iCZ7x(X%SDkm@`-$X^FI#FKA=?VA8jd`GrF3{<|9@ts|UOIx>`TRl)x)i(4! zVqK1178248PoY+zy&b-K_%Oy7g$1LI+PVzSss7D$wDbGdl?MTRO~_3yx};tzTQz$r zSe*>=WM;>E0%_2DZ|vGpUk`K^A_F2WgkGGN_tjVSqN1X_;l#xEe>Y_`nRX?JRuvab z&g~`&C+yn9tq{;bzH_ItrY6OpN)iIAqhPS4RrcG0}H-ItzJ63yu82&@oOwU+_mf1X}n+g2RO*VZncK44<-BB z+G+Yq=F+7-dwvP<@5T-$&i;rIO9hgIw?BI0!*bRmde8z!{OebMCn_45k1IEu%%;5w zZ2pLs8`5bugFNbyN1`6vx%0719fnqA*1>c_p8opl;C9=-g_85G(`0|)akx&hT0i8E z*A@6EL~^dPMBnD8U_geo*8BDX#{gcTd}-NoZ9(W=)2}TPcDLmocn>*d*J+ov2jn5X zXFPA=Qd371{#Zkjvdg7$5|ZN*kx0rQ<9P{LJPXA|<1mAld=H zeF6pxh+y>)4x?&9&JdUXE;854k?u3tb-luOx$vDg{YKA04)&K8U7-bQ)+Wt*$g!p+ zd>R)h=2(eXDrI1_slN=}1S%ohp zYxPt}n<|U+ZLLX3DU^`n%%gKDue)jSGZ|@jXG+Vz=eq5l&YUz)X3nM`O}_;8bW6G= z_o!T>E7p}a=o+%+4G~%088Lh6<#L=(cY(ZrFR_KH+jR%FgZ+7u*Ku0ym53ZDlD%;M zDK00U$79jCFr3=+e>+Zd8Kbx^y8rpdw;+ePi0(rEcF{vXXUH9M*J=IbOtmtzv9U2p zZ8n=LDb51T5%B!EI7_u9F0HyYe&&bWyDz1GlxsT+qsKmW{8-WTmSZB|aUiV( zp-$K&$n7N5VfYthn(2a0mpq8WDj|Q##oe9cXkS151>`UX`LAYm5)73sDbrS_7t)At z*5MiTSA0^HksSw%*X)LU1ay357LSh~J$h6Zm8R3Ap?k~D-LOHIy{AFm-Px^**;QYa zRWHuV0((CzdpO8}4s*y3Xwud&^^FK$SLZ;dLr&F+Ft25_rg2cGMHE*=P(hwTxPLCH!Q#wALd+)uu>YY1x z@80P^ABRO1AI(Ks%hl*K+3~t~e6n@AtgJn{^)dCj`q*8&RP*TJAcw=-+1WIg>Og-! zi0R>uof>t-y6A!jjiN=dZvEf4lN?@2@VXN~XWf0N=0ImPpPrm-n>8vX&)n@Ol2R#B znbf1LwNQFh?-AAi|L(|>>jb9nKL5a# z9Oin*V%Hps8x@|4J7>=Pz-uLu-d02$AM6y*6+OQCyoDT5;^I)icc$llc4<5}_oyZ} z9q6GAFnMu9vAj6DbA5(iJ=DU~vNpz>?Ab;zfJ01KKV`b&+4+RMK#-yA2MrCG_ zjasUD`OG&}adz8*Hiir*E=5IYiqq0M(?ZkbGuepsVqLeqJEOB(2kKohauw41-dFoo zTMPU9LH@!E;jl%)zA-iRc}Di9+Jk~xPK8|TB|^jN?%g<&O~C;*1>ZTr|1HqT^~&AZ zt2|$RWm0odWs$lF-$Id8uw<=`?m#1}vaQK}T3tBj~iK{rDR^4%a1L}Fip6pKf zo^E+P(CcIO@2Z!pRH`=%LEgUw>`rv2>e~rA)5v2sH_8=VnBt-*_gW4*wPuqbAjy{F zg8t9slNhyMMJprJo3Y9#Q_FY~k2ZAkutg4!9=0@%*iP77rNsdba<2F7igPm&jID>o z#Kgo_Rqc*a9xqlw4X(wq?9avVNq zlfWb>_yT3k)!mnn1Ko?Cg6jldkn@@v0Zpnql3mf#LUJI^Vez+xlB;b|b15a~Lmi@X zJWG2YK1tUT^v0&MU$F+&){6@@u6Tr zjdB19{%^XtMFoAbLxMTGeca3`Dl2Pk)9Z^WWs<-7woPeKX~Znm6;#ut=)i4DZGI`h zOUtV7N~y{@4xQgO_dr`{X@zvA z9J2{nIpTZ?Ix9NJfxgt`Nv!vrR&C#Sx@&moL?lHYuRFE;i^icGLGYMgK=2as!*F+y zzYB7^=2C^ii(DQ062r07cvB{%yjs=fMwz`zF6@(vkk(-#is~cOIV0CsxT=)reLM7O z{`m-UPzCo=aF7%BcH;2FTvT^-HCu;GT{Si0(*uFSLtPj@?fr^guIS!|F@Y(-mgIM0 zaW8WisqhzQofDQsa1z#?_ca*OC3#HY)*TC(}?XH@?&Z-WxtL~JYjrGCdlLMQysqz8SfFa-G>$_VQx`Nh36<)yN?DnC)#7fB z!>_%4IZIsJ+?=ICB0tL7{@(1QvYaHs45Uw{tXPiEHi zq;9v>)C6A~O&ks3E?4zOPYwjEGlgLhcHN7M-5uy4zvVcsRg7q(#oprRXf3(HQ)IUJ z(u5qhYprT2kK(wXIgT4Cestix!M$rbb2e+FyM>a9riL|Pi${b zWYL!fd*tdHml<@G>e3Yo=eHL4-U>46j7L+xp|&jsyRdcav_GR z?TLwOu)`KNH6uRBVLeKlQl-)kmWV=@sXCVuBE7nXm4b>5UH&(vkkqhs7x<)`RO!=hk@B#+>Rab5%2HV z@qUDT;C_V5J-1;)dF|B@?)S7eM0aW)%WxBPyXuLse{y(u{0LS@BmIVYYLo{hWD2@W zboZVy!GJQ!6dA~Det&WKgV$KiKP2R^X|e|>@v@5htOl`G9KBCW0iDKWi+vohILtX5 z^p*J^*^es_9A7ZZoR6G~M`F*2FVBc^fIH)yC5P$^JM5o4eyi0V`;&p#WgX~oN6;>J z0et0m>jc5dfw0Ihzd--h$)=yy!QEN%TWxJW>+df)pr5|OSDf3oFFG2ZXzc}>q&b_B zMpg&^BI6+advZH0JMHW&ICIl5U)0LyHUE0eet<6}U*hm=L-*YCgZ@xG46Ceyo+d7D zd3%z`xob`i3j~46u;DJPA=%%@|0kPmUi4qEJc4B@?^XHJXFAqO`V1r1zKLtsR*;NE zNzF#Pd#CU{q(+zR9chQO!m{&Hv4xPQX#j3VXTf1#kFu$KhQ1i<)SPUJuM zj6L-LfC+56y*~W^lm#th`;^yuyU3>Y=Bs#gX zxN*THx|cicONSWMm{YK(W-A(|v90N^r041!rU`A>rg4C?uVnZw%yymDml4p z^m^gTU=MovKC&c}*us#r9&ZPCq7Nqfe2aR-pda$Z&s?U*NA?7pOv(Y%6~k)7gUQK0 zPXzxS#^$&-EO5FRvD@!aGJV(U+5=erBbz^6`zYjanHk5nd2`k^-vU{R(Sp&GUG>oM zZ5lf{)4a0iGhRQkVSen#&u&g#tE(%ltE+q2en+0jqO)y0J_P+)(#k#;`K>=vJhLjj zDUys|mm@j;KfzeA0IK^LwAwBofAX$JdD#!-1bxj)vM1(_E%vq6zP{+w){!n8mrh3; zP?>3?t*o`RwXLm94=ZA`CPfMH&zg&g9c98Cs=H{;pvT01{ONu+!|ngfTKN5O>D1Ks z9zV8_B>{)%4%Nf)K|f~~9kP!c9En^VwmOiYuRDl&ySn`A%x**wgO0!UE)4c?Ms(|g2CMy12+&Pq_u%a! ziOWhQZw%-Gfyx`CR6=wgpC=AI^yt$zfZw|H0Q}u;1(u~|^$B3tVn=nvYQ4ed2zgxS zE>vK*U!tfik_qSiodN)Tp2_W+;!qadsW~ZX1U+VRZAlf|$MhE>%)cUcmcFa5x76XP zJduPuW)*eUUzl&>!y);g^^r$>h9i^xfsWT$ICA<@{~MmBOC;O{I_0brprKJlb|J+N zgZ&Vmu|4|e&9I`IX0;XsGxg9iuu zuqIF5#P}!U6;uFJ7mT4u{r~d{{YO5J)tr*#)Qq8zwfTvo#i?CPtTX5!huvS|)--)a zw#q}{A!(XCZ|$>Mts^5NR&tLlRg*lYuGAyZt6S$YJjeGH{cYSNYBb}WgdFH;5svdY zJ~6}?^eSp<6xf?_U?H9R$5?|PZITxa^q>|(e$2hsyTr=+`}M~s1`m^+} zk2rdWpck2C5|LhA$x9JQGc#F_$6+?9IdeQ+jvIysW^EuLAuqlmuUj6mzB@0AxVyL$ z4qu-aJCQT;`sS@0+g~r-xOdA*nUt*3k`V|&2YJh}RphC_r-R6Ig#F?g!ysM&;#ElG zL7#6|M+Tbw0&44d(q-Q%l06rGzZ+>}TLX6*pw|{x?0MNM(^eHS2w6q_?+H`NP_lgzP>mx6aB=_u_k3P+) z?qe7vNjYG^WP0@gS$Q~#=Lw3FI z^kQ#lUte#p+rA4F$6!E4qNPdBj>arwkE;qgrLh@`!#X>ea{d=7=N{8m702;%aa^D< zV6csc@^TEk>mZD>DT%9=&`nn;gh)mlB7!rdB9AJME`b_S!eiwj ztdeHfL{c_bjmTcch>`u}|Hkh*x3{+)Iw$_<;Qj;ar@!axl#^7s(}uH{Y;^fAa2w@GE+?S3Ep z{Oz~%^F4tvUh2BKPS&D;Oly$Rx%c=!JlS~bVug~%%PXR^tFgEVUFh02#JbG1Hj4fs zK|iWiefYX6=Vd3lDs^3Z}T+Ya;&Ni@f!YgQA1J`fWyK%5;X(4!FEX-yLqx}StO zvq`UuOHP2T0^S!C>=UXTiWi?HgPSd*;fB$KaJ9bkRLETcolYqut+(&mx3K>6{O>(6 z(xBB&wIz3z1iCvgYY78VLd(Bg2Z+2ir8OlLRQf6^D$l010h^$|1oUdv`+2I5dGy!v zw0Uo7b($(eu6+&YXc+P65lgLzaR@ILFc;IX>f_gL+Az^7-f8e=hu$F%q3A7}estPl zClWei9YrA0N6X`Y}!prk%Okx6*BdR;WvleVA97X%R&DC&^KGs4G%(E9BPQ3WVdbTMFDE;wHAn3hB92y`<(J4RpFY&niX{j{c{56Ajx2`3ml z3fQ;c>p4Jo)B2IDr>0~gI!SKW&s+)ExP68iybs8Cn>KJ{GmNBl7`%LMaDv`qk|)q8 zHxsyH^j%19*lhfyv{Tm^M^|oc=wK(aO{nJfg)QB^NrbM+Cg#s=d3U|a7w%$7!w0WjnU;tsxcgfeU z!?dyx7KV9G__}WK*;7dg`FeRQjqo#4cN+G;pa+uVW{6GJVKT>Y@9r}s&UvEy?;{8Q z&z$ienRm*$b0Z@-4u%F5>Am6&pQ(Y?1u=tp?;Tih9fz8ispN9RXD5#@M; zUofRC52d6oL`9K%EKJWmrz2O^$de5Sa+{ki%nln=5G-1gS{}57_x38x_&7y$jFZ## zx)WV0t*op2e!iCY`o#BDyx=f6mT!;;VjCm~uFlJ6-XzA55Fs*gIpRz!<4JhY;1C}BLr<47kbpwp6LEtidvj$ud5s%uc(|KfsBujHs zu&DiuCeolf92|`Gx_Pw4UJ1D9V@qY-!+W&I#AW{29FwE2=PFt>@h#h zt83>+6l!>Rt$O|(1e@nSZo3i;tX{b|f1ug3=c{HsbI`g!Gpgm$tGA*1!O`1o2iI&x ze~V5d{Gu)+_2JOdQD)kZ&6#$XrqM%POeS3#xfef}x)b&Uawo^A)iBnHv>qa$3)#(Y zR|nLNF`uH5`Pw=Zv9=FJftcKx8M3trvP+}!MTCi;sSA~5@A^0wGD`#u@a zPY`s4>LQPxrPgNUXj3-qyEOLw<+i9bTa1v~Ku*z7&4C=f5?|kSQ)=pZSd@+)E_k?i zT4z2LVvRNH_2KEyau{9QA$#!gq;zw5EY|%xY(Y?Tu#1U(cRSU3Gql}Tr)Y!D;p>R+ zw(%-nUWEudt==&Ci0tMwJzX_LXTGT6u(Dv*>;aNd?bVmxQmIcUh_B~$Q*>zk{BFCy z%pTQYi!|7RM07$f6{4IEt}wZ~n3}pV7`B(#d)`p&b9#qEXHK?S^3&g(9w0+5GT9D{ zo{2i14x5j6bdF8;-V3=)J5(Y%&2B&sX#e?~Q^vo)NsRsGcy@L+4^NhF5{B*of!({N zr1aDBlG4(W&u9R;Zx5Bg*H2tkDNxI_=3$*$U6)m$%_z_Y_}WHCZGMPxqc+5MF~Ead zK!>mIj*LSIZ(1DGV+O=DsDIvc4_o5X4y&biF6F@NB*$Env3I157c78za&+`6tm$S$ ze7FT2*N~7?+Y>w32|7|a0vn=R8TE4rzCm92=1_5cNsWYotuwTg^)7#}SqeWW=VL&W z&F(X5U%YriMdV_JR;AL`W#y~TvkAJeX|ru=?%Td#qwm~S^`r3rdWmkw(A_ZEroDXB-mrlx2GAF?s==(t${^?w zUiWO9p;$Nv7+M5$C|z)MitbC$BcpUVD^JsFOHju4S{?LWD!ggyMk3}wPEN{}u3wi8 zkUd1N|8nb6fB#&6Z@)!7hCdi0E?dJqLVU;gxrsU|WE*0l z%F)~gbllSvYF?;4p6^DdPo+Iefy}C|^Ia#!LicZx|=kx;>#>W*m5$35-OP}~2($)sWSM+5L zV}#I2OF4kVH+~tA(W`!DFJ@7pL)Lh~OgZ6=68MPisZB)3;w5VTVLA2y%=mIR^!oVN za9o=7%<|Go>#b`m-M`^#21YutbVv5&T}nwX)w)%$9r>>m^wyho>i54Tc5$@-0|-^qv5389|oe03Z9LVZLDo@$A6KChyh0HFb zH|ekA^*^-Xq<(=~-FL`Hb?zd+to(?BY9G`5mrZ$+6K9vnVpwKiz>6mbx@hn2sV$OM zx`58#I~W^2XUVr*-@~%AlU^LLIT;BlEKM=)I%iqUKdFR$1L*kb*CV^R%J|T279Vra znbN;OkGa_B0*5r+_(=H?N}9)@vyFLnOlern>=agSth1P*!@GE9=pzJ1!2Y8(j?VDtI3JWOqCdKV*>@q}he~y2-0s-K{cKKo9a*x=?b8&f7b>u^^`# z%sPvuKfgeogGi~_NSvZWKRhb=lQR0m(e&}y`hKv*ItTLp1ie~L)Q%>VE6@SmrS>9S zop8E9eaLtW=m4kEnA=l$nS}C3RVZb_Q zLr^-sTY=1-lhBT_YrJoOi%O^Huy^;Q?o>K=1xUtEJY7?Lw5zbeUY7t>e@cVp)&9rjhRZL@fiLU zrln!fK{?De4Re>ji@tQZr)STlo*U5|+k?w_7{SVxy8+FklYbz`r^BqH6dUm7(J8rS zCC8(KT(EbX@d`PmvtZT@qCVohi>Ld*B$kaXduBN)RY5fS4+&j-@}B`Z#sT6_jg1|5 zQ#-m;e1nd%<0_h=PNX#j&POZG76Kd8g+`pxtWE^ zON@Zd>}y5+D#o}g10)b5_$AIpgIp6BNR=*F+*~lm}B~8kn%Sz?&C8hFo&_{(Bb_!y|k|xpJD$#tM6v`FKZc zQ~INxPFy{1I_G(iQ*?DcnQ5hw1GXa-K4flvSxOT1azhW<|(3Ixh;XVH5*TL2eCp0E53{WhKEG`gQ5;{d6>n1~Y%ma5 ze%K}aNC~DK+Vp_bAjJX&l~pX!HM@JUkSiCE6(PF9szj`{VmUYnXKNuyYDA-?mnbI= zsh~ZyRfU{fDpf5|C4zE^Q2q(TcV>4o9$LVOR9;-yQ7`@Y`{vD?H?#AWj`#f-Tvb8Q zUxWKlaGD_9;s-W;cL!JpYxaX9{H|njNAxrP{08)3)lS)azB%(9Qkr}U?AFTRqbo-b zTZUFDhsq_bTvp4Lx;{EpLvo`M^rK}B=xpIG%i}ZL;Rk1KDR4;S-xqIb96ccCbGjfp zVqD)Z!Ce(JzK^vBkLS;AqgJx}6XJ(3+PUn0kpH{vllyxveEH@X`^Y5bH zJ^uSU3>{aL@axuK2%L&cu2tNv0bO7hWcOYE(F<#j|L_L}`pfU;&!0?zdu64RR?CK= zOP65uu<`3BHspiAXcZJDAca~fGrg@ zXaUNypPzhv!T|cGVXbP_jO{5Sw?W=(En_)N(2?B$eXCq1IZZ<^LUX_)o>TO(4;^ez zlZuqxP(hyLE{ivC?6?#-Q@L5-8-bNImmP%IEA*pTR~CjEX8 z>A)_?&e&qn8IoWk7-CsWpnHEm4E)p9JqzF|z|j9S{59x_T{BPGjLSp#~jHQiDq zsGg;YW;(C;L2N8*xG7Ur(2`b z8bu!(CFsatG1p-T$UZs|9U086-xhmRX~Aq@w%2m8^k#3-ZFF_ndLtHP`GtGq!0v zF(NuA?-t2{4)Wg*ku4V(*eCs~(j&iZ!r?(axGLfd-NZEC>G{!N$R4mC5ZNI+Vej5I zn}=C>ihe7XZ|1j>Eu(4}O4({!B`sA-!_$vinp{q`q;;za^stn1OfTsG&iSKXRNxrc%gd^^9xB5b@^qq~|8u$i?VRV;s)e zf3rCiOXGobOKn<)Va2d;l?Zwhi&p#<);vsZwwX=Nn-#}|`{(8h+MJ%4vvZD?gEOtE0_g@+bTz-JE3tKTXm%mBT z^LK7yBdUL~7w|#fgS3hXN=v3Unl-gnBF?@MADXTjHBuFI^^8Owlkn`cr-xk~GHVT6 z#mn>-^h(q-l*t_jANT-SAV8EK@>Q9n2(Ueq}&dkrOkQyCnK;ggPO| z!yt^^*Ig{wK!&^Lanorve**{f19reCeD?G>rPnliRX8yXIZHf5&~vKoNYWQ(*fz-* z;M!rwjoWTUpPSd?b=&sliR6qt&>W%*1D%m$NS>BNOZ>WuaL+ZDw=a%ugIoqxhoO$i zPT7Ip&JOh1>l3g~w^?jVcxVAZ8$PIk`gn^Ic*!H^URYH!r*tQ3yJ=+Z`dpMqp7Gq=oE`nlZHw)q z<}8`Pyv9Ty7BW^A+L-Fd;#SWMUWE3$YX$SzC9eC9%Tsndasz)S=<92=XoJ-|7oJLw z{ubjnFh|C`N(Vmp@h9Zzu?)~L%jvq8Fy|4~qlIEtuefH^p6h8iEpuL&)dX@RGsN9F z`N);~?C60q#6BxMSIPP{#5UbJp5PceOX}Lf{8tqHgB#sJ!AgJ^y4)AOy<2b!$cE8t%=oOIDMpsA~@74TSHqZwM`NJLD9VqXm`O76C)V;u~ zRZEY*_`}3`kgxeg8yII7;h9nLG|;s=vi7XrsO$6fLN-&V7xe|#?6KXt9?95quH7GD z)A{Y2ocy^Uxcj0H_yc`-JoMifd%DEn8K5(EA=JU=ucIf&ylJtPPZ13ae}EbQrV zV26r&v4U421KtMG8GFGj7VWNxQ_yGk`{d-P)Sm!n`72G`LEb*lp9=jK8G`zrYrqR+?Y^hyzW7cvbqA4f-Sr5ueUzLvaeN$c zN4~mq=gtS4q#5s%SFUt3c+fwz)XZ9+$XWABkh2YCQFBE14o3Rk8(kf|4|{N)uJ1bFF9hp%-l;Rvb+;eJ;5k1mnn*vn zRR5`tmENP7u0(G#8I97WR;;HNeh)bt=Pb5U&1rCd;(_ZHiyEwno#Y`YP z=)oSiJ!{S?@Z$sdh<6zNiBL0eLe3l2ve3@Qxsb|0^hxP~+r$6B&T?ARtbF0Q@`N77 z;R&Z;nSQP}xQPjUTE$82e&nx658Oi1fxoe{+C1BsAngAEz5qf00MAd3Cq<=4x Z{{;$xH 0 && tarr[rule] != nil && !override { + return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} + } + + } else { + tarr = make([]*transText, 7, 7) + t.cardinalTanslations[key] = tarr + } + + trans := &transText{ + text: text, + indexes: make([]int, 2, 2), + } + + tarr[rule] = trans + + idx := strings.Index(text, paramZero) + if idx == -1 { + tarr[rule] = nil + return &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} + } + + trans.indexes[0] = idx + trans.indexes[1] = idx + len(paramZero) + + return nil +} + +// AddOrdinal adds an ordinal plural translation for a particular language/locale +// {0} is the only replacement type accepted and only one variable is accepted as +// multiple cannot be used for a plural rule determination, unless it is a range; +// see AddRange below. +// eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - 1st, 2nd, 3rd... +func (t *translator) AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error { + + var verified bool + + // verify plural rule exists for locale + for _, pr := range t.PluralsOrdinal() { + if pr == rule { + verified = true + break + } + } + + if !verified { + return &ErrOrdinalTranslation{text: fmt.Sprintf("error: ordinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} + } + + tarr, ok := t.ordinalTanslations[key] + if ok { + // verify not adding a conflicting record + if len(tarr) > 0 && tarr[rule] != nil && !override { + return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} + } + + } else { + tarr = make([]*transText, 7, 7) + t.ordinalTanslations[key] = tarr + } + + trans := &transText{ + text: text, + indexes: make([]int, 2, 2), + } + + tarr[rule] = trans + + idx := strings.Index(text, paramZero) + if idx == -1 { + tarr[rule] = nil + return &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} + } + + trans.indexes[0] = idx + trans.indexes[1] = idx + len(paramZero) + + return nil +} + +// AddRange adds a range plural translation for a particular language/locale +// {0} and {1} are the only replacement types accepted and only these are accepted. +// eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left' +func (t *translator) AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error { + + var verified bool + + // verify plural rule exists for locale + for _, pr := range t.PluralsRange() { + if pr == rule { + verified = true + break + } + } + + if !verified { + return &ErrRangeTranslation{text: fmt.Sprintf("error: range plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} + } + + tarr, ok := t.rangeTanslations[key] + if ok { + // verify not adding a conflicting record + if len(tarr) > 0 && tarr[rule] != nil && !override { + return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} + } + + } else { + tarr = make([]*transText, 7, 7) + t.rangeTanslations[key] = tarr + } + + trans := &transText{ + text: text, + indexes: make([]int, 4, 4), + } + + tarr[rule] = trans + + idx := strings.Index(text, paramZero) + if idx == -1 { + tarr[rule] = nil + return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation? locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} + } + + trans.indexes[0] = idx + trans.indexes[1] = idx + len(paramZero) + + idx = strings.Index(text, paramOne) + if idx == -1 { + tarr[rule] = nil + return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters. locale: '%s' key: '%v' text: '%s'", paramOne, t.Locale(), key, text)} + } + + trans.indexes[2] = idx + trans.indexes[3] = idx + len(paramOne) + + return nil +} + +// T creates the translation for the locale given the 'key' and params passed in +func (t *translator) T(key interface{}, params ...string) (string, error) { + + trans, ok := t.translations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + b := make([]byte, 0, 64) + + var start, end, count int + + for i := 0; i < len(trans.indexes); i++ { + end = trans.indexes[i] + b = append(b, trans.text[start:end]...) + b = append(b, params[count]...) + i++ + start = trans.indexes[i] + count++ + } + + b = append(b, trans.text[start:]...) + + return string(b), nil +} + +// C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in +func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) { + + tarr, ok := t.cardinalTanslations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + rule := t.CardinalPluralRule(num, digits) + + trans := tarr[rule] + + b := make([]byte, 0, 64) + b = append(b, trans.text[:trans.indexes[0]]...) + b = append(b, param...) + b = append(b, trans.text[trans.indexes[1]:]...) + + return string(b), nil +} + +// O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in +func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) { + + tarr, ok := t.ordinalTanslations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + rule := t.OrdinalPluralRule(num, digits) + + trans := tarr[rule] + + b := make([]byte, 0, 64) + b = append(b, trans.text[:trans.indexes[0]]...) + b = append(b, param...) + b = append(b, trans.text[trans.indexes[1]:]...) + + return string(b), nil +} + +// R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments +// and 'param1' and 'param2' passed in +func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) { + + tarr, ok := t.rangeTanslations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + rule := t.RangePluralRule(num1, digits1, num2, digits2) + + trans := tarr[rule] + + b := make([]byte, 0, 64) + b = append(b, trans.text[:trans.indexes[0]]...) + b = append(b, param1...) + b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...) + b = append(b, param2...) + b = append(b, trans.text[trans.indexes[3]:]...) + + return string(b), nil +} + +// VerifyTranslations checks to ensures that no plural rules have been +// missed within the translations. +func (t *translator) VerifyTranslations() error { + + for k, v := range t.cardinalTanslations { + + for _, rule := range t.PluralsCardinal() { + + if v[rule] == nil { + return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k} + } + } + } + + for k, v := range t.ordinalTanslations { + + for _, rule := range t.PluralsOrdinal() { + + if v[rule] == nil { + return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k} + } + } + } + + for k, v := range t.rangeTanslations { + + for _, rule := range t.PluralsRange() { + + if v[rule] == nil { + return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k} + } + } + } + + return nil +} diff --git a/taskman-server/vendor/github.com/go-playground/universal-translator/universal_translator.go b/taskman-server/vendor/github.com/go-playground/universal-translator/universal_translator.go new file mode 100644 index 00000000..dbf707f5 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/universal-translator/universal_translator.go @@ -0,0 +1,113 @@ +package ut + +import ( + "strings" + + "github.com/go-playground/locales" +) + +// UniversalTranslator holds all locale & translation data +type UniversalTranslator struct { + translators map[string]Translator + fallback Translator +} + +// New returns a new UniversalTranslator instance set with +// the fallback locale and locales it should support +func New(fallback locales.Translator, supportedLocales ...locales.Translator) *UniversalTranslator { + + t := &UniversalTranslator{ + translators: make(map[string]Translator), + } + + for _, v := range supportedLocales { + + trans := newTranslator(v) + t.translators[strings.ToLower(trans.Locale())] = trans + + if fallback.Locale() == v.Locale() { + t.fallback = trans + } + } + + if t.fallback == nil && fallback != nil { + t.fallback = newTranslator(fallback) + } + + return t +} + +// FindTranslator trys to find a Translator based on an array of locales +// and returns the first one it can find, otherwise returns the +// fallback translator. +func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator, found bool) { + + for _, locale := range locales { + + if trans, found = t.translators[strings.ToLower(locale)]; found { + return + } + } + + return t.fallback, false +} + +// GetTranslator returns the specified translator for the given locale, +// or fallback if not found +func (t *UniversalTranslator) GetTranslator(locale string) (trans Translator, found bool) { + + if trans, found = t.translators[strings.ToLower(locale)]; found { + return + } + + return t.fallback, false +} + +// GetFallback returns the fallback locale +func (t *UniversalTranslator) GetFallback() Translator { + return t.fallback +} + +// AddTranslator adds the supplied translator, if it already exists the override param +// will be checked and if false an error will be returned, otherwise the translator will be +// overridden; if the fallback matches the supplied translator it will be overridden as well +// NOTE: this is normally only used when translator is embedded within a library +func (t *UniversalTranslator) AddTranslator(translator locales.Translator, override bool) error { + + lc := strings.ToLower(translator.Locale()) + _, ok := t.translators[lc] + if ok && !override { + return &ErrExistingTranslator{locale: translator.Locale()} + } + + trans := newTranslator(translator) + + if t.fallback.Locale() == translator.Locale() { + + // because it's optional to have a fallback, I don't impose that limitation + // don't know why you wouldn't but... + if !override { + return &ErrExistingTranslator{locale: translator.Locale()} + } + + t.fallback = trans + } + + t.translators[lc] = trans + + return nil +} + +// VerifyTranslations runs through all locales and identifies any issues +// eg. missing plural rules for a locale +func (t *UniversalTranslator) VerifyTranslations() (err error) { + + for _, trans := range t.translators { + err = trans.VerifyTranslations() + if err != nil { + return + } + } + + return +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/.gitignore b/taskman-server/vendor/github.com/go-playground/validator/v10/.gitignore new file mode 100644 index 00000000..6e43fac0 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/.gitignore @@ -0,0 +1,30 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test +bin + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof +*.test +*.out +*.txt +cover.html +README.html diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/.travis.yml b/taskman-server/vendor/github.com/go-playground/validator/v10/.travis.yml new file mode 100644 index 00000000..85a7be34 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/.travis.yml @@ -0,0 +1,29 @@ +language: go +go: + - 1.15.2 + - tip +matrix: + allow_failures: + - go: tip + +notifications: + email: + recipients: dean.karn@gmail.com + on_success: change + on_failure: always + +before_install: + - go install github.com/mattn/goveralls + - mkdir -p $GOPATH/src/gopkg.in + - ln -s $GOPATH/src/github.com/$TRAVIS_REPO_SLUG $GOPATH/src/gopkg.in/validator.v9 + +# Only clone the most recent commit. +git: + depth: 1 + +script: + - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... + +after_success: | + [ $TRAVIS_GO_VERSION = 1.15.2 ] && + goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/LICENSE b/taskman-server/vendor/github.com/go-playground/validator/v10/LICENSE new file mode 100644 index 00000000..6a2ae9aa --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Dean Karn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/Makefile b/taskman-server/vendor/github.com/go-playground/validator/v10/Makefile new file mode 100644 index 00000000..19c91ed7 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/Makefile @@ -0,0 +1,18 @@ +GOCMD=GO111MODULE=on go + +linters-install: + @golangci-lint --version >/dev/null 2>&1 || { \ + echo "installing linting tools..."; \ + curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.21.0; \ + } + +lint: linters-install + $(PWD)/bin/golangci-lint run + +test: + $(GOCMD) test -cover -race ./... + +bench: + $(GOCMD) test -bench=. -benchmem ./... + +.PHONY: test lint linters-install \ No newline at end of file diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/README.md b/taskman-server/vendor/github.com/go-playground/validator/v10/README.md new file mode 100644 index 00000000..04fbb3c8 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/README.md @@ -0,0 +1,299 @@ +Package validator +================ +[![Join the chat at https://gitter.im/go-playground/validator](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-playground/validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +![Project status](https://img.shields.io/badge/version-10.4.1-green.svg) +[![Build Status](https://travis-ci.org/go-playground/validator.svg?branch=master)](https://travis-ci.org/go-playground/validator) +[![Coverage Status](https://coveralls.io/repos/go-playground/validator/badge.svg?branch=master&service=github)](https://coveralls.io/github/go-playground/validator?branch=master) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/validator)](https://goreportcard.com/report/github.com/go-playground/validator) +[![GoDoc](https://godoc.org/github.com/go-playground/validator?status.svg)](https://pkg.go.dev/github.com/go-playground/validator/v10) +![License](https://img.shields.io/dub/l/vibe-d.svg) + +Package validator implements value validations for structs and individual fields based on tags. + +It has the following **unique** features: + +- Cross Field and Cross Struct validations by using validation tags or custom validators. +- Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated. +- Ability to dive into both map keys and values for validation +- Handles type interface by determining it's underlying type prior to validation. +- Handles custom field types such as sql driver Valuer see [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29) +- Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs +- Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError +- Customizable i18n aware error messages. +- Default validator for the [gin](https://github.com/gin-gonic/gin) web framework; upgrading from v8 to v9 in gin see [here](https://github.com/go-playground/validator/tree/master/_examples/gin-upgrading-overriding) + +Installation +------------ + +Use go get. + + go get github.com/go-playground/validator/v10 + +Then import the validator package into your own code. + + import "github.com/go-playground/validator/v10" + +Error Return Value +------- + +Validation functions return type error + +They return type error to avoid the issue discussed in the following, where err is always != nil: + +* http://stackoverflow.com/a/29138676/3158232 +* https://github.com/go-playground/validator/issues/134 + +Validator only InvalidValidationError for bad validation input, nil or ValidationErrors as type error; so, in your code all you need to do is check if the error returned is not nil, and if it's not check if error is InvalidValidationError ( if necessary, most of the time it isn't ) type cast it to type ValidationErrors like so: + +```go +err := validate.Struct(mystruct) +validationErrors := err.(validator.ValidationErrors) + ``` + +Usage and documentation +------ + +Please see https://godoc.org/github.com/go-playground/validator for detailed usage docs. + +##### Examples: + +- [Simple](https://github.com/go-playground/validator/blob/master/_examples/simple/main.go) +- [Custom Field Types](https://github.com/go-playground/validator/blob/master/_examples/custom/main.go) +- [Struct Level](https://github.com/go-playground/validator/blob/master/_examples/struct-level/main.go) +- [Translations & Custom Errors](https://github.com/go-playground/validator/blob/master/_examples/translations/main.go) +- [Gin upgrade and/or override validator](https://github.com/go-playground/validator/tree/v9/_examples/gin-upgrading-overriding) +- [wash - an example application putting it all together](https://github.com/bluesuncorp/wash) + +Baked-in Validations +------ + +### Fields: + +| Tag | Description | +| - | - | +| eqcsfield | Field Equals Another Field (relative)| +| eqfield | Field Equals Another Field | +| fieldcontains | NOT DOCUMENTED IN doc.go | +| fieldexcludes | NOT DOCUMENTED IN doc.go | +| gtcsfield | Field Greater Than Another Relative Field | +| gtecsfield | Field Greater Than or Equal To Another Relative Field | +| gtefield | Field Greater Than or Equal To Another Field | +| gtfield | Field Greater Than Another Field | +| ltcsfield | Less Than Another Relative Field | +| ltecsfield | Less Than or Equal To Another Relative Field | +| ltefield | Less Than or Equal To Another Field | +| ltfield | Less Than Another Field | +| necsfield | Field Does Not Equal Another Field (relative) | +| nefield | Field Does Not Equal Another Field | + +### Network: + +| Tag | Description | +| - | - | +| cidr | Classless Inter-Domain Routing CIDR | +| cidrv4 | Classless Inter-Domain Routing CIDRv4 | +| cidrv6 | Classless Inter-Domain Routing CIDRv6 | +| datauri | Data URL | +| fqdn | Full Qualified Domain Name (FQDN) | +| hostname | Hostname RFC 952 | +| hostname_port | HostPort | +| hostname_rfc1123 | Hostname RFC 1123 | +| ip | Internet Protocol Address IP | +| ip4_addr | Internet Protocol Address IPv4 | +| ip6_addr |Internet Protocol Address IPv6 | +| ip_addr | Internet Protocol Address IP | +| ipv4 | Internet Protocol Address IPv4 | +| ipv6 | Internet Protocol Address IPv6 | +| mac | Media Access Control Address MAC | +| tcp4_addr | Transmission Control Protocol Address TCPv4 | +| tcp6_addr | Transmission Control Protocol Address TCPv6 | +| tcp_addr | Transmission Control Protocol Address TCP | +| udp4_addr | User Datagram Protocol Address UDPv4 | +| udp6_addr | User Datagram Protocol Address UDPv6 | +| udp_addr | User Datagram Protocol Address UDP | +| unix_addr | Unix domain socket end point Address | +| uri | URI String | +| url | URL String | +| url_encoded | URL Encoded | +| urn_rfc2141 | Urn RFC 2141 String | + +### Strings: + +| Tag | Description | +| - | - | +| alpha | Alpha Only | +| alphanum | Alphanumeric | +| alphanumunicode | Alphanumeric Unicode | +| alphaunicode | Alpha Unicode | +| ascii | ASCII | +| contains | Contains | +| containsany | Contains Any | +| containsrune | Contains Rune | +| endswith | Ends With | +| lowercase | Lowercase | +| multibyte | Multi-Byte Characters | +| number | NOT DOCUMENTED IN doc.go | +| numeric | Numeric | +| printascii | Printable ASCII | +| startswith | Starts With | +| uppercase | Uppercase | + +### Format: +| Tag | Description | +| - | - | +| base64 | Base64 String | +| base64url | Base64URL String | +| btc_addr | Bitcoin Address | +| btc_addr_bech32 | Bitcoin Bech32 Address (segwit) | +| datetime | Datetime | +| e164 | e164 formatted phone number | +| email | E-mail String +| eth_addr | Ethereum Address | +| hexadecimal | Hexadecimal String | +| hexcolor | Hexcolor String | +| hsl | HSL String | +| hsla | HSLA String | +| html | HTML Tags | +| html_encoded | HTML Encoded | +| isbn | International Standard Book Number | +| isbn10 | International Standard Book Number 10 | +| isbn13 | International Standard Book Number 13 | +| json | JSON | +| latitude | Latitude | +| longitude | Longitude | +| rgb | RGB String | +| rgba | RGBA String | +| ssn | Social Security Number SSN | +| uuid | Universally Unique Identifier UUID | +| uuid3 | Universally Unique Identifier UUID v3 | +| uuid3_rfc4122 | Universally Unique Identifier UUID v3 RFC4122 | +| uuid4 | Universally Unique Identifier UUID v4 | +| uuid4_rfc4122 | Universally Unique Identifier UUID v4 RFC4122 | +| uuid5 | Universally Unique Identifier UUID v5 | +| uuid5_rfc4122 | Universally Unique Identifier UUID v5 RFC4122 | +| uuid_rfc4122 | Universally Unique Identifier UUID RFC4122 | + +### Comparisons: +| Tag | Description | +| - | - | +| eq | Equals | +| gt | Greater than| +| gte |Greater than or equal | +| lt | Less Than | +| lte | Less Than or Equal | +| ne | Not Equal | + +### Other: +| Tag | Description | +| - | - | +| dir | Directory | +| endswith | Ends With | +| excludes | Excludes | +| excludesall | Excludes All | +| excludesrune | Excludes Rune | +| file | File path | +| isdefault | Is Default | +| len | Length | +| max | Maximum | +| min | Minimum | +| oneof | One Of | +| required | Required | +| required_if | Required If | +| required_unless | Required Unless | +| required_with | Required With | +| required_with_all | Required With All | +| required_without | Required Without | +| required_without_all | Required Without All | +| excluded_with | Excluded With | +| excluded_with_all | Excluded With All | +| excluded_without | Excluded Without | +| excluded_without_all | Excluded Without All | +| unique | Unique | + +Benchmarks +------ +###### Run on MacBook Pro (15-inch, 2017) go version go1.10.2 darwin/amd64 +```go +goos: darwin +goarch: amd64 +pkg: github.com/go-playground/validator +BenchmarkFieldSuccess-8 20000000 83.6 ns/op 0 B/op 0 allocs/op +BenchmarkFieldSuccessParallel-8 50000000 26.8 ns/op 0 B/op 0 allocs/op +BenchmarkFieldFailure-8 5000000 291 ns/op 208 B/op 4 allocs/op +BenchmarkFieldFailureParallel-8 20000000 107 ns/op 208 B/op 4 allocs/op +BenchmarkFieldArrayDiveSuccess-8 2000000 623 ns/op 201 B/op 11 allocs/op +BenchmarkFieldArrayDiveSuccessParallel-8 10000000 237 ns/op 201 B/op 11 allocs/op +BenchmarkFieldArrayDiveFailure-8 2000000 859 ns/op 412 B/op 16 allocs/op +BenchmarkFieldArrayDiveFailureParallel-8 5000000 335 ns/op 413 B/op 16 allocs/op +BenchmarkFieldMapDiveSuccess-8 1000000 1292 ns/op 432 B/op 18 allocs/op +BenchmarkFieldMapDiveSuccessParallel-8 3000000 467 ns/op 432 B/op 18 allocs/op +BenchmarkFieldMapDiveFailure-8 1000000 1082 ns/op 512 B/op 16 allocs/op +BenchmarkFieldMapDiveFailureParallel-8 5000000 425 ns/op 512 B/op 16 allocs/op +BenchmarkFieldMapDiveWithKeysSuccess-8 1000000 1539 ns/op 480 B/op 21 allocs/op +BenchmarkFieldMapDiveWithKeysSuccessParallel-8 3000000 613 ns/op 480 B/op 21 allocs/op +BenchmarkFieldMapDiveWithKeysFailure-8 1000000 1413 ns/op 721 B/op 21 allocs/op +BenchmarkFieldMapDiveWithKeysFailureParallel-8 3000000 575 ns/op 721 B/op 21 allocs/op +BenchmarkFieldCustomTypeSuccess-8 10000000 216 ns/op 32 B/op 2 allocs/op +BenchmarkFieldCustomTypeSuccessParallel-8 20000000 82.2 ns/op 32 B/op 2 allocs/op +BenchmarkFieldCustomTypeFailure-8 5000000 274 ns/op 208 B/op 4 allocs/op +BenchmarkFieldCustomTypeFailureParallel-8 20000000 116 ns/op 208 B/op 4 allocs/op +BenchmarkFieldOrTagSuccess-8 2000000 740 ns/op 16 B/op 1 allocs/op +BenchmarkFieldOrTagSuccessParallel-8 3000000 474 ns/op 16 B/op 1 allocs/op +BenchmarkFieldOrTagFailure-8 3000000 471 ns/op 224 B/op 5 allocs/op +BenchmarkFieldOrTagFailureParallel-8 3000000 414 ns/op 224 B/op 5 allocs/op +BenchmarkStructLevelValidationSuccess-8 10000000 213 ns/op 32 B/op 2 allocs/op +BenchmarkStructLevelValidationSuccessParallel-8 20000000 91.8 ns/op 32 B/op 2 allocs/op +BenchmarkStructLevelValidationFailure-8 3000000 473 ns/op 304 B/op 8 allocs/op +BenchmarkStructLevelValidationFailureParallel-8 10000000 234 ns/op 304 B/op 8 allocs/op +BenchmarkStructSimpleCustomTypeSuccess-8 5000000 385 ns/op 32 B/op 2 allocs/op +BenchmarkStructSimpleCustomTypeSuccessParallel-8 10000000 161 ns/op 32 B/op 2 allocs/op +BenchmarkStructSimpleCustomTypeFailure-8 2000000 640 ns/op 424 B/op 9 allocs/op +BenchmarkStructSimpleCustomTypeFailureParallel-8 5000000 318 ns/op 440 B/op 10 allocs/op +BenchmarkStructFilteredSuccess-8 2000000 597 ns/op 288 B/op 9 allocs/op +BenchmarkStructFilteredSuccessParallel-8 10000000 266 ns/op 288 B/op 9 allocs/op +BenchmarkStructFilteredFailure-8 3000000 454 ns/op 256 B/op 7 allocs/op +BenchmarkStructFilteredFailureParallel-8 10000000 214 ns/op 256 B/op 7 allocs/op +BenchmarkStructPartialSuccess-8 3000000 502 ns/op 256 B/op 6 allocs/op +BenchmarkStructPartialSuccessParallel-8 10000000 225 ns/op 256 B/op 6 allocs/op +BenchmarkStructPartialFailure-8 2000000 702 ns/op 480 B/op 11 allocs/op +BenchmarkStructPartialFailureParallel-8 5000000 329 ns/op 480 B/op 11 allocs/op +BenchmarkStructExceptSuccess-8 2000000 793 ns/op 496 B/op 12 allocs/op +BenchmarkStructExceptSuccessParallel-8 10000000 193 ns/op 240 B/op 5 allocs/op +BenchmarkStructExceptFailure-8 2000000 639 ns/op 464 B/op 10 allocs/op +BenchmarkStructExceptFailureParallel-8 5000000 300 ns/op 464 B/op 10 allocs/op +BenchmarkStructSimpleCrossFieldSuccess-8 3000000 417 ns/op 72 B/op 3 allocs/op +BenchmarkStructSimpleCrossFieldSuccessParallel-8 10000000 163 ns/op 72 B/op 3 allocs/op +BenchmarkStructSimpleCrossFieldFailure-8 2000000 645 ns/op 304 B/op 8 allocs/op +BenchmarkStructSimpleCrossFieldFailureParallel-8 5000000 285 ns/op 304 B/op 8 allocs/op +BenchmarkStructSimpleCrossStructCrossFieldSuccess-8 3000000 588 ns/op 80 B/op 4 allocs/op +BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel-8 10000000 221 ns/op 80 B/op 4 allocs/op +BenchmarkStructSimpleCrossStructCrossFieldFailure-8 2000000 868 ns/op 320 B/op 9 allocs/op +BenchmarkStructSimpleCrossStructCrossFieldFailureParallel-8 5000000 337 ns/op 320 B/op 9 allocs/op +BenchmarkStructSimpleSuccess-8 5000000 260 ns/op 0 B/op 0 allocs/op +BenchmarkStructSimpleSuccessParallel-8 20000000 90.6 ns/op 0 B/op 0 allocs/op +BenchmarkStructSimpleFailure-8 2000000 619 ns/op 424 B/op 9 allocs/op +BenchmarkStructSimpleFailureParallel-8 5000000 296 ns/op 424 B/op 9 allocs/op +BenchmarkStructComplexSuccess-8 1000000 1454 ns/op 128 B/op 8 allocs/op +BenchmarkStructComplexSuccessParallel-8 3000000 579 ns/op 128 B/op 8 allocs/op +BenchmarkStructComplexFailure-8 300000 4140 ns/op 3041 B/op 53 allocs/op +BenchmarkStructComplexFailureParallel-8 1000000 2127 ns/op 3041 B/op 53 allocs/op +BenchmarkOneof-8 10000000 140 ns/op 0 B/op 0 allocs/op +BenchmarkOneofParallel-8 20000000 70.1 ns/op 0 B/op 0 allocs/op +``` + +Complementary Software +---------------------- + +Here is a list of software that complements using this library either pre or post validation. + +* [form](https://github.com/go-playground/form) - Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support. +* [mold](https://github.com/go-playground/mold) - A general library to help modify or set data within data structures and other objects + +How to Contribute +------ + +Make a pull request... + +License +------ +Distributed under MIT License, please see license file within the code for more details. diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/baked_in.go b/taskman-server/vendor/github.com/go-playground/validator/v10/baked_in.go new file mode 100644 index 00000000..6ce762d1 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/baked_in.go @@ -0,0 +1,2285 @@ +package validator + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net" + "net/url" + "os" + "reflect" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + "golang.org/x/crypto/sha3" + + urn "github.com/leodido/go-urn" +) + +// Func accepts a FieldLevel interface for all validation needs. The return +// value should be true when validation succeeds. +type Func func(fl FieldLevel) bool + +// FuncCtx accepts a context.Context and FieldLevel interface for all +// validation needs. The return value should be true when validation succeeds. +type FuncCtx func(ctx context.Context, fl FieldLevel) bool + +// wrapFunc wraps noramal Func makes it compatible with FuncCtx +func wrapFunc(fn Func) FuncCtx { + if fn == nil { + return nil // be sure not to wrap a bad function. + } + return func(ctx context.Context, fl FieldLevel) bool { + return fn(fl) + } +} + +var ( + restrictedTags = map[string]struct{}{ + diveTag: {}, + keysTag: {}, + endKeysTag: {}, + structOnlyTag: {}, + omitempty: {}, + skipValidationTag: {}, + utf8HexComma: {}, + utf8Pipe: {}, + noStructLevelTag: {}, + requiredTag: {}, + isdefault: {}, + } + + // BakedInAliasValidators is a default mapping of a single validation tag that + // defines a common or complex set of validation(s) to simplify + // adding validation to structs. + bakedInAliases = map[string]string{ + "iscolor": "hexcolor|rgb|rgba|hsl|hsla", + "country_code": "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric", + } + + // BakedInValidators is the default map of ValidationFunc + // you can add, remove or even replace items to suite your needs, + // or even disregard and use your own map if so desired. + bakedInValidators = map[string]Func{ + "required": hasValue, + "required_if": requiredIf, + "required_unless": requiredUnless, + "required_with": requiredWith, + "required_with_all": requiredWithAll, + "required_without": requiredWithout, + "required_without_all": requiredWithoutAll, + "excluded_with": excludedWith, + "excluded_with_all": excludedWithAll, + "excluded_without": excludedWithout, + "excluded_without_all": excludedWithoutAll, + "isdefault": isDefault, + "len": hasLengthOf, + "min": hasMinOf, + "max": hasMaxOf, + "eq": isEq, + "ne": isNe, + "lt": isLt, + "lte": isLte, + "gt": isGt, + "gte": isGte, + "eqfield": isEqField, + "eqcsfield": isEqCrossStructField, + "necsfield": isNeCrossStructField, + "gtcsfield": isGtCrossStructField, + "gtecsfield": isGteCrossStructField, + "ltcsfield": isLtCrossStructField, + "ltecsfield": isLteCrossStructField, + "nefield": isNeField, + "gtefield": isGteField, + "gtfield": isGtField, + "ltefield": isLteField, + "ltfield": isLtField, + "fieldcontains": fieldContains, + "fieldexcludes": fieldExcludes, + "alpha": isAlpha, + "alphanum": isAlphanum, + "alphaunicode": isAlphaUnicode, + "alphanumunicode": isAlphanumUnicode, + "numeric": isNumeric, + "number": isNumber, + "hexadecimal": isHexadecimal, + "hexcolor": isHEXColor, + "rgb": isRGB, + "rgba": isRGBA, + "hsl": isHSL, + "hsla": isHSLA, + "e164": isE164, + "email": isEmail, + "url": isURL, + "uri": isURI, + "urn_rfc2141": isUrnRFC2141, // RFC 2141 + "file": isFile, + "base64": isBase64, + "base64url": isBase64URL, + "contains": contains, + "containsany": containsAny, + "containsrune": containsRune, + "excludes": excludes, + "excludesall": excludesAll, + "excludesrune": excludesRune, + "startswith": startsWith, + "endswith": endsWith, + "startsnotwith": startsNotWith, + "endsnotwith": endsNotWith, + "isbn": isISBN, + "isbn10": isISBN10, + "isbn13": isISBN13, + "eth_addr": isEthereumAddress, + "btc_addr": isBitcoinAddress, + "btc_addr_bech32": isBitcoinBech32Address, + "uuid": isUUID, + "uuid3": isUUID3, + "uuid4": isUUID4, + "uuid5": isUUID5, + "uuid_rfc4122": isUUIDRFC4122, + "uuid3_rfc4122": isUUID3RFC4122, + "uuid4_rfc4122": isUUID4RFC4122, + "uuid5_rfc4122": isUUID5RFC4122, + "ascii": isASCII, + "printascii": isPrintableASCII, + "multibyte": hasMultiByteCharacter, + "datauri": isDataURI, + "latitude": isLatitude, + "longitude": isLongitude, + "ssn": isSSN, + "ipv4": isIPv4, + "ipv6": isIPv6, + "ip": isIP, + "cidrv4": isCIDRv4, + "cidrv6": isCIDRv6, + "cidr": isCIDR, + "tcp4_addr": isTCP4AddrResolvable, + "tcp6_addr": isTCP6AddrResolvable, + "tcp_addr": isTCPAddrResolvable, + "udp4_addr": isUDP4AddrResolvable, + "udp6_addr": isUDP6AddrResolvable, + "udp_addr": isUDPAddrResolvable, + "ip4_addr": isIP4AddrResolvable, + "ip6_addr": isIP6AddrResolvable, + "ip_addr": isIPAddrResolvable, + "unix_addr": isUnixAddrResolvable, + "mac": isMAC, + "hostname": isHostnameRFC952, // RFC 952 + "hostname_rfc1123": isHostnameRFC1123, // RFC 1123 + "fqdn": isFQDN, + "unique": isUnique, + "oneof": isOneOf, + "html": isHTML, + "html_encoded": isHTMLEncoded, + "url_encoded": isURLEncoded, + "dir": isDir, + "json": isJSON, + "hostname_port": isHostnamePort, + "lowercase": isLowercase, + "uppercase": isUppercase, + "datetime": isDatetime, + "timezone": isTimeZone, + "iso3166_1_alpha2": isIso3166Alpha2, + "iso3166_1_alpha3": isIso3166Alpha3, + "iso3166_1_alpha_numeric": isIso3166AlphaNumeric, + } +) + +var oneofValsCache = map[string][]string{} +var oneofValsCacheRWLock = sync.RWMutex{} + +func parseOneOfParam2(s string) []string { + oneofValsCacheRWLock.RLock() + vals, ok := oneofValsCache[s] + oneofValsCacheRWLock.RUnlock() + if !ok { + oneofValsCacheRWLock.Lock() + vals = splitParamsRegex.FindAllString(s, -1) + for i := 0; i < len(vals); i++ { + vals[i] = strings.Replace(vals[i], "'", "", -1) + } + oneofValsCache[s] = vals + oneofValsCacheRWLock.Unlock() + } + return vals +} + +func isURLEncoded(fl FieldLevel) bool { + return uRLEncodedRegex.MatchString(fl.Field().String()) +} + +func isHTMLEncoded(fl FieldLevel) bool { + return hTMLEncodedRegex.MatchString(fl.Field().String()) +} + +func isHTML(fl FieldLevel) bool { + return hTMLRegex.MatchString(fl.Field().String()) +} + +func isOneOf(fl FieldLevel) bool { + vals := parseOneOfParam2(fl.Param()) + + field := fl.Field() + + var v string + switch field.Kind() { + case reflect.String: + v = field.String() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v = strconv.FormatInt(field.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + v = strconv.FormatUint(field.Uint(), 10) + default: + panic(fmt.Sprintf("Bad field type %T", field.Interface())) + } + for i := 0; i < len(vals); i++ { + if vals[i] == v { + return true + } + } + return false +} + +// isUnique is the validation function for validating if each array|slice|map value is unique +func isUnique(fl FieldLevel) bool { + + field := fl.Field() + param := fl.Param() + v := reflect.ValueOf(struct{}{}) + + switch field.Kind() { + case reflect.Slice, reflect.Array: + elem := field.Type().Elem() + if elem.Kind() == reflect.Ptr { + elem = elem.Elem() + } + + if param == "" { + m := reflect.MakeMap(reflect.MapOf(elem, v.Type())) + + for i := 0; i < field.Len(); i++ { + m.SetMapIndex(reflect.Indirect(field.Index(i)), v) + } + return field.Len() == m.Len() + } + + sf, ok := elem.FieldByName(param) + if !ok { + panic(fmt.Sprintf("Bad field name %s", param)) + } + + sfTyp := sf.Type + if sfTyp.Kind() == reflect.Ptr { + sfTyp = sfTyp.Elem() + } + + m := reflect.MakeMap(reflect.MapOf(sfTyp, v.Type())) + for i := 0; i < field.Len(); i++ { + m.SetMapIndex(reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param)), v) + } + return field.Len() == m.Len() + case reflect.Map: + m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) + + for _, k := range field.MapKeys() { + m.SetMapIndex(field.MapIndex(k), v) + } + return field.Len() == m.Len() + default: + panic(fmt.Sprintf("Bad field type %T", field.Interface())) + } +} + +// IsMAC is the validation function for validating if the field's value is a valid MAC address. +func isMAC(fl FieldLevel) bool { + + _, err := net.ParseMAC(fl.Field().String()) + + return err == nil +} + +// IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. +func isCIDRv4(fl FieldLevel) bool { + + ip, _, err := net.ParseCIDR(fl.Field().String()) + + return err == nil && ip.To4() != nil +} + +// IsCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address. +func isCIDRv6(fl FieldLevel) bool { + + ip, _, err := net.ParseCIDR(fl.Field().String()) + + return err == nil && ip.To4() == nil +} + +// IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address. +func isCIDR(fl FieldLevel) bool { + + _, _, err := net.ParseCIDR(fl.Field().String()) + + return err == nil +} + +// IsIPv4 is the validation function for validating if a value is a valid v4 IP address. +func isIPv4(fl FieldLevel) bool { + + ip := net.ParseIP(fl.Field().String()) + + return ip != nil && ip.To4() != nil +} + +// IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address. +func isIPv6(fl FieldLevel) bool { + + ip := net.ParseIP(fl.Field().String()) + + return ip != nil && ip.To4() == nil +} + +// IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address. +func isIP(fl FieldLevel) bool { + + ip := net.ParseIP(fl.Field().String()) + + return ip != nil +} + +// IsSSN is the validation function for validating if the field's value is a valid SSN. +func isSSN(fl FieldLevel) bool { + + field := fl.Field() + + if field.Len() != 11 { + return false + } + + return sSNRegex.MatchString(field.String()) +} + +// IsLongitude is the validation function for validating if the field's value is a valid longitude coordinate. +func isLongitude(fl FieldLevel) bool { + field := fl.Field() + + var v string + switch field.Kind() { + case reflect.String: + v = field.String() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v = strconv.FormatInt(field.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + v = strconv.FormatUint(field.Uint(), 10) + case reflect.Float32: + v = strconv.FormatFloat(field.Float(), 'f', -1, 32) + case reflect.Float64: + v = strconv.FormatFloat(field.Float(), 'f', -1, 64) + default: + panic(fmt.Sprintf("Bad field type %T", field.Interface())) + } + + return longitudeRegex.MatchString(v) +} + +// IsLatitude is the validation function for validating if the field's value is a valid latitude coordinate. +func isLatitude(fl FieldLevel) bool { + field := fl.Field() + + var v string + switch field.Kind() { + case reflect.String: + v = field.String() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + v = strconv.FormatInt(field.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + v = strconv.FormatUint(field.Uint(), 10) + case reflect.Float32: + v = strconv.FormatFloat(field.Float(), 'f', -1, 32) + case reflect.Float64: + v = strconv.FormatFloat(field.Float(), 'f', -1, 64) + default: + panic(fmt.Sprintf("Bad field type %T", field.Interface())) + } + + return latitudeRegex.MatchString(v) +} + +// IsDataURI is the validation function for validating if the field's value is a valid data URI. +func isDataURI(fl FieldLevel) bool { + + uri := strings.SplitN(fl.Field().String(), ",", 2) + + if len(uri) != 2 { + return false + } + + if !dataURIRegex.MatchString(uri[0]) { + return false + } + + return base64Regex.MatchString(uri[1]) +} + +// HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. +func hasMultiByteCharacter(fl FieldLevel) bool { + + field := fl.Field() + + if field.Len() == 0 { + return true + } + + return multibyteRegex.MatchString(field.String()) +} + +// IsPrintableASCII is the validation function for validating if the field's value is a valid printable ASCII character. +func isPrintableASCII(fl FieldLevel) bool { + return printableASCIIRegex.MatchString(fl.Field().String()) +} + +// IsASCII is the validation function for validating if the field's value is a valid ASCII character. +func isASCII(fl FieldLevel) bool { + return aSCIIRegex.MatchString(fl.Field().String()) +} + +// IsUUID5 is the validation function for validating if the field's value is a valid v5 UUID. +func isUUID5(fl FieldLevel) bool { + return uUID5Regex.MatchString(fl.Field().String()) +} + +// IsUUID4 is the validation function for validating if the field's value is a valid v4 UUID. +func isUUID4(fl FieldLevel) bool { + return uUID4Regex.MatchString(fl.Field().String()) +} + +// IsUUID3 is the validation function for validating if the field's value is a valid v3 UUID. +func isUUID3(fl FieldLevel) bool { + return uUID3Regex.MatchString(fl.Field().String()) +} + +// IsUUID is the validation function for validating if the field's value is a valid UUID of any version. +func isUUID(fl FieldLevel) bool { + return uUIDRegex.MatchString(fl.Field().String()) +} + +// IsUUID5RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v5 UUID. +func isUUID5RFC4122(fl FieldLevel) bool { + return uUID5RFC4122Regex.MatchString(fl.Field().String()) +} + +// IsUUID4RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v4 UUID. +func isUUID4RFC4122(fl FieldLevel) bool { + return uUID4RFC4122Regex.MatchString(fl.Field().String()) +} + +// IsUUID3RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v3 UUID. +func isUUID3RFC4122(fl FieldLevel) bool { + return uUID3RFC4122Regex.MatchString(fl.Field().String()) +} + +// IsUUIDRFC4122 is the validation function for validating if the field's value is a valid RFC4122 UUID of any version. +func isUUIDRFC4122(fl FieldLevel) bool { + return uUIDRFC4122Regex.MatchString(fl.Field().String()) +} + +// IsISBN is the validation function for validating if the field's value is a valid v10 or v13 ISBN. +func isISBN(fl FieldLevel) bool { + return isISBN10(fl) || isISBN13(fl) +} + +// IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. +func isISBN13(fl FieldLevel) bool { + + s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4) + + if !iSBN13Regex.MatchString(s) { + return false + } + + var checksum int32 + var i int32 + + factor := []int32{1, 3} + + for i = 0; i < 12; i++ { + checksum += factor[i%2] * int32(s[i]-'0') + } + + return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0 +} + +// IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. +func isISBN10(fl FieldLevel) bool { + + s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3) + + if !iSBN10Regex.MatchString(s) { + return false + } + + var checksum int32 + var i int32 + + for i = 0; i < 9; i++ { + checksum += (i + 1) * int32(s[i]-'0') + } + + if s[9] == 'X' { + checksum += 10 * 10 + } else { + checksum += 10 * int32(s[9]-'0') + } + + return checksum%11 == 0 +} + +// IsEthereumAddress is the validation function for validating if the field's value is a valid Ethereum address. +func isEthereumAddress(fl FieldLevel) bool { + address := fl.Field().String() + + if !ethAddressRegex.MatchString(address) { + return false + } + + if ethaddressRegexUpper.MatchString(address) || ethAddressRegexLower.MatchString(address) { + return true + } + + // Checksum validation. Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md + address = address[2:] // Skip "0x" prefix. + h := sha3.NewLegacyKeccak256() + // hash.Hash's io.Writer implementation says it never returns an error. https://golang.org/pkg/hash/#Hash + _, _ = h.Write([]byte(strings.ToLower(address))) + hash := hex.EncodeToString(h.Sum(nil)) + + for i := 0; i < len(address); i++ { + if address[i] <= '9' { // Skip 0-9 digits: they don't have upper/lower-case. + continue + } + if hash[i] > '7' && address[i] >= 'a' || hash[i] <= '7' && address[i] <= 'F' { + return false + } + } + + return true +} + +// IsBitcoinAddress is the validation function for validating if the field's value is a valid btc address +func isBitcoinAddress(fl FieldLevel) bool { + address := fl.Field().String() + + if !btcAddressRegex.MatchString(address) { + return false + } + + alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") + + decode := [25]byte{} + + for _, n := range []byte(address) { + d := bytes.IndexByte(alphabet, n) + + for i := 24; i >= 0; i-- { + d += 58 * int(decode[i]) + decode[i] = byte(d % 256) + d /= 256 + } + } + + h := sha256.New() + _, _ = h.Write(decode[:21]) + d := h.Sum([]byte{}) + h = sha256.New() + _, _ = h.Write(d) + + validchecksum := [4]byte{} + computedchecksum := [4]byte{} + + copy(computedchecksum[:], h.Sum(d[:0])) + copy(validchecksum[:], decode[21:]) + + return validchecksum == computedchecksum +} + +// IsBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address +func isBitcoinBech32Address(fl FieldLevel) bool { + address := fl.Field().String() + + if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) { + return false + } + + am := len(address) % 8 + + if am == 0 || am == 3 || am == 5 { + return false + } + + address = strings.ToLower(address) + + alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l" + + hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc + addr := address[3:] + dp := make([]int, 0, len(addr)) + + for _, c := range addr { + dp = append(dp, strings.IndexRune(alphabet, c)) + } + + ver := dp[0] + + if ver < 0 || ver > 16 { + return false + } + + if ver == 0 { + if len(address) != 42 && len(address) != 62 { + return false + } + } + + values := append(hr, dp...) + + GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} + + p := 1 + + for _, v := range values { + b := p >> 25 + p = (p&0x1ffffff)<<5 ^ v + + for i := 0; i < 5; i++ { + if (b>>uint(i))&1 == 1 { + p ^= GEN[i] + } + } + } + + if p != 1 { + return false + } + + b := uint(0) + acc := 0 + mv := (1 << 5) - 1 + var sw []int + + for _, v := range dp[1 : len(dp)-6] { + acc = (acc << 5) | v + b += 5 + for b >= 8 { + b -= 8 + sw = append(sw, (acc>>b)&mv) + } + } + + if len(sw) < 2 || len(sw) > 40 { + return false + } + + return true +} + +// ExcludesRune is the validation function for validating that the field's value does not contain the rune specified within the param. +func excludesRune(fl FieldLevel) bool { + return !containsRune(fl) +} + +// ExcludesAll is the validation function for validating that the field's value does not contain any of the characters specified within the param. +func excludesAll(fl FieldLevel) bool { + return !containsAny(fl) +} + +// Excludes is the validation function for validating that the field's value does not contain the text specified within the param. +func excludes(fl FieldLevel) bool { + return !contains(fl) +} + +// ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. +func containsRune(fl FieldLevel) bool { + + r, _ := utf8.DecodeRuneInString(fl.Param()) + + return strings.ContainsRune(fl.Field().String(), r) +} + +// ContainsAny is the validation function for validating that the field's value contains any of the characters specified within the param. +func containsAny(fl FieldLevel) bool { + return strings.ContainsAny(fl.Field().String(), fl.Param()) +} + +// Contains is the validation function for validating that the field's value contains the text specified within the param. +func contains(fl FieldLevel) bool { + return strings.Contains(fl.Field().String(), fl.Param()) +} + +// StartsWith is the validation function for validating that the field's value starts with the text specified within the param. +func startsWith(fl FieldLevel) bool { + return strings.HasPrefix(fl.Field().String(), fl.Param()) +} + +// EndsWith is the validation function for validating that the field's value ends with the text specified within the param. +func endsWith(fl FieldLevel) bool { + return strings.HasSuffix(fl.Field().String(), fl.Param()) +} + +// StartsNotWith is the validation function for validating that the field's value does not start with the text specified within the param. +func startsNotWith(fl FieldLevel) bool { + return !startsWith(fl) +} + +// EndsNotWith is the validation function for validating that the field's value does not end with the text specified within the param. +func endsNotWith(fl FieldLevel) bool { + return !endsWith(fl) +} + +// FieldContains is the validation function for validating if the current field's value contains the field specified by the param's value. +func fieldContains(fl FieldLevel) bool { + field := fl.Field() + + currentField, _, ok := fl.GetStructFieldOK() + + if !ok { + return false + } + + return strings.Contains(field.String(), currentField.String()) +} + +// FieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value. +func fieldExcludes(fl FieldLevel) bool { + field := fl.Field() + + currentField, _, ok := fl.GetStructFieldOK() + if !ok { + return true + } + + return !strings.Contains(field.String(), currentField.String()) +} + +// IsNeField is the validation function for validating if the current field's value is not equal to the field specified by the param's value. +func isNeField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + currentField, currentKind, ok := fl.GetStructFieldOK() + + if !ok || currentKind != kind { + return true + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return field.Int() != currentField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return field.Uint() != currentField.Uint() + + case reflect.Float32, reflect.Float64: + return field.Float() != currentField.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(field.Len()) != int64(currentField.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != currentField.Type() { + return true + } + + if fieldType == timeType { + + t := currentField.Interface().(time.Time) + fieldTime := field.Interface().(time.Time) + + return !fieldTime.Equal(t) + } + + } + + // default reflect.String: + return field.String() != currentField.String() +} + +// IsNe is the validation function for validating that the field's value does not equal the provided param value. +func isNe(fl FieldLevel) bool { + return !isEq(fl) +} + +// IsLteCrossStructField is the validation function for validating if the current field's value is less than or equal to the field, within a separate struct, specified by the param's value. +func isLteCrossStructField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + topField, topKind, ok := fl.GetStructFieldOK() + if !ok || topKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return field.Int() <= topField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return field.Uint() <= topField.Uint() + + case reflect.Float32, reflect.Float64: + return field.Float() <= topField.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(field.Len()) <= int64(topField.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != topField.Type() { + return false + } + + if fieldType == timeType { + + fieldTime := field.Interface().(time.Time) + topTime := topField.Interface().(time.Time) + + return fieldTime.Before(topTime) || fieldTime.Equal(topTime) + } + } + + // default reflect.String: + return field.String() <= topField.String() +} + +// IsLtCrossStructField is the validation function for validating if the current field's value is less than the field, within a separate struct, specified by the param's value. +// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. +func isLtCrossStructField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + topField, topKind, ok := fl.GetStructFieldOK() + if !ok || topKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return field.Int() < topField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return field.Uint() < topField.Uint() + + case reflect.Float32, reflect.Float64: + return field.Float() < topField.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(field.Len()) < int64(topField.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != topField.Type() { + return false + } + + if fieldType == timeType { + + fieldTime := field.Interface().(time.Time) + topTime := topField.Interface().(time.Time) + + return fieldTime.Before(topTime) + } + } + + // default reflect.String: + return field.String() < topField.String() +} + +// IsGteCrossStructField is the validation function for validating if the current field's value is greater than or equal to the field, within a separate struct, specified by the param's value. +func isGteCrossStructField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + topField, topKind, ok := fl.GetStructFieldOK() + if !ok || topKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return field.Int() >= topField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return field.Uint() >= topField.Uint() + + case reflect.Float32, reflect.Float64: + return field.Float() >= topField.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(field.Len()) >= int64(topField.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != topField.Type() { + return false + } + + if fieldType == timeType { + + fieldTime := field.Interface().(time.Time) + topTime := topField.Interface().(time.Time) + + return fieldTime.After(topTime) || fieldTime.Equal(topTime) + } + } + + // default reflect.String: + return field.String() >= topField.String() +} + +// IsGtCrossStructField is the validation function for validating if the current field's value is greater than the field, within a separate struct, specified by the param's value. +func isGtCrossStructField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + topField, topKind, ok := fl.GetStructFieldOK() + if !ok || topKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return field.Int() > topField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return field.Uint() > topField.Uint() + + case reflect.Float32, reflect.Float64: + return field.Float() > topField.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(field.Len()) > int64(topField.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != topField.Type() { + return false + } + + if fieldType == timeType { + + fieldTime := field.Interface().(time.Time) + topTime := topField.Interface().(time.Time) + + return fieldTime.After(topTime) + } + } + + // default reflect.String: + return field.String() > topField.String() +} + +// IsNeCrossStructField is the validation function for validating that the current field's value is not equal to the field, within a separate struct, specified by the param's value. +func isNeCrossStructField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + topField, currentKind, ok := fl.GetStructFieldOK() + if !ok || currentKind != kind { + return true + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return topField.Int() != field.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return topField.Uint() != field.Uint() + + case reflect.Float32, reflect.Float64: + return topField.Float() != field.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(topField.Len()) != int64(field.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != topField.Type() { + return true + } + + if fieldType == timeType { + + t := field.Interface().(time.Time) + fieldTime := topField.Interface().(time.Time) + + return !fieldTime.Equal(t) + } + } + + // default reflect.String: + return topField.String() != field.String() +} + +// IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value. +func isEqCrossStructField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + topField, topKind, ok := fl.GetStructFieldOK() + if !ok || topKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return topField.Int() == field.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return topField.Uint() == field.Uint() + + case reflect.Float32, reflect.Float64: + return topField.Float() == field.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(topField.Len()) == int64(field.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != topField.Type() { + return false + } + + if fieldType == timeType { + + t := field.Interface().(time.Time) + fieldTime := topField.Interface().(time.Time) + + return fieldTime.Equal(t) + } + } + + // default reflect.String: + return topField.String() == field.String() +} + +// IsEqField is the validation function for validating if the current field's value is equal to the field specified by the param's value. +func isEqField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + currentField, currentKind, ok := fl.GetStructFieldOK() + if !ok || currentKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return field.Int() == currentField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return field.Uint() == currentField.Uint() + + case reflect.Float32, reflect.Float64: + return field.Float() == currentField.Float() + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(field.Len()) == int64(currentField.Len()) + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != currentField.Type() { + return false + } + + if fieldType == timeType { + + t := currentField.Interface().(time.Time) + fieldTime := field.Interface().(time.Time) + + return fieldTime.Equal(t) + } + + } + + // default reflect.String: + return field.String() == currentField.String() +} + +// IsEq is the validation function for validating if the current field's value is equal to the param's value. +func isEq(fl FieldLevel) bool { + + field := fl.Field() + param := fl.Param() + + switch field.Kind() { + + case reflect.String: + return field.String() == param + + case reflect.Slice, reflect.Map, reflect.Array: + p := asInt(param) + + return int64(field.Len()) == p + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p := asIntFromType(field.Type(), param) + + return field.Int() == p + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p := asUint(param) + + return field.Uint() == p + + case reflect.Float32, reflect.Float64: + p := asFloat(param) + + return field.Float() == p + + case reflect.Bool: + p := asBool(param) + + return field.Bool() == p + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// IsBase64 is the validation function for validating if the current field's value is a valid base 64. +func isBase64(fl FieldLevel) bool { + return base64Regex.MatchString(fl.Field().String()) +} + +// IsBase64URL is the validation function for validating if the current field's value is a valid base64 URL safe string. +func isBase64URL(fl FieldLevel) bool { + return base64URLRegex.MatchString(fl.Field().String()) +} + +// IsURI is the validation function for validating if the current field's value is a valid URI. +func isURI(fl FieldLevel) bool { + + field := fl.Field() + + switch field.Kind() { + + case reflect.String: + + s := field.String() + + // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 + // emulate browser and strip the '#' suffix prior to validation. see issue-#237 + if i := strings.Index(s, "#"); i > -1 { + s = s[:i] + } + + if len(s) == 0 { + return false + } + + _, err := url.ParseRequestURI(s) + + return err == nil + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// IsURL is the validation function for validating if the current field's value is a valid URL. +func isURL(fl FieldLevel) bool { + + field := fl.Field() + + switch field.Kind() { + + case reflect.String: + + var i int + s := field.String() + + // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 + // emulate browser and strip the '#' suffix prior to validation. see issue-#237 + if i = strings.Index(s, "#"); i > -1 { + s = s[:i] + } + + if len(s) == 0 { + return false + } + + url, err := url.ParseRequestURI(s) + + if err != nil || url.Scheme == "" { + return false + } + + return true + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. +func isUrnRFC2141(fl FieldLevel) bool { + field := fl.Field() + + switch field.Kind() { + + case reflect.String: + + str := field.String() + + _, match := urn.Parse([]byte(str)) + + return match + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// IsFile is the validation function for validating if the current field's value is a valid file path. +func isFile(fl FieldLevel) bool { + field := fl.Field() + + switch field.Kind() { + case reflect.String: + fileInfo, err := os.Stat(field.String()) + if err != nil { + return false + } + + return !fileInfo.IsDir() + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// IsE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number. +func isE164(fl FieldLevel) bool { + return e164Regex.MatchString(fl.Field().String()) +} + +// IsEmail is the validation function for validating if the current field's value is a valid email address. +func isEmail(fl FieldLevel) bool { + return emailRegex.MatchString(fl.Field().String()) +} + +// IsHSLA is the validation function for validating if the current field's value is a valid HSLA color. +func isHSLA(fl FieldLevel) bool { + return hslaRegex.MatchString(fl.Field().String()) +} + +// IsHSL is the validation function for validating if the current field's value is a valid HSL color. +func isHSL(fl FieldLevel) bool { + return hslRegex.MatchString(fl.Field().String()) +} + +// IsRGBA is the validation function for validating if the current field's value is a valid RGBA color. +func isRGBA(fl FieldLevel) bool { + return rgbaRegex.MatchString(fl.Field().String()) +} + +// IsRGB is the validation function for validating if the current field's value is a valid RGB color. +func isRGB(fl FieldLevel) bool { + return rgbRegex.MatchString(fl.Field().String()) +} + +// IsHEXColor is the validation function for validating if the current field's value is a valid HEX color. +func isHEXColor(fl FieldLevel) bool { + return hexcolorRegex.MatchString(fl.Field().String()) +} + +// IsHexadecimal is the validation function for validating if the current field's value is a valid hexadecimal. +func isHexadecimal(fl FieldLevel) bool { + return hexadecimalRegex.MatchString(fl.Field().String()) +} + +// IsNumber is the validation function for validating if the current field's value is a valid number. +func isNumber(fl FieldLevel) bool { + switch fl.Field().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: + return true + default: + return numberRegex.MatchString(fl.Field().String()) + } +} + +// IsNumeric is the validation function for validating if the current field's value is a valid numeric value. +func isNumeric(fl FieldLevel) bool { + switch fl.Field().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: + return true + default: + return numericRegex.MatchString(fl.Field().String()) + } +} + +// IsAlphanum is the validation function for validating if the current field's value is a valid alphanumeric value. +func isAlphanum(fl FieldLevel) bool { + return alphaNumericRegex.MatchString(fl.Field().String()) +} + +// IsAlpha is the validation function for validating if the current field's value is a valid alpha value. +func isAlpha(fl FieldLevel) bool { + return alphaRegex.MatchString(fl.Field().String()) +} + +// IsAlphanumUnicode is the validation function for validating if the current field's value is a valid alphanumeric unicode value. +func isAlphanumUnicode(fl FieldLevel) bool { + return alphaUnicodeNumericRegex.MatchString(fl.Field().String()) +} + +// IsAlphaUnicode is the validation function for validating if the current field's value is a valid alpha unicode value. +func isAlphaUnicode(fl FieldLevel) bool { + return alphaUnicodeRegex.MatchString(fl.Field().String()) +} + +// isDefault is the opposite of required aka hasValue +func isDefault(fl FieldLevel) bool { + return !hasValue(fl) +} + +// HasValue is the validation function for validating if the current field's value is not the default static value. +func hasValue(fl FieldLevel) bool { + field := fl.Field() + switch field.Kind() { + case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: + return !field.IsNil() + default: + if fl.(*validate).fldIsPointer && field.Interface() != nil { + return true + } + return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() + } +} + +// requireCheckField is a func for check field kind +func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue bool) bool { + field := fl.Field() + kind := field.Kind() + var nullable, found bool + if len(param) > 0 { + field, kind, nullable, found = fl.GetStructFieldOKAdvanced2(fl.Parent(), param) + if !found { + return defaultNotFoundValue + } + } + switch kind { + case reflect.Invalid: + return defaultNotFoundValue + case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: + return field.IsNil() + default: + if nullable && field.Interface() != nil { + return false + } + return field.IsValid() && field.Interface() == reflect.Zero(field.Type()).Interface() + } +} + +// requireCheckFieldValue is a func for check field value +func requireCheckFieldValue(fl FieldLevel, param string, value string, defaultNotFoundValue bool) bool { + field, kind, _, found := fl.GetStructFieldOKAdvanced2(fl.Parent(), param) + if !found { + return defaultNotFoundValue + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return field.Int() == asInt(value) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return field.Uint() == asUint(value) + + case reflect.Float32, reflect.Float64: + return field.Float() == asFloat(value) + + case reflect.Slice, reflect.Map, reflect.Array: + return int64(field.Len()) == asInt(value) + } + + // default reflect.String: + return field.String() == value +} + +// requiredIf is the validation function +// The field under validation must be present and not empty only if all the other specified fields are equal to the value following with the specified field. +func requiredIf(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + if len(params)%2 != 0 { + panic(fmt.Sprintf("Bad param number for required_if %s", fl.FieldName())) + } + for i := 0; i < len(params); i += 2 { + if !requireCheckFieldValue(fl, params[i], params[i+1], false) { + return true + } + } + return hasValue(fl) +} + +// requiredUnless is the validation function +// The field under validation must be present and not empty only unless all the other specified fields are equal to the value following with the specified field. +func requiredUnless(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + if len(params)%2 != 0 { + panic(fmt.Sprintf("Bad param number for required_unless %s", fl.FieldName())) + } + + for i := 0; i < len(params); i += 2 { + if requireCheckFieldValue(fl, params[i], params[i+1], false) { + return true + } + } + return hasValue(fl) +} + +// ExcludedWith is the validation function +// The field under validation must not be present or is empty if any of the other specified fields are present. +func excludedWith(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + for _, param := range params { + if !requireCheckFieldKind(fl, param, true) { + return !hasValue(fl) + } + } + return true +} + +// RequiredWith is the validation function +// The field under validation must be present and not empty only if any of the other specified fields are present. +func requiredWith(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + for _, param := range params { + if !requireCheckFieldKind(fl, param, true) { + return hasValue(fl) + } + } + return true +} + +// ExcludedWithAll is the validation function +// The field under validation must not be present or is empty if all of the other specified fields are present. +func excludedWithAll(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + for _, param := range params { + if requireCheckFieldKind(fl, param, true) { + return true + } + } + return !hasValue(fl) +} + +// RequiredWithAll is the validation function +// The field under validation must be present and not empty only if all of the other specified fields are present. +func requiredWithAll(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + for _, param := range params { + if requireCheckFieldKind(fl, param, true) { + return true + } + } + return hasValue(fl) +} + +// ExcludedWithout is the validation function +// The field under validation must not be present or is empty when any of the other specified fields are not present. +func excludedWithout(fl FieldLevel) bool { + if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { + return !hasValue(fl) + } + return true +} + +// RequiredWithout is the validation function +// The field under validation must be present and not empty only when any of the other specified fields are not present. +func requiredWithout(fl FieldLevel) bool { + if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { + return hasValue(fl) + } + return true +} + +// RequiredWithoutAll is the validation function +// The field under validation must not be present or is empty when all of the other specified fields are not present. +func excludedWithoutAll(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + for _, param := range params { + if !requireCheckFieldKind(fl, param, true) { + return true + } + } + return !hasValue(fl) +} + +// RequiredWithoutAll is the validation function +// The field under validation must be present and not empty only when all of the other specified fields are not present. +func requiredWithoutAll(fl FieldLevel) bool { + params := parseOneOfParam2(fl.Param()) + for _, param := range params { + if !requireCheckFieldKind(fl, param, true) { + return true + } + } + return hasValue(fl) +} + +// IsGteField is the validation function for validating if the current field's value is greater than or equal to the field specified by the param's value. +func isGteField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + currentField, currentKind, ok := fl.GetStructFieldOK() + if !ok || currentKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + + return field.Int() >= currentField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + + return field.Uint() >= currentField.Uint() + + case reflect.Float32, reflect.Float64: + + return field.Float() >= currentField.Float() + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != currentField.Type() { + return false + } + + if fieldType == timeType { + + t := currentField.Interface().(time.Time) + fieldTime := field.Interface().(time.Time) + + return fieldTime.After(t) || fieldTime.Equal(t) + } + } + + // default reflect.String + return len(field.String()) >= len(currentField.String()) +} + +// IsGtField is the validation function for validating if the current field's value is greater than the field specified by the param's value. +func isGtField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + currentField, currentKind, ok := fl.GetStructFieldOK() + if !ok || currentKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + + return field.Int() > currentField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + + return field.Uint() > currentField.Uint() + + case reflect.Float32, reflect.Float64: + + return field.Float() > currentField.Float() + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != currentField.Type() { + return false + } + + if fieldType == timeType { + + t := currentField.Interface().(time.Time) + fieldTime := field.Interface().(time.Time) + + return fieldTime.After(t) + } + } + + // default reflect.String + return len(field.String()) > len(currentField.String()) +} + +// IsGte is the validation function for validating if the current field's value is greater than or equal to the param's value. +func isGte(fl FieldLevel) bool { + + field := fl.Field() + param := fl.Param() + + switch field.Kind() { + + case reflect.String: + p := asInt(param) + + return int64(utf8.RuneCountInString(field.String())) >= p + + case reflect.Slice, reflect.Map, reflect.Array: + p := asInt(param) + + return int64(field.Len()) >= p + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p := asIntFromType(field.Type(), param) + + return field.Int() >= p + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p := asUint(param) + + return field.Uint() >= p + + case reflect.Float32, reflect.Float64: + p := asFloat(param) + + return field.Float() >= p + + case reflect.Struct: + + if field.Type() == timeType { + + now := time.Now().UTC() + t := field.Interface().(time.Time) + + return t.After(now) || t.Equal(now) + } + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// IsGt is the validation function for validating if the current field's value is greater than the param's value. +func isGt(fl FieldLevel) bool { + + field := fl.Field() + param := fl.Param() + + switch field.Kind() { + + case reflect.String: + p := asInt(param) + + return int64(utf8.RuneCountInString(field.String())) > p + + case reflect.Slice, reflect.Map, reflect.Array: + p := asInt(param) + + return int64(field.Len()) > p + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p := asIntFromType(field.Type(), param) + + return field.Int() > p + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p := asUint(param) + + return field.Uint() > p + + case reflect.Float32, reflect.Float64: + p := asFloat(param) + + return field.Float() > p + case reflect.Struct: + + if field.Type() == timeType { + + return field.Interface().(time.Time).After(time.Now().UTC()) + } + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// HasLengthOf is the validation function for validating if the current field's value is equal to the param's value. +func hasLengthOf(fl FieldLevel) bool { + + field := fl.Field() + param := fl.Param() + + switch field.Kind() { + + case reflect.String: + p := asInt(param) + + return int64(utf8.RuneCountInString(field.String())) == p + + case reflect.Slice, reflect.Map, reflect.Array: + p := asInt(param) + + return int64(field.Len()) == p + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p := asIntFromType(field.Type(), param) + + return field.Int() == p + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p := asUint(param) + + return field.Uint() == p + + case reflect.Float32, reflect.Float64: + p := asFloat(param) + + return field.Float() == p + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// HasMinOf is the validation function for validating if the current field's value is greater than or equal to the param's value. +func hasMinOf(fl FieldLevel) bool { + return isGte(fl) +} + +// IsLteField is the validation function for validating if the current field's value is less than or equal to the field specified by the param's value. +func isLteField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + currentField, currentKind, ok := fl.GetStructFieldOK() + if !ok || currentKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + + return field.Int() <= currentField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + + return field.Uint() <= currentField.Uint() + + case reflect.Float32, reflect.Float64: + + return field.Float() <= currentField.Float() + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != currentField.Type() { + return false + } + + if fieldType == timeType { + + t := currentField.Interface().(time.Time) + fieldTime := field.Interface().(time.Time) + + return fieldTime.Before(t) || fieldTime.Equal(t) + } + } + + // default reflect.String + return len(field.String()) <= len(currentField.String()) +} + +// IsLtField is the validation function for validating if the current field's value is less than the field specified by the param's value. +func isLtField(fl FieldLevel) bool { + + field := fl.Field() + kind := field.Kind() + + currentField, currentKind, ok := fl.GetStructFieldOK() + if !ok || currentKind != kind { + return false + } + + switch kind { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + + return field.Int() < currentField.Int() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + + return field.Uint() < currentField.Uint() + + case reflect.Float32, reflect.Float64: + + return field.Float() < currentField.Float() + + case reflect.Struct: + + fieldType := field.Type() + + // Not Same underlying type i.e. struct and time + if fieldType != currentField.Type() { + return false + } + + if fieldType == timeType { + + t := currentField.Interface().(time.Time) + fieldTime := field.Interface().(time.Time) + + return fieldTime.Before(t) + } + } + + // default reflect.String + return len(field.String()) < len(currentField.String()) +} + +// IsLte is the validation function for validating if the current field's value is less than or equal to the param's value. +func isLte(fl FieldLevel) bool { + + field := fl.Field() + param := fl.Param() + + switch field.Kind() { + + case reflect.String: + p := asInt(param) + + return int64(utf8.RuneCountInString(field.String())) <= p + + case reflect.Slice, reflect.Map, reflect.Array: + p := asInt(param) + + return int64(field.Len()) <= p + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p := asIntFromType(field.Type(), param) + + return field.Int() <= p + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p := asUint(param) + + return field.Uint() <= p + + case reflect.Float32, reflect.Float64: + p := asFloat(param) + + return field.Float() <= p + + case reflect.Struct: + + if field.Type() == timeType { + + now := time.Now().UTC() + t := field.Interface().(time.Time) + + return t.Before(now) || t.Equal(now) + } + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// IsLt is the validation function for validating if the current field's value is less than the param's value. +func isLt(fl FieldLevel) bool { + + field := fl.Field() + param := fl.Param() + + switch field.Kind() { + + case reflect.String: + p := asInt(param) + + return int64(utf8.RuneCountInString(field.String())) < p + + case reflect.Slice, reflect.Map, reflect.Array: + p := asInt(param) + + return int64(field.Len()) < p + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + p := asIntFromType(field.Type(), param) + + return field.Int() < p + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + p := asUint(param) + + return field.Uint() < p + + case reflect.Float32, reflect.Float64: + p := asFloat(param) + + return field.Float() < p + + case reflect.Struct: + + if field.Type() == timeType { + + return field.Interface().(time.Time).Before(time.Now().UTC()) + } + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// HasMaxOf is the validation function for validating if the current field's value is less than or equal to the param's value. +func hasMaxOf(fl FieldLevel) bool { + return isLte(fl) +} + +// IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. +func isTCP4AddrResolvable(fl FieldLevel) bool { + + if !isIP4Addr(fl) { + return false + } + + _, err := net.ResolveTCPAddr("tcp4", fl.Field().String()) + return err == nil +} + +// IsTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address. +func isTCP6AddrResolvable(fl FieldLevel) bool { + + if !isIP6Addr(fl) { + return false + } + + _, err := net.ResolveTCPAddr("tcp6", fl.Field().String()) + + return err == nil +} + +// IsTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address. +func isTCPAddrResolvable(fl FieldLevel) bool { + + if !isIP4Addr(fl) && !isIP6Addr(fl) { + return false + } + + _, err := net.ResolveTCPAddr("tcp", fl.Field().String()) + + return err == nil +} + +// IsUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address. +func isUDP4AddrResolvable(fl FieldLevel) bool { + + if !isIP4Addr(fl) { + return false + } + + _, err := net.ResolveUDPAddr("udp4", fl.Field().String()) + + return err == nil +} + +// IsUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address. +func isUDP6AddrResolvable(fl FieldLevel) bool { + + if !isIP6Addr(fl) { + return false + } + + _, err := net.ResolveUDPAddr("udp6", fl.Field().String()) + + return err == nil +} + +// IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. +func isUDPAddrResolvable(fl FieldLevel) bool { + + if !isIP4Addr(fl) && !isIP6Addr(fl) { + return false + } + + _, err := net.ResolveUDPAddr("udp", fl.Field().String()) + + return err == nil +} + +// IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. +func isIP4AddrResolvable(fl FieldLevel) bool { + + if !isIPv4(fl) { + return false + } + + _, err := net.ResolveIPAddr("ip4", fl.Field().String()) + + return err == nil +} + +// IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. +func isIP6AddrResolvable(fl FieldLevel) bool { + + if !isIPv6(fl) { + return false + } + + _, err := net.ResolveIPAddr("ip6", fl.Field().String()) + + return err == nil +} + +// IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. +func isIPAddrResolvable(fl FieldLevel) bool { + + if !isIP(fl) { + return false + } + + _, err := net.ResolveIPAddr("ip", fl.Field().String()) + + return err == nil +} + +// IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. +func isUnixAddrResolvable(fl FieldLevel) bool { + + _, err := net.ResolveUnixAddr("unix", fl.Field().String()) + + return err == nil +} + +func isIP4Addr(fl FieldLevel) bool { + + val := fl.Field().String() + + if idx := strings.LastIndex(val, ":"); idx != -1 { + val = val[0:idx] + } + + ip := net.ParseIP(val) + + return ip != nil && ip.To4() != nil +} + +func isIP6Addr(fl FieldLevel) bool { + + val := fl.Field().String() + + if idx := strings.LastIndex(val, ":"); idx != -1 { + if idx != 0 && val[idx-1:idx] == "]" { + val = val[1 : idx-1] + } + } + + ip := net.ParseIP(val) + + return ip != nil && ip.To4() == nil +} + +func isHostnameRFC952(fl FieldLevel) bool { + return hostnameRegexRFC952.MatchString(fl.Field().String()) +} + +func isHostnameRFC1123(fl FieldLevel) bool { + return hostnameRegexRFC1123.MatchString(fl.Field().String()) +} + +func isFQDN(fl FieldLevel) bool { + val := fl.Field().String() + + if val == "" { + return false + } + + return fqdnRegexRFC1123.MatchString(val) +} + +// IsDir is the validation function for validating if the current field's value is a valid directory. +func isDir(fl FieldLevel) bool { + field := fl.Field() + + if field.Kind() == reflect.String { + fileInfo, err := os.Stat(field.String()) + if err != nil { + return false + } + + return fileInfo.IsDir() + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// isJSON is the validation function for validating if the current field's value is a valid json string. +func isJSON(fl FieldLevel) bool { + field := fl.Field() + + if field.Kind() == reflect.String { + val := field.String() + return json.Valid([]byte(val)) + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// isHostnamePort validates a : combination for fields typically used for socket address. +func isHostnamePort(fl FieldLevel) bool { + val := fl.Field().String() + host, port, err := net.SplitHostPort(val) + if err != nil { + return false + } + // Port must be a iny <= 65535. + if portNum, err := strconv.ParseInt(port, 10, 32); err != nil || portNum > 65535 || portNum < 1 { + return false + } + + // If host is specified, it should match a DNS name + if host != "" { + return hostnameRegexRFC1123.MatchString(host) + } + return true +} + +// isLowercase is the validation function for validating if the current field's value is a lowercase string. +func isLowercase(fl FieldLevel) bool { + field := fl.Field() + + if field.Kind() == reflect.String { + if field.String() == "" { + return false + } + return field.String() == strings.ToLower(field.String()) + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// isUppercase is the validation function for validating if the current field's value is an uppercase string. +func isUppercase(fl FieldLevel) bool { + field := fl.Field() + + if field.Kind() == reflect.String { + if field.String() == "" { + return false + } + return field.String() == strings.ToUpper(field.String()) + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// isDatetime is the validation function for validating if the current field's value is a valid datetime string. +func isDatetime(fl FieldLevel) bool { + field := fl.Field() + param := fl.Param() + + if field.Kind() == reflect.String { + _, err := time.Parse(param, field.String()) + + return err == nil + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// isTimeZone is the validation function for validating if the current field's value is a valid time zone string. +func isTimeZone(fl FieldLevel) bool { + field := fl.Field() + + if field.Kind() == reflect.String { + // empty value is converted to UTC by time.LoadLocation but disallow it as it is not a valid time zone name + if field.String() == "" { + return false + } + + // Local value is converted to the current system time zone by time.LoadLocation but disallow it as it is not a valid time zone name + if strings.ToLower(field.String()) == "local" { + return false + } + + _, err := time.LoadLocation(field.String()) + return err == nil + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + +// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-2 country code. +func isIso3166Alpha2(fl FieldLevel) bool { + val := fl.Field().String() + return iso3166_1_alpha2[val] +} + +// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-3 country code. +func isIso3166Alpha3(fl FieldLevel) bool { + val := fl.Field().String() + return iso3166_1_alpha3[val] +} + +// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-numeric country code. +func isIso3166AlphaNumeric(fl FieldLevel) bool { + field := fl.Field() + + var code int + switch field.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + code = int(field.Int() % 1000) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + code = int(field.Uint() % 1000) + default: + panic(fmt.Sprintf("Bad field type %T", field.Interface())) + } + return iso3166_1_alpha_numeric[code] +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/cache.go b/taskman-server/vendor/github.com/go-playground/validator/v10/cache.go new file mode 100644 index 00000000..0d18d6ec --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/cache.go @@ -0,0 +1,322 @@ +package validator + +import ( + "fmt" + "reflect" + "strings" + "sync" + "sync/atomic" +) + +type tagType uint8 + +const ( + typeDefault tagType = iota + typeOmitEmpty + typeIsDefault + typeNoStructLevel + typeStructOnly + typeDive + typeOr + typeKeys + typeEndKeys +) + +const ( + invalidValidation = "Invalid validation tag on field '%s'" + undefinedValidation = "Undefined validation function '%s' on field '%s'" + keysTagNotDefined = "'" + endKeysTag + "' tag encountered without a corresponding '" + keysTag + "' tag" +) + +type structCache struct { + lock sync.Mutex + m atomic.Value // map[reflect.Type]*cStruct +} + +func (sc *structCache) Get(key reflect.Type) (c *cStruct, found bool) { + c, found = sc.m.Load().(map[reflect.Type]*cStruct)[key] + return +} + +func (sc *structCache) Set(key reflect.Type, value *cStruct) { + m := sc.m.Load().(map[reflect.Type]*cStruct) + nm := make(map[reflect.Type]*cStruct, len(m)+1) + for k, v := range m { + nm[k] = v + } + nm[key] = value + sc.m.Store(nm) +} + +type tagCache struct { + lock sync.Mutex + m atomic.Value // map[string]*cTag +} + +func (tc *tagCache) Get(key string) (c *cTag, found bool) { + c, found = tc.m.Load().(map[string]*cTag)[key] + return +} + +func (tc *tagCache) Set(key string, value *cTag) { + m := tc.m.Load().(map[string]*cTag) + nm := make(map[string]*cTag, len(m)+1) + for k, v := range m { + nm[k] = v + } + nm[key] = value + tc.m.Store(nm) +} + +type cStruct struct { + name string + fields []*cField + fn StructLevelFuncCtx +} + +type cField struct { + idx int + name string + altName string + namesEqual bool + cTags *cTag +} + +type cTag struct { + tag string + aliasTag string + actualAliasTag string + param string + keys *cTag // only populated when using tag's 'keys' and 'endkeys' for map key validation + next *cTag + fn FuncCtx + typeof tagType + hasTag bool + hasAlias bool + hasParam bool // true if parameter used eg. eq= where the equal sign has been set + isBlockEnd bool // indicates the current tag represents the last validation in the block + runValidationWhenNil bool +} + +func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStruct { + v.structCache.lock.Lock() + defer v.structCache.lock.Unlock() // leave as defer! because if inner panics, it will never get unlocked otherwise! + + typ := current.Type() + + // could have been multiple trying to access, but once first is done this ensures struct + // isn't parsed again. + cs, ok := v.structCache.Get(typ) + if ok { + return cs + } + + cs = &cStruct{name: sName, fields: make([]*cField, 0), fn: v.structLevelFuncs[typ]} + + numFields := current.NumField() + + var ctag *cTag + var fld reflect.StructField + var tag string + var customName string + + for i := 0; i < numFields; i++ { + + fld = typ.Field(i) + + if !fld.Anonymous && len(fld.PkgPath) > 0 { + continue + } + + tag = fld.Tag.Get(v.tagName) + + if tag == skipValidationTag { + continue + } + + customName = fld.Name + + if v.hasTagNameFunc { + name := v.tagNameFunc(fld) + if len(name) > 0 { + customName = name + } + } + + // NOTE: cannot use shared tag cache, because tags may be equal, but things like alias may be different + // and so only struct level caching can be used instead of combined with Field tag caching + + if len(tag) > 0 { + ctag, _ = v.parseFieldTagsRecursive(tag, fld.Name, "", false) + } else { + // even if field doesn't have validations need cTag for traversing to potential inner/nested + // elements of the field. + ctag = new(cTag) + } + + cs.fields = append(cs.fields, &cField{ + idx: i, + name: fld.Name, + altName: customName, + cTags: ctag, + namesEqual: fld.Name == customName, + }) + } + v.structCache.Set(typ, cs) + return cs +} + +func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias string, hasAlias bool) (firstCtag *cTag, current *cTag) { + var t string + noAlias := len(alias) == 0 + tags := strings.Split(tag, tagSeparator) + + for i := 0; i < len(tags); i++ { + t = tags[i] + if noAlias { + alias = t + } + + // check map for alias and process new tags, otherwise process as usual + if tagsVal, found := v.aliases[t]; found { + if i == 0 { + firstCtag, current = v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) + } else { + next, curr := v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) + current.next, current = next, curr + + } + continue + } + + var prevTag tagType + + if i == 0 { + current = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true, typeof: typeDefault} + firstCtag = current + } else { + prevTag = current.typeof + current.next = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} + current = current.next + } + + switch t { + case diveTag: + current.typeof = typeDive + continue + + case keysTag: + current.typeof = typeKeys + + if i == 0 || prevTag != typeDive { + panic(fmt.Sprintf("'%s' tag must be immediately preceded by the '%s' tag", keysTag, diveTag)) + } + + current.typeof = typeKeys + + // need to pass along only keys tag + // need to increment i to skip over the keys tags + b := make([]byte, 0, 64) + + i++ + + for ; i < len(tags); i++ { + + b = append(b, tags[i]...) + b = append(b, ',') + + if tags[i] == endKeysTag { + break + } + } + + current.keys, _ = v.parseFieldTagsRecursive(string(b[:len(b)-1]), fieldName, "", false) + continue + + case endKeysTag: + current.typeof = typeEndKeys + + // if there are more in tags then there was no keysTag defined + // and an error should be thrown + if i != len(tags)-1 { + panic(keysTagNotDefined) + } + return + + case omitempty: + current.typeof = typeOmitEmpty + continue + + case structOnlyTag: + current.typeof = typeStructOnly + continue + + case noStructLevelTag: + current.typeof = typeNoStructLevel + continue + + default: + if t == isdefault { + current.typeof = typeIsDefault + } + // if a pipe character is needed within the param you must use the utf8Pipe representation "0x7C" + orVals := strings.Split(t, orSeparator) + + for j := 0; j < len(orVals); j++ { + vals := strings.SplitN(orVals[j], tagKeySeparator, 2) + if noAlias { + alias = vals[0] + current.aliasTag = alias + } else { + current.actualAliasTag = t + } + + if j > 0 { + current.next = &cTag{aliasTag: alias, actualAliasTag: current.actualAliasTag, hasAlias: hasAlias, hasTag: true} + current = current.next + } + current.hasParam = len(vals) > 1 + + current.tag = vals[0] + if len(current.tag) == 0 { + panic(strings.TrimSpace(fmt.Sprintf(invalidValidation, fieldName))) + } + + if wrapper, ok := v.validations[current.tag]; ok { + current.fn = wrapper.fn + current.runValidationWhenNil = wrapper.runValidatinOnNil + } else { + panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, current.tag, fieldName))) + } + + if len(orVals) > 1 { + current.typeof = typeOr + } + + if len(vals) > 1 { + current.param = strings.Replace(strings.Replace(vals[1], utf8HexComma, ",", -1), utf8Pipe, "|", -1) + } + } + current.isBlockEnd = true + } + } + return +} + +func (v *Validate) fetchCacheTag(tag string) *cTag { + // find cached tag + ctag, found := v.tagCache.Get(tag) + if !found { + v.tagCache.lock.Lock() + defer v.tagCache.lock.Unlock() + + // could have been multiple trying to access, but once first is done this ensures tag + // isn't parsed again. + ctag, found = v.tagCache.Get(tag) + if !found { + ctag, _ = v.parseFieldTagsRecursive(tag, "", "", false) + v.tagCache.Set(tag, ctag) + } + } + return ctag +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/country_codes.go b/taskman-server/vendor/github.com/go-playground/validator/v10/country_codes.go new file mode 100644 index 00000000..ef81eada --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/country_codes.go @@ -0,0 +1,162 @@ +package validator + +var iso3166_1_alpha2 = map[string]bool{ + // see: https://www.iso.org/iso-3166-country-codes.html + "AF": true, "AX": true, "AL": true, "DZ": true, "AS": true, + "AD": true, "AO": true, "AI": true, "AQ": true, "AG": true, + "AR": true, "AM": true, "AW": true, "AU": true, "AT": true, + "AZ": true, "BS": true, "BH": true, "BD": true, "BB": true, + "BY": true, "BE": true, "BZ": true, "BJ": true, "BM": true, + "BT": true, "BO": true, "BQ": true, "BA": true, "BW": true, + "BV": true, "BR": true, "IO": true, "BN": true, "BG": true, + "BF": true, "BI": true, "KH": true, "CM": true, "CA": true, + "CV": true, "KY": true, "CF": true, "TD": true, "CL": true, + "CN": true, "CX": true, "CC": true, "CO": true, "KM": true, + "CG": true, "CD": true, "CK": true, "CR": true, "CI": true, + "HR": true, "CU": true, "CW": true, "CY": true, "CZ": true, + "DK": true, "DJ": true, "DM": true, "DO": true, "EC": true, + "EG": true, "SV": true, "GQ": true, "ER": true, "EE": true, + "ET": true, "FK": true, "FO": true, "FJ": true, "FI": true, + "FR": true, "GF": true, "PF": true, "TF": true, "GA": true, + "GM": true, "GE": true, "DE": true, "GH": true, "GI": true, + "GR": true, "GL": true, "GD": true, "GP": true, "GU": true, + "GT": true, "GG": true, "GN": true, "GW": true, "GY": true, + "HT": true, "HM": true, "VA": true, "HN": true, "HK": true, + "HU": true, "IS": true, "IN": true, "ID": true, "IR": true, + "IQ": true, "IE": true, "IM": true, "IL": true, "IT": true, + "JM": true, "JP": true, "JE": true, "JO": true, "KZ": true, + "KE": true, "KI": true, "KP": true, "KR": true, "KW": true, + "KG": true, "LA": true, "LV": true, "LB": true, "LS": true, + "LR": true, "LY": true, "LI": true, "LT": true, "LU": true, + "MO": true, "MK": true, "MG": true, "MW": true, "MY": true, + "MV": true, "ML": true, "MT": true, "MH": true, "MQ": true, + "MR": true, "MU": true, "YT": true, "MX": true, "FM": true, + "MD": true, "MC": true, "MN": true, "ME": true, "MS": true, + "MA": true, "MZ": true, "MM": true, "NA": true, "NR": true, + "NP": true, "NL": true, "NC": true, "NZ": true, "NI": true, + "NE": true, "NG": true, "NU": true, "NF": true, "MP": true, + "NO": true, "OM": true, "PK": true, "PW": true, "PS": true, + "PA": true, "PG": true, "PY": true, "PE": true, "PH": true, + "PN": true, "PL": true, "PT": true, "PR": true, "QA": true, + "RE": true, "RO": true, "RU": true, "RW": true, "BL": true, + "SH": true, "KN": true, "LC": true, "MF": true, "PM": true, + "VC": true, "WS": true, "SM": true, "ST": true, "SA": true, + "SN": true, "RS": true, "SC": true, "SL": true, "SG": true, + "SX": true, "SK": true, "SI": true, "SB": true, "SO": true, + "ZA": true, "GS": true, "SS": true, "ES": true, "LK": true, + "SD": true, "SR": true, "SJ": true, "SZ": true, "SE": true, + "CH": true, "SY": true, "TW": true, "TJ": true, "TZ": true, + "TH": true, "TL": true, "TG": true, "TK": true, "TO": true, + "TT": true, "TN": true, "TR": true, "TM": true, "TC": true, + "TV": true, "UG": true, "UA": true, "AE": true, "GB": true, + "US": true, "UM": true, "UY": true, "UZ": true, "VU": true, + "VE": true, "VN": true, "VG": true, "VI": true, "WF": true, + "EH": true, "YE": true, "ZM": true, "ZW": true, +} + +var iso3166_1_alpha3 = map[string]bool{ + // see: https://www.iso.org/iso-3166-country-codes.html + "AFG": true, "ALB": true, "DZA": true, "ASM": true, "AND": true, + "AGO": true, "AIA": true, "ATA": true, "ATG": true, "ARG": true, + "ARM": true, "ABW": true, "AUS": true, "AUT": true, "AZE": true, + "BHS": true, "BHR": true, "BGD": true, "BRB": true, "BLR": true, + "BEL": true, "BLZ": true, "BEN": true, "BMU": true, "BTN": true, + "BOL": true, "BES": true, "BIH": true, "BWA": true, "BVT": true, + "BRA": true, "IOT": true, "BRN": true, "BGR": true, "BFA": true, + "BDI": true, "CPV": true, "KHM": true, "CMR": true, "CAN": true, + "CYM": true, "CAF": true, "TCD": true, "CHL": true, "CHN": true, + "CXR": true, "CCK": true, "COL": true, "COM": true, "COD": true, + "COG": true, "COK": true, "CRI": true, "HRV": true, "CUB": true, + "CUW": true, "CYP": true, "CZE": true, "CIV": true, "DNK": true, + "DJI": true, "DMA": true, "DOM": true, "ECU": true, "EGY": true, + "SLV": true, "GNQ": true, "ERI": true, "EST": true, "SWZ": true, + "ETH": true, "FLK": true, "FRO": true, "FJI": true, "FIN": true, + "FRA": true, "GUF": true, "PYF": true, "ATF": true, "GAB": true, + "GMB": true, "GEO": true, "DEU": true, "GHA": true, "GIB": true, + "GRC": true, "GRL": true, "GRD": true, "GLP": true, "GUM": true, + "GTM": true, "GGY": true, "GIN": true, "GNB": true, "GUY": true, + "HTI": true, "HMD": true, "VAT": true, "HND": true, "HKG": true, + "HUN": true, "ISL": true, "IND": true, "IDN": true, "IRN": true, + "IRQ": true, "IRL": true, "IMN": true, "ISR": true, "ITA": true, + "JAM": true, "JPN": true, "JEY": true, "JOR": true, "KAZ": true, + "KEN": true, "KIR": true, "PRK": true, "KOR": true, "KWT": true, + "KGZ": true, "LAO": true, "LVA": true, "LBN": true, "LSO": true, + "LBR": true, "LBY": true, "LIE": true, "LTU": true, "LUX": true, + "MAC": true, "MDG": true, "MWI": true, "MYS": true, "MDV": true, + "MLI": true, "MLT": true, "MHL": true, "MTQ": true, "MRT": true, + "MUS": true, "MYT": true, "MEX": true, "FSM": true, "MDA": true, + "MCO": true, "MNG": true, "MNE": true, "MSR": true, "MAR": true, + "MOZ": true, "MMR": true, "NAM": true, "NRU": true, "NPL": true, + "NLD": true, "NCL": true, "NZL": true, "NIC": true, "NER": true, + "NGA": true, "NIU": true, "NFK": true, "MKD": true, "MNP": true, + "NOR": true, "OMN": true, "PAK": true, "PLW": true, "PSE": true, + "PAN": true, "PNG": true, "PRY": true, "PER": true, "PHL": true, + "PCN": true, "POL": true, "PRT": true, "PRI": true, "QAT": true, + "ROU": true, "RUS": true, "RWA": true, "REU": true, "BLM": true, + "SHN": true, "KNA": true, "LCA": true, "MAF": true, "SPM": true, + "VCT": true, "WSM": true, "SMR": true, "STP": true, "SAU": true, + "SEN": true, "SRB": true, "SYC": true, "SLE": true, "SGP": true, + "SXM": true, "SVK": true, "SVN": true, "SLB": true, "SOM": true, + "ZAF": true, "SGS": true, "SSD": true, "ESP": true, "LKA": true, + "SDN": true, "SUR": true, "SJM": true, "SWE": true, "CHE": true, + "SYR": true, "TWN": true, "TJK": true, "TZA": true, "THA": true, + "TLS": true, "TGO": true, "TKL": true, "TON": true, "TTO": true, + "TUN": true, "TUR": true, "TKM": true, "TCA": true, "TUV": true, + "UGA": true, "UKR": true, "ARE": true, "GBR": true, "UMI": true, + "USA": true, "URY": true, "UZB": true, "VUT": true, "VEN": true, + "VNM": true, "VGB": true, "VIR": true, "WLF": true, "ESH": true, + "YEM": true, "ZMB": true, "ZWE": true, "ALA": true, +} +var iso3166_1_alpha_numeric = map[int]bool{ + // see: https://www.iso.org/iso-3166-country-codes.html + 4: true, 8: true, 12: true, 16: true, 20: true, + 24: true, 660: true, 10: true, 28: true, 32: true, + 51: true, 533: true, 36: true, 40: true, 31: true, + 44: true, 48: true, 50: true, 52: true, 112: true, + 56: true, 84: true, 204: true, 60: true, 64: true, + 68: true, 535: true, 70: true, 72: true, 74: true, + 76: true, 86: true, 96: true, 100: true, 854: true, + 108: true, 132: true, 116: true, 120: true, 124: true, + 136: true, 140: true, 148: true, 152: true, 156: true, + 162: true, 166: true, 170: true, 174: true, 180: true, + 178: true, 184: true, 188: true, 191: true, 192: true, + 531: true, 196: true, 203: true, 384: true, 208: true, + 262: true, 212: true, 214: true, 218: true, 818: true, + 222: true, 226: true, 232: true, 233: true, 748: true, + 231: true, 238: true, 234: true, 242: true, 246: true, + 250: true, 254: true, 258: true, 260: true, 266: true, + 270: true, 268: true, 276: true, 288: true, 292: true, + 300: true, 304: true, 308: true, 312: true, 316: true, + 320: true, 831: true, 324: true, 624: true, 328: true, + 332: true, 334: true, 336: true, 340: true, 344: true, + 348: true, 352: true, 356: true, 360: true, 364: true, + 368: true, 372: true, 833: true, 376: true, 380: true, + 388: true, 392: true, 832: true, 400: true, 398: true, + 404: true, 296: true, 408: true, 410: true, 414: true, + 417: true, 418: true, 428: true, 422: true, 426: true, + 430: true, 434: true, 438: true, 440: true, 442: true, + 446: true, 450: true, 454: true, 458: true, 462: true, + 466: true, 470: true, 584: true, 474: true, 478: true, + 480: true, 175: true, 484: true, 583: true, 498: true, + 492: true, 496: true, 499: true, 500: true, 504: true, + 508: true, 104: true, 516: true, 520: true, 524: true, + 528: true, 540: true, 554: true, 558: true, 562: true, + 566: true, 570: true, 574: true, 807: true, 580: true, + 578: true, 512: true, 586: true, 585: true, 275: true, + 591: true, 598: true, 600: true, 604: true, 608: true, + 612: true, 616: true, 620: true, 630: true, 634: true, + 642: true, 643: true, 646: true, 638: true, 652: true, + 654: true, 659: true, 662: true, 663: true, 666: true, + 670: true, 882: true, 674: true, 678: true, 682: true, + 686: true, 688: true, 690: true, 694: true, 702: true, + 534: true, 703: true, 705: true, 90: true, 706: true, + 710: true, 239: true, 728: true, 724: true, 144: true, + 729: true, 740: true, 744: true, 752: true, 756: true, + 760: true, 158: true, 762: true, 834: true, 764: true, + 626: true, 768: true, 772: true, 776: true, 780: true, + 788: true, 792: true, 795: true, 796: true, 798: true, + 800: true, 804: true, 784: true, 826: true, 581: true, + 840: true, 858: true, 860: true, 548: true, 862: true, + 704: true, 92: true, 850: true, 876: true, 732: true, + 887: true, 894: true, 716: true, 248: true, +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/doc.go b/taskman-server/vendor/github.com/go-playground/validator/v10/doc.go new file mode 100644 index 00000000..a816c20a --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/doc.go @@ -0,0 +1,1308 @@ +/* +Package validator implements value validations for structs and individual fields +based on tags. + +It can also handle Cross-Field and Cross-Struct validation for nested structs +and has the ability to dive into arrays and maps of any type. + +see more examples https://github.com/go-playground/validator/tree/master/_examples + +Validation Functions Return Type error + +Doing things this way is actually the way the standard library does, see the +file.Open method here: + + https://golang.org/pkg/os/#Open. + +The authors return type "error" to avoid the issue discussed in the following, +where err is always != nil: + + http://stackoverflow.com/a/29138676/3158232 + https://github.com/go-playground/validator/issues/134 + +Validator only InvalidValidationError for bad validation input, nil or +ValidationErrors as type error; so, in your code all you need to do is check +if the error returned is not nil, and if it's not check if error is +InvalidValidationError ( if necessary, most of the time it isn't ) type cast +it to type ValidationErrors like so err.(validator.ValidationErrors). + +Custom Validation Functions + +Custom Validation functions can be added. Example: + + // Structure + func customFunc(fl validator.FieldLevel) bool { + + if fl.Field().String() == "invalid" { + return false + } + + return true + } + + validate.RegisterValidation("custom tag name", customFunc) + // NOTES: using the same tag name as an existing function + // will overwrite the existing one + +Cross-Field Validation + +Cross-Field Validation can be done via the following tags: + - eqfield + - nefield + - gtfield + - gtefield + - ltfield + - ltefield + - eqcsfield + - necsfield + - gtcsfield + - gtecsfield + - ltcsfield + - ltecsfield + +If, however, some custom cross-field validation is required, it can be done +using a custom validation. + +Why not just have cross-fields validation tags (i.e. only eqcsfield and not +eqfield)? + +The reason is efficiency. If you want to check a field within the same struct +"eqfield" only has to find the field on the same struct (1 level). But, if we +used "eqcsfield" it could be multiple levels down. Example: + + type Inner struct { + StartDate time.Time + } + + type Outer struct { + InnerStructField *Inner + CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"` + } + + now := time.Now() + + inner := &Inner{ + StartDate: now, + } + + outer := &Outer{ + InnerStructField: inner, + CreatedAt: now, + } + + errs := validate.Struct(outer) + + // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed + // into the function + // when calling validate.VarWithValue(val, field, tag) val will be + // whatever you pass, struct, field... + // when calling validate.Field(field, tag) val will be nil + +Multiple Validators + +Multiple validators on a field will process in the order defined. Example: + + type Test struct { + Field `validate:"max=10,min=1"` + } + + // max will be checked then min + +Bad Validator definitions are not handled by the library. Example: + + type Test struct { + Field `validate:"min=10,max=0"` + } + + // this definition of min max will never succeed + +Using Validator Tags + +Baked In Cross-Field validation only compares fields on the same struct. +If Cross-Field + Cross-Struct validation is needed you should implement your +own custom validator. + +Comma (",") is the default separator of validation tags. If you wish to +have a comma included within the parameter (i.e. excludesall=,) you will need to +use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma, +so the above will become excludesall=0x2C. + + type Test struct { + Field `validate:"excludesall=,"` // BAD! Do not include a comma. + Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation. + } + +Pipe ("|") is the 'or' validation tags deparator. If you wish to +have a pipe included within the parameter i.e. excludesall=| you will need to +use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe, +so the above will become excludesall=0x7C + + type Test struct { + Field `validate:"excludesall=|"` // BAD! Do not include a a pipe! + Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation. + } + + +Baked In Validators and Tags + +Here is a list of the current built in validators: + + +Skip Field + +Tells the validation to skip this struct field; this is particularly +handy in ignoring embedded structs from being validated. (Usage: -) + Usage: - + + +Or Operator + +This is the 'or' operator allowing multiple validators to be used and +accepted. (Usage: rgb|rgba) <-- this would allow either rgb or rgba +colors to be accepted. This can also be combined with 'and' for example +( Usage: omitempty,rgb|rgba) + + Usage: | + +StructOnly + +When a field that is a nested struct is encountered, and contains this flag +any validation on the nested struct will be run, but none of the nested +struct fields will be validated. This is useful if inside of your program +you know the struct will be valid, but need to verify it has been assigned. +NOTE: only "required" and "omitempty" can be used on a struct itself. + + Usage: structonly + +NoStructLevel + +Same as structonly tag except that any struct level validations will not run. + + Usage: nostructlevel + +Omit Empty + +Allows conditional validation, for example if a field is not set with +a value (Determined by the "required" validator) then other validation +such as min or max won't run, but if a value is set validation will run. + + Usage: omitempty + +Dive + +This tells the validator to dive into a slice, array or map and validate that +level of the slice, array or map with the validation tags that follow. +Multidimensional nesting is also supported, each level you wish to dive will +require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see +the Keys & EndKeys section just below. + + Usage: dive + +Example #1 + + [][]string with validation tag "gt=0,dive,len=1,dive,required" + // gt=0 will be applied to [] + // len=1 will be applied to []string + // required will be applied to string + +Example #2 + + [][]string with validation tag "gt=0,dive,dive,required" + // gt=0 will be applied to [] + // []string will be spared validation + // required will be applied to string + +Keys & EndKeys + +These are to be used together directly after the dive tag and tells the validator +that anything between 'keys' and 'endkeys' applies to the keys of a map and not the +values; think of it like the 'dive' tag, but for map keys instead of values. +Multidimensional nesting is also supported, each level you wish to validate will +require another 'keys' and 'endkeys' tag. These tags are only valid for maps. + + Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags + +Example #1 + + map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required" + // gt=0 will be applied to the map itself + // eg=1|eq=2 will be applied to the map keys + // required will be applied to map values + +Example #2 + + map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required" + // gt=0 will be applied to the map itself + // eg=1|eq=2 will be applied to each array element in the the map keys + // required will be applied to map values + +Required + +This validates that the value is not the data types default zero value. +For numbers ensures value is not zero. For strings ensures value is +not "". For slices, maps, pointers, interfaces, channels and functions +ensures the value is not nil. + + Usage: required + +Required If + +The field under validation must be present and not empty only if all +the other specified fields are equal to the value following the specified +field. For strings ensures value is not "". For slices, maps, pointers, +interfaces, channels and functions ensures the value is not nil. + + Usage: required_if + +Examples: + + // require the field if the Field1 is equal to the parameter given: + Usage: required_if=Field1 foobar + + // require the field if the Field1 and Field2 is equal to the value respectively: + Usage: required_if=Field1 foo Field2 bar + +Required Unless + +The field under validation must be present and not empty unless all +the other specified fields are equal to the value following the specified +field. For strings ensures value is not "". For slices, maps, pointers, +interfaces, channels and functions ensures the value is not nil. + + Usage: required_unless + +Examples: + + // require the field unless the Field1 is equal to the parameter given: + Usage: required_unless=Field1 foobar + + // require the field unless the Field1 and Field2 is equal to the value respectively: + Usage: required_unless=Field1 foo Field2 bar + +Required With + +The field under validation must be present and not empty only if any +of the other specified fields are present. For strings ensures value is +not "". For slices, maps, pointers, interfaces, channels and functions +ensures the value is not nil. + + Usage: required_with + +Examples: + + // require the field if the Field1 is present: + Usage: required_with=Field1 + + // require the field if the Field1 or Field2 is present: + Usage: required_with=Field1 Field2 + +Required With All + +The field under validation must be present and not empty only if all +of the other specified fields are present. For strings ensures value is +not "". For slices, maps, pointers, interfaces, channels and functions +ensures the value is not nil. + + Usage: required_with_all + +Example: + + // require the field if the Field1 and Field2 is present: + Usage: required_with_all=Field1 Field2 + +Required Without + +The field under validation must be present and not empty only when any +of the other specified fields are not present. For strings ensures value is +not "". For slices, maps, pointers, interfaces, channels and functions +ensures the value is not nil. + + Usage: required_without + +Examples: + + // require the field if the Field1 is not present: + Usage: required_without=Field1 + + // require the field if the Field1 or Field2 is not present: + Usage: required_without=Field1 Field2 + +Required Without All + +The field under validation must be present and not empty only when all +of the other specified fields are not present. For strings ensures value is +not "". For slices, maps, pointers, interfaces, channels and functions +ensures the value is not nil. + + Usage: required_without_all + +Example: + + // require the field if the Field1 and Field2 is not present: + Usage: required_without_all=Field1 Field2 + +Is Default + +This validates that the value is the default value and is almost the +opposite of required. + + Usage: isdefault + +Length + +For numbers, length will ensure that the value is +equal to the parameter given. For strings, it checks that +the string length is exactly that number of characters. For slices, +arrays, and maps, validates the number of items. + +Example #1 + + Usage: len=10 + +Example #2 (time.Duration) + +For time.Duration, len will ensure that the value is equal to the duration given +in the parameter. + + Usage: len=1h30m + +Maximum + +For numbers, max will ensure that the value is +less than or equal to the parameter given. For strings, it checks +that the string length is at most that number of characters. For +slices, arrays, and maps, validates the number of items. + +Example #1 + + Usage: max=10 + +Example #2 (time.Duration) + +For time.Duration, max will ensure that the value is less than or equal to the +duration given in the parameter. + + Usage: max=1h30m + +Minimum + +For numbers, min will ensure that the value is +greater or equal to the parameter given. For strings, it checks that +the string length is at least that number of characters. For slices, +arrays, and maps, validates the number of items. + +Example #1 + + Usage: min=10 + +Example #2 (time.Duration) + +For time.Duration, min will ensure that the value is greater than or equal to +the duration given in the parameter. + + Usage: min=1h30m + +Equals + +For strings & numbers, eq will ensure that the value is +equal to the parameter given. For slices, arrays, and maps, +validates the number of items. + +Example #1 + + Usage: eq=10 + +Example #2 (time.Duration) + +For time.Duration, eq will ensure that the value is equal to the duration given +in the parameter. + + Usage: eq=1h30m + +Not Equal + +For strings & numbers, ne will ensure that the value is not +equal to the parameter given. For slices, arrays, and maps, +validates the number of items. + +Example #1 + + Usage: ne=10 + +Example #2 (time.Duration) + +For time.Duration, ne will ensure that the value is not equal to the duration +given in the parameter. + + Usage: ne=1h30m + +One Of + +For strings, ints, and uints, oneof will ensure that the value +is one of the values in the parameter. The parameter should be +a list of values separated by whitespace. Values may be +strings or numbers. To match strings with spaces in them, include +the target string between single quotes. + + Usage: oneof=red green + oneof='red green' 'blue yellow' + oneof=5 7 9 + +Greater Than + +For numbers, this will ensure that the value is greater than the +parameter given. For strings, it checks that the string length +is greater than that number of characters. For slices, arrays +and maps it validates the number of items. + +Example #1 + + Usage: gt=10 + +Example #2 (time.Time) + +For time.Time ensures the time value is greater than time.Now.UTC(). + + Usage: gt + +Example #3 (time.Duration) + +For time.Duration, gt will ensure that the value is greater than the duration +given in the parameter. + + Usage: gt=1h30m + +Greater Than or Equal + +Same as 'min' above. Kept both to make terminology with 'len' easier. + +Example #1 + + Usage: gte=10 + +Example #2 (time.Time) + +For time.Time ensures the time value is greater than or equal to time.Now.UTC(). + + Usage: gte + +Example #3 (time.Duration) + +For time.Duration, gte will ensure that the value is greater than or equal to +the duration given in the parameter. + + Usage: gte=1h30m + +Less Than + +For numbers, this will ensure that the value is less than the parameter given. +For strings, it checks that the string length is less than that number of +characters. For slices, arrays, and maps it validates the number of items. + +Example #1 + + Usage: lt=10 + +Example #2 (time.Time) + +For time.Time ensures the time value is less than time.Now.UTC(). + + Usage: lt + +Example #3 (time.Duration) + +For time.Duration, lt will ensure that the value is less than the duration given +in the parameter. + + Usage: lt=1h30m + +Less Than or Equal + +Same as 'max' above. Kept both to make terminology with 'len' easier. + +Example #1 + + Usage: lte=10 + +Example #2 (time.Time) + +For time.Time ensures the time value is less than or equal to time.Now.UTC(). + + Usage: lte + +Example #3 (time.Duration) + +For time.Duration, lte will ensure that the value is less than or equal to the +duration given in the parameter. + + Usage: lte=1h30m + +Field Equals Another Field + +This will validate the field value against another fields value either within +a struct or passed in field. + +Example #1: + + // Validation on Password field using: + Usage: eqfield=ConfirmPassword + +Example #2: + + // Validating by field: + validate.VarWithValue(password, confirmpassword, "eqfield") + +Field Equals Another Field (relative) + +This does the same as eqfield except that it validates the field provided relative +to the top level struct. + + Usage: eqcsfield=InnerStructField.Field) + +Field Does Not Equal Another Field + +This will validate the field value against another fields value either within +a struct or passed in field. + +Examples: + + // Confirm two colors are not the same: + // + // Validation on Color field: + Usage: nefield=Color2 + + // Validating by field: + validate.VarWithValue(color1, color2, "nefield") + +Field Does Not Equal Another Field (relative) + +This does the same as nefield except that it validates the field provided +relative to the top level struct. + + Usage: necsfield=InnerStructField.Field + +Field Greater Than Another Field + +Only valid for Numbers, time.Duration and time.Time types, this will validate +the field value against another fields value either within a struct or passed in +field. usage examples are for validation of a Start and End date: + +Example #1: + + // Validation on End field using: + validate.Struct Usage(gtfield=Start) + +Example #2: + + // Validating by field: + validate.VarWithValue(start, end, "gtfield") + +Field Greater Than Another Relative Field + +This does the same as gtfield except that it validates the field provided +relative to the top level struct. + + Usage: gtcsfield=InnerStructField.Field + +Field Greater Than or Equal To Another Field + +Only valid for Numbers, time.Duration and time.Time types, this will validate +the field value against another fields value either within a struct or passed in +field. usage examples are for validation of a Start and End date: + +Example #1: + + // Validation on End field using: + validate.Struct Usage(gtefield=Start) + +Example #2: + + // Validating by field: + validate.VarWithValue(start, end, "gtefield") + +Field Greater Than or Equal To Another Relative Field + +This does the same as gtefield except that it validates the field provided relative +to the top level struct. + + Usage: gtecsfield=InnerStructField.Field + +Less Than Another Field + +Only valid for Numbers, time.Duration and time.Time types, this will validate +the field value against another fields value either within a struct or passed in +field. usage examples are for validation of a Start and End date: + +Example #1: + + // Validation on End field using: + validate.Struct Usage(ltfield=Start) + +Example #2: + + // Validating by field: + validate.VarWithValue(start, end, "ltfield") + +Less Than Another Relative Field + +This does the same as ltfield except that it validates the field provided relative +to the top level struct. + + Usage: ltcsfield=InnerStructField.Field + +Less Than or Equal To Another Field + +Only valid for Numbers, time.Duration and time.Time types, this will validate +the field value against another fields value either within a struct or passed in +field. usage examples are for validation of a Start and End date: + +Example #1: + + // Validation on End field using: + validate.Struct Usage(ltefield=Start) + +Example #2: + + // Validating by field: + validate.VarWithValue(start, end, "ltefield") + +Less Than or Equal To Another Relative Field + +This does the same as ltefield except that it validates the field provided relative +to the top level struct. + + Usage: ltecsfield=InnerStructField.Field + +Field Contains Another Field + +This does the same as contains except for struct fields. It should only be used +with string types. See the behavior of reflect.Value.String() for behavior on +other types. + + Usage: containsfield=InnerStructField.Field + +Field Excludes Another Field + +This does the same as excludes except for struct fields. It should only be used +with string types. See the behavior of reflect.Value.String() for behavior on +other types. + + Usage: excludesfield=InnerStructField.Field + +Unique + +For arrays & slices, unique will ensure that there are no duplicates. +For maps, unique will ensure that there are no duplicate values. +For slices of struct, unique will ensure that there are no duplicate values +in a field of the struct specified via a parameter. + + // For arrays, slices, and maps: + Usage: unique + + // For slices of struct: + Usage: unique=field + +Alpha Only + +This validates that a string value contains ASCII alpha characters only + + Usage: alpha + +Alphanumeric + +This validates that a string value contains ASCII alphanumeric characters only + + Usage: alphanum + +Alpha Unicode + +This validates that a string value contains unicode alpha characters only + + Usage: alphaunicode + +Alphanumeric Unicode + +This validates that a string value contains unicode alphanumeric characters only + + Usage: alphanumunicode + +Number + +This validates that a string value contains number values only. +For integers or float it returns true. + + Usage: number + +Numeric + +This validates that a string value contains a basic numeric value. +basic excludes exponents etc... +for integers or float it returns true. + + Usage: numeric + +Hexadecimal String + +This validates that a string value contains a valid hexadecimal. + + Usage: hexadecimal + +Hexcolor String + +This validates that a string value contains a valid hex color including +hashtag (#) + + Usage: hexcolor + +Lowercase String + +This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string. + + Usage: lowercase + +Uppercase String + +This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string. + + Usage: uppercase + +RGB String + +This validates that a string value contains a valid rgb color + + Usage: rgb + +RGBA String + +This validates that a string value contains a valid rgba color + + Usage: rgba + +HSL String + +This validates that a string value contains a valid hsl color + + Usage: hsl + +HSLA String + +This validates that a string value contains a valid hsla color + + Usage: hsla + +E.164 Phone Number String + +This validates that a string value contains a valid E.164 Phone number +https://en.wikipedia.org/wiki/E.164 (ex. +1123456789) + + Usage: e164 + +E-mail String + +This validates that a string value contains a valid email +This may not conform to all possibilities of any rfc standard, but neither +does any email provider accept all possibilities. + + Usage: email + +JSON String + +This validates that a string value is valid JSON + + Usage: json + +File path + +This validates that a string value contains a valid file path and that +the file exists on the machine. +This is done using os.Stat, which is a platform independent function. + + Usage: file + +URL String + +This validates that a string value contains a valid url +This will accept any url the golang request uri accepts but must contain +a schema for example http:// or rtmp:// + + Usage: url + +URI String + +This validates that a string value contains a valid uri +This will accept any uri the golang request uri accepts + + Usage: uri + +Urn RFC 2141 String + +This validataes that a string value contains a valid URN +according to the RFC 2141 spec. + + Usage: urn_rfc2141 + +Base64 String + +This validates that a string value contains a valid base64 value. +Although an empty string is valid base64 this will report an empty string +as an error, if you wish to accept an empty string as valid you can use +this with the omitempty tag. + + Usage: base64 + +Base64URL String + +This validates that a string value contains a valid base64 URL safe value +according the the RFC4648 spec. +Although an empty string is a valid base64 URL safe value, this will report +an empty string as an error, if you wish to accept an empty string as valid +you can use this with the omitempty tag. + + Usage: base64url + +Bitcoin Address + +This validates that a string value contains a valid bitcoin address. +The format of the string is checked to ensure it matches one of the three formats +P2PKH, P2SH and performs checksum validation. + + Usage: btc_addr + +Bitcoin Bech32 Address (segwit) + +This validates that a string value contains a valid bitcoin Bech32 address as defined +by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) +Special thanks to Pieter Wuille for providng reference implementations. + + Usage: btc_addr_bech32 + +Ethereum Address + +This validates that a string value contains a valid ethereum address. +The format of the string is checked to ensure it matches the standard Ethereum address format. + + Usage: eth_addr + +Contains + +This validates that a string value contains the substring value. + + Usage: contains=@ + +Contains Any + +This validates that a string value contains any Unicode code points +in the substring value. + + Usage: containsany=!@#? + +Contains Rune + +This validates that a string value contains the supplied rune value. + + Usage: containsrune=@ + +Excludes + +This validates that a string value does not contain the substring value. + + Usage: excludes=@ + +Excludes All + +This validates that a string value does not contain any Unicode code +points in the substring value. + + Usage: excludesall=!@#? + +Excludes Rune + +This validates that a string value does not contain the supplied rune value. + + Usage: excludesrune=@ + +Starts With + +This validates that a string value starts with the supplied string value + + Usage: startswith=hello + +Ends With + +This validates that a string value ends with the supplied string value + + Usage: endswith=goodbye + +Does Not Start With + +This validates that a string value does not start with the supplied string value + + Usage: startsnotwith=hello + +Does Not End With + +This validates that a string value does not end with the supplied string value + + Usage: endsnotwith=goodbye + +International Standard Book Number + +This validates that a string value contains a valid isbn10 or isbn13 value. + + Usage: isbn + +International Standard Book Number 10 + +This validates that a string value contains a valid isbn10 value. + + Usage: isbn10 + +International Standard Book Number 13 + +This validates that a string value contains a valid isbn13 value. + + Usage: isbn13 + +Universally Unique Identifier UUID + +This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead. + + Usage: uuid + +Universally Unique Identifier UUID v3 + +This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead. + + Usage: uuid3 + +Universally Unique Identifier UUID v4 + +This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead. + + Usage: uuid4 + +Universally Unique Identifier UUID v5 + +This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead. + + Usage: uuid5 + +ASCII + +This validates that a string value contains only ASCII characters. +NOTE: if the string is blank, this validates as true. + + Usage: ascii + +Printable ASCII + +This validates that a string value contains only printable ASCII characters. +NOTE: if the string is blank, this validates as true. + + Usage: printascii + +Multi-Byte Characters + +This validates that a string value contains one or more multibyte characters. +NOTE: if the string is blank, this validates as true. + + Usage: multibyte + +Data URL + +This validates that a string value contains a valid DataURI. +NOTE: this will also validate that the data portion is valid base64 + + Usage: datauri + +Latitude + +This validates that a string value contains a valid latitude. + + Usage: latitude + +Longitude + +This validates that a string value contains a valid longitude. + + Usage: longitude + +Social Security Number SSN + +This validates that a string value contains a valid U.S. Social Security Number. + + Usage: ssn + +Internet Protocol Address IP + +This validates that a string value contains a valid IP Address. + + Usage: ip + +Internet Protocol Address IPv4 + +This validates that a string value contains a valid v4 IP Address. + + Usage: ipv4 + +Internet Protocol Address IPv6 + +This validates that a string value contains a valid v6 IP Address. + + Usage: ipv6 + +Classless Inter-Domain Routing CIDR + +This validates that a string value contains a valid CIDR Address. + + Usage: cidr + +Classless Inter-Domain Routing CIDRv4 + +This validates that a string value contains a valid v4 CIDR Address. + + Usage: cidrv4 + +Classless Inter-Domain Routing CIDRv6 + +This validates that a string value contains a valid v6 CIDR Address. + + Usage: cidrv6 + +Transmission Control Protocol Address TCP + +This validates that a string value contains a valid resolvable TCP Address. + + Usage: tcp_addr + +Transmission Control Protocol Address TCPv4 + +This validates that a string value contains a valid resolvable v4 TCP Address. + + Usage: tcp4_addr + +Transmission Control Protocol Address TCPv6 + +This validates that a string value contains a valid resolvable v6 TCP Address. + + Usage: tcp6_addr + +User Datagram Protocol Address UDP + +This validates that a string value contains a valid resolvable UDP Address. + + Usage: udp_addr + +User Datagram Protocol Address UDPv4 + +This validates that a string value contains a valid resolvable v4 UDP Address. + + Usage: udp4_addr + +User Datagram Protocol Address UDPv6 + +This validates that a string value contains a valid resolvable v6 UDP Address. + + Usage: udp6_addr + +Internet Protocol Address IP + +This validates that a string value contains a valid resolvable IP Address. + + Usage: ip_addr + +Internet Protocol Address IPv4 + +This validates that a string value contains a valid resolvable v4 IP Address. + + Usage: ip4_addr + +Internet Protocol Address IPv6 + +This validates that a string value contains a valid resolvable v6 IP Address. + + Usage: ip6_addr + +Unix domain socket end point Address + +This validates that a string value contains a valid Unix Address. + + Usage: unix_addr + +Media Access Control Address MAC + +This validates that a string value contains a valid MAC Address. + + Usage: mac + +Note: See Go's ParseMAC for accepted formats and types: + + http://golang.org/src/net/mac.go?s=866:918#L29 + +Hostname RFC 952 + +This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952 + + Usage: hostname + +Hostname RFC 1123 + +This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123 + + Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias. + +Full Qualified Domain Name (FQDN) + +This validates that a string value contains a valid FQDN. + + Usage: fqdn + +HTML Tags + +This validates that a string value appears to be an HTML element tag +including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element + + Usage: html + +HTML Encoded + +This validates that a string value is a proper character reference in decimal +or hexadecimal format + + Usage: html_encoded + +URL Encoded + +This validates that a string value is percent-encoded (URL encoded) according +to https://tools.ietf.org/html/rfc3986#section-2.1 + + Usage: url_encoded + +Directory + +This validates that a string value contains a valid directory and that +it exists on the machine. +This is done using os.Stat, which is a platform independent function. + + Usage: dir + +HostPort + +This validates that a string value contains a valid DNS hostname and port that +can be used to valiate fields typically passed to sockets and connections. + + Usage: hostname_port + +Datetime + +This validates that a string value is a valid datetime based on the supplied datetime format. +Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/ + + Usage: datetime=2006-01-02 + +Iso3166-1 alpha-2 + +This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard. +see: https://www.iso.org/iso-3166-country-codes.html + + Usage: iso3166_1_alpha2 + +Iso3166-1 alpha-3 + +This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard. +see: https://www.iso.org/iso-3166-country-codes.html + + Usage: iso3166_1_alpha3 + +Iso3166-1 alpha-numeric + +This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard. +see: https://www.iso.org/iso-3166-country-codes.html + + Usage: iso3166_1_alpha3 + +TimeZone + +This validates that a string value is a valid time zone based on the time zone database present on the system. +Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator. +More information on https://golang.org/pkg/time/#LoadLocation + + Usage: timezone + + +Alias Validators and Tags + +NOTE: When returning an error, the tag returned in "FieldError" will be +the alias tag unless the dive tag is part of the alias. Everything after the +dive tag is not reported as the alias tag. Also, the "ActualTag" in the before +case will be the actual tag within the alias that failed. + +Here is a list of the current built in alias tags: + + "iscolor" + alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor) + "country_code" + alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code) + +Validator notes: + + regex + a regex validator won't be added because commas and = signs can be part + of a regex which conflict with the validation definitions. Although + workarounds can be made, they take away from using pure regex's. + Furthermore it's quick and dirty but the regex's become harder to + maintain and are not reusable, so it's as much a programming philosophy + as anything. + + In place of this new validator functions should be created; a regex can + be used within the validator function and even be precompiled for better + efficiency within regexes.go. + + And the best reason, you can submit a pull request and we can keep on + adding to the validation library of this package! + +Non standard validators + +A collection of validation rules that are frequently needed but are more +complex than the ones found in the baked in validators. +A non standard validator must be registered manually like you would +with your own custom validation functions. + +Example of registration and use: + + type Test struct { + TestField string `validate:"yourtag"` + } + + t := &Test{ + TestField: "Test" + } + + validate := validator.New() + validate.RegisterValidation("yourtag", validators.NotBlank) + +Here is a list of the current non standard validators: + + NotBlank + This validates that the value is not blank or with length zero. + For strings ensures they do not contain only spaces. For channels, maps, slices and arrays + ensures they don't have zero length. For others, a non empty value is required. + + Usage: notblank + +Panics + +This package panics when bad input is provided, this is by design, bad code like +that should not make it to production. + + type Test struct { + TestField string `validate:"nonexistantfunction=1"` + } + + t := &Test{ + TestField: "Test" + } + + validate.Struct(t) // this will panic +*/ +package validator diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/errors.go b/taskman-server/vendor/github.com/go-playground/validator/v10/errors.go new file mode 100644 index 00000000..63293cf9 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/errors.go @@ -0,0 +1,275 @@ +package validator + +import ( + "bytes" + "fmt" + "reflect" + "strings" + + ut "github.com/go-playground/universal-translator" +) + +const ( + fieldErrMsg = "Key: '%s' Error:Field validation for '%s' failed on the '%s' tag" +) + +// ValidationErrorsTranslations is the translation return type +type ValidationErrorsTranslations map[string]string + +// InvalidValidationError describes an invalid argument passed to +// `Struct`, `StructExcept`, StructPartial` or `Field` +type InvalidValidationError struct { + Type reflect.Type +} + +// Error returns InvalidValidationError message +func (e *InvalidValidationError) Error() string { + + if e.Type == nil { + return "validator: (nil)" + } + + return "validator: (nil " + e.Type.String() + ")" +} + +// ValidationErrors is an array of FieldError's +// for use in custom error messages post validation. +type ValidationErrors []FieldError + +// Error is intended for use in development + debugging and not intended to be a production error message. +// It allows ValidationErrors to subscribe to the Error interface. +// All information to create an error message specific to your application is contained within +// the FieldError found within the ValidationErrors array +func (ve ValidationErrors) Error() string { + + buff := bytes.NewBufferString("") + + var fe *fieldError + + for i := 0; i < len(ve); i++ { + + fe = ve[i].(*fieldError) + buff.WriteString(fe.Error()) + buff.WriteString("\n") + } + + return strings.TrimSpace(buff.String()) +} + +// Translate translates all of the ValidationErrors +func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { + + trans := make(ValidationErrorsTranslations) + + var fe *fieldError + + for i := 0; i < len(ve); i++ { + fe = ve[i].(*fieldError) + + // // in case an Anonymous struct was used, ensure that the key + // // would be 'Username' instead of ".Username" + // if len(fe.ns) > 0 && fe.ns[:1] == "." { + // trans[fe.ns[1:]] = fe.Translate(ut) + // continue + // } + + trans[fe.ns] = fe.Translate(ut) + } + + return trans +} + +// FieldError contains all functions to get error details +type FieldError interface { + + // returns the validation tag that failed. if the + // validation was an alias, this will return the + // alias name and not the underlying tag that failed. + // + // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" + // will return "iscolor" + Tag() string + + // returns the validation tag that failed, even if an + // alias the actual tag within the alias will be returned. + // If an 'or' validation fails the entire or will be returned. + // + // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" + // will return "hexcolor|rgb|rgba|hsl|hsla" + ActualTag() string + + // returns the namespace for the field error, with the tag + // name taking precedence over the field's actual name. + // + // eg. JSON name "User.fname" + // + // See StructNamespace() for a version that returns actual names. + // + // NOTE: this field can be blank when validating a single primitive field + // using validate.Field(...) as there is no way to extract it's name + Namespace() string + + // returns the namespace for the field error, with the field's + // actual name. + // + // eq. "User.FirstName" see Namespace for comparison + // + // NOTE: this field can be blank when validating a single primitive field + // using validate.Field(...) as there is no way to extract its name + StructNamespace() string + + // returns the fields name with the tag name taking precedence over the + // field's actual name. + // + // eq. JSON name "fname" + // see StructField for comparison + Field() string + + // returns the field's actual name from the struct, when able to determine. + // + // eq. "FirstName" + // see Field for comparison + StructField() string + + // returns the actual field's value in case needed for creating the error + // message + Value() interface{} + + // returns the param value, in string form for comparison; this will also + // help with generating an error message + Param() string + + // Kind returns the Field's reflect Kind + // + // eg. time.Time's kind is a struct + Kind() reflect.Kind + + // Type returns the Field's reflect Type + // + // // eg. time.Time's type is time.Time + Type() reflect.Type + + // returns the FieldError's translated error + // from the provided 'ut.Translator' and registered 'TranslationFunc' + // + // NOTE: if no registered translator can be found it returns the same as + // calling fe.Error() + Translate(ut ut.Translator) string + + // Error returns the FieldError's message + Error() string +} + +// compile time interface checks +var _ FieldError = new(fieldError) +var _ error = new(fieldError) + +// fieldError contains a single field's validation error along +// with other properties that may be needed for error message creation +// it complies with the FieldError interface +type fieldError struct { + v *Validate + tag string + actualTag string + ns string + structNs string + fieldLen uint8 + structfieldLen uint8 + value interface{} + param string + kind reflect.Kind + typ reflect.Type +} + +// Tag returns the validation tag that failed. +func (fe *fieldError) Tag() string { + return fe.tag +} + +// ActualTag returns the validation tag that failed, even if an +// alias the actual tag within the alias will be returned. +func (fe *fieldError) ActualTag() string { + return fe.actualTag +} + +// Namespace returns the namespace for the field error, with the tag +// name taking precedence over the field's actual name. +func (fe *fieldError) Namespace() string { + return fe.ns +} + +// StructNamespace returns the namespace for the field error, with the field's +// actual name. +func (fe *fieldError) StructNamespace() string { + return fe.structNs +} + +// Field returns the field's name with the tag name taking precedence over the +// field's actual name. +func (fe *fieldError) Field() string { + + return fe.ns[len(fe.ns)-int(fe.fieldLen):] + // // return fe.field + // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] + + // log.Println("FLD:", fld) + + // if len(fld) > 0 && fld[:1] == "." { + // return fld[1:] + // } + + // return fld +} + +// returns the field's actual name from the struct, when able to determine. +func (fe *fieldError) StructField() string { + // return fe.structField + return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):] +} + +// Value returns the actual field's value in case needed for creating the error +// message +func (fe *fieldError) Value() interface{} { + return fe.value +} + +// Param returns the param value, in string form for comparison; this will +// also help with generating an error message +func (fe *fieldError) Param() string { + return fe.param +} + +// Kind returns the Field's reflect Kind +func (fe *fieldError) Kind() reflect.Kind { + return fe.kind +} + +// Type returns the Field's reflect Type +func (fe *fieldError) Type() reflect.Type { + return fe.typ +} + +// Error returns the fieldError's error message +func (fe *fieldError) Error() string { + return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag) +} + +// Translate returns the FieldError's translated error +// from the provided 'ut.Translator' and registered 'TranslationFunc' +// +// NOTE: if no registered translation can be found, it returns the original +// untranslated error message. +func (fe *fieldError) Translate(ut ut.Translator) string { + + m, ok := fe.v.transTagFunc[ut] + if !ok { + return fe.Error() + } + + fn, ok := m[fe.tag] + if !ok { + return fe.Error() + } + + return fn(ut, fe) +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/field_level.go b/taskman-server/vendor/github.com/go-playground/validator/v10/field_level.go new file mode 100644 index 00000000..f0e2a9a8 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/field_level.go @@ -0,0 +1,119 @@ +package validator + +import "reflect" + +// FieldLevel contains all the information and helper functions +// to validate a field +type FieldLevel interface { + // returns the top level struct, if any + Top() reflect.Value + + // returns the current fields parent struct, if any or + // the comparison value if called 'VarWithValue' + Parent() reflect.Value + + // returns current field for validation + Field() reflect.Value + + // returns the field's name with the tag + // name taking precedence over the fields actual name. + FieldName() string + + // returns the struct field's name + StructFieldName() string + + // returns param for validation against current field + Param() string + + // GetTag returns the current validations tag name + GetTag() string + + // ExtractType gets the actual underlying type of field value. + // It will dive into pointers, customTypes and return you the + // underlying value and it's kind. + ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) + + // traverses the parent struct to retrieve a specific field denoted by the provided namespace + // in the param and returns the field, field kind and whether is was successful in retrieving + // the field at all. + // + // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field + // could not be retrieved because it didn't exist. + // + // Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. + GetStructFieldOK() (reflect.Value, reflect.Kind, bool) + + // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for + // the field and namespace allowing more extensibility for validators. + // + // Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. + GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) + + // traverses the parent struct to retrieve a specific field denoted by the provided namespace + // in the param and returns the field, field kind, if it's a nullable type and whether is was successful in retrieving + // the field at all. + // + // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field + // could not be retrieved because it didn't exist. + GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) + + // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for + // the field and namespace allowing more extensibility for validators. + GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) +} + +var _ FieldLevel = new(validate) + +// Field returns current field for validation +func (v *validate) Field() reflect.Value { + return v.flField +} + +// FieldName returns the field's name with the tag +// name taking precedence over the fields actual name. +func (v *validate) FieldName() string { + return v.cf.altName +} + +// GetTag returns the current validations tag name +func (v *validate) GetTag() string { + return v.ct.tag +} + +// StructFieldName returns the struct field's name +func (v *validate) StructFieldName() string { + return v.cf.name +} + +// Param returns param for validation against current field +func (v *validate) Param() string { + return v.ct.param +} + +// GetStructFieldOK returns Param returns param for validation against current field +// +// Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. +func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) { + current, kind, _, found := v.getStructFieldOKInternal(v.slflParent, v.ct.param) + return current, kind, found +} + +// GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for +// the field and namespace allowing more extensibility for validators. +// +// Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. +func (v *validate) GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) { + current, kind, _, found := v.GetStructFieldOKAdvanced2(val, namespace) + return current, kind, found +} + +// GetStructFieldOK returns Param returns param for validation against current field +func (v *validate) GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) { + return v.getStructFieldOKInternal(v.slflParent, v.ct.param) +} + +// GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for +// the field and namespace allowing more extensibility for validators. +func (v *validate) GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) { + return v.getStructFieldOKInternal(val, namespace) +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/logo.png b/taskman-server/vendor/github.com/go-playground/validator/v10/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..355000f5247d50e979cf5db5de38188ef4649a34 GIT binary patch literal 13443 zcmbVz^LHiB^LK39wrv|5-`KWoTN~T9%?&s9Mte8f*xWeZ`~Lg^&kxU>)6-|>Om|IH zcUM=vsybFxSr!?A009gP3|U@IN*z>Z{#W2&KzAW<*L_e0I`lYd#@osT8GH952<>}$=#%H%txCM^!YLYIPG*~?*PoX}XfpXD#$r$vg% zUJ@M8Sa6}E0bs?J()q&Aj2!Xx^!*X7wf45!j09TZ!t8tmiZrhYa~rM!hkOgG3jNOL z$t%hsiEZp{`uZS=pUq3db%5@e>LpqUR%RzF4Fp&XYtszH3NMj(x&yBfN!B@dDe(i*$ zFaI9z`VK(*+SzZ3Km$V|gFS(NfPUS&ND}#zKM&MsZR;zy@SJwDwy5moK{eH84yz0`{Dhd+jynpps_Wzr*Rl)ctU%7jk!=>D(g}(sK zP}YV(B1|d_4NeR~4qlx?36qk5ng9u-wt+@fOTlvqhk>WQ%HxtjxBspSS(-6OpP;_x z73LX72W9oA=yUj&B*sjt0z}2U44ACNztdo!tbwR&pl8vCLjf!@HDwcP;p{h$JYsrk zE3Pp7L^A>!xwNPSX+2zrQgJ8|CCr11n`u|=C}{? zlHLN%{DxBD;+;&!6Se$BciUB@EQ~Y8_ZT-Q&4p}|A3l`R=AVR9Kt+V~a3a3V{l=)gHBK2op+X}BW7o(X1K2eRTZ^; ziO?#OmuWkXeCj2*{H(1C#qnQ>tz|Kq>*#cF7g)+?3G3(pVB@N37)9YHmYxa}CVb-% z@SHf5CnrEMiI6-&fkkOb9ema$%-Ld}qN54xNf|CDt?#e@Aec&IEcEEpu3Ak5Y z>0@s)b7yHEr~UCsek0JVuF%66MBgBxj-d!wQu4Evlx;p|pZG{&=4VV)*pIE{{f=SO z;V$)QC5ae=-6(Nc68{(S;2ymNVxIiwAs9}A@vA2?55kfV(qK>S6caF|bywd&p8ydL zB}xJ~6Di7u^Xl{s1E&b!{FXH0#>1$=MTNA7+vd;Pm*#B`iYRecX>5H7^iqDqQ{GQH zKNNh0?p}h?nEjh_Ft*^M`+(a;L*rKgPp=E!!}stvVxG|YKY=Yh25?+RloCoyT3T~2 zr1!?YL58}YTlyj1sTl_H(oBl48zJPwJFr9|r(>T7Npe$Hyl7Pm(dZ}|x;n!X(4wtZ zeNCCz4LTygy(gl;pV;dp+-Lpq=weiOW2Z_Lt@RNd_s43tZ>$@23^%6`T}rfexq!%# z)e|oR;kRY~2fW@V(in6QZzE*6TubN0<>|v2xiX)v6->d$no+&np8 z=DZPj>yPVL2Y2U^MJuW`R8R{2@Rg&}`S+$yEgsGihuW$3 z2y*A5Rm-TCh*xaY#R1q)HfzQS_%fPHCL7200}u=S#u`m zvW%z6F_UcmBq~g~s|d}v6$Q?noL`Z(X;@Q$i>kw^bF}I3A8QQyAE_nz-`H~a9o2}- ztPUs0q(DTZ^Yx3oA6C5I?{nHCX0qfW&C2r}h~~slhe!$_Hh1WB`w?_|D{JsF#zpgf z;F^yDTZs-$?`myzyDj@=x}@L4b~_KtUWzV+uiL${48Qh^ZdoywlRNR<*WLFY>v0fq zeWQS`g6{8q<#x){FrCbZlcTAh?+fw^gB-2LpRnlF^}`$D;(KxTOLn;dXs3Yl(uW$g6hyw3{wZdTVg|kdSet`n+SACG=!&%#r zl+Ha_MzD$G>iQb%tW~Uus7-zOMPI__Qo92dK3VKkGgR#;-!`uw++~l5J?MT+BUCv3 zcItfZO)uKXlipj1XD?F|>3frjQWA;$JV>TcHHrcrR=Ql;-B}Bb4;f|uVo(S7xL(QP zE%c8{bnchCJ%aG)3x8gx0`Hqq`eapfWqK`~Ec6Mea`v0{J?4~x(S2D#-7sMBR1X;{ zO-QlMUsyD!#jI^8v6y2J8TinHz_zsU@;3|?TfT0F2b2A7aX&aEQGc;IZ>UV*cToht z27rX9TA$h1ZMxk`KX|$6o$)=$PxIM3k^FhGmiJMaA3fBM6(M#efLJ9ucfbo2TkroP zxE4Dv?B_Nkef;0LYVj3nk|C9-MLv{y^-tY`SD(5phR2KMn}9@?I@SQ^#m* zu>9T8l>)311+yf)qc`Zp%3Cp9FS4PN18t5zZGy-!{f^5eJQA&Fb>Llf4kF^OZ}Tu z=jyadHyzlQLaf@_eAf{CFb}_v=Gj*BLc$VrMAe%hAL@6JaXkt^p&>`#SXjBAX!3#; zZ(sPdwtkoS08=HP@lruhHm*fIlu{y~LTu@+@;u*LBUU~nbQ7S{eH09xc5^_Xtu!q@ z6^P#P!A-(qwW30Th;TBWNp{b1+lP1D!2Y2In`HJ8=DTs8;1)Y~TE2Tco&agHaJGJRtE&{R2y^@Gnpny|$qxXc2=Ps$@$~9mxET{1Q$%i!i#frlzo0UOe_Y zMxNvLk98G99Jhl+-rMB_{OyQsE?70nTDUTZf%>P_;7WAz0a+FG*4EALUD*p3UWt_( z3yZrIM%L#2dleC=K}bD*)-@4195ctqtgM0iQACxJ?F&0O<{t?%^dK1pMJo*-dHj;E z%Vt=-^pa?Z(eb%_rx~$m@yuyvX^t!IvZZ&&LJtY`#;x+PXT-Gb~(3>gv;tf~4N37#aCX z-tW%A@AM^Cf&WBJl*|wp9s0RGq_rCL)=Klfe3e8BUY|7FGZM)#ZdT04zyZ#{*|<&8 z+dsxt9B+krqDfJbykPO==|6C|yAi)*jkV&C{Du7Y#drV0`{jGeFSFOANIz#B-ncz= zB?v}IR2j5eCJ`2>yNMN9<}h!(e$i><|KSPd(Ff^lC-7pg&G~QJ8T0JD-37gq1-K+V z;1?GW_CVrGX3V0m%yvW#+uGLl^01=9zyGrgZ5fJ6GeeULS25^4)YCL=-Z!w`r$tH= zj-ikdG|nI;y1wvvk2)h7^hL0Xvnxw)Y1u}&9Vv%k1};Z0IqW?AQ8)B@QOUa?ayt31 zX^`u?pa(0F6YpbrT;e2^auw#%0BX_ub?}_ieYF;4rGRd*1_vX-+Xv9I&yR@ zZF(3;`kXg0vHdTn$5Ie;gpS4@djPPJ60-Z_1?!DwQz9NO2jKDbkZ^oJbQVc?6v#&0 zAW|kWVx3>tw#eTFT> z$S^|&ZWo)7Lyes7r)@VL=2A|$JW1nr)ed9~F&(_uHC1f;YO_5oj&Afj!0(9M)7c*f z$rra8Ji?1Bc%e|v^CcS{(B7RRCc7Wrrs=I7)f#8IE{rDM)o~`?Y8!;pSaL!lLHCZ% z2RHV1+l?QSk}_AkH)`_s#(xKJ?jwKC`csy*aOGtV&`hmHIG<5hXtzm+=iQkb{pyZ< z%;RxAP~z<%lTo;vNWd4mn;*jW+1tVM*tJ0j)}5|LR4#M7r{PkXJaW;yHBr@9pIuiG z8V1M4Ci1&Z6T1I>(C@#6rJT=}4_MR%kp=0LFD)iInpDCFQ;rm ziA+yF-c%|NyQ8);!vM6)#xu8qylq9(nieBl!@e}S5}R@)8LEU)Q|o0z)Z3vP);l2n zvCG7gtlR2XtjF1}fhC?!r{BZ4#sNRJi-Kgt?Rd(rePR;wmE}rqM-z^#fA_=ptrRR~ zqS-A)prf=s19gdfPBn?#&j;!a+e1!wX7|RMt|@0KQ_^z7My)2imN}+? z&Ro$-#EC#FN(11}WJ|$X)eQ0hf7Xye3AhvowX$0|1+x+uY~g?ccTKswq+io;vFNd6 zr7#C9z4;>@b-tg$UzV@9U5hK{mDW{6%YjDa>FJu9Z8hZyN}pshPN=W>uI!^Q$kMqm z+}IiQA9sdYvoB1IiBfX#m0axM;6c8}N>K$tD8kW56>r1h5t8J!3X0YAj1|Aw&~l@A zxf2^V`F;A0W?i!7*yQ+#;?4!!1ZQrBEI$9+-N z6P_sTrV&}s7MX}77Nq}~KmQy&5T&0ZWX--y(<$MEOLGIm!7k)jQOWggN0!Rg^`Bj3z7;;PquhhFnoqJeAbUfHR~d2;C{_De_Ogp81i65*qU(X5fweyv+B#w>RW0 zm&_w7Zm z`YWfGxm^7MK^A>0nDITy;gz^Lzudv@BC>+^JOVExD%|?aa0W#9qe``&CHjF6vqV zB8&tSqdhz{r4(|w3!g-DZKg>^k=!a74kk`D{P(2>&R~8kXP)^Ns3jTlnM7|b=I@?W z*3YW^eW^H83@t)lUE4LAm#(ICbAZTgW?ohHU;Ok91QJvMGp6fHL|&TQb|ICaXi{OO zrD__`B5>e)a6orX^!P5CsJZqQhI9-E6v4*!cC1vUi2?G|44quG+rfLS+7ZX;meFoT zMa+fb0pH+x{|o<7L^;cM5J4}K*7m~l#N2_qa(YL%G9rt7(fo;z(CaJOODkCKPA9`Bop?dIYFl3wBU&l zdqN~tz4k#i1&+HT_N>0Qm%uxG;}xqfaciIXXK|67VNTu0yzMz6pt6)m~ z7y^EZ+(wMlK9yMiwkhp&>cmXQoRzGf`o{MmkrGaxJY*%s0Dza_WczOvC8IXtY4zGE zoAfaSy~MQoF^;l5RWb}DJq*S_&wp|_lkCAaR~iQkooeXo>yX+1hRw(?%#&k0 zm|IG1?>%mpBmLr(*DC>|Vr>bN;nKsdZLlS4*_h%G1n`;;6|sE0rg^T9KG)Swoz!z& zJra776~H1@daS@C;jzI*0~;x5(E1Fpo!nLAV=SmM;Q>*#bxdaC<;wO{!IV4ONwN}f z8NK=|T>UjQ5%%_C3KAVb1}wC~Feno-GH|l>&?HI*RX~t*0XtJ~S0R6Kst$kD*7mw& z{mR31-KopNO5bKJqku0*PjnBKFE_1y_|tmDtiN7SF!NZpwNb5#sV6w^bu9#1B5K7# z0N}))422cqc#^(uW?wJU*^KLe?VU&(*c6j;U6^LZcQoK4POU1{yKSH^?k2$VGLEWB zog!7!3_Kl%apr)=%d3Rpw_4BDLZf!1tIdN&D;Yg?X2&jp0vSBqbz)XX`Wu2%`IWJS1s3lhZ7H--?PJxQLg$XONw$8qE z@4G(S5}8yFwM`{Rdz9E__ZH{{Gusj%$t#w4+ac&G3wkM0n&qZPP}J9r*av-Zq- z%NdhH1sgs~Oq9{PLkkxDiK6MQo36OTZrr&F7k6+F*a}5hV<;1u+B`QQSF#ti5`pI3 z@gvRFovLjNAri8~54co-plD$yQSX*b95r9t@B%~eI2r9NqXw{mGRKtdG5*|wk~yO zW)?msL*Rlpy{X4OLKx;RTX5`t1RY4!(bJ`a7rJ?=xM7fwcCL;k7j%-*cj9NLfbojM= zsFk;>hWcz(m*MFBO66YXrs>D4!BqdqWy_oZ>c&}P@|L*1a zVk(-?<3wy?;t9XLM*dyTj^XbicaVIM%BJouomO8jaqzV51LbTf>Ywq=#cXFtO*-oC z$O(ezf}G*);p^d{5Cc9apUxWE7RHp-F$ne9h?~C!5ok6%glp3JFOLJd2A-Fm@I}Id-s z30mMGUBh}2LTd&+z4*b8fB8hNy+ke`kmJbFXYm9=Ud96znCvs;Xa*GB`{*jEPp($~+DX+RP*)$prD03Z~ zot>}r&YE}7>5Wkie5E(*NC^ihU`EdF6Ezw%Y_=C72{{2}2gipm z*Kp)Aa`c2J&xYYZ876z^z{Zt5pR2|?72(fT&g8MYt4OgJ8>+ZDr_oB=>9xhEw%27Y zdZWI$a9GrD@5Los+iFbyl507c-TMRH3x)MMT{uczOKy3!ra7;z>2})#CRqJW`Jr@s z)uA36KCgr8c)q);G>N2B3p4kyV4NWuoxzls;Xqq+eg~fI$A3otuea;KAQGd#L@`_H zA12vy0BVLhln8XMstlX5M43pjjcZzAO3GUc$zV-2^wq;7JE(EwPLoa!*2(XgxwSlx z2_J0xvN3`hnHWW^kuO7z`%AW8B~t4yhgSPHzS%y%$=}V7s+fZJ0#{k0^O+*L0|Zg4 zfX#xMrgl!s6Xo=iNk_&jq83fy!YAvDSuT8GO6%m58Pi*2YUR|;TQb;TdN=rqTpKIZ z-p&;$N{lIA6N##--%mV~CtEEa4=)@J`4YoT@$9}xH&qcX>lvW>wj*s%n1(JbS$r*d zK9ca~LMdTQ7v!Y34Q6Zh;50&tLX-E@$j3m@9%{iLEyrjeeM_lyMFuI6_pPMcUemdp z%6;iM!PP84B5GQ70B|+R^|BqipYC7_%BZRXP;eo#KZ6EBvBzlpn}@P3p}|8#I(4 zul0x<>TxI(s0g?8v|a89+n1)Jx##kH*g@FY*niUw?{Sqmm)Xi-;WBKlUieBT&& zR3bfdZ|yI{!e~+H2q@uF@=N3k*$H|RZpj@5hvmw~_Py+wV14-k8ynOVi-{@1gB;!g zop(C8F2W!)$gD|@VYtF3M2`gl44ny?45baF7yCBl4PB@{E_nNFz6{2b zr3nxXdd~S*FLLzzO#wytqw(3PI0_%D56fEkMQPca=JX$gqH9aJ{ZpKvk8&kz zVxpVpl56nj^P5R4Lm_KK_6WeFW0cD?IY zZu%H?$YfA5eBYF>2g^}+ig>LD^PgW_C#jRJ$|LNXlubK_b)pT9uqy)nlg?;4DG*(P@1w56aN4^TZM6bWUyCM1*1Czy}HIA#1w25=*y73 z^<0dmnQg(qFmL~t3lPYXx1H8~Zxg@d(x{4t40F=4{->PSRp{RzUszJHDlXejc7G)lY;8~fKsU-hk(590&9v& zFxr}ZKJqco?V2qb5bnkeLoQVbyu32=?$Kwh?;N0OiGN|7=6`RkdoJ(JT@djZ8dUCb za?z#~&v8Fm?V}L${Zr&aQ8JC0EF>X56u4pkjt-w^+1bG$r9f1OrJ$<6qE&iV7_}kN zQweT&?sbJOanV*#E0|bLjkCC(vOm|{V<5MsimhiSt-uxzjxz9SMUvMQK{`~RZ+v_m ztb%l8kCZHm@?oa?Mb$L;Bv2$(K*V=w5SD>$*ITQ!W*n%SOXJlQO>pLoRxLI#%aHpA zmYUE<8T)d$P6F=j$+`7W&dSV^FR;c5cvU=igm6$Q0Bz?EE|?msF@JEX89DoMOUuTr z`R{3)%|h-VtA7`wTgs8)s;PQ6$6IvQTsUzrO=Y6G!D)=Xx9w0$Gba6n1y?{dK@SoK ze54vzFH|9D2~QbpUTb_H)IYDfa|J}Lq9?%CFHbsIB8(vc1WUKbA`4uL=6b&iurle2 zi(4jg{2hA5K*7uKNnBA0KV4x*3NO0jb^QuEWV&39?%#Ve9aEQ)AWUUwycBSf_o%|` zTcm^fRU(B}U8I(N*#z&8fsGAkKpBAt5@UnRa>N{07@%qaw@bs$K2R5VP#c$2^Q%RQ zVuW0slT(*~U8kk?duR;_jOTpmwrrbx->n}JX^_|@zO|a)Ik@>X7HOQ(!z(#CF@`^7JGf2aEfn1S0v}oHKo%uVUMDjl3<>f#kD$hfw(^nW(aRB6AaG-TDAh%oHjEJ=J$;2s zNEtTUsuZa{ji(_8)1j8gUOb~B9fXBSc)M%Hfsu<`&aJGt{{#rePUQ zno1K;1#~H`?Rd#V$}MtvkS~UOgsP~@^u^u{ua{D3V=Fa{2IKwI7>|!cOUteP#X!Z_ z0=9Z(Y!#lhZpJ0TKxMl6%R?6~lt!EvNztb>dbADO5-ZkYS1f(TlqF6|c^Euh&Dojz z>7lTs0ClkTp5>|*~0 z_E{QdSna;}KOcu@*xbF3xyhffB&XIT`p{6hS*F))v#>=YEtJB9Cr*b2YtK$qd9@hS zP$+_%N43)URxgAF_fx!4#yRV$Y6W06mtQ<`6RwW>A*AaHVyEylR` z2)a@71;tKHeL9Ik*CB!~)Qw;=Fl6gGLG;?;LTeerep>@XsgVh4FN73z`?Z=yj9;v% zBxr{}l;h6)J_enD_Xs$w_!zAMpK(;B2{L7;9924=)DeQQG^=eR>S_sq&5Q6tF?!ZR z5Qknd!5HirCsnTIK}aSQLQ_)EQtb#JSG@QUVD}mpOr(idOXutsza|QP5K1WjdsWrs zkY855Sph`j8nzw^f)v# zwC?)Bwo9-}lWq~G9ow>)3->q?FnXQ<$)Y*Vq?hu8MmH8aL1yGrPXCBBQZxc2c}gM_ zazx&=nWtc(!DSU&y7M>VVWHK|f42Z4$ zgM>V`3TB$s+ZXAeFq65x>B{Mdc~^YySq_px;%mpmr2Huz$C}=8-KJN$50%RxgBJ`5 zP&~~O#I1B_1NXRe11=!ZG+8?m1fW)N1v3M~LuJCB_sLZ){E+CtNyJ{zEW!m2t6~4F z%H681*4phFkdH+Wb0LC&2rz`YF05QDpj#b^CS9c1iNN6yizQhsjIRb7ouDlN!>cKa zg7n0;K8z}XHxXi2Ecua32b&VylFo$*L~5$eud(~1>99o0y8R!-= zN_$<&9xytjEu>6segSMd2}6=@3VVB@GhvK>e5(3kr&=sV&}-F69b-m9?Ip^S&_1rK z)REQFT(LR2P6B9EqR$$Fjhw z@@PRbM9s{1I>jgtQ$A{Too_2xnL(GQD!IAjpSUUis4yB{sY$2}MT}d+!IfS_pu32*B z(%fM}`E)&K1vl5$L@*MaDwYf>96D4c;kb|PKTS;+YgrY9Ko@0Q)3$VlDZzF2D5qzp z3ooIC#iZNaZ8P4)aA|hlnC{a}TPrb~vTu2a+lFss)C;W1zZ926mndG{GXR|B)WfV} z(w*ugyn0Rs7_}^z1)X+M+)NXwrEUSMFwNFX_HD7RuV z!p-X54t?QhInx8)RxXg9Gk>_MaF-=XqAoa3dpy^>ZnMr+Cdt={MR4L zlI?2b=gsG3&Ijqpwy~pkv)Y=9n_|E|4ghMbhOV!U-CR;Kg+YdeFwVdfiyc*SZ33P= z$^Lo3LKgdGzEro#sbQm;1h}cbE=gD;VPV$RSAC(NX#P3$r*wNcQV1ac_8s?7<*v7Pd5{UE zcj<@b8s(}ugB+l6X(Y2RciZYZr@$lnh&EYVD&Q;@IV#m~)&N`>i%eC8QGg&uMXI=s zQLp~@6So9V;*{|ZngyWwRLWwzOCrXEh&`MazZ2wm)kNAKFDMMTX_jGA!oO_hJ-YRa z$^tLI^PHPVUu(o9eNPBKBkY8oY*JvIpawcN$Hq>rF`BD0kq%ngOwjI!^ei&^{U1>= z!^&Yoa|y-vSLjPKIP(7C?$zHcE6TomiB6zAM~x|S=v76w%>=hQ$rVordZSPGH_r!u za~NE4L)9W;Zi;ur8=N=;g2x`9ew-T?zd44CWDowkmcCKC2ZEkwyy{Cgf?DBwA)VTz zfJ;~J*q-_{>l2=#Z#w%BHa5yiZUb#89mRN|$!s*X41Sj}m@%Y%D8!j#oex}HpuLkT zi_70a875WHbj(&5q=Cb3*-Fn-b_=@DxVxh?M%~C#aO%I9A zfDhFlS)5h5m^sgc`qgo&LB;4CbJ+4Do$EQJL-i45cQ|%b4D${*iHS6$Z!lFja4{Z& zm_cQ;+$jmX_Ipjb?|qoQbz3TEQd@UgHO-t8i&2#uH*%Y+@t8HptKD;^>9mRb|w53r?9PIIfP$v|io_ z*cIdNpF96_?%r4O-CUdtgPsVgQ7~>`(Iv=~Vz&=N0I0@6UyQtkp156a;eRI#QPSg> zAcDjr+gD33>K!@@N;gSJr1%xowp?n{?=lK{fWo0V0xrMs(WD=)!hLrQ-FS z@!mYs_Wz~@&+paJijML41V^ce^;23KtbY_xNJKz@7&zTeFEoHm7;$(UI=YQFs#$@ptk!EQ42Y4FfxEf@TOsVt37 z}4AVbnC9Ri){mLjd@o@_vA;wzpV8G_ypN3Y=M08M6ZfM2Xtkpu^=A9}u!A?A z)0NYU%Y#TSSE#tnm?KTmo4 zd|UY(Tqjl;m?`7^R${$QG*ZIW=)p?(%lWYXyf8k9{rdP=)z$ty1cAPSJfgXTOPXN1 z^D-Pknjk$jWsP@0+o&sn#8=lA=)a-i-j|YE5DwZ9s#vk3w-c?}%C?C;Q@<(1;-i>L zl}SN#MAX*71GGR14&RiPaHe@3srrMMPYHjml+|aGSDU_fRi{h1_NlT;MHYR@D(IR3 zt6;N#m)Tdz?)V=$7s!&Z;ZdmJFd0m>InR~Umqz^)eM=coLx(q4tw%~Z0U73ho^=Mj zF)fREGIOlh6`*ARYk?K%ir!a_Yvw9snW){J#zyP<3!#qD8Q_2~d|so+(Xc54smil}_4kGqEK^l7mVKQmM+ zBR70H=a2QXGB!3jg`P(Kg~lE^KQr-y_EVJi%}cMMzb+f?)6-|yp{QzpZdk)-9EhXzQpEZ(ZuvkddnL`d4Y{JQ>J+Eg}}BSGkUqgbqYuem+;8++@MM(|;Eh?pTI_O&4Gy6PBOnIB)^cWfo! V^Rh-@K?jDw` + splitParamsRegexString = `'[^']*'|\S+` +) + +var ( + alphaRegex = regexp.MustCompile(alphaRegexString) + alphaNumericRegex = regexp.MustCompile(alphaNumericRegexString) + alphaUnicodeRegex = regexp.MustCompile(alphaUnicodeRegexString) + alphaUnicodeNumericRegex = regexp.MustCompile(alphaUnicodeNumericRegexString) + numericRegex = regexp.MustCompile(numericRegexString) + numberRegex = regexp.MustCompile(numberRegexString) + hexadecimalRegex = regexp.MustCompile(hexadecimalRegexString) + hexcolorRegex = regexp.MustCompile(hexcolorRegexString) + rgbRegex = regexp.MustCompile(rgbRegexString) + rgbaRegex = regexp.MustCompile(rgbaRegexString) + hslRegex = regexp.MustCompile(hslRegexString) + hslaRegex = regexp.MustCompile(hslaRegexString) + e164Regex = regexp.MustCompile(e164RegexString) + emailRegex = regexp.MustCompile(emailRegexString) + base64Regex = regexp.MustCompile(base64RegexString) + base64URLRegex = regexp.MustCompile(base64URLRegexString) + iSBN10Regex = regexp.MustCompile(iSBN10RegexString) + iSBN13Regex = regexp.MustCompile(iSBN13RegexString) + uUID3Regex = regexp.MustCompile(uUID3RegexString) + uUID4Regex = regexp.MustCompile(uUID4RegexString) + uUID5Regex = regexp.MustCompile(uUID5RegexString) + uUIDRegex = regexp.MustCompile(uUIDRegexString) + uUID3RFC4122Regex = regexp.MustCompile(uUID3RFC4122RegexString) + uUID4RFC4122Regex = regexp.MustCompile(uUID4RFC4122RegexString) + uUID5RFC4122Regex = regexp.MustCompile(uUID5RFC4122RegexString) + uUIDRFC4122Regex = regexp.MustCompile(uUIDRFC4122RegexString) + aSCIIRegex = regexp.MustCompile(aSCIIRegexString) + printableASCIIRegex = regexp.MustCompile(printableASCIIRegexString) + multibyteRegex = regexp.MustCompile(multibyteRegexString) + dataURIRegex = regexp.MustCompile(dataURIRegexString) + latitudeRegex = regexp.MustCompile(latitudeRegexString) + longitudeRegex = regexp.MustCompile(longitudeRegexString) + sSNRegex = regexp.MustCompile(sSNRegexString) + hostnameRegexRFC952 = regexp.MustCompile(hostnameRegexStringRFC952) + hostnameRegexRFC1123 = regexp.MustCompile(hostnameRegexStringRFC1123) + fqdnRegexRFC1123 = regexp.MustCompile(fqdnRegexStringRFC1123) + btcAddressRegex = regexp.MustCompile(btcAddressRegexString) + btcUpperAddressRegexBech32 = regexp.MustCompile(btcAddressUpperRegexStringBech32) + btcLowerAddressRegexBech32 = regexp.MustCompile(btcAddressLowerRegexStringBech32) + ethAddressRegex = regexp.MustCompile(ethAddressRegexString) + ethaddressRegexUpper = regexp.MustCompile(ethAddressUpperRegexString) + ethAddressRegexLower = regexp.MustCompile(ethAddressLowerRegexString) + uRLEncodedRegex = regexp.MustCompile(uRLEncodedRegexString) + hTMLEncodedRegex = regexp.MustCompile(hTMLEncodedRegexString) + hTMLRegex = regexp.MustCompile(hTMLRegexString) + splitParamsRegex = regexp.MustCompile(splitParamsRegexString) +) diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/struct_level.go b/taskman-server/vendor/github.com/go-playground/validator/v10/struct_level.go new file mode 100644 index 00000000..57691ee3 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/struct_level.go @@ -0,0 +1,175 @@ +package validator + +import ( + "context" + "reflect" +) + +// StructLevelFunc accepts all values needed for struct level validation +type StructLevelFunc func(sl StructLevel) + +// StructLevelFuncCtx accepts all values needed for struct level validation +// but also allows passing of contextual validation information via context.Context. +type StructLevelFuncCtx func(ctx context.Context, sl StructLevel) + +// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx +func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx { + return func(ctx context.Context, sl StructLevel) { + fn(sl) + } +} + +// StructLevel contains all the information and helper functions +// to validate a struct +type StructLevel interface { + + // returns the main validation object, in case one wants to call validations internally. + // this is so you don't have to use anonymous functions to get access to the validate + // instance. + Validator() *Validate + + // returns the top level struct, if any + Top() reflect.Value + + // returns the current fields parent struct, if any + Parent() reflect.Value + + // returns the current struct. + Current() reflect.Value + + // ExtractType gets the actual underlying type of field value. + // It will dive into pointers, customTypes and return you the + // underlying value and its kind. + ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) + + // reports an error just by passing the field and tag information + // + // NOTES: + // + // fieldName and altName get appended to the existing namespace that + // validator is on. e.g. pass 'FirstName' or 'Names[0]' depending + // on the nesting + // + // tag can be an existing validation tag or just something you make up + // and process on the flip side it's up to you. + ReportError(field interface{}, fieldName, structFieldName string, tag, param string) + + // reports an error just by passing ValidationErrors + // + // NOTES: + // + // relativeNamespace and relativeActualNamespace get appended to the + // existing namespace that validator is on. + // e.g. pass 'User.FirstName' or 'Users[0].FirstName' depending + // on the nesting. most of the time they will be blank, unless you validate + // at a level lower the the current field depth + ReportValidationErrors(relativeNamespace, relativeActualNamespace string, errs ValidationErrors) +} + +var _ StructLevel = new(validate) + +// Top returns the top level struct +// +// NOTE: this can be the same as the current struct being validated +// if not is a nested struct. +// +// this is only called when within Struct and Field Level validation and +// should not be relied upon for an acurate value otherwise. +func (v *validate) Top() reflect.Value { + return v.top +} + +// Parent returns the current structs parent +// +// NOTE: this can be the same as the current struct being validated +// if not is a nested struct. +// +// this is only called when within Struct and Field Level validation and +// should not be relied upon for an acurate value otherwise. +func (v *validate) Parent() reflect.Value { + return v.slflParent +} + +// Current returns the current struct. +func (v *validate) Current() reflect.Value { + return v.slCurrent +} + +// Validator returns the main validation object, in case one want to call validations internally. +func (v *validate) Validator() *Validate { + return v.v +} + +// ExtractType gets the actual underlying type of field value. +func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) { + return v.extractTypeInternal(field, false) +} + +// ReportError reports an error just by passing the field and tag information +func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { + + fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) + + if len(structFieldName) == 0 { + structFieldName = fieldName + } + + v.str1 = string(append(v.ns, fieldName...)) + + if v.v.hasTagNameFunc || fieldName != structFieldName { + v.str2 = string(append(v.actualNs, structFieldName...)) + } else { + v.str2 = v.str1 + } + + if kind == reflect.Invalid { + + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: tag, + actualTag: tag, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(fieldName)), + structfieldLen: uint8(len(structFieldName)), + param: param, + kind: kind, + }, + ) + return + } + + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: tag, + actualTag: tag, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(fieldName)), + structfieldLen: uint8(len(structFieldName)), + value: fv.Interface(), + param: param, + kind: kind, + typ: fv.Type(), + }, + ) +} + +// ReportValidationErrors reports ValidationErrors obtained from running validations within the Struct Level validation. +// +// NOTE: this function prepends the current namespace to the relative ones. +func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors) { + + var err *fieldError + + for i := 0; i < len(errs); i++ { + + err = errs[i].(*fieldError) + err.ns = string(append(append(v.ns, relativeNamespace...), err.ns...)) + err.structNs = string(append(append(v.actualNs, relativeStructNamespace...), err.structNs...)) + + v.errs = append(v.errs, err) + } +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/translations.go b/taskman-server/vendor/github.com/go-playground/validator/v10/translations.go new file mode 100644 index 00000000..4d9d75c1 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/translations.go @@ -0,0 +1,11 @@ +package validator + +import ut "github.com/go-playground/universal-translator" + +// TranslationFunc is the function type used to register or override +// custom translations +type TranslationFunc func(ut ut.Translator, fe FieldError) string + +// RegisterTranslationsFunc allows for registering of translations +// for a 'ut.Translator' for use within the 'TranslationFunc' +type RegisterTranslationsFunc func(ut ut.Translator) error diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/util.go b/taskman-server/vendor/github.com/go-playground/validator/v10/util.go new file mode 100644 index 00000000..56420f43 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/util.go @@ -0,0 +1,288 @@ +package validator + +import ( + "reflect" + "strconv" + "strings" + "time" +) + +// extractTypeInternal gets the actual underlying type of field value. +// It will dive into pointers, customTypes and return you the +// underlying value and it's kind. +func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { + +BEGIN: + switch current.Kind() { + case reflect.Ptr: + + nullable = true + + if current.IsNil() { + return current, reflect.Ptr, nullable + } + + current = current.Elem() + goto BEGIN + + case reflect.Interface: + + nullable = true + + if current.IsNil() { + return current, reflect.Interface, nullable + } + + current = current.Elem() + goto BEGIN + + case reflect.Invalid: + return current, reflect.Invalid, nullable + + default: + + if v.v.hasCustomFuncs { + + if fn, ok := v.v.customFuncs[current.Type()]; ok { + current = reflect.ValueOf(fn(current)) + goto BEGIN + } + } + + return current, current.Kind(), nullable + } +} + +// getStructFieldOKInternal traverses a struct to retrieve a specific field denoted by the provided namespace and +// returns the field, field kind and whether is was successful in retrieving the field at all. +// +// NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field +// could not be retrieved because it didn't exist. +func (v *validate) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, nullable bool, found bool) { + +BEGIN: + current, kind, nullable = v.ExtractType(val) + if kind == reflect.Invalid { + return + } + + if namespace == "" { + found = true + return + } + + switch kind { + + case reflect.Ptr, reflect.Interface: + return + + case reflect.Struct: + + typ := current.Type() + fld := namespace + var ns string + + if typ != timeType { + + idx := strings.Index(namespace, namespaceSeparator) + + if idx != -1 { + fld = namespace[:idx] + ns = namespace[idx+1:] + } else { + ns = "" + } + + bracketIdx := strings.Index(fld, leftBracket) + if bracketIdx != -1 { + fld = fld[:bracketIdx] + + ns = namespace[bracketIdx:] + } + + val = current.FieldByName(fld) + namespace = ns + goto BEGIN + } + + case reflect.Array, reflect.Slice: + idx := strings.Index(namespace, leftBracket) + idx2 := strings.Index(namespace, rightBracket) + + arrIdx, _ := strconv.Atoi(namespace[idx+1 : idx2]) + + if arrIdx >= current.Len() { + return + } + + startIdx := idx2 + 1 + + if startIdx < len(namespace) { + if namespace[startIdx:startIdx+1] == namespaceSeparator { + startIdx++ + } + } + + val = current.Index(arrIdx) + namespace = namespace[startIdx:] + goto BEGIN + + case reflect.Map: + idx := strings.Index(namespace, leftBracket) + 1 + idx2 := strings.Index(namespace, rightBracket) + + endIdx := idx2 + + if endIdx+1 < len(namespace) { + if namespace[endIdx+1:endIdx+2] == namespaceSeparator { + endIdx++ + } + } + + key := namespace[idx:idx2] + + switch current.Type().Key().Kind() { + case reflect.Int: + i, _ := strconv.Atoi(key) + val = current.MapIndex(reflect.ValueOf(i)) + namespace = namespace[endIdx+1:] + + case reflect.Int8: + i, _ := strconv.ParseInt(key, 10, 8) + val = current.MapIndex(reflect.ValueOf(int8(i))) + namespace = namespace[endIdx+1:] + + case reflect.Int16: + i, _ := strconv.ParseInt(key, 10, 16) + val = current.MapIndex(reflect.ValueOf(int16(i))) + namespace = namespace[endIdx+1:] + + case reflect.Int32: + i, _ := strconv.ParseInt(key, 10, 32) + val = current.MapIndex(reflect.ValueOf(int32(i))) + namespace = namespace[endIdx+1:] + + case reflect.Int64: + i, _ := strconv.ParseInt(key, 10, 64) + val = current.MapIndex(reflect.ValueOf(i)) + namespace = namespace[endIdx+1:] + + case reflect.Uint: + i, _ := strconv.ParseUint(key, 10, 0) + val = current.MapIndex(reflect.ValueOf(uint(i))) + namespace = namespace[endIdx+1:] + + case reflect.Uint8: + i, _ := strconv.ParseUint(key, 10, 8) + val = current.MapIndex(reflect.ValueOf(uint8(i))) + namespace = namespace[endIdx+1:] + + case reflect.Uint16: + i, _ := strconv.ParseUint(key, 10, 16) + val = current.MapIndex(reflect.ValueOf(uint16(i))) + namespace = namespace[endIdx+1:] + + case reflect.Uint32: + i, _ := strconv.ParseUint(key, 10, 32) + val = current.MapIndex(reflect.ValueOf(uint32(i))) + namespace = namespace[endIdx+1:] + + case reflect.Uint64: + i, _ := strconv.ParseUint(key, 10, 64) + val = current.MapIndex(reflect.ValueOf(i)) + namespace = namespace[endIdx+1:] + + case reflect.Float32: + f, _ := strconv.ParseFloat(key, 32) + val = current.MapIndex(reflect.ValueOf(float32(f))) + namespace = namespace[endIdx+1:] + + case reflect.Float64: + f, _ := strconv.ParseFloat(key, 64) + val = current.MapIndex(reflect.ValueOf(f)) + namespace = namespace[endIdx+1:] + + case reflect.Bool: + b, _ := strconv.ParseBool(key) + val = current.MapIndex(reflect.ValueOf(b)) + namespace = namespace[endIdx+1:] + + // reflect.Type = string + default: + val = current.MapIndex(reflect.ValueOf(key)) + namespace = namespace[endIdx+1:] + } + + goto BEGIN + } + + // if got here there was more namespace, cannot go any deeper + panic("Invalid field namespace") +} + +// asInt returns the parameter as a int64 +// or panics if it can't convert +func asInt(param string) int64 { + i, err := strconv.ParseInt(param, 0, 64) + panicIf(err) + + return i +} + +// asIntFromTimeDuration parses param as time.Duration and returns it as int64 +// or panics on error. +func asIntFromTimeDuration(param string) int64 { + d, err := time.ParseDuration(param) + if err != nil { + // attempt parsing as an an integer assuming nanosecond precision + return asInt(param) + } + return int64(d) +} + +// asIntFromType calls the proper function to parse param as int64, +// given a field's Type t. +func asIntFromType(t reflect.Type, param string) int64 { + switch t { + case timeDurationType: + return asIntFromTimeDuration(param) + default: + return asInt(param) + } +} + +// asUint returns the parameter as a uint64 +// or panics if it can't convert +func asUint(param string) uint64 { + + i, err := strconv.ParseUint(param, 0, 64) + panicIf(err) + + return i +} + +// asFloat returns the parameter as a float64 +// or panics if it can't convert +func asFloat(param string) float64 { + + i, err := strconv.ParseFloat(param, 64) + panicIf(err) + + return i +} + +// asBool returns the parameter as a bool +// or panics if it can't convert +func asBool(param string) bool { + + i, err := strconv.ParseBool(param) + panicIf(err) + + return i +} + +func panicIf(err error) { + if err != nil { + panic(err.Error()) + } +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/validator.go b/taskman-server/vendor/github.com/go-playground/validator/v10/validator.go new file mode 100644 index 00000000..f097f394 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/validator.go @@ -0,0 +1,477 @@ +package validator + +import ( + "context" + "fmt" + "reflect" + "strconv" +) + +// per validate construct +type validate struct { + v *Validate + top reflect.Value + ns []byte + actualNs []byte + errs ValidationErrors + includeExclude map[string]struct{} // reset only if StructPartial or StructExcept are called, no need otherwise + ffn FilterFunc + slflParent reflect.Value // StructLevel & FieldLevel + slCurrent reflect.Value // StructLevel & FieldLevel + flField reflect.Value // StructLevel & FieldLevel + cf *cField // StructLevel & FieldLevel + ct *cTag // StructLevel & FieldLevel + misc []byte // misc reusable + str1 string // misc reusable + str2 string // misc reusable + fldIsPointer bool // StructLevel & FieldLevel + isPartial bool + hasExcludes bool +} + +// parent and current will be the same the first run of validateStruct +func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) { + + cs, ok := v.v.structCache.Get(typ) + if !ok { + cs = v.v.extractStructCache(current, typ.Name()) + } + + if len(ns) == 0 && len(cs.name) != 0 { + + ns = append(ns, cs.name...) + ns = append(ns, '.') + + structNs = append(structNs, cs.name...) + structNs = append(structNs, '.') + } + + // ct is nil on top level struct, and structs as fields that have no tag info + // so if nil or if not nil and the structonly tag isn't present + if ct == nil || ct.typeof != typeStructOnly { + + var f *cField + + for i := 0; i < len(cs.fields); i++ { + + f = cs.fields[i] + + if v.isPartial { + + if v.ffn != nil { + // used with StructFiltered + if v.ffn(append(structNs, f.name...)) { + continue + } + + } else { + // used with StructPartial & StructExcept + _, ok = v.includeExclude[string(append(structNs, f.name...))] + + if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) { + continue + } + } + } + + v.traverseField(ctx, parent, current.Field(f.idx), ns, structNs, f, f.cTags) + } + } + + // check if any struct level validations, after all field validations already checked. + // first iteration will have no info about nostructlevel tag, and is checked prior to + // calling the next iteration of validateStruct called from traverseField. + if cs.fn != nil { + + v.slflParent = parent + v.slCurrent = current + v.ns = ns + v.actualNs = structNs + + cs.fn(ctx, v) + } +} + +// traverseField validates any field, be it a struct or single field, ensures it's validity and passes it along to be validated via it's tag options +func (v *validate) traverseField(ctx context.Context, parent reflect.Value, current reflect.Value, ns []byte, structNs []byte, cf *cField, ct *cTag) { + var typ reflect.Type + var kind reflect.Kind + + current, kind, v.fldIsPointer = v.extractTypeInternal(current, false) + + switch kind { + case reflect.Ptr, reflect.Interface, reflect.Invalid: + + if ct == nil { + return + } + + if ct.typeof == typeOmitEmpty || ct.typeof == typeIsDefault { + return + } + + if ct.hasTag { + if kind == reflect.Invalid { + v.str1 = string(append(ns, cf.altName...)) + if v.v.hasTagNameFunc { + v.str2 = string(append(structNs, cf.name...)) + } else { + v.str2 = v.str1 + } + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: ct.aliasTag, + actualTag: ct.tag, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(cf.altName)), + structfieldLen: uint8(len(cf.name)), + param: ct.param, + kind: kind, + }, + ) + return + } + + v.str1 = string(append(ns, cf.altName...)) + if v.v.hasTagNameFunc { + v.str2 = string(append(structNs, cf.name...)) + } else { + v.str2 = v.str1 + } + if !ct.runValidationWhenNil { + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: ct.aliasTag, + actualTag: ct.tag, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(cf.altName)), + structfieldLen: uint8(len(cf.name)), + value: current.Interface(), + param: ct.param, + kind: kind, + typ: current.Type(), + }, + ) + return + } + } + + case reflect.Struct: + + typ = current.Type() + + if typ != timeType { + + if ct != nil { + + if ct.typeof == typeStructOnly { + goto CONTINUE + } else if ct.typeof == typeIsDefault { + // set Field Level fields + v.slflParent = parent + v.flField = current + v.cf = cf + v.ct = ct + + if !ct.fn(ctx, v) { + v.str1 = string(append(ns, cf.altName...)) + + if v.v.hasTagNameFunc { + v.str2 = string(append(structNs, cf.name...)) + } else { + v.str2 = v.str1 + } + + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: ct.aliasTag, + actualTag: ct.tag, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(cf.altName)), + structfieldLen: uint8(len(cf.name)), + value: current.Interface(), + param: ct.param, + kind: kind, + typ: typ, + }, + ) + return + } + } + + ct = ct.next + } + + if ct != nil && ct.typeof == typeNoStructLevel { + return + } + + CONTINUE: + // if len == 0 then validating using 'Var' or 'VarWithValue' + // Var - doesn't make much sense to do it that way, should call 'Struct', but no harm... + // VarWithField - this allows for validating against each field within the struct against a specific value + // pretty handy in certain situations + if len(cf.name) > 0 { + ns = append(append(ns, cf.altName...), '.') + structNs = append(append(structNs, cf.name...), '.') + } + + v.validateStruct(ctx, current, current, typ, ns, structNs, ct) + return + } + } + + if !ct.hasTag { + return + } + + typ = current.Type() + +OUTER: + for { + if ct == nil { + return + } + + switch ct.typeof { + + case typeOmitEmpty: + + // set Field Level fields + v.slflParent = parent + v.flField = current + v.cf = cf + v.ct = ct + + if !hasValue(v) { + return + } + + ct = ct.next + continue + + case typeEndKeys: + return + + case typeDive: + + ct = ct.next + + // traverse slice or map here + // or panic ;) + switch kind { + case reflect.Slice, reflect.Array: + + var i64 int64 + reusableCF := &cField{} + + for i := 0; i < current.Len(); i++ { + + i64 = int64(i) + + v.misc = append(v.misc[0:0], cf.name...) + v.misc = append(v.misc, '[') + v.misc = strconv.AppendInt(v.misc, i64, 10) + v.misc = append(v.misc, ']') + + reusableCF.name = string(v.misc) + + if cf.namesEqual { + reusableCF.altName = reusableCF.name + } else { + + v.misc = append(v.misc[0:0], cf.altName...) + v.misc = append(v.misc, '[') + v.misc = strconv.AppendInt(v.misc, i64, 10) + v.misc = append(v.misc, ']') + + reusableCF.altName = string(v.misc) + } + v.traverseField(ctx, parent, current.Index(i), ns, structNs, reusableCF, ct) + } + + case reflect.Map: + + var pv string + reusableCF := &cField{} + + for _, key := range current.MapKeys() { + + pv = fmt.Sprintf("%v", key.Interface()) + + v.misc = append(v.misc[0:0], cf.name...) + v.misc = append(v.misc, '[') + v.misc = append(v.misc, pv...) + v.misc = append(v.misc, ']') + + reusableCF.name = string(v.misc) + + if cf.namesEqual { + reusableCF.altName = reusableCF.name + } else { + v.misc = append(v.misc[0:0], cf.altName...) + v.misc = append(v.misc, '[') + v.misc = append(v.misc, pv...) + v.misc = append(v.misc, ']') + + reusableCF.altName = string(v.misc) + } + + if ct != nil && ct.typeof == typeKeys && ct.keys != nil { + v.traverseField(ctx, parent, key, ns, structNs, reusableCF, ct.keys) + // can be nil when just keys being validated + if ct.next != nil { + v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct.next) + } + } else { + v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct) + } + } + + default: + // throw error, if not a slice or map then should not have gotten here + // bad dive tag + panic("dive error! can't dive on a non slice or map") + } + + return + + case typeOr: + + v.misc = v.misc[0:0] + + for { + + // set Field Level fields + v.slflParent = parent + v.flField = current + v.cf = cf + v.ct = ct + + if ct.fn(ctx, v) { + + // drain rest of the 'or' values, then continue or leave + for { + + ct = ct.next + + if ct == nil { + return + } + + if ct.typeof != typeOr { + continue OUTER + } + } + } + + v.misc = append(v.misc, '|') + v.misc = append(v.misc, ct.tag...) + + if ct.hasParam { + v.misc = append(v.misc, '=') + v.misc = append(v.misc, ct.param...) + } + + if ct.isBlockEnd || ct.next == nil { + // if we get here, no valid 'or' value and no more tags + v.str1 = string(append(ns, cf.altName...)) + + if v.v.hasTagNameFunc { + v.str2 = string(append(structNs, cf.name...)) + } else { + v.str2 = v.str1 + } + + if ct.hasAlias { + + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: ct.aliasTag, + actualTag: ct.actualAliasTag, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(cf.altName)), + structfieldLen: uint8(len(cf.name)), + value: current.Interface(), + param: ct.param, + kind: kind, + typ: typ, + }, + ) + + } else { + + tVal := string(v.misc)[1:] + + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: tVal, + actualTag: tVal, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(cf.altName)), + structfieldLen: uint8(len(cf.name)), + value: current.Interface(), + param: ct.param, + kind: kind, + typ: typ, + }, + ) + } + + return + } + + ct = ct.next + } + + default: + + // set Field Level fields + v.slflParent = parent + v.flField = current + v.cf = cf + v.ct = ct + + if !ct.fn(ctx, v) { + + v.str1 = string(append(ns, cf.altName...)) + + if v.v.hasTagNameFunc { + v.str2 = string(append(structNs, cf.name...)) + } else { + v.str2 = v.str1 + } + + v.errs = append(v.errs, + &fieldError{ + v: v.v, + tag: ct.aliasTag, + actualTag: ct.tag, + ns: v.str1, + structNs: v.str2, + fieldLen: uint8(len(cf.altName)), + structfieldLen: uint8(len(cf.name)), + value: current.Interface(), + param: ct.param, + kind: kind, + typ: typ, + }, + ) + + return + } + ct = ct.next + } + } + +} diff --git a/taskman-server/vendor/github.com/go-playground/validator/v10/validator_instance.go b/taskman-server/vendor/github.com/go-playground/validator/v10/validator_instance.go new file mode 100644 index 00000000..fe6a4877 --- /dev/null +++ b/taskman-server/vendor/github.com/go-playground/validator/v10/validator_instance.go @@ -0,0 +1,619 @@ +package validator + +import ( + "context" + "errors" + "fmt" + "reflect" + "strings" + "sync" + "time" + + ut "github.com/go-playground/universal-translator" +) + +const ( + defaultTagName = "validate" + utf8HexComma = "0x2C" + utf8Pipe = "0x7C" + tagSeparator = "," + orSeparator = "|" + tagKeySeparator = "=" + structOnlyTag = "structonly" + noStructLevelTag = "nostructlevel" + omitempty = "omitempty" + isdefault = "isdefault" + requiredWithoutAllTag = "required_without_all" + requiredWithoutTag = "required_without" + requiredWithTag = "required_with" + requiredWithAllTag = "required_with_all" + requiredIfTag = "required_if" + requiredUnlessTag = "required_unless" + skipValidationTag = "-" + diveTag = "dive" + keysTag = "keys" + endKeysTag = "endkeys" + requiredTag = "required" + namespaceSeparator = "." + leftBracket = "[" + rightBracket = "]" + restrictedTagChars = ".[],|=+()`~!@#$%^&*\\\"/?<>{}" + restrictedAliasErr = "Alias '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" + restrictedTagErr = "Tag '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" +) + +var ( + timeDurationType = reflect.TypeOf(time.Duration(0)) + timeType = reflect.TypeOf(time.Time{}) + + defaultCField = &cField{namesEqual: true} +) + +// FilterFunc is the type used to filter fields using +// StructFiltered(...) function. +// returning true results in the field being filtered/skiped from +// validation +type FilterFunc func(ns []byte) bool + +// CustomTypeFunc allows for overriding or adding custom field type handler functions +// field = field value of the type to return a value to be validated +// example Valuer from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29 +type CustomTypeFunc func(field reflect.Value) interface{} + +// TagNameFunc allows for adding of a custom tag name parser +type TagNameFunc func(field reflect.StructField) string + +type internalValidationFuncWrapper struct { + fn FuncCtx + runValidatinOnNil bool +} + +// Validate contains the validator settings and cache +type Validate struct { + tagName string + pool *sync.Pool + hasCustomFuncs bool + hasTagNameFunc bool + tagNameFunc TagNameFunc + structLevelFuncs map[reflect.Type]StructLevelFuncCtx + customFuncs map[reflect.Type]CustomTypeFunc + aliases map[string]string + validations map[string]internalValidationFuncWrapper + transTagFunc map[ut.Translator]map[string]TranslationFunc // map[]map[]TranslationFunc + tagCache *tagCache + structCache *structCache +} + +// New returns a new instance of 'validate' with sane defaults. +func New() *Validate { + + tc := new(tagCache) + tc.m.Store(make(map[string]*cTag)) + + sc := new(structCache) + sc.m.Store(make(map[reflect.Type]*cStruct)) + + v := &Validate{ + tagName: defaultTagName, + aliases: make(map[string]string, len(bakedInAliases)), + validations: make(map[string]internalValidationFuncWrapper, len(bakedInValidators)), + tagCache: tc, + structCache: sc, + } + + // must copy alias validators for separate validations to be used in each validator instance + for k, val := range bakedInAliases { + v.RegisterAlias(k, val) + } + + // must copy validators for separate validations to be used in each instance + for k, val := range bakedInValidators { + + switch k { + // these require that even if the value is nil that the validation should run, omitempty still overrides this behaviour + case requiredIfTag, requiredUnlessTag, requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag: + _ = v.registerValidation(k, wrapFunc(val), true, true) + default: + // no need to error check here, baked in will always be valid + _ = v.registerValidation(k, wrapFunc(val), true, false) + } + } + + v.pool = &sync.Pool{ + New: func() interface{} { + return &validate{ + v: v, + ns: make([]byte, 0, 64), + actualNs: make([]byte, 0, 64), + misc: make([]byte, 32), + } + }, + } + + return v +} + +// SetTagName allows for changing of the default tag name of 'validate' +func (v *Validate) SetTagName(name string) { + v.tagName = name +} + +// RegisterTagNameFunc registers a function to get alternate names for StructFields. +// +// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names: +// +// validate.RegisterTagNameFunc(func(fld reflect.StructField) string { +// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] +// if name == "-" { +// return "" +// } +// return name +// }) +func (v *Validate) RegisterTagNameFunc(fn TagNameFunc) { + v.tagNameFunc = fn + v.hasTagNameFunc = true +} + +// RegisterValidation adds a validation with the given tag +// +// NOTES: +// - if the key already exists, the previous validation function will be replaced. +// - this method is not thread-safe it is intended that these all be registered prior to any validation +func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool) error { + return v.RegisterValidationCtx(tag, wrapFunc(fn), callValidationEvenIfNull...) +} + +// RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation +// allowing context.Context validation support. +func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, callValidationEvenIfNull ...bool) error { + var nilCheckable bool + if len(callValidationEvenIfNull) > 0 { + nilCheckable = callValidationEvenIfNull[0] + } + return v.registerValidation(tag, fn, false, nilCheckable) +} + +func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilCheckable bool) error { + if len(tag) == 0 { + return errors.New("Function Key cannot be empty") + } + + if fn == nil { + return errors.New("Function cannot be empty") + } + + _, ok := restrictedTags[tag] + if !bakedIn && (ok || strings.ContainsAny(tag, restrictedTagChars)) { + panic(fmt.Sprintf(restrictedTagErr, tag)) + } + v.validations[tag] = internalValidationFuncWrapper{fn: fn, runValidatinOnNil: nilCheckable} + return nil +} + +// RegisterAlias registers a mapping of a single validation tag that +// defines a common or complex set of validation(s) to simplify adding validation +// to structs. +// +// NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation +func (v *Validate) RegisterAlias(alias, tags string) { + + _, ok := restrictedTags[alias] + + if ok || strings.ContainsAny(alias, restrictedTagChars) { + panic(fmt.Sprintf(restrictedAliasErr, alias)) + } + + v.aliases[alias] = tags +} + +// RegisterStructValidation registers a StructLevelFunc against a number of types. +// +// NOTE: +// - this method is not thread-safe it is intended that these all be registered prior to any validation +func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{}) { + v.RegisterStructValidationCtx(wrapStructLevelFunc(fn), types...) +} + +// RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing +// of contextual validation information via context.Context. +// +// NOTE: +// - this method is not thread-safe it is intended that these all be registered prior to any validation +func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) { + + if v.structLevelFuncs == nil { + v.structLevelFuncs = make(map[reflect.Type]StructLevelFuncCtx) + } + + for _, t := range types { + tv := reflect.ValueOf(t) + if tv.Kind() == reflect.Ptr { + t = reflect.Indirect(tv).Interface() + } + + v.structLevelFuncs[reflect.TypeOf(t)] = fn + } +} + +// RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types +// +// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation +func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { + + if v.customFuncs == nil { + v.customFuncs = make(map[reflect.Type]CustomTypeFunc) + } + + for _, t := range types { + v.customFuncs[reflect.TypeOf(t)] = fn + } + + v.hasCustomFuncs = true +} + +// RegisterTranslation registers translations against the provided tag. +func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) { + + if v.transTagFunc == nil { + v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc) + } + + if err = registerFn(trans); err != nil { + return + } + + m, ok := v.transTagFunc[trans] + if !ok { + m = make(map[string]TranslationFunc) + v.transTagFunc[trans] = m + } + + m[tag] = translationFn + + return +} + +// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified. +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) Struct(s interface{}) error { + return v.StructCtx(context.Background(), s) +} + +// StructCtx validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified +// and also allows passing of context.Context for contextual validation information. +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error) { + + val := reflect.ValueOf(s) + top := val + + if val.Kind() == reflect.Ptr && !val.IsNil() { + val = val.Elem() + } + + if val.Kind() != reflect.Struct || val.Type() == timeType { + return &InvalidValidationError{Type: reflect.TypeOf(s)} + } + + // good to validate + vd := v.pool.Get().(*validate) + vd.top = top + vd.isPartial = false + // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept + + vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + + v.pool.Put(vd) + + return +} + +// StructFiltered validates a structs exposed fields, that pass the FilterFunc check and automatically validates +// nested structs, unless otherwise specified. +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error { + return v.StructFilteredCtx(context.Background(), s, fn) +} + +// StructFilteredCtx validates a structs exposed fields, that pass the FilterFunc check and automatically validates +// nested structs, unless otherwise specified and also allows passing of contextual validation information via +// context.Context +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error) { + val := reflect.ValueOf(s) + top := val + + if val.Kind() == reflect.Ptr && !val.IsNil() { + val = val.Elem() + } + + if val.Kind() != reflect.Struct || val.Type() == timeType { + return &InvalidValidationError{Type: reflect.TypeOf(s)} + } + + // good to validate + vd := v.pool.Get().(*validate) + vd.top = top + vd.isPartial = true + vd.ffn = fn + // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept + + vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + + v.pool.Put(vd) + + return +} + +// StructPartial validates the fields passed in only, ignoring all others. +// Fields may be provided in a namespaced fashion relative to the struct provided +// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) StructPartial(s interface{}, fields ...string) error { + return v.StructPartialCtx(context.Background(), s, fields...) +} + +// StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual +// validation validation information via context.Context +// Fields may be provided in a namespaced fashion relative to the struct provided +// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error) { + val := reflect.ValueOf(s) + top := val + + if val.Kind() == reflect.Ptr && !val.IsNil() { + val = val.Elem() + } + + if val.Kind() != reflect.Struct || val.Type() == timeType { + return &InvalidValidationError{Type: reflect.TypeOf(s)} + } + + // good to validate + vd := v.pool.Get().(*validate) + vd.top = top + vd.isPartial = true + vd.ffn = nil + vd.hasExcludes = false + vd.includeExclude = make(map[string]struct{}) + + typ := val.Type() + name := typ.Name() + + for _, k := range fields { + + flds := strings.Split(k, namespaceSeparator) + if len(flds) > 0 { + + vd.misc = append(vd.misc[0:0], name...) + vd.misc = append(vd.misc, '.') + + for _, s := range flds { + + idx := strings.Index(s, leftBracket) + + if idx != -1 { + for idx != -1 { + vd.misc = append(vd.misc, s[:idx]...) + vd.includeExclude[string(vd.misc)] = struct{}{} + + idx2 := strings.Index(s, rightBracket) + idx2++ + vd.misc = append(vd.misc, s[idx:idx2]...) + vd.includeExclude[string(vd.misc)] = struct{}{} + s = s[idx2:] + idx = strings.Index(s, leftBracket) + } + } else { + + vd.misc = append(vd.misc, s...) + vd.includeExclude[string(vd.misc)] = struct{}{} + } + + vd.misc = append(vd.misc, '.') + } + } + } + + vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + + v.pool.Put(vd) + + return +} + +// StructExcept validates all fields except the ones passed in. +// Fields may be provided in a namespaced fashion relative to the struct provided +// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) StructExcept(s interface{}, fields ...string) error { + return v.StructExceptCtx(context.Background(), s, fields...) +} + +// StructExceptCtx validates all fields except the ones passed in and allows passing of contextual +// validation validation information via context.Context +// Fields may be provided in a namespaced fashion relative to the struct provided +// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error) { + val := reflect.ValueOf(s) + top := val + + if val.Kind() == reflect.Ptr && !val.IsNil() { + val = val.Elem() + } + + if val.Kind() != reflect.Struct || val.Type() == timeType { + return &InvalidValidationError{Type: reflect.TypeOf(s)} + } + + // good to validate + vd := v.pool.Get().(*validate) + vd.top = top + vd.isPartial = true + vd.ffn = nil + vd.hasExcludes = true + vd.includeExclude = make(map[string]struct{}) + + typ := val.Type() + name := typ.Name() + + for _, key := range fields { + + vd.misc = vd.misc[0:0] + + if len(name) > 0 { + vd.misc = append(vd.misc, name...) + vd.misc = append(vd.misc, '.') + } + + vd.misc = append(vd.misc, key...) + vd.includeExclude[string(vd.misc)] = struct{}{} + } + + vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + + v.pool.Put(vd) + + return +} + +// Var validates a single variable using tag style validation. +// eg. +// var i int +// validate.Var(i, "gt=1,lt=10") +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) Var(field interface{}, tag string) error { + return v.VarCtx(context.Background(), field, tag) +} + +// VarCtx validates a single variable using tag style validation and allows passing of contextual +// validation validation information via context.Context. +// eg. +// var i int +// validate.Var(i, "gt=1,lt=10") +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) (err error) { + if len(tag) == 0 || tag == skipValidationTag { + return nil + } + + ctag := v.fetchCacheTag(tag) + val := reflect.ValueOf(field) + vd := v.pool.Get().(*validate) + vd.top = val + vd.isPartial = false + vd.traverseField(ctx, val, val, vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + v.pool.Put(vd) + return +} + +// VarWithValue validates a single variable, against another variable/field's value using tag style validation +// eg. +// s1 := "abcd" +// s2 := "abcd" +// validate.VarWithValue(s1, s2, "eqcsfield") // returns true +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error { + return v.VarWithValueCtx(context.Background(), field, other, tag) +} + +// VarWithValueCtx validates a single variable, against another variable/field's value using tag style validation and +// allows passing of contextual validation validation information via context.Context. +// eg. +// s1 := "abcd" +// s2 := "abcd" +// validate.VarWithValue(s1, s2, "eqcsfield") // returns true +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error) { + if len(tag) == 0 || tag == skipValidationTag { + return nil + } + ctag := v.fetchCacheTag(tag) + otherVal := reflect.ValueOf(other) + vd := v.pool.Get().(*validate) + vd.top = otherVal + vd.isPartial = false + vd.traverseField(ctx, otherVal, reflect.ValueOf(field), vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + v.pool.Put(vd) + return +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/.gitignore b/taskman-server/vendor/github.com/go-sql-driver/mysql/.gitignore new file mode 100644 index 00000000..2de28da1 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +Icon? +ehthumbs.db +Thumbs.db +.idea diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/AUTHORS b/taskman-server/vendor/github.com/go-sql-driver/mysql/AUTHORS new file mode 100644 index 00000000..05132751 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/AUTHORS @@ -0,0 +1,124 @@ +# This is the official list of Go-MySQL-Driver authors for copyright purposes. + +# If you are submitting a patch, please add your name or the name of the +# organization which holds the copyright to this list in alphabetical order. + +# Names should be added to this file as +# Name +# The email address is not required for organizations. +# Please keep the list sorted. + + +# Individual Persons + +Aaron Hopkins +Achille Roussel +Alex Snast +Alexey Palazhchenko +Andrew Reid +Animesh Ray +Arne Hormann +Ariel Mashraki +Asta Xie +Bulat Gaifullin +Caine Jette +Carlos Nieto +Chris Kirkland +Chris Moos +Craig Wilson +Daniel Montoya +Daniel Nichter +Daniël van Eeden +Dave Protasowski +DisposaBoy +Egor Smolyakov +Erwan Martin +Evan Shaw +Frederick Mayle +Gustavo Kristic +Hajime Nakagami +Hanno Braun +Henri Yandell +Hirotaka Yamamoto +Huyiguang +ICHINOSE Shogo +Ilia Cimpoes +INADA Naoki +Jacek Szwec +James Harr +Janek Vedock +Jeff Hodges +Jeffrey Charles +Jerome Meyer +Jiajia Zhong +Jian Zhen +Joshua Prunier +Julien Lefevre +Julien Schmidt +Justin Li +Justin Nuß +Kamil Dziedzic +Kei Kamikawa +Kevin Malachowski +Kieron Woodhouse +Lance Tian +Lennart Rudolph +Leonardo YongUk Kim +Linh Tran Tuan +Lion Yang +Luca Looz +Lucas Liu +Lunny Xiao +Luke Scott +Maciej Zimnoch +Michael Woolnough +Nathanial Murphy +Nicola Peduzzi +Olivier Mengué +oscarzhao +Paul Bonser +Peter Schultz +Rebecca Chin +Reed Allman +Richard Wilkes +Robert Russell +Runrioter Wung +Santhosh Kumar Tekuri +Sho Iizuka +Sho Ikeda +Shuode Li +Simon J Mudd +Soroush Pour +Stan Putrya +Stanley Gunawan +Steven Hartland +Tan Jinhua <312841925 at qq.com> +Thomas Wodarek +Tim Ruffles +Tom Jenkinson +Vladimir Kovpak +Vladyslav Zhelezniak +Xiangyu Hu +Xiaobing Jiang +Xiuming Chen +Xuehong Chan +Zhenye Xie +Zhixin Wen +Ziheng Lyu + +# Organizations + +Barracuda Networks, Inc. +Counting Ltd. +DigitalOcean Inc. +dyves labs AG +Facebook Inc. +GitHub Inc. +Google Inc. +InfoSum Ltd. +Keybase Inc. +Multiplay Ltd. +Percona LLC +Pivotal Inc. +Stripe Inc. +Zendesk Inc. diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md b/taskman-server/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md new file mode 100644 index 00000000..77024a82 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/CHANGELOG.md @@ -0,0 +1,253 @@ +## Version 1.7 (2022-11-29) + +Changes: + + - Drop support of Go 1.12 (#1211) + - Refactoring `(*textRows).readRow` in a more clear way (#1230) + - util: Reduce boundary check in escape functions. (#1316) + - enhancement for mysqlConn handleAuthResult (#1250) + +New Features: + + - support Is comparison on MySQLError (#1210) + - return unsigned in database type name when necessary (#1238) + - Add API to express like a --ssl-mode=PREFERRED MySQL client (#1370) + - Add SQLState to MySQLError (#1321) + +Bugfixes: + + - Fix parsing 0 year. (#1257) + + +## Version 1.6 (2021-04-01) + +Changes: + + - Migrate the CI service from travis-ci to GitHub Actions (#1176, #1183, #1190) + - `NullTime` is deprecated (#960, #1144) + - Reduce allocations when building SET command (#1111) + - Performance improvement for time formatting (#1118) + - Performance improvement for time parsing (#1098, #1113) + +New Features: + + - Implement `driver.Validator` interface (#1106, #1174) + - Support returning `uint64` from `Valuer` in `ConvertValue` (#1143) + - Add `json.RawMessage` for converter and prepared statement (#1059) + - Interpolate `json.RawMessage` as `string` (#1058) + - Implements `CheckNamedValue` (#1090) + +Bugfixes: + + - Stop rounding times (#1121, #1172) + - Put zero filler into the SSL handshake packet (#1066) + - Fix checking cancelled connections back into the connection pool (#1095) + - Fix remove last 0 byte for mysql_old_password when password is empty (#1133) + + +## Version 1.5 (2020-01-07) + +Changes: + + - Dropped support Go 1.9 and lower (#823, #829, #886, #1016, #1017) + - Improve buffer handling (#890) + - Document potentially insecure TLS configs (#901) + - Use a double-buffering scheme to prevent data races (#943) + - Pass uint64 values without converting them to string (#838, #955) + - Update collations and make utf8mb4 default (#877, #1054) + - Make NullTime compatible with sql.NullTime in Go 1.13+ (#995) + - Removed CloudSQL support (#993, #1007) + - Add Go Module support (#1003) + +New Features: + + - Implement support of optional TLS (#900) + - Check connection liveness (#934, #964, #997, #1048, #1051, #1052) + - Implement Connector Interface (#941, #958, #1020, #1035) + +Bugfixes: + + - Mark connections as bad on error during ping (#875) + - Mark connections as bad on error during dial (#867) + - Fix connection leak caused by rapid context cancellation (#1024) + - Mark connections as bad on error during Conn.Prepare (#1030) + + +## Version 1.4.1 (2018-11-14) + +Bugfixes: + + - Fix TIME format for binary columns (#818) + - Fix handling of empty auth plugin names (#835) + - Fix caching_sha2_password with empty password (#826) + - Fix canceled context broke mysqlConn (#862) + - Fix OldAuthSwitchRequest support (#870) + - Fix Auth Response packet for cleartext password (#887) + +## Version 1.4 (2018-06-03) + +Changes: + + - Documentation fixes (#530, #535, #567) + - Refactoring (#575, #579, #580, #581, #603, #615, #704) + - Cache column names (#444) + - Sort the DSN parameters in DSNs generated from a config (#637) + - Allow native password authentication by default (#644) + - Use the default port if it is missing in the DSN (#668) + - Removed the `strict` mode (#676) + - Do not query `max_allowed_packet` by default (#680) + - Dropped support Go 1.6 and lower (#696) + - Updated `ConvertValue()` to match the database/sql/driver implementation (#760) + - Document the usage of `0000-00-00T00:00:00` as the time.Time zero value (#783) + - Improved the compatibility of the authentication system (#807) + +New Features: + + - Multi-Results support (#537) + - `rejectReadOnly` DSN option (#604) + - `context.Context` support (#608, #612, #627, #761) + - Transaction isolation level support (#619, #744) + - Read-Only transactions support (#618, #634) + - `NewConfig` function which initializes a config with default values (#679) + - Implemented the `ColumnType` interfaces (#667, #724) + - Support for custom string types in `ConvertValue` (#623) + - Implemented `NamedValueChecker`, improving support for uint64 with high bit set (#690, #709, #710) + - `caching_sha2_password` authentication plugin support (#794, #800, #801, #802) + - Implemented `driver.SessionResetter` (#779) + - `sha256_password` authentication plugin support (#808) + +Bugfixes: + + - Use the DSN hostname as TLS default ServerName if `tls=true` (#564, #718) + - Fixed LOAD LOCAL DATA INFILE for empty files (#590) + - Removed columns definition cache since it sometimes cached invalid data (#592) + - Don't mutate registered TLS configs (#600) + - Make RegisterTLSConfig concurrency-safe (#613) + - Handle missing auth data in the handshake packet correctly (#646) + - Do not retry queries when data was written to avoid data corruption (#302, #736) + - Cache the connection pointer for error handling before invalidating it (#678) + - Fixed imports for appengine/cloudsql (#700) + - Fix sending STMT_LONG_DATA for 0 byte data (#734) + - Set correct capacity for []bytes read from length-encoded strings (#766) + - Make RegisterDial concurrency-safe (#773) + + +## Version 1.3 (2016-12-01) + +Changes: + + - Go 1.1 is no longer supported + - Use decimals fields in MySQL to format time types (#249) + - Buffer optimizations (#269) + - TLS ServerName defaults to the host (#283) + - Refactoring (#400, #410, #437) + - Adjusted documentation for second generation CloudSQL (#485) + - Documented DSN system var quoting rules (#502) + - Made statement.Close() calls idempotent to avoid errors in Go 1.6+ (#512) + +New Features: + + - Enable microsecond resolution on TIME, DATETIME and TIMESTAMP (#249) + - Support for returning table alias on Columns() (#289, #359, #382) + - Placeholder interpolation, can be actived with the DSN parameter `interpolateParams=true` (#309, #318, #490) + - Support for uint64 parameters with high bit set (#332, #345) + - Cleartext authentication plugin support (#327) + - Exported ParseDSN function and the Config struct (#403, #419, #429) + - Read / Write timeouts (#401) + - Support for JSON field type (#414) + - Support for multi-statements and multi-results (#411, #431) + - DSN parameter to set the driver-side max_allowed_packet value manually (#489) + - Native password authentication plugin support (#494, #524) + +Bugfixes: + + - Fixed handling of queries without columns and rows (#255) + - Fixed a panic when SetKeepAlive() failed (#298) + - Handle ERR packets while reading rows (#321) + - Fixed reading NULL length-encoded integers in MySQL 5.6+ (#349) + - Fixed absolute paths support in LOAD LOCAL DATA INFILE (#356) + - Actually zero out bytes in handshake response (#378) + - Fixed race condition in registering LOAD DATA INFILE handler (#383) + - Fixed tests with MySQL 5.7.9+ (#380) + - QueryUnescape TLS config names (#397) + - Fixed "broken pipe" error by writing to closed socket (#390) + - Fixed LOAD LOCAL DATA INFILE buffering (#424) + - Fixed parsing of floats into float64 when placeholders are used (#434) + - Fixed DSN tests with Go 1.7+ (#459) + - Handle ERR packets while waiting for EOF (#473) + - Invalidate connection on error while discarding additional results (#513) + - Allow terminating packets of length 0 (#516) + + +## Version 1.2 (2014-06-03) + +Changes: + + - We switched back to a "rolling release". `go get` installs the current master branch again + - Version v1 of the driver will not be maintained anymore. Go 1.0 is no longer supported by this driver + - Exported errors to allow easy checking from application code + - Enabled TCP Keepalives on TCP connections + - Optimized INFILE handling (better buffer size calculation, lazy init, ...) + - The DSN parser also checks for a missing separating slash + - Faster binary date / datetime to string formatting + - Also exported the MySQLWarning type + - mysqlConn.Close returns the first error encountered instead of ignoring all errors + - writePacket() automatically writes the packet size to the header + - readPacket() uses an iterative approach instead of the recursive approach to merge splitted packets + +New Features: + + - `RegisterDial` allows the usage of a custom dial function to establish the network connection + - Setting the connection collation is possible with the `collation` DSN parameter. This parameter should be preferred over the `charset` parameter + - Logging of critical errors is configurable with `SetLogger` + - Google CloudSQL support + +Bugfixes: + + - Allow more than 32 parameters in prepared statements + - Various old_password fixes + - Fixed TestConcurrent test to pass Go's race detection + - Fixed appendLengthEncodedInteger for large numbers + - Renamed readLengthEnodedString to readLengthEncodedString and skipLengthEnodedString to skipLengthEncodedString (fixed typo) + + +## Version 1.1 (2013-11-02) + +Changes: + + - Go-MySQL-Driver now requires Go 1.1 + - Connections now use the collation `utf8_general_ci` by default. Adding `&charset=UTF8` to the DSN should not be necessary anymore + - Made closing rows and connections error tolerant. This allows for example deferring rows.Close() without checking for errors + - `[]byte(nil)` is now treated as a NULL value. Before, it was treated like an empty string / `[]byte("")` + - DSN parameter values must now be url.QueryEscape'ed. This allows text values to contain special characters, such as '&'. + - Use the IO buffer also for writing. This results in zero allocations (by the driver) for most queries + - Optimized the buffer for reading + - stmt.Query now caches column metadata + - New Logo + - Changed the copyright header to include all contributors + - Improved the LOAD INFILE documentation + - The driver struct is now exported to make the driver directly accessible + - Refactored the driver tests + - Added more benchmarks and moved all to a separate file + - Other small refactoring + +New Features: + + - Added *old_passwords* support: Required in some cases, but must be enabled by adding `allowOldPasswords=true` to the DSN since it is insecure + - Added a `clientFoundRows` parameter: Return the number of matching rows instead of the number of rows changed on UPDATEs + - Added TLS/SSL support: Use a TLS/SSL encrypted connection to the server. Custom TLS configs can be registered and used + +Bugfixes: + + - Fixed MySQL 4.1 support: MySQL 4.1 sends packets with lengths which differ from the specification + - Convert to DB timezone when inserting `time.Time` + - Splitted packets (more than 16MB) are now merged correctly + - Fixed false positive `io.EOF` errors when the data was fully read + - Avoid panics on reuse of closed connections + - Fixed empty string producing false nil values + - Fixed sign byte for positive TIME fields + + +## Version 1.0 (2013-05-14) + +Initial Release diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/LICENSE b/taskman-server/vendor/github.com/go-sql-driver/mysql/LICENSE new file mode 100644 index 00000000..14e2f777 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/README.md b/taskman-server/vendor/github.com/go-sql-driver/mysql/README.md new file mode 100644 index 00000000..25de2e5a --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/README.md @@ -0,0 +1,531 @@ +# Go-MySQL-Driver + +A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) package + +![Go-MySQL-Driver logo](https://raw.github.com/wiki/go-sql-driver/mysql/gomysql_m.png "Golang Gopher holding the MySQL Dolphin") + +--------------------------------------- + * [Features](#features) + * [Requirements](#requirements) + * [Installation](#installation) + * [Usage](#usage) + * [DSN (Data Source Name)](#dsn-data-source-name) + * [Password](#password) + * [Protocol](#protocol) + * [Address](#address) + * [Parameters](#parameters) + * [Examples](#examples) + * [Connection pool and timeouts](#connection-pool-and-timeouts) + * [context.Context Support](#contextcontext-support) + * [ColumnType Support](#columntype-support) + * [LOAD DATA LOCAL INFILE support](#load-data-local-infile-support) + * [time.Time support](#timetime-support) + * [Unicode support](#unicode-support) + * [Testing / Development](#testing--development) + * [License](#license) + +--------------------------------------- + +## Features + * Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance") + * Native Go implementation. No C-bindings, just pure Go + * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](https://godoc.org/github.com/go-sql-driver/mysql#DialFunc) + * Automatic handling of broken connections + * Automatic Connection Pooling *(by database/sql package)* + * Supports queries larger than 16MB + * Full [`sql.RawBytes`](https://golang.org/pkg/database/sql/#RawBytes) support. + * Intelligent `LONG DATA` handling in prepared statements + * Secure `LOAD DATA LOCAL INFILE` support with file allowlisting and `io.Reader` support + * Optional `time.Time` parsing + * Optional placeholder interpolation + +## Requirements + * Go 1.13 or higher. We aim to support the 3 latest versions of Go. + * MySQL (4.1+), MariaDB, Percona Server, Google CloudSQL or Sphinx (2.2.3+) + +--------------------------------------- + +## Installation +Simple install the package to your [$GOPATH](https://github.com/golang/go/wiki/GOPATH "GOPATH") with the [go tool](https://golang.org/cmd/go/ "go command") from shell: +```bash +$ go get -u github.com/go-sql-driver/mysql +``` +Make sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`. + +## Usage +_Go MySQL Driver_ is an implementation of Go's `database/sql/driver` interface. You only need to import the driver and can use the full [`database/sql`](https://golang.org/pkg/database/sql/) API then. + +Use `mysql` as `driverName` and a valid [DSN](#dsn-data-source-name) as `dataSourceName`: + +```go +import ( + "database/sql" + "time" + + _ "github.com/go-sql-driver/mysql" +) + +// ... + +db, err := sql.Open("mysql", "user:password@/dbname") +if err != nil { + panic(err) +} +// See "Important settings" section. +db.SetConnMaxLifetime(time.Minute * 3) +db.SetMaxOpenConns(10) +db.SetMaxIdleConns(10) +``` + +[Examples are available in our Wiki](https://github.com/go-sql-driver/mysql/wiki/Examples "Go-MySQL-Driver Examples"). + +### Important settings + +`db.SetConnMaxLifetime()` is required to ensure connections are closed by the driver safely before connection is closed by MySQL server, OS, or other middlewares. Since some middlewares close idle connections by 5 minutes, we recommend timeout shorter than 5 minutes. This setting helps load balancing and changing system variables too. + +`db.SetMaxOpenConns()` is highly recommended to limit the number of connection used by the application. There is no recommended limit number because it depends on application and MySQL server. + +`db.SetMaxIdleConns()` is recommended to be set same to `db.SetMaxOpenConns()`. When it is smaller than `SetMaxOpenConns()`, connections can be opened and closed much more frequently than you expect. Idle connections can be closed by the `db.SetConnMaxLifetime()`. If you want to close idle connections more rapidly, you can use `db.SetConnMaxIdleTime()` since Go 1.15. + + +### DSN (Data Source Name) + +The Data Source Name has a common format, like e.g. [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php) uses it, but without type-prefix (optional parts marked by squared brackets): +``` +[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN] +``` + +A DSN in its fullest form: +``` +username:password@protocol(address)/dbname?param=value +``` + +Except for the databasename, all values are optional. So the minimal DSN is: +``` +/dbname +``` + +If you do not want to preselect a database, leave `dbname` empty: +``` +/ +``` +This has the same effect as an empty DSN string: +``` + +``` + +Alternatively, [Config.FormatDSN](https://godoc.org/github.com/go-sql-driver/mysql#Config.FormatDSN) can be used to create a DSN string by filling a struct. + +#### Password +Passwords can consist of any character. Escaping is **not** necessary. + +#### Protocol +See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available. +In general you should use an Unix domain socket if available and TCP otherwise for best performance. + +#### Address +For TCP and UDP networks, addresses have the form `host[:port]`. +If `port` is omitted, the default port will be used. +If `host` is a literal IPv6 address, it must be enclosed in square brackets. +The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form. + +For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. `/var/run/mysqld/mysqld.sock` or `/tmp/mysql.sock`. + +#### Parameters +*Parameters are case-sensitive!* + +Notice that any of `true`, `TRUE`, `True` or `1` is accepted to stand for a true boolean value. Not surprisingly, false can be specified as any of: `false`, `FALSE`, `False` or `0`. + +##### `allowAllFiles` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +`allowAllFiles=true` disables the file allowlist for `LOAD DATA LOCAL INFILE` and allows *all* files. +[*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html) + +##### `allowCleartextPasswords` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +`allowCleartextPasswords=true` allows using the [cleartext client side plugin](https://dev.mysql.com/doc/en/cleartext-pluggable-authentication.html) if required by an account, such as one defined with the [PAM authentication plugin](http://dev.mysql.com/doc/en/pam-authentication-plugin.html). Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include [TLS / SSL](#tls), IPsec, or a private network. + + +##### `allowFallbackToPlaintext` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +`allowFallbackToPlaintext=true` acts like a `--ssl-mode=PREFERRED` MySQL client as described in [Command Options for Connecting to the Server](https://dev.mysql.com/doc/refman/5.7/en/connection-options.html#option_general_ssl-mode) + +##### `allowNativePasswords` + +``` +Type: bool +Valid Values: true, false +Default: true +``` +`allowNativePasswords=false` disallows the usage of MySQL native password method. + +##### `allowOldPasswords` + +``` +Type: bool +Valid Values: true, false +Default: false +``` +`allowOldPasswords=true` allows the usage of the insecure old password method. This should be avoided, but is necessary in some cases. See also [the old_passwords wiki page](https://github.com/go-sql-driver/mysql/wiki/old_passwords). + +##### `charset` + +``` +Type: string +Valid Values: +Default: none +``` + +Sets the charset used for client-server interaction (`"SET NAMES "`). If multiple charsets are set (separated by a comma), the following charset is used if setting the charset failes. This enables for example support for `utf8mb4` ([introduced in MySQL 5.5.3](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)) with fallback to `utf8` for older servers (`charset=utf8mb4,utf8`). + +Usage of the `charset` parameter is discouraged because it issues additional queries to the server. +Unless you need the fallback behavior, please use `collation` instead. + +##### `checkConnLiveness` + +``` +Type: bool +Valid Values: true, false +Default: true +``` + +On supported platforms connections retrieved from the connection pool are checked for liveness before using them. If the check fails, the respective connection is marked as bad and the query retried with another connection. +`checkConnLiveness=false` disables this liveness check of connections. + +##### `collation` + +``` +Type: string +Valid Values: +Default: utf8mb4_general_ci +``` + +Sets the collation used for client-server interaction on connection. In contrast to `charset`, `collation` does not issue additional queries. If the specified collation is unavailable on the target server, the connection will fail. + +A list of valid charsets for a server is retrievable with `SHOW COLLATION`. + +The default collation (`utf8mb4_general_ci`) is supported from MySQL 5.5. You should use an older collation (e.g. `utf8_general_ci`) for older MySQL. + +Collations for charset "ucs2", "utf16", "utf16le", and "utf32" can not be used ([ref](https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset)). + + +##### `clientFoundRows` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +`clientFoundRows=true` causes an UPDATE to return the number of matching rows instead of the number of rows changed. + +##### `columnsWithAlias` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +When `columnsWithAlias` is true, calls to `sql.Rows.Columns()` will return the table alias and the column name separated by a dot. For example: + +``` +SELECT u.id FROM users as u +``` + +will return `u.id` instead of just `id` if `columnsWithAlias=true`. + +##### `interpolateParams` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +If `interpolateParams` is true, placeholders (`?`) in calls to `db.Query()` and `db.Exec()` are interpolated into a single query string with given parameters. This reduces the number of roundtrips, since the driver has to prepare a statement, execute it with given parameters and close the statement again with `interpolateParams=false`. + +*This can not be used together with the multibyte encodings BIG5, CP932, GB2312, GBK or SJIS. These are rejected as they may [introduce a SQL injection vulnerability](http://stackoverflow.com/a/12118602/3430118)!* + +##### `loc` + +``` +Type: string +Valid Values: +Default: UTC +``` + +Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](https://golang.org/pkg/time/#LoadLocation) for details. + +Note that this sets the location for time.Time values but does not change MySQL's [time_zone setting](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html). For that see the [time_zone system variable](#system-variables), which can also be set as a DSN parameter. + +Please keep in mind, that param values must be [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`. + +##### `maxAllowedPacket` +``` +Type: decimal number +Default: 4194304 +``` + +Max packet size allowed in bytes. The default value is 4 MiB and should be adjusted to match the server settings. `maxAllowedPacket=0` can be used to automatically fetch the `max_allowed_packet` variable from server *on every connection*. + +##### `multiStatements` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +Allow multiple statements in one query. While this allows batch queries, it also greatly increases the risk of SQL injections. Only the result of the first query is returned, all other results are silently discarded. + +When `multiStatements` is used, `?` parameters must only be used in the first statement. + +##### `parseTime` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +`parseTime=true` changes the output type of `DATE` and `DATETIME` values to `time.Time` instead of `[]byte` / `string` +The date or datetime like `0000-00-00 00:00:00` is converted into zero value of `time.Time`. + + +##### `readTimeout` + +``` +Type: duration +Default: 0 +``` + +I/O read timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. + +##### `rejectReadOnly` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + + +`rejectReadOnly=true` causes the driver to reject read-only connections. This +is for a possible race condition during an automatic failover, where the mysql +client gets connected to a read-only replica after the failover. + +Note that this should be a fairly rare case, as an automatic failover normally +happens when the primary is down, and the race condition shouldn't happen +unless it comes back up online as soon as the failover is kicked off. On the +other hand, when this happens, a MySQL application can get stuck on a +read-only connection until restarted. It is however fairly easy to reproduce, +for example, using a manual failover on AWS Aurora's MySQL-compatible cluster. + +If you are not relying on read-only transactions to reject writes that aren't +supposed to happen, setting this on some MySQL providers (such as AWS Aurora) +is safer for failovers. + +Note that ERROR 1290 can be returned for a `read-only` server and this option will +cause a retry for that error. However the same error number is used for some +other cases. You should ensure your application will never cause an ERROR 1290 +except for `read-only` mode when enabling this option. + + +##### `serverPubKey` + +``` +Type: string +Valid Values: +Default: none +``` + +Server public keys can be registered with [`mysql.RegisterServerPubKey`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterServerPubKey), which can then be used by the assigned name in the DSN. +Public keys are used to transmit encrypted data, e.g. for authentication. +If the server's public key is known, it should be set manually to avoid expensive and potentially insecure transmissions of the public key from the server to the client each time it is required. + + +##### `timeout` + +``` +Type: duration +Default: OS default +``` + +Timeout for establishing connections, aka dial timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. + + +##### `tls` + +``` +Type: bool / string +Valid Values: true, false, skip-verify, preferred, +Default: false +``` + +`tls=true` enables TLS / SSL encrypted connection to the server. Use `skip-verify` if you want to use a self-signed or invalid certificate (server side) or use `preferred` to use TLS only when advertised by the server. This is similar to `skip-verify`, but additionally allows a fallback to a connection which is not encrypted. Neither `skip-verify` nor `preferred` add any reliable security. You can use a custom TLS config after registering it with [`mysql.RegisterTLSConfig`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterTLSConfig). + + +##### `writeTimeout` + +``` +Type: duration +Default: 0 +``` + +I/O write timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*. + + +##### System Variables + +Any other parameters are interpreted as system variables: + * `=`: `SET =` + * `=`: `SET =` + * `=%27%27`: `SET =''` + +Rules: +* The values for string variables must be quoted with `'`. +* The values must also be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed! + (which implies values of string variables must be wrapped with `%27`). + +Examples: + * `autocommit=1`: `SET autocommit=1` + * [`time_zone=%27Europe%2FParis%27`](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html): `SET time_zone='Europe/Paris'` + * [`transaction_isolation=%27REPEATABLE-READ%27`](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_transaction_isolation): `SET transaction_isolation='REPEATABLE-READ'` + + +#### Examples +``` +user@unix(/path/to/socket)/dbname +``` + +``` +root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local +``` + +``` +user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true +``` + +Treat warnings as errors by setting the system variable [`sql_mode`](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html): +``` +user:password@/dbname?sql_mode=TRADITIONAL +``` + +TCP via IPv6: +``` +user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci +``` + +TCP on a remote host, e.g. Amazon RDS: +``` +id:password@tcp(your-amazonaws-uri.com:3306)/dbname +``` + +Google Cloud SQL on App Engine: +``` +user:password@unix(/cloudsql/project-id:region-name:instance-name)/dbname +``` + +TCP using default port (3306) on localhost: +``` +user:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped +``` + +Use the default protocol (tcp) and host (localhost:3306): +``` +user:password@/dbname +``` + +No Database preselected: +``` +user:password@/ +``` + + +### Connection pool and timeouts +The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see `*DB.SetMaxOpenConns`, `*DB.SetMaxIdleConns`, and `*DB.SetConnMaxLifetime` in the [database/sql documentation](https://golang.org/pkg/database/sql/). The read, write, and dial timeouts for each individual connection are configured with the DSN parameters [`readTimeout`](#readtimeout), [`writeTimeout`](#writetimeout), and [`timeout`](#timeout), respectively. + +## `ColumnType` Support +This driver supports the [`ColumnType` interface](https://golang.org/pkg/database/sql/#ColumnType) introduced in Go 1.8, with the exception of [`ColumnType.Length()`](https://golang.org/pkg/database/sql/#ColumnType.Length), which is currently not supported. All Unsigned database type names will be returned `UNSIGNED ` with `INT`, `TINYINT`, `SMALLINT`, `BIGINT`. + +## `context.Context` Support +Go 1.8 added `database/sql` support for `context.Context`. This driver supports query timeouts and cancellation via contexts. +See [context support in the database/sql package](https://golang.org/doc/go1.8#database_sql) for more details. + + +### `LOAD DATA LOCAL INFILE` support +For this feature you need direct access to the package. Therefore you must change the import path (no `_`): +```go +import "github.com/go-sql-driver/mysql" +``` + +Files must be explicitly allowed by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the allowlist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html)). + +To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore. + +See the [godoc of Go-MySQL-Driver](https://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details. + + +### `time.Time` support +The default internal output type of MySQL `DATE` and `DATETIME` values is `[]byte` which allows you to scan the value into a `[]byte`, `string` or `sql.RawBytes` variable in your program. + +However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` variables, which is the logical equivalent in Go to `DATE` and `DATETIME` in MySQL. You can do that by changing the internal output type from `[]byte` to `time.Time` with the DSN parameter `parseTime=true`. You can set the default [`time.Time` location](https://golang.org/pkg/time/#Location) with the `loc` DSN parameter. + +**Caution:** As of Go 1.1, this makes `time.Time` the only variable type you can scan `DATE` and `DATETIME` values into. This breaks for example [`sql.RawBytes` support](https://github.com/go-sql-driver/mysql/wiki/Examples#rawbytes). + + +### Unicode support +Since version 1.5 Go-MySQL-Driver automatically uses the collation ` utf8mb4_general_ci` by default. + +Other collations / charsets can be set using the [`collation`](#collation) DSN parameter. + +Version 1.0 of the driver recommended adding `&charset=utf8` (alias for `SET NAMES utf8`) to the DSN to enable proper UTF-8 support. This is not necessary anymore. The [`collation`](#collation) parameter should be preferred to set another collation / charset than the default. + +See http://dev.mysql.com/doc/refman/8.0/en/charset-unicode.html for more details on MySQL's Unicode support. + +## Testing / Development +To run the driver tests you may need to adjust the configuration. See the [Testing Wiki-Page](https://github.com/go-sql-driver/mysql/wiki/Testing "Testing") for details. + +Go-MySQL-Driver is not feature-complete yet. Your help is very appreciated. +If you want to contribute, you can work on an [open issue](https://github.com/go-sql-driver/mysql/issues?state=open) or review a [pull request](https://github.com/go-sql-driver/mysql/pulls). + +See the [Contribution Guidelines](https://github.com/go-sql-driver/mysql/blob/master/.github/CONTRIBUTING.md) for details. + +--------------------------------------- + +## License +Go-MySQL-Driver is licensed under the [Mozilla Public License Version 2.0](https://raw.github.com/go-sql-driver/mysql/master/LICENSE) + +Mozilla summarizes the license scope as follows: +> MPL: The copyleft applies to any files containing MPLed code. + + +That means: + * You can **use** the **unchanged** source code both in private and commercially. + * When distributing, you **must publish** the source code of any **changed files** licensed under the MPL 2.0 under a) the MPL 2.0 itself or b) a compatible license (e.g. GPL 3.0 or Apache License 2.0). + * You **needn't publish** the source code of your library as long as the files licensed under the MPL 2.0 are **unchanged**. + +Please read the [MPL 2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) if you have further questions regarding the license. + +You can read the full terms here: [LICENSE](https://raw.github.com/go-sql-driver/mysql/master/LICENSE). + +![Go Gopher and MySQL Dolphin](https://raw.github.com/wiki/go-sql-driver/mysql/go-mysql-driver_m.jpg "Golang Gopher transporting the MySQL Dolphin in a wheelbarrow") diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/atomic_bool.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/atomic_bool.go new file mode 100644 index 00000000..1b7e19f3 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/atomic_bool.go @@ -0,0 +1,19 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package. +// +// Copyright 2022 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. +//go:build go1.19 +// +build go1.19 + +package mysql + +import "sync/atomic" + +/****************************************************************************** +* Sync utils * +******************************************************************************/ + +type atomicBool = atomic.Bool diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/atomic_bool_go118.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/atomic_bool_go118.go new file mode 100644 index 00000000..2e9a7f0b --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/atomic_bool_go118.go @@ -0,0 +1,47 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package. +// +// Copyright 2022 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. +//go:build !go1.19 +// +build !go1.19 + +package mysql + +import "sync/atomic" + +/****************************************************************************** +* Sync utils * +******************************************************************************/ + +// atomicBool is an implementation of atomic.Bool for older version of Go. +// it is a wrapper around uint32 for usage as a boolean value with +// atomic access. +type atomicBool struct { + _ noCopy + value uint32 +} + +// Load returns whether the current boolean value is true +func (ab *atomicBool) Load() bool { + return atomic.LoadUint32(&ab.value) > 0 +} + +// Store sets the value of the bool regardless of the previous value +func (ab *atomicBool) Store(value bool) { + if value { + atomic.StoreUint32(&ab.value, 1) + } else { + atomic.StoreUint32(&ab.value, 0) + } +} + +// Swap sets the value of the bool and returns the old value. +func (ab *atomicBool) Swap(value bool) bool { + if value { + return atomic.SwapUint32(&ab.value, 1) > 0 + } + return atomic.SwapUint32(&ab.value, 0) > 0 +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/auth.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/auth.go new file mode 100644 index 00000000..1ff203e5 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/auth.go @@ -0,0 +1,437 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/sha1" + "crypto/sha256" + "crypto/x509" + "encoding/pem" + "fmt" + "sync" +) + +// server pub keys registry +var ( + serverPubKeyLock sync.RWMutex + serverPubKeyRegistry map[string]*rsa.PublicKey +) + +// RegisterServerPubKey registers a server RSA public key which can be used to +// send data in a secure manner to the server without receiving the public key +// in a potentially insecure way from the server first. +// Registered keys can afterwards be used adding serverPubKey= to the DSN. +// +// Note: The provided rsa.PublicKey instance is exclusively owned by the driver +// after registering it and may not be modified. +// +// data, err := ioutil.ReadFile("mykey.pem") +// if err != nil { +// log.Fatal(err) +// } +// +// block, _ := pem.Decode(data) +// if block == nil || block.Type != "PUBLIC KEY" { +// log.Fatal("failed to decode PEM block containing public key") +// } +// +// pub, err := x509.ParsePKIXPublicKey(block.Bytes) +// if err != nil { +// log.Fatal(err) +// } +// +// if rsaPubKey, ok := pub.(*rsa.PublicKey); ok { +// mysql.RegisterServerPubKey("mykey", rsaPubKey) +// } else { +// log.Fatal("not a RSA public key") +// } +func RegisterServerPubKey(name string, pubKey *rsa.PublicKey) { + serverPubKeyLock.Lock() + if serverPubKeyRegistry == nil { + serverPubKeyRegistry = make(map[string]*rsa.PublicKey) + } + + serverPubKeyRegistry[name] = pubKey + serverPubKeyLock.Unlock() +} + +// DeregisterServerPubKey removes the public key registered with the given name. +func DeregisterServerPubKey(name string) { + serverPubKeyLock.Lock() + if serverPubKeyRegistry != nil { + delete(serverPubKeyRegistry, name) + } + serverPubKeyLock.Unlock() +} + +func getServerPubKey(name string) (pubKey *rsa.PublicKey) { + serverPubKeyLock.RLock() + if v, ok := serverPubKeyRegistry[name]; ok { + pubKey = v + } + serverPubKeyLock.RUnlock() + return +} + +// Hash password using pre 4.1 (old password) method +// https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c +type myRnd struct { + seed1, seed2 uint32 +} + +const myRndMaxVal = 0x3FFFFFFF + +// Pseudo random number generator +func newMyRnd(seed1, seed2 uint32) *myRnd { + return &myRnd{ + seed1: seed1 % myRndMaxVal, + seed2: seed2 % myRndMaxVal, + } +} + +// Tested to be equivalent to MariaDB's floating point variant +// http://play.golang.org/p/QHvhd4qved +// http://play.golang.org/p/RG0q4ElWDx +func (r *myRnd) NextByte() byte { + r.seed1 = (r.seed1*3 + r.seed2) % myRndMaxVal + r.seed2 = (r.seed1 + r.seed2 + 33) % myRndMaxVal + + return byte(uint64(r.seed1) * 31 / myRndMaxVal) +} + +// Generate binary hash from byte string using insecure pre 4.1 method +func pwHash(password []byte) (result [2]uint32) { + var add uint32 = 7 + var tmp uint32 + + result[0] = 1345345333 + result[1] = 0x12345671 + + for _, c := range password { + // skip spaces and tabs in password + if c == ' ' || c == '\t' { + continue + } + + tmp = uint32(c) + result[0] ^= (((result[0] & 63) + add) * tmp) + (result[0] << 8) + result[1] += (result[1] << 8) ^ result[0] + add += tmp + } + + // Remove sign bit (1<<31)-1) + result[0] &= 0x7FFFFFFF + result[1] &= 0x7FFFFFFF + + return +} + +// Hash password using insecure pre 4.1 method +func scrambleOldPassword(scramble []byte, password string) []byte { + scramble = scramble[:8] + + hashPw := pwHash([]byte(password)) + hashSc := pwHash(scramble) + + r := newMyRnd(hashPw[0]^hashSc[0], hashPw[1]^hashSc[1]) + + var out [8]byte + for i := range out { + out[i] = r.NextByte() + 64 + } + + mask := r.NextByte() + for i := range out { + out[i] ^= mask + } + + return out[:] +} + +// Hash password using 4.1+ method (SHA1) +func scramblePassword(scramble []byte, password string) []byte { + if len(password) == 0 { + return nil + } + + // stage1Hash = SHA1(password) + crypt := sha1.New() + crypt.Write([]byte(password)) + stage1 := crypt.Sum(nil) + + // scrambleHash = SHA1(scramble + SHA1(stage1Hash)) + // inner Hash + crypt.Reset() + crypt.Write(stage1) + hash := crypt.Sum(nil) + + // outer Hash + crypt.Reset() + crypt.Write(scramble) + crypt.Write(hash) + scramble = crypt.Sum(nil) + + // token = scrambleHash XOR stage1Hash + for i := range scramble { + scramble[i] ^= stage1[i] + } + return scramble +} + +// Hash password using MySQL 8+ method (SHA256) +func scrambleSHA256Password(scramble []byte, password string) []byte { + if len(password) == 0 { + return nil + } + + // XOR(SHA256(password), SHA256(SHA256(SHA256(password)), scramble)) + + crypt := sha256.New() + crypt.Write([]byte(password)) + message1 := crypt.Sum(nil) + + crypt.Reset() + crypt.Write(message1) + message1Hash := crypt.Sum(nil) + + crypt.Reset() + crypt.Write(message1Hash) + crypt.Write(scramble) + message2 := crypt.Sum(nil) + + for i := range message1 { + message1[i] ^= message2[i] + } + + return message1 +} + +func encryptPassword(password string, seed []byte, pub *rsa.PublicKey) ([]byte, error) { + plain := make([]byte, len(password)+1) + copy(plain, password) + for i := range plain { + j := i % len(seed) + plain[i] ^= seed[j] + } + sha1 := sha1.New() + return rsa.EncryptOAEP(sha1, rand.Reader, pub, plain, nil) +} + +func (mc *mysqlConn) sendEncryptedPassword(seed []byte, pub *rsa.PublicKey) error { + enc, err := encryptPassword(mc.cfg.Passwd, seed, pub) + if err != nil { + return err + } + return mc.writeAuthSwitchPacket(enc) +} + +func (mc *mysqlConn) auth(authData []byte, plugin string) ([]byte, error) { + switch plugin { + case "caching_sha2_password": + authResp := scrambleSHA256Password(authData, mc.cfg.Passwd) + return authResp, nil + + case "mysql_old_password": + if !mc.cfg.AllowOldPasswords { + return nil, ErrOldPassword + } + if len(mc.cfg.Passwd) == 0 { + return nil, nil + } + // Note: there are edge cases where this should work but doesn't; + // this is currently "wontfix": + // https://github.com/go-sql-driver/mysql/issues/184 + authResp := append(scrambleOldPassword(authData[:8], mc.cfg.Passwd), 0) + return authResp, nil + + case "mysql_clear_password": + if !mc.cfg.AllowCleartextPasswords { + return nil, ErrCleartextPassword + } + // http://dev.mysql.com/doc/refman/5.7/en/cleartext-authentication-plugin.html + // http://dev.mysql.com/doc/refman/5.7/en/pam-authentication-plugin.html + return append([]byte(mc.cfg.Passwd), 0), nil + + case "mysql_native_password": + if !mc.cfg.AllowNativePasswords { + return nil, ErrNativePassword + } + // https://dev.mysql.com/doc/internals/en/secure-password-authentication.html + // Native password authentication only need and will need 20-byte challenge. + authResp := scramblePassword(authData[:20], mc.cfg.Passwd) + return authResp, nil + + case "sha256_password": + if len(mc.cfg.Passwd) == 0 { + return []byte{0}, nil + } + // unlike caching_sha2_password, sha256_password does not accept + // cleartext password on unix transport. + if mc.cfg.TLS != nil { + // write cleartext auth packet + return append([]byte(mc.cfg.Passwd), 0), nil + } + + pubKey := mc.cfg.pubKey + if pubKey == nil { + // request public key from server + return []byte{1}, nil + } + + // encrypted password + enc, err := encryptPassword(mc.cfg.Passwd, authData, pubKey) + return enc, err + + default: + errLog.Print("unknown auth plugin:", plugin) + return nil, ErrUnknownPlugin + } +} + +func (mc *mysqlConn) handleAuthResult(oldAuthData []byte, plugin string) error { + // Read Result Packet + authData, newPlugin, err := mc.readAuthResult() + if err != nil { + return err + } + + // handle auth plugin switch, if requested + if newPlugin != "" { + // If CLIENT_PLUGIN_AUTH capability is not supported, no new cipher is + // sent and we have to keep using the cipher sent in the init packet. + if authData == nil { + authData = oldAuthData + } else { + // copy data from read buffer to owned slice + copy(oldAuthData, authData) + } + + plugin = newPlugin + + authResp, err := mc.auth(authData, plugin) + if err != nil { + return err + } + if err = mc.writeAuthSwitchPacket(authResp); err != nil { + return err + } + + // Read Result Packet + authData, newPlugin, err = mc.readAuthResult() + if err != nil { + return err + } + + // Do not allow to change the auth plugin more than once + if newPlugin != "" { + return ErrMalformPkt + } + } + + switch plugin { + + // https://insidemysql.com/preparing-your-community-connector-for-mysql-8-part-2-sha256/ + case "caching_sha2_password": + switch len(authData) { + case 0: + return nil // auth successful + case 1: + switch authData[0] { + case cachingSha2PasswordFastAuthSuccess: + if err = mc.readResultOK(); err == nil { + return nil // auth successful + } + + case cachingSha2PasswordPerformFullAuthentication: + if mc.cfg.TLS != nil || mc.cfg.Net == "unix" { + // write cleartext auth packet + err = mc.writeAuthSwitchPacket(append([]byte(mc.cfg.Passwd), 0)) + if err != nil { + return err + } + } else { + pubKey := mc.cfg.pubKey + if pubKey == nil { + // request public key from server + data, err := mc.buf.takeSmallBuffer(4 + 1) + if err != nil { + return err + } + data[4] = cachingSha2PasswordRequestPublicKey + err = mc.writePacket(data) + if err != nil { + return err + } + + if data, err = mc.readPacket(); err != nil { + return err + } + + if data[0] != iAuthMoreData { + return fmt.Errorf("unexpect resp from server for caching_sha2_password perform full authentication") + } + + // parse public key + block, rest := pem.Decode(data[1:]) + if block == nil { + return fmt.Errorf("No Pem data found, data: %s", rest) + } + pkix, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return err + } + pubKey = pkix.(*rsa.PublicKey) + } + + // send encrypted password + err = mc.sendEncryptedPassword(oldAuthData, pubKey) + if err != nil { + return err + } + } + return mc.readResultOK() + + default: + return ErrMalformPkt + } + default: + return ErrMalformPkt + } + + case "sha256_password": + switch len(authData) { + case 0: + return nil // auth successful + default: + block, _ := pem.Decode(authData) + if block == nil { + return fmt.Errorf("no Pem data found, data: %s", authData) + } + + pub, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return err + } + + // send encrypted password + err = mc.sendEncryptedPassword(oldAuthData, pub.(*rsa.PublicKey)) + if err != nil { + return err + } + return mc.readResultOK() + } + + default: + return nil // auth successful + } + + return err +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/buffer.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/buffer.go new file mode 100644 index 00000000..0774c5c8 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/buffer.go @@ -0,0 +1,182 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "io" + "net" + "time" +) + +const defaultBufSize = 4096 +const maxCachedBufSize = 256 * 1024 + +// A buffer which is used for both reading and writing. +// This is possible since communication on each connection is synchronous. +// In other words, we can't write and read simultaneously on the same connection. +// The buffer is similar to bufio.Reader / Writer but zero-copy-ish +// Also highly optimized for this particular use case. +// This buffer is backed by two byte slices in a double-buffering scheme +type buffer struct { + buf []byte // buf is a byte buffer who's length and capacity are equal. + nc net.Conn + idx int + length int + timeout time.Duration + dbuf [2][]byte // dbuf is an array with the two byte slices that back this buffer + flipcnt uint // flipccnt is the current buffer counter for double-buffering +} + +// newBuffer allocates and returns a new buffer. +func newBuffer(nc net.Conn) buffer { + fg := make([]byte, defaultBufSize) + return buffer{ + buf: fg, + nc: nc, + dbuf: [2][]byte{fg, nil}, + } +} + +// flip replaces the active buffer with the background buffer +// this is a delayed flip that simply increases the buffer counter; +// the actual flip will be performed the next time we call `buffer.fill` +func (b *buffer) flip() { + b.flipcnt += 1 +} + +// fill reads into the buffer until at least _need_ bytes are in it +func (b *buffer) fill(need int) error { + n := b.length + // fill data into its double-buffering target: if we've called + // flip on this buffer, we'll be copying to the background buffer, + // and then filling it with network data; otherwise we'll just move + // the contents of the current buffer to the front before filling it + dest := b.dbuf[b.flipcnt&1] + + // grow buffer if necessary to fit the whole packet. + if need > len(dest) { + // Round up to the next multiple of the default size + dest = make([]byte, ((need/defaultBufSize)+1)*defaultBufSize) + + // if the allocated buffer is not too large, move it to backing storage + // to prevent extra allocations on applications that perform large reads + if len(dest) <= maxCachedBufSize { + b.dbuf[b.flipcnt&1] = dest + } + } + + // if we're filling the fg buffer, move the existing data to the start of it. + // if we're filling the bg buffer, copy over the data + if n > 0 { + copy(dest[:n], b.buf[b.idx:]) + } + + b.buf = dest + b.idx = 0 + + for { + if b.timeout > 0 { + if err := b.nc.SetReadDeadline(time.Now().Add(b.timeout)); err != nil { + return err + } + } + + nn, err := b.nc.Read(b.buf[n:]) + n += nn + + switch err { + case nil: + if n < need { + continue + } + b.length = n + return nil + + case io.EOF: + if n >= need { + b.length = n + return nil + } + return io.ErrUnexpectedEOF + + default: + return err + } + } +} + +// returns next N bytes from buffer. +// The returned slice is only guaranteed to be valid until the next read +func (b *buffer) readNext(need int) ([]byte, error) { + if b.length < need { + // refill + if err := b.fill(need); err != nil { + return nil, err + } + } + + offset := b.idx + b.idx += need + b.length -= need + return b.buf[offset:b.idx], nil +} + +// takeBuffer returns a buffer with the requested size. +// If possible, a slice from the existing buffer is returned. +// Otherwise a bigger buffer is made. +// Only one buffer (total) can be used at a time. +func (b *buffer) takeBuffer(length int) ([]byte, error) { + if b.length > 0 { + return nil, ErrBusyBuffer + } + + // test (cheap) general case first + if length <= cap(b.buf) { + return b.buf[:length], nil + } + + if length < maxPacketSize { + b.buf = make([]byte, length) + return b.buf, nil + } + + // buffer is larger than we want to store. + return make([]byte, length), nil +} + +// takeSmallBuffer is shortcut which can be used if length is +// known to be smaller than defaultBufSize. +// Only one buffer (total) can be used at a time. +func (b *buffer) takeSmallBuffer(length int) ([]byte, error) { + if b.length > 0 { + return nil, ErrBusyBuffer + } + return b.buf[:length], nil +} + +// takeCompleteBuffer returns the complete existing buffer. +// This can be used if the necessary buffer size is unknown. +// cap and len of the returned buffer will be equal. +// Only one buffer (total) can be used at a time. +func (b *buffer) takeCompleteBuffer() ([]byte, error) { + if b.length > 0 { + return nil, ErrBusyBuffer + } + return b.buf, nil +} + +// store stores buf, an updated buffer, if its suitable to do so. +func (b *buffer) store(buf []byte) error { + if b.length > 0 { + return ErrBusyBuffer + } else if cap(buf) <= maxPacketSize && cap(buf) > cap(b.buf) { + b.buf = buf[:cap(buf)] + } + return nil +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/collations.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/collations.go new file mode 100644 index 00000000..295bfbe5 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/collations.go @@ -0,0 +1,266 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2014 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +const defaultCollation = "utf8mb4_general_ci" +const binaryCollation = "binary" + +// A list of available collations mapped to the internal ID. +// To update this map use the following MySQL query: +// +// SELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS WHERE ID<256 ORDER BY ID +// +// Handshake packet have only 1 byte for collation_id. So we can't use collations with ID > 255. +// +// ucs2, utf16, and utf32 can't be used for connection charset. +// https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset +// They are commented out to reduce this map. +var collations = map[string]byte{ + "big5_chinese_ci": 1, + "latin2_czech_cs": 2, + "dec8_swedish_ci": 3, + "cp850_general_ci": 4, + "latin1_german1_ci": 5, + "hp8_english_ci": 6, + "koi8r_general_ci": 7, + "latin1_swedish_ci": 8, + "latin2_general_ci": 9, + "swe7_swedish_ci": 10, + "ascii_general_ci": 11, + "ujis_japanese_ci": 12, + "sjis_japanese_ci": 13, + "cp1251_bulgarian_ci": 14, + "latin1_danish_ci": 15, + "hebrew_general_ci": 16, + "tis620_thai_ci": 18, + "euckr_korean_ci": 19, + "latin7_estonian_cs": 20, + "latin2_hungarian_ci": 21, + "koi8u_general_ci": 22, + "cp1251_ukrainian_ci": 23, + "gb2312_chinese_ci": 24, + "greek_general_ci": 25, + "cp1250_general_ci": 26, + "latin2_croatian_ci": 27, + "gbk_chinese_ci": 28, + "cp1257_lithuanian_ci": 29, + "latin5_turkish_ci": 30, + "latin1_german2_ci": 31, + "armscii8_general_ci": 32, + "utf8_general_ci": 33, + "cp1250_czech_cs": 34, + //"ucs2_general_ci": 35, + "cp866_general_ci": 36, + "keybcs2_general_ci": 37, + "macce_general_ci": 38, + "macroman_general_ci": 39, + "cp852_general_ci": 40, + "latin7_general_ci": 41, + "latin7_general_cs": 42, + "macce_bin": 43, + "cp1250_croatian_ci": 44, + "utf8mb4_general_ci": 45, + "utf8mb4_bin": 46, + "latin1_bin": 47, + "latin1_general_ci": 48, + "latin1_general_cs": 49, + "cp1251_bin": 50, + "cp1251_general_ci": 51, + "cp1251_general_cs": 52, + "macroman_bin": 53, + //"utf16_general_ci": 54, + //"utf16_bin": 55, + //"utf16le_general_ci": 56, + "cp1256_general_ci": 57, + "cp1257_bin": 58, + "cp1257_general_ci": 59, + //"utf32_general_ci": 60, + //"utf32_bin": 61, + //"utf16le_bin": 62, + "binary": 63, + "armscii8_bin": 64, + "ascii_bin": 65, + "cp1250_bin": 66, + "cp1256_bin": 67, + "cp866_bin": 68, + "dec8_bin": 69, + "greek_bin": 70, + "hebrew_bin": 71, + "hp8_bin": 72, + "keybcs2_bin": 73, + "koi8r_bin": 74, + "koi8u_bin": 75, + "utf8_tolower_ci": 76, + "latin2_bin": 77, + "latin5_bin": 78, + "latin7_bin": 79, + "cp850_bin": 80, + "cp852_bin": 81, + "swe7_bin": 82, + "utf8_bin": 83, + "big5_bin": 84, + "euckr_bin": 85, + "gb2312_bin": 86, + "gbk_bin": 87, + "sjis_bin": 88, + "tis620_bin": 89, + //"ucs2_bin": 90, + "ujis_bin": 91, + "geostd8_general_ci": 92, + "geostd8_bin": 93, + "latin1_spanish_ci": 94, + "cp932_japanese_ci": 95, + "cp932_bin": 96, + "eucjpms_japanese_ci": 97, + "eucjpms_bin": 98, + "cp1250_polish_ci": 99, + //"utf16_unicode_ci": 101, + //"utf16_icelandic_ci": 102, + //"utf16_latvian_ci": 103, + //"utf16_romanian_ci": 104, + //"utf16_slovenian_ci": 105, + //"utf16_polish_ci": 106, + //"utf16_estonian_ci": 107, + //"utf16_spanish_ci": 108, + //"utf16_swedish_ci": 109, + //"utf16_turkish_ci": 110, + //"utf16_czech_ci": 111, + //"utf16_danish_ci": 112, + //"utf16_lithuanian_ci": 113, + //"utf16_slovak_ci": 114, + //"utf16_spanish2_ci": 115, + //"utf16_roman_ci": 116, + //"utf16_persian_ci": 117, + //"utf16_esperanto_ci": 118, + //"utf16_hungarian_ci": 119, + //"utf16_sinhala_ci": 120, + //"utf16_german2_ci": 121, + //"utf16_croatian_ci": 122, + //"utf16_unicode_520_ci": 123, + //"utf16_vietnamese_ci": 124, + //"ucs2_unicode_ci": 128, + //"ucs2_icelandic_ci": 129, + //"ucs2_latvian_ci": 130, + //"ucs2_romanian_ci": 131, + //"ucs2_slovenian_ci": 132, + //"ucs2_polish_ci": 133, + //"ucs2_estonian_ci": 134, + //"ucs2_spanish_ci": 135, + //"ucs2_swedish_ci": 136, + //"ucs2_turkish_ci": 137, + //"ucs2_czech_ci": 138, + //"ucs2_danish_ci": 139, + //"ucs2_lithuanian_ci": 140, + //"ucs2_slovak_ci": 141, + //"ucs2_spanish2_ci": 142, + //"ucs2_roman_ci": 143, + //"ucs2_persian_ci": 144, + //"ucs2_esperanto_ci": 145, + //"ucs2_hungarian_ci": 146, + //"ucs2_sinhala_ci": 147, + //"ucs2_german2_ci": 148, + //"ucs2_croatian_ci": 149, + //"ucs2_unicode_520_ci": 150, + //"ucs2_vietnamese_ci": 151, + //"ucs2_general_mysql500_ci": 159, + //"utf32_unicode_ci": 160, + //"utf32_icelandic_ci": 161, + //"utf32_latvian_ci": 162, + //"utf32_romanian_ci": 163, + //"utf32_slovenian_ci": 164, + //"utf32_polish_ci": 165, + //"utf32_estonian_ci": 166, + //"utf32_spanish_ci": 167, + //"utf32_swedish_ci": 168, + //"utf32_turkish_ci": 169, + //"utf32_czech_ci": 170, + //"utf32_danish_ci": 171, + //"utf32_lithuanian_ci": 172, + //"utf32_slovak_ci": 173, + //"utf32_spanish2_ci": 174, + //"utf32_roman_ci": 175, + //"utf32_persian_ci": 176, + //"utf32_esperanto_ci": 177, + //"utf32_hungarian_ci": 178, + //"utf32_sinhala_ci": 179, + //"utf32_german2_ci": 180, + //"utf32_croatian_ci": 181, + //"utf32_unicode_520_ci": 182, + //"utf32_vietnamese_ci": 183, + "utf8_unicode_ci": 192, + "utf8_icelandic_ci": 193, + "utf8_latvian_ci": 194, + "utf8_romanian_ci": 195, + "utf8_slovenian_ci": 196, + "utf8_polish_ci": 197, + "utf8_estonian_ci": 198, + "utf8_spanish_ci": 199, + "utf8_swedish_ci": 200, + "utf8_turkish_ci": 201, + "utf8_czech_ci": 202, + "utf8_danish_ci": 203, + "utf8_lithuanian_ci": 204, + "utf8_slovak_ci": 205, + "utf8_spanish2_ci": 206, + "utf8_roman_ci": 207, + "utf8_persian_ci": 208, + "utf8_esperanto_ci": 209, + "utf8_hungarian_ci": 210, + "utf8_sinhala_ci": 211, + "utf8_german2_ci": 212, + "utf8_croatian_ci": 213, + "utf8_unicode_520_ci": 214, + "utf8_vietnamese_ci": 215, + "utf8_general_mysql500_ci": 223, + "utf8mb4_unicode_ci": 224, + "utf8mb4_icelandic_ci": 225, + "utf8mb4_latvian_ci": 226, + "utf8mb4_romanian_ci": 227, + "utf8mb4_slovenian_ci": 228, + "utf8mb4_polish_ci": 229, + "utf8mb4_estonian_ci": 230, + "utf8mb4_spanish_ci": 231, + "utf8mb4_swedish_ci": 232, + "utf8mb4_turkish_ci": 233, + "utf8mb4_czech_ci": 234, + "utf8mb4_danish_ci": 235, + "utf8mb4_lithuanian_ci": 236, + "utf8mb4_slovak_ci": 237, + "utf8mb4_spanish2_ci": 238, + "utf8mb4_roman_ci": 239, + "utf8mb4_persian_ci": 240, + "utf8mb4_esperanto_ci": 241, + "utf8mb4_hungarian_ci": 242, + "utf8mb4_sinhala_ci": 243, + "utf8mb4_german2_ci": 244, + "utf8mb4_croatian_ci": 245, + "utf8mb4_unicode_520_ci": 246, + "utf8mb4_vietnamese_ci": 247, + "gb18030_chinese_ci": 248, + "gb18030_bin": 249, + "gb18030_unicode_520_ci": 250, + "utf8mb4_0900_ai_ci": 255, +} + +// A denylist of collations which is unsafe to interpolate parameters. +// These multibyte encodings may contains 0x5c (`\`) in their trailing bytes. +var unsafeCollations = map[string]bool{ + "big5_chinese_ci": true, + "sjis_japanese_ci": true, + "gbk_chinese_ci": true, + "big5_bin": true, + "gb2312_bin": true, + "gbk_bin": true, + "sjis_bin": true, + "cp932_japanese_ci": true, + "cp932_bin": true, + "gb18030_chinese_ci": true, + "gb18030_bin": true, + "gb18030_unicode_520_ci": true, +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck.go new file mode 100644 index 00000000..0ea72172 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck.go @@ -0,0 +1,55 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +//go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || solaris || illumos +// +build linux darwin dragonfly freebsd netbsd openbsd solaris illumos + +package mysql + +import ( + "errors" + "io" + "net" + "syscall" +) + +var errUnexpectedRead = errors.New("unexpected read from socket") + +func connCheck(conn net.Conn) error { + var sysErr error + + sysConn, ok := conn.(syscall.Conn) + if !ok { + return nil + } + rawConn, err := sysConn.SyscallConn() + if err != nil { + return err + } + + err = rawConn.Read(func(fd uintptr) bool { + var buf [1]byte + n, err := syscall.Read(int(fd), buf[:]) + switch { + case n == 0 && err == nil: + sysErr = io.EOF + case n > 0: + sysErr = errUnexpectedRead + case err == syscall.EAGAIN || err == syscall.EWOULDBLOCK: + sysErr = nil + default: + sysErr = err + } + return true + }) + if err != nil { + return err + } + + return sysErr +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck_dummy.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck_dummy.go new file mode 100644 index 00000000..a56c138f --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/conncheck_dummy.go @@ -0,0 +1,18 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2019 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd && !solaris && !illumos +// +build !linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd,!solaris,!illumos + +package mysql + +import "net" + +func connCheck(conn net.Conn) error { + return nil +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/connection.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/connection.go new file mode 100644 index 00000000..9539077c --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/connection.go @@ -0,0 +1,650 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "context" + "database/sql" + "database/sql/driver" + "encoding/json" + "io" + "net" + "strconv" + "strings" + "time" +) + +type mysqlConn struct { + buf buffer + netConn net.Conn + rawConn net.Conn // underlying connection when netConn is TLS connection. + affectedRows uint64 + insertId uint64 + cfg *Config + maxAllowedPacket int + maxWriteSize int + writeTimeout time.Duration + flags clientFlag + status statusFlag + sequence uint8 + parseTime bool + reset bool // set when the Go SQL package calls ResetSession + + // for context support (Go 1.8+) + watching bool + watcher chan<- context.Context + closech chan struct{} + finished chan<- struct{} + canceled atomicError // set non-nil if conn is canceled + closed atomicBool // set when conn is closed, before closech is closed +} + +// Handles parameters set in DSN after the connection is established +func (mc *mysqlConn) handleParams() (err error) { + var cmdSet strings.Builder + for param, val := range mc.cfg.Params { + switch param { + // Charset: character_set_connection, character_set_client, character_set_results + case "charset": + charsets := strings.Split(val, ",") + for i := range charsets { + // ignore errors here - a charset may not exist + err = mc.exec("SET NAMES " + charsets[i]) + if err == nil { + break + } + } + if err != nil { + return + } + + // Other system vars accumulated in a single SET command + default: + if cmdSet.Len() == 0 { + // Heuristic: 29 chars for each other key=value to reduce reallocations + cmdSet.Grow(4 + len(param) + 1 + len(val) + 30*(len(mc.cfg.Params)-1)) + cmdSet.WriteString("SET ") + } else { + cmdSet.WriteByte(',') + } + cmdSet.WriteString(param) + cmdSet.WriteByte('=') + cmdSet.WriteString(val) + } + } + + if cmdSet.Len() > 0 { + err = mc.exec(cmdSet.String()) + if err != nil { + return + } + } + + return +} + +func (mc *mysqlConn) markBadConn(err error) error { + if mc == nil { + return err + } + if err != errBadConnNoWrite { + return err + } + return driver.ErrBadConn +} + +func (mc *mysqlConn) Begin() (driver.Tx, error) { + return mc.begin(false) +} + +func (mc *mysqlConn) begin(readOnly bool) (driver.Tx, error) { + if mc.closed.Load() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + var q string + if readOnly { + q = "START TRANSACTION READ ONLY" + } else { + q = "START TRANSACTION" + } + err := mc.exec(q) + if err == nil { + return &mysqlTx{mc}, err + } + return nil, mc.markBadConn(err) +} + +func (mc *mysqlConn) Close() (err error) { + // Makes Close idempotent + if !mc.closed.Load() { + err = mc.writeCommandPacket(comQuit) + } + + mc.cleanup() + + return +} + +// Closes the network connection and unsets internal variables. Do not call this +// function after successfully authentication, call Close instead. This function +// is called before auth or on auth failure because MySQL will have already +// closed the network connection. +func (mc *mysqlConn) cleanup() { + if mc.closed.Swap(true) { + return + } + + // Makes cleanup idempotent + close(mc.closech) + if mc.netConn == nil { + return + } + if err := mc.netConn.Close(); err != nil { + errLog.Print(err) + } +} + +func (mc *mysqlConn) error() error { + if mc.closed.Load() { + if err := mc.canceled.Value(); err != nil { + return err + } + return ErrInvalidConn + } + return nil +} + +func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) { + if mc.closed.Load() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + // Send command + err := mc.writeCommandPacketStr(comStmtPrepare, query) + if err != nil { + // STMT_PREPARE is safe to retry. So we can return ErrBadConn here. + errLog.Print(err) + return nil, driver.ErrBadConn + } + + stmt := &mysqlStmt{ + mc: mc, + } + + // Read Result + columnCount, err := stmt.readPrepareResultPacket() + if err == nil { + if stmt.paramCount > 0 { + if err = mc.readUntilEOF(); err != nil { + return nil, err + } + } + + if columnCount > 0 { + err = mc.readUntilEOF() + } + } + + return stmt, err +} + +func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (string, error) { + // Number of ? should be same to len(args) + if strings.Count(query, "?") != len(args) { + return "", driver.ErrSkip + } + + buf, err := mc.buf.takeCompleteBuffer() + if err != nil { + // can not take the buffer. Something must be wrong with the connection + errLog.Print(err) + return "", ErrInvalidConn + } + buf = buf[:0] + argPos := 0 + + for i := 0; i < len(query); i++ { + q := strings.IndexByte(query[i:], '?') + if q == -1 { + buf = append(buf, query[i:]...) + break + } + buf = append(buf, query[i:i+q]...) + i += q + + arg := args[argPos] + argPos++ + + if arg == nil { + buf = append(buf, "NULL"...) + continue + } + + switch v := arg.(type) { + case int64: + buf = strconv.AppendInt(buf, v, 10) + case uint64: + // Handle uint64 explicitly because our custom ConvertValue emits unsigned values + buf = strconv.AppendUint(buf, v, 10) + case float64: + buf = strconv.AppendFloat(buf, v, 'g', -1, 64) + case bool: + if v { + buf = append(buf, '1') + } else { + buf = append(buf, '0') + } + case time.Time: + if v.IsZero() { + buf = append(buf, "'0000-00-00'"...) + } else { + buf = append(buf, '\'') + buf, err = appendDateTime(buf, v.In(mc.cfg.Loc)) + if err != nil { + return "", err + } + buf = append(buf, '\'') + } + case json.RawMessage: + buf = append(buf, '\'') + if mc.status&statusNoBackslashEscapes == 0 { + buf = escapeBytesBackslash(buf, v) + } else { + buf = escapeBytesQuotes(buf, v) + } + buf = append(buf, '\'') + case []byte: + if v == nil { + buf = append(buf, "NULL"...) + } else { + buf = append(buf, "_binary'"...) + if mc.status&statusNoBackslashEscapes == 0 { + buf = escapeBytesBackslash(buf, v) + } else { + buf = escapeBytesQuotes(buf, v) + } + buf = append(buf, '\'') + } + case string: + buf = append(buf, '\'') + if mc.status&statusNoBackslashEscapes == 0 { + buf = escapeStringBackslash(buf, v) + } else { + buf = escapeStringQuotes(buf, v) + } + buf = append(buf, '\'') + default: + return "", driver.ErrSkip + } + + if len(buf)+4 > mc.maxAllowedPacket { + return "", driver.ErrSkip + } + } + if argPos != len(args) { + return "", driver.ErrSkip + } + return string(buf), nil +} + +func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, error) { + if mc.closed.Load() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + if len(args) != 0 { + if !mc.cfg.InterpolateParams { + return nil, driver.ErrSkip + } + // try to interpolate the parameters to save extra roundtrips for preparing and closing a statement + prepared, err := mc.interpolateParams(query, args) + if err != nil { + return nil, err + } + query = prepared + } + mc.affectedRows = 0 + mc.insertId = 0 + + err := mc.exec(query) + if err == nil { + return &mysqlResult{ + affectedRows: int64(mc.affectedRows), + insertId: int64(mc.insertId), + }, err + } + return nil, mc.markBadConn(err) +} + +// Internal function to execute commands +func (mc *mysqlConn) exec(query string) error { + // Send command + if err := mc.writeCommandPacketStr(comQuery, query); err != nil { + return mc.markBadConn(err) + } + + // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return err + } + + if resLen > 0 { + // columns + if err := mc.readUntilEOF(); err != nil { + return err + } + + // rows + if err := mc.readUntilEOF(); err != nil { + return err + } + } + + return mc.discardResults() +} + +func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) { + return mc.query(query, args) +} + +func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) { + if mc.closed.Load() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + if len(args) != 0 { + if !mc.cfg.InterpolateParams { + return nil, driver.ErrSkip + } + // try client-side prepare to reduce roundtrip + prepared, err := mc.interpolateParams(query, args) + if err != nil { + return nil, err + } + query = prepared + } + // Send command + err := mc.writeCommandPacketStr(comQuery, query) + if err == nil { + // Read Result + var resLen int + resLen, err = mc.readResultSetHeaderPacket() + if err == nil { + rows := new(textRows) + rows.mc = mc + + if resLen == 0 { + rows.rs.done = true + + switch err := rows.NextResultSet(); err { + case nil, io.EOF: + return rows, nil + default: + return nil, err + } + } + + // Columns + rows.rs.columns, err = mc.readColumns(resLen) + return rows, err + } + } + return nil, mc.markBadConn(err) +} + +// Gets the value of the given MySQL System Variable +// The returned byte slice is only valid until the next read +func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) { + // Send command + if err := mc.writeCommandPacketStr(comQuery, "SELECT @@"+name); err != nil { + return nil, err + } + + // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err == nil { + rows := new(textRows) + rows.mc = mc + rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}} + + if resLen > 0 { + // Columns + if err := mc.readUntilEOF(); err != nil { + return nil, err + } + } + + dest := make([]driver.Value, resLen) + if err = rows.readRow(dest); err == nil { + return dest[0].([]byte), mc.readUntilEOF() + } + } + return nil, err +} + +// finish is called when the query has canceled. +func (mc *mysqlConn) cancel(err error) { + mc.canceled.Set(err) + mc.cleanup() +} + +// finish is called when the query has succeeded. +func (mc *mysqlConn) finish() { + if !mc.watching || mc.finished == nil { + return + } + select { + case mc.finished <- struct{}{}: + mc.watching = false + case <-mc.closech: + } +} + +// Ping implements driver.Pinger interface +func (mc *mysqlConn) Ping(ctx context.Context) (err error) { + if mc.closed.Load() { + errLog.Print(ErrInvalidConn) + return driver.ErrBadConn + } + + if err = mc.watchCancel(ctx); err != nil { + return + } + defer mc.finish() + + if err = mc.writeCommandPacket(comPing); err != nil { + return mc.markBadConn(err) + } + + return mc.readResultOK() +} + +// BeginTx implements driver.ConnBeginTx interface +func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { + if mc.closed.Load() { + return nil, driver.ErrBadConn + } + + if err := mc.watchCancel(ctx); err != nil { + return nil, err + } + defer mc.finish() + + if sql.IsolationLevel(opts.Isolation) != sql.LevelDefault { + level, err := mapIsolationLevel(opts.Isolation) + if err != nil { + return nil, err + } + err = mc.exec("SET TRANSACTION ISOLATION LEVEL " + level) + if err != nil { + return nil, err + } + } + + return mc.begin(opts.ReadOnly) +} + +func (mc *mysqlConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } + + if err := mc.watchCancel(ctx); err != nil { + return nil, err + } + + rows, err := mc.query(query, dargs) + if err != nil { + mc.finish() + return nil, err + } + rows.finish = mc.finish + return rows, err +} + +func (mc *mysqlConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } + + if err := mc.watchCancel(ctx); err != nil { + return nil, err + } + defer mc.finish() + + return mc.Exec(query, dargs) +} + +func (mc *mysqlConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + if err := mc.watchCancel(ctx); err != nil { + return nil, err + } + + stmt, err := mc.Prepare(query) + mc.finish() + if err != nil { + return nil, err + } + + select { + default: + case <-ctx.Done(): + stmt.Close() + return nil, ctx.Err() + } + return stmt, nil +} + +func (stmt *mysqlStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } + + if err := stmt.mc.watchCancel(ctx); err != nil { + return nil, err + } + + rows, err := stmt.query(dargs) + if err != nil { + stmt.mc.finish() + return nil, err + } + rows.finish = stmt.mc.finish + return rows, err +} + +func (stmt *mysqlStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { + dargs, err := namedValueToValue(args) + if err != nil { + return nil, err + } + + if err := stmt.mc.watchCancel(ctx); err != nil { + return nil, err + } + defer stmt.mc.finish() + + return stmt.Exec(dargs) +} + +func (mc *mysqlConn) watchCancel(ctx context.Context) error { + if mc.watching { + // Reach here if canceled, + // so the connection is already invalid + mc.cleanup() + return nil + } + // When ctx is already cancelled, don't watch it. + if err := ctx.Err(); err != nil { + return err + } + // When ctx is not cancellable, don't watch it. + if ctx.Done() == nil { + return nil + } + // When watcher is not alive, can't watch it. + if mc.watcher == nil { + return nil + } + + mc.watching = true + mc.watcher <- ctx + return nil +} + +func (mc *mysqlConn) startWatcher() { + watcher := make(chan context.Context, 1) + mc.watcher = watcher + finished := make(chan struct{}) + mc.finished = finished + go func() { + for { + var ctx context.Context + select { + case ctx = <-watcher: + case <-mc.closech: + return + } + + select { + case <-ctx.Done(): + mc.cancel(ctx.Err()) + case <-finished: + case <-mc.closech: + return + } + } + }() +} + +func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) { + nv.Value, err = converter{}.ConvertValue(nv.Value) + return +} + +// ResetSession implements driver.SessionResetter. +// (From Go 1.10) +func (mc *mysqlConn) ResetSession(ctx context.Context) error { + if mc.closed.Load() { + return driver.ErrBadConn + } + mc.reset = true + return nil +} + +// IsValid implements driver.Validator interface +// (From Go 1.15) +func (mc *mysqlConn) IsValid() bool { + return !mc.closed.Load() +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/connector.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/connector.go new file mode 100644 index 00000000..d567b4e4 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/connector.go @@ -0,0 +1,146 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2018 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "context" + "database/sql/driver" + "net" +) + +type connector struct { + cfg *Config // immutable private copy. +} + +// Connect implements driver.Connector interface. +// Connect returns a connection to the database. +func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { + var err error + + // New mysqlConn + mc := &mysqlConn{ + maxAllowedPacket: maxPacketSize, + maxWriteSize: maxPacketSize - 1, + closech: make(chan struct{}), + cfg: c.cfg, + } + mc.parseTime = mc.cfg.ParseTime + + // Connect to Server + dialsLock.RLock() + dial, ok := dials[mc.cfg.Net] + dialsLock.RUnlock() + if ok { + dctx := ctx + if mc.cfg.Timeout > 0 { + var cancel context.CancelFunc + dctx, cancel = context.WithTimeout(ctx, c.cfg.Timeout) + defer cancel() + } + mc.netConn, err = dial(dctx, mc.cfg.Addr) + } else { + nd := net.Dialer{Timeout: mc.cfg.Timeout} + mc.netConn, err = nd.DialContext(ctx, mc.cfg.Net, mc.cfg.Addr) + } + + if err != nil { + return nil, err + } + + // Enable TCP Keepalives on TCP connections + if tc, ok := mc.netConn.(*net.TCPConn); ok { + if err := tc.SetKeepAlive(true); err != nil { + // Don't send COM_QUIT before handshake. + mc.netConn.Close() + mc.netConn = nil + return nil, err + } + } + + // Call startWatcher for context support (From Go 1.8) + mc.startWatcher() + if err := mc.watchCancel(ctx); err != nil { + mc.cleanup() + return nil, err + } + defer mc.finish() + + mc.buf = newBuffer(mc.netConn) + + // Set I/O timeouts + mc.buf.timeout = mc.cfg.ReadTimeout + mc.writeTimeout = mc.cfg.WriteTimeout + + // Reading Handshake Initialization Packet + authData, plugin, err := mc.readHandshakePacket() + if err != nil { + mc.cleanup() + return nil, err + } + + if plugin == "" { + plugin = defaultAuthPlugin + } + + // Send Client Authentication Packet + authResp, err := mc.auth(authData, plugin) + if err != nil { + // try the default auth plugin, if using the requested plugin failed + errLog.Print("could not use requested auth plugin '"+plugin+"': ", err.Error()) + plugin = defaultAuthPlugin + authResp, err = mc.auth(authData, plugin) + if err != nil { + mc.cleanup() + return nil, err + } + } + if err = mc.writeHandshakeResponsePacket(authResp, plugin); err != nil { + mc.cleanup() + return nil, err + } + + // Handle response to auth packet, switch methods if possible + if err = mc.handleAuthResult(authData, plugin); err != nil { + // Authentication failed and MySQL has already closed the connection + // (https://dev.mysql.com/doc/internals/en/authentication-fails.html). + // Do not send COM_QUIT, just cleanup and return the error. + mc.cleanup() + return nil, err + } + + if mc.cfg.MaxAllowedPacket > 0 { + mc.maxAllowedPacket = mc.cfg.MaxAllowedPacket + } else { + // Get max allowed packet size + maxap, err := mc.getSystemVar("max_allowed_packet") + if err != nil { + mc.Close() + return nil, err + } + mc.maxAllowedPacket = stringToInt(maxap) - 1 + } + if mc.maxAllowedPacket < maxPacketSize { + mc.maxWriteSize = mc.maxAllowedPacket + } + + // Handle DSN Params + err = mc.handleParams() + if err != nil { + mc.Close() + return nil, err + } + + return mc, nil +} + +// Driver implements driver.Connector interface. +// Driver returns &MySQLDriver{}. +func (c *connector) Driver() driver.Driver { + return &MySQLDriver{} +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/const.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/const.go new file mode 100644 index 00000000..b1e6b85e --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/const.go @@ -0,0 +1,174 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +const ( + defaultAuthPlugin = "mysql_native_password" + defaultMaxAllowedPacket = 4 << 20 // 4 MiB + minProtocolVersion = 10 + maxPacketSize = 1<<24 - 1 + timeFormat = "2006-01-02 15:04:05.999999" +) + +// MySQL constants documentation: +// http://dev.mysql.com/doc/internals/en/client-server-protocol.html + +const ( + iOK byte = 0x00 + iAuthMoreData byte = 0x01 + iLocalInFile byte = 0xfb + iEOF byte = 0xfe + iERR byte = 0xff +) + +// https://dev.mysql.com/doc/internals/en/capability-flags.html#packet-Protocol::CapabilityFlags +type clientFlag uint32 + +const ( + clientLongPassword clientFlag = 1 << iota + clientFoundRows + clientLongFlag + clientConnectWithDB + clientNoSchema + clientCompress + clientODBC + clientLocalFiles + clientIgnoreSpace + clientProtocol41 + clientInteractive + clientSSL + clientIgnoreSIGPIPE + clientTransactions + clientReserved + clientSecureConn + clientMultiStatements + clientMultiResults + clientPSMultiResults + clientPluginAuth + clientConnectAttrs + clientPluginAuthLenEncClientData + clientCanHandleExpiredPasswords + clientSessionTrack + clientDeprecateEOF +) + +const ( + comQuit byte = iota + 1 + comInitDB + comQuery + comFieldList + comCreateDB + comDropDB + comRefresh + comShutdown + comStatistics + comProcessInfo + comConnect + comProcessKill + comDebug + comPing + comTime + comDelayedInsert + comChangeUser + comBinlogDump + comTableDump + comConnectOut + comRegisterSlave + comStmtPrepare + comStmtExecute + comStmtSendLongData + comStmtClose + comStmtReset + comSetOption + comStmtFetch +) + +// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType +type fieldType byte + +const ( + fieldTypeDecimal fieldType = iota + fieldTypeTiny + fieldTypeShort + fieldTypeLong + fieldTypeFloat + fieldTypeDouble + fieldTypeNULL + fieldTypeTimestamp + fieldTypeLongLong + fieldTypeInt24 + fieldTypeDate + fieldTypeTime + fieldTypeDateTime + fieldTypeYear + fieldTypeNewDate + fieldTypeVarChar + fieldTypeBit +) +const ( + fieldTypeJSON fieldType = iota + 0xf5 + fieldTypeNewDecimal + fieldTypeEnum + fieldTypeSet + fieldTypeTinyBLOB + fieldTypeMediumBLOB + fieldTypeLongBLOB + fieldTypeBLOB + fieldTypeVarString + fieldTypeString + fieldTypeGeometry +) + +type fieldFlag uint16 + +const ( + flagNotNULL fieldFlag = 1 << iota + flagPriKey + flagUniqueKey + flagMultipleKey + flagBLOB + flagUnsigned + flagZeroFill + flagBinary + flagEnum + flagAutoIncrement + flagTimestamp + flagSet + flagUnknown1 + flagUnknown2 + flagUnknown3 + flagUnknown4 +) + +// http://dev.mysql.com/doc/internals/en/status-flags.html +type statusFlag uint16 + +const ( + statusInTrans statusFlag = 1 << iota + statusInAutocommit + statusReserved // Not in documentation + statusMoreResultsExists + statusNoGoodIndexUsed + statusNoIndexUsed + statusCursorExists + statusLastRowSent + statusDbDropped + statusNoBackslashEscapes + statusMetadataChanged + statusQueryWasSlow + statusPsOutParams + statusInTransReadonly + statusSessionStateChanged +) + +const ( + cachingSha2PasswordRequestPublicKey = 2 + cachingSha2PasswordFastAuthSuccess = 3 + cachingSha2PasswordPerformFullAuthentication = 4 +) diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/driver.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/driver.go new file mode 100644 index 00000000..ad7aec21 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/driver.go @@ -0,0 +1,107 @@ +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +// Package mysql provides a MySQL driver for Go's database/sql package. +// +// The driver should be used via the database/sql package: +// +// import "database/sql" +// import _ "github.com/go-sql-driver/mysql" +// +// db, err := sql.Open("mysql", "user:password@/dbname") +// +// See https://github.com/go-sql-driver/mysql#usage for details +package mysql + +import ( + "context" + "database/sql" + "database/sql/driver" + "net" + "sync" +) + +// MySQLDriver is exported to make the driver directly accessible. +// In general the driver is used via the database/sql package. +type MySQLDriver struct{} + +// DialFunc is a function which can be used to establish the network connection. +// Custom dial functions must be registered with RegisterDial +// +// Deprecated: users should register a DialContextFunc instead +type DialFunc func(addr string) (net.Conn, error) + +// DialContextFunc is a function which can be used to establish the network connection. +// Custom dial functions must be registered with RegisterDialContext +type DialContextFunc func(ctx context.Context, addr string) (net.Conn, error) + +var ( + dialsLock sync.RWMutex + dials map[string]DialContextFunc +) + +// RegisterDialContext registers a custom dial function. It can then be used by the +// network address mynet(addr), where mynet is the registered new network. +// The current context for the connection and its address is passed to the dial function. +func RegisterDialContext(net string, dial DialContextFunc) { + dialsLock.Lock() + defer dialsLock.Unlock() + if dials == nil { + dials = make(map[string]DialContextFunc) + } + dials[net] = dial +} + +// RegisterDial registers a custom dial function. It can then be used by the +// network address mynet(addr), where mynet is the registered new network. +// addr is passed as a parameter to the dial function. +// +// Deprecated: users should call RegisterDialContext instead +func RegisterDial(network string, dial DialFunc) { + RegisterDialContext(network, func(_ context.Context, addr string) (net.Conn, error) { + return dial(addr) + }) +} + +// Open new Connection. +// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how +// the DSN string is formatted +func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { + cfg, err := ParseDSN(dsn) + if err != nil { + return nil, err + } + c := &connector{ + cfg: cfg, + } + return c.Connect(context.Background()) +} + +func init() { + sql.Register("mysql", &MySQLDriver{}) +} + +// NewConnector returns new driver.Connector. +func NewConnector(cfg *Config) (driver.Connector, error) { + cfg = cfg.Clone() + // normalize the contents of cfg so calls to NewConnector have the same + // behavior as MySQLDriver.OpenConnector + if err := cfg.normalize(); err != nil { + return nil, err + } + return &connector{cfg: cfg}, nil +} + +// OpenConnector implements driver.DriverContext. +func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error) { + cfg, err := ParseDSN(dsn) + if err != nil { + return nil, err + } + return &connector{ + cfg: cfg, + }, nil +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/dsn.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/dsn.go new file mode 100644 index 00000000..4b71aaab --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/dsn.go @@ -0,0 +1,577 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "bytes" + "crypto/rsa" + "crypto/tls" + "errors" + "fmt" + "math/big" + "net" + "net/url" + "sort" + "strconv" + "strings" + "time" +) + +var ( + errInvalidDSNUnescaped = errors.New("invalid DSN: did you forget to escape a param value?") + errInvalidDSNAddr = errors.New("invalid DSN: network address not terminated (missing closing brace)") + errInvalidDSNNoSlash = errors.New("invalid DSN: missing the slash separating the database name") + errInvalidDSNUnsafeCollation = errors.New("invalid DSN: interpolateParams can not be used with unsafe collations") +) + +// Config is a configuration parsed from a DSN string. +// If a new Config is created instead of being parsed from a DSN string, +// the NewConfig function should be used, which sets default values. +type Config struct { + User string // Username + Passwd string // Password (requires User) + Net string // Network type + Addr string // Network address (requires Net) + DBName string // Database name + Params map[string]string // Connection parameters + Collation string // Connection collation + Loc *time.Location // Location for time.Time values + MaxAllowedPacket int // Max packet size allowed + ServerPubKey string // Server public key name + pubKey *rsa.PublicKey // Server public key + TLSConfig string // TLS configuration name + TLS *tls.Config // TLS configuration, its priority is higher than TLSConfig + Timeout time.Duration // Dial timeout + ReadTimeout time.Duration // I/O read timeout + WriteTimeout time.Duration // I/O write timeout + + AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE + AllowCleartextPasswords bool // Allows the cleartext client side plugin + AllowFallbackToPlaintext bool // Allows fallback to unencrypted connection if server does not support TLS + AllowNativePasswords bool // Allows the native password authentication method + AllowOldPasswords bool // Allows the old insecure password method + CheckConnLiveness bool // Check connections for liveness before using them + ClientFoundRows bool // Return number of matching rows instead of rows changed + ColumnsWithAlias bool // Prepend table alias to column names + InterpolateParams bool // Interpolate placeholders into query string + MultiStatements bool // Allow multiple statements in one query + ParseTime bool // Parse time values to time.Time + RejectReadOnly bool // Reject read-only connections +} + +// NewConfig creates a new Config and sets default values. +func NewConfig() *Config { + return &Config{ + Collation: defaultCollation, + Loc: time.UTC, + MaxAllowedPacket: defaultMaxAllowedPacket, + AllowNativePasswords: true, + CheckConnLiveness: true, + } +} + +func (cfg *Config) Clone() *Config { + cp := *cfg + if cp.TLS != nil { + cp.TLS = cfg.TLS.Clone() + } + if len(cp.Params) > 0 { + cp.Params = make(map[string]string, len(cfg.Params)) + for k, v := range cfg.Params { + cp.Params[k] = v + } + } + if cfg.pubKey != nil { + cp.pubKey = &rsa.PublicKey{ + N: new(big.Int).Set(cfg.pubKey.N), + E: cfg.pubKey.E, + } + } + return &cp +} + +func (cfg *Config) normalize() error { + if cfg.InterpolateParams && unsafeCollations[cfg.Collation] { + return errInvalidDSNUnsafeCollation + } + + // Set default network if empty + if cfg.Net == "" { + cfg.Net = "tcp" + } + + // Set default address if empty + if cfg.Addr == "" { + switch cfg.Net { + case "tcp": + cfg.Addr = "127.0.0.1:3306" + case "unix": + cfg.Addr = "/tmp/mysql.sock" + default: + return errors.New("default addr for network '" + cfg.Net + "' unknown") + } + } else if cfg.Net == "tcp" { + cfg.Addr = ensureHavePort(cfg.Addr) + } + + if cfg.TLS == nil { + switch cfg.TLSConfig { + case "false", "": + // don't set anything + case "true": + cfg.TLS = &tls.Config{} + case "skip-verify": + cfg.TLS = &tls.Config{InsecureSkipVerify: true} + case "preferred": + cfg.TLS = &tls.Config{InsecureSkipVerify: true} + cfg.AllowFallbackToPlaintext = true + default: + cfg.TLS = getTLSConfigClone(cfg.TLSConfig) + if cfg.TLS == nil { + return errors.New("invalid value / unknown config name: " + cfg.TLSConfig) + } + } + } + + if cfg.TLS != nil && cfg.TLS.ServerName == "" && !cfg.TLS.InsecureSkipVerify { + host, _, err := net.SplitHostPort(cfg.Addr) + if err == nil { + cfg.TLS.ServerName = host + } + } + + if cfg.ServerPubKey != "" { + cfg.pubKey = getServerPubKey(cfg.ServerPubKey) + if cfg.pubKey == nil { + return errors.New("invalid value / unknown server pub key name: " + cfg.ServerPubKey) + } + } + + return nil +} + +func writeDSNParam(buf *bytes.Buffer, hasParam *bool, name, value string) { + buf.Grow(1 + len(name) + 1 + len(value)) + if !*hasParam { + *hasParam = true + buf.WriteByte('?') + } else { + buf.WriteByte('&') + } + buf.WriteString(name) + buf.WriteByte('=') + buf.WriteString(value) +} + +// FormatDSN formats the given Config into a DSN string which can be passed to +// the driver. +func (cfg *Config) FormatDSN() string { + var buf bytes.Buffer + + // [username[:password]@] + if len(cfg.User) > 0 { + buf.WriteString(cfg.User) + if len(cfg.Passwd) > 0 { + buf.WriteByte(':') + buf.WriteString(cfg.Passwd) + } + buf.WriteByte('@') + } + + // [protocol[(address)]] + if len(cfg.Net) > 0 { + buf.WriteString(cfg.Net) + if len(cfg.Addr) > 0 { + buf.WriteByte('(') + buf.WriteString(cfg.Addr) + buf.WriteByte(')') + } + } + + // /dbname + buf.WriteByte('/') + buf.WriteString(cfg.DBName) + + // [?param1=value1&...¶mN=valueN] + hasParam := false + + if cfg.AllowAllFiles { + hasParam = true + buf.WriteString("?allowAllFiles=true") + } + + if cfg.AllowCleartextPasswords { + writeDSNParam(&buf, &hasParam, "allowCleartextPasswords", "true") + } + + if cfg.AllowFallbackToPlaintext { + writeDSNParam(&buf, &hasParam, "allowFallbackToPlaintext", "true") + } + + if !cfg.AllowNativePasswords { + writeDSNParam(&buf, &hasParam, "allowNativePasswords", "false") + } + + if cfg.AllowOldPasswords { + writeDSNParam(&buf, &hasParam, "allowOldPasswords", "true") + } + + if !cfg.CheckConnLiveness { + writeDSNParam(&buf, &hasParam, "checkConnLiveness", "false") + } + + if cfg.ClientFoundRows { + writeDSNParam(&buf, &hasParam, "clientFoundRows", "true") + } + + if col := cfg.Collation; col != defaultCollation && len(col) > 0 { + writeDSNParam(&buf, &hasParam, "collation", col) + } + + if cfg.ColumnsWithAlias { + writeDSNParam(&buf, &hasParam, "columnsWithAlias", "true") + } + + if cfg.InterpolateParams { + writeDSNParam(&buf, &hasParam, "interpolateParams", "true") + } + + if cfg.Loc != time.UTC && cfg.Loc != nil { + writeDSNParam(&buf, &hasParam, "loc", url.QueryEscape(cfg.Loc.String())) + } + + if cfg.MultiStatements { + writeDSNParam(&buf, &hasParam, "multiStatements", "true") + } + + if cfg.ParseTime { + writeDSNParam(&buf, &hasParam, "parseTime", "true") + } + + if cfg.ReadTimeout > 0 { + writeDSNParam(&buf, &hasParam, "readTimeout", cfg.ReadTimeout.String()) + } + + if cfg.RejectReadOnly { + writeDSNParam(&buf, &hasParam, "rejectReadOnly", "true") + } + + if len(cfg.ServerPubKey) > 0 { + writeDSNParam(&buf, &hasParam, "serverPubKey", url.QueryEscape(cfg.ServerPubKey)) + } + + if cfg.Timeout > 0 { + writeDSNParam(&buf, &hasParam, "timeout", cfg.Timeout.String()) + } + + if len(cfg.TLSConfig) > 0 { + writeDSNParam(&buf, &hasParam, "tls", url.QueryEscape(cfg.TLSConfig)) + } + + if cfg.WriteTimeout > 0 { + writeDSNParam(&buf, &hasParam, "writeTimeout", cfg.WriteTimeout.String()) + } + + if cfg.MaxAllowedPacket != defaultMaxAllowedPacket { + writeDSNParam(&buf, &hasParam, "maxAllowedPacket", strconv.Itoa(cfg.MaxAllowedPacket)) + } + + // other params + if cfg.Params != nil { + var params []string + for param := range cfg.Params { + params = append(params, param) + } + sort.Strings(params) + for _, param := range params { + writeDSNParam(&buf, &hasParam, param, url.QueryEscape(cfg.Params[param])) + } + } + + return buf.String() +} + +// ParseDSN parses the DSN string to a Config +func ParseDSN(dsn string) (cfg *Config, err error) { + // New config with some default values + cfg = NewConfig() + + // [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN] + // Find the last '/' (since the password or the net addr might contain a '/') + foundSlash := false + for i := len(dsn) - 1; i >= 0; i-- { + if dsn[i] == '/' { + foundSlash = true + var j, k int + + // left part is empty if i <= 0 + if i > 0 { + // [username[:password]@][protocol[(address)]] + // Find the last '@' in dsn[:i] + for j = i; j >= 0; j-- { + if dsn[j] == '@' { + // username[:password] + // Find the first ':' in dsn[:j] + for k = 0; k < j; k++ { + if dsn[k] == ':' { + cfg.Passwd = dsn[k+1 : j] + break + } + } + cfg.User = dsn[:k] + + break + } + } + + // [protocol[(address)]] + // Find the first '(' in dsn[j+1:i] + for k = j + 1; k < i; k++ { + if dsn[k] == '(' { + // dsn[i-1] must be == ')' if an address is specified + if dsn[i-1] != ')' { + if strings.ContainsRune(dsn[k+1:i], ')') { + return nil, errInvalidDSNUnescaped + } + return nil, errInvalidDSNAddr + } + cfg.Addr = dsn[k+1 : i-1] + break + } + } + cfg.Net = dsn[j+1 : k] + } + + // dbname[?param1=value1&...¶mN=valueN] + // Find the first '?' in dsn[i+1:] + for j = i + 1; j < len(dsn); j++ { + if dsn[j] == '?' { + if err = parseDSNParams(cfg, dsn[j+1:]); err != nil { + return + } + break + } + } + cfg.DBName = dsn[i+1 : j] + + break + } + } + + if !foundSlash && len(dsn) > 0 { + return nil, errInvalidDSNNoSlash + } + + if err = cfg.normalize(); err != nil { + return nil, err + } + return +} + +// parseDSNParams parses the DSN "query string" +// Values must be url.QueryEscape'ed +func parseDSNParams(cfg *Config, params string) (err error) { + for _, v := range strings.Split(params, "&") { + param := strings.SplitN(v, "=", 2) + if len(param) != 2 { + continue + } + + // cfg params + switch value := param[1]; param[0] { + // Disable INFILE allowlist / enable all files + case "allowAllFiles": + var isBool bool + cfg.AllowAllFiles, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Use cleartext authentication mode (MySQL 5.5.10+) + case "allowCleartextPasswords": + var isBool bool + cfg.AllowCleartextPasswords, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Allow fallback to unencrypted connection if server does not support TLS + case "allowFallbackToPlaintext": + var isBool bool + cfg.AllowFallbackToPlaintext, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Use native password authentication + case "allowNativePasswords": + var isBool bool + cfg.AllowNativePasswords, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Use old authentication mode (pre MySQL 4.1) + case "allowOldPasswords": + var isBool bool + cfg.AllowOldPasswords, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Check connections for Liveness before using them + case "checkConnLiveness": + var isBool bool + cfg.CheckConnLiveness, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Switch "rowsAffected" mode + case "clientFoundRows": + var isBool bool + cfg.ClientFoundRows, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Collation + case "collation": + cfg.Collation = value + + case "columnsWithAlias": + var isBool bool + cfg.ColumnsWithAlias, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Compression + case "compress": + return errors.New("compression not implemented yet") + + // Enable client side placeholder substitution + case "interpolateParams": + var isBool bool + cfg.InterpolateParams, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Time Location + case "loc": + if value, err = url.QueryUnescape(value); err != nil { + return + } + cfg.Loc, err = time.LoadLocation(value) + if err != nil { + return + } + + // multiple statements in one query + case "multiStatements": + var isBool bool + cfg.MultiStatements, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // time.Time parsing + case "parseTime": + var isBool bool + cfg.ParseTime, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // I/O read Timeout + case "readTimeout": + cfg.ReadTimeout, err = time.ParseDuration(value) + if err != nil { + return + } + + // Reject read-only connections + case "rejectReadOnly": + var isBool bool + cfg.RejectReadOnly, isBool = readBool(value) + if !isBool { + return errors.New("invalid bool value: " + value) + } + + // Server public key + case "serverPubKey": + name, err := url.QueryUnescape(value) + if err != nil { + return fmt.Errorf("invalid value for server pub key name: %v", err) + } + cfg.ServerPubKey = name + + // Strict mode + case "strict": + panic("strict mode has been removed. See https://github.com/go-sql-driver/mysql/wiki/strict-mode") + + // Dial Timeout + case "timeout": + cfg.Timeout, err = time.ParseDuration(value) + if err != nil { + return + } + + // TLS-Encryption + case "tls": + boolValue, isBool := readBool(value) + if isBool { + if boolValue { + cfg.TLSConfig = "true" + } else { + cfg.TLSConfig = "false" + } + } else if vl := strings.ToLower(value); vl == "skip-verify" || vl == "preferred" { + cfg.TLSConfig = vl + } else { + name, err := url.QueryUnescape(value) + if err != nil { + return fmt.Errorf("invalid value for TLS config name: %v", err) + } + cfg.TLSConfig = name + } + + // I/O write Timeout + case "writeTimeout": + cfg.WriteTimeout, err = time.ParseDuration(value) + if err != nil { + return + } + case "maxAllowedPacket": + cfg.MaxAllowedPacket, err = strconv.Atoi(value) + if err != nil { + return + } + default: + // lazy init + if cfg.Params == nil { + cfg.Params = make(map[string]string) + } + + if cfg.Params[param[0]], err = url.QueryUnescape(value); err != nil { + return + } + } + } + + return +} + +func ensureHavePort(addr string) string { + if _, _, err := net.SplitHostPort(addr); err != nil { + return net.JoinHostPort(addr, "3306") + } + return addr +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/errors.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/errors.go new file mode 100644 index 00000000..7c037e7d --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/errors.go @@ -0,0 +1,77 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "errors" + "fmt" + "log" + "os" +) + +// Various errors the driver might return. Can change between driver versions. +var ( + ErrInvalidConn = errors.New("invalid connection") + ErrMalformPkt = errors.New("malformed packet") + ErrNoTLS = errors.New("TLS requested but server does not support TLS") + ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") + ErrNativePassword = errors.New("this user requires mysql native password authentication.") + ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") + ErrUnknownPlugin = errors.New("this authentication plugin is not supported") + ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") + ErrPktSync = errors.New("commands out of sync. You can't run this command now") + ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") + ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") + ErrBusyBuffer = errors.New("busy buffer") + + // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. + // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn + // to trigger a resend. + // See https://github.com/go-sql-driver/mysql/pull/302 + errBadConnNoWrite = errors.New("bad connection") +) + +var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) + +// Logger is used to log critical error messages. +type Logger interface { + Print(v ...interface{}) +} + +// SetLogger is used to set the logger for critical errors. +// The initial logger is os.Stderr. +func SetLogger(logger Logger) error { + if logger == nil { + return errors.New("logger is nil") + } + errLog = logger + return nil +} + +// MySQLError is an error type which represents a single MySQL error +type MySQLError struct { + Number uint16 + SQLState [5]byte + Message string +} + +func (me *MySQLError) Error() string { + if me.SQLState != [5]byte{} { + return fmt.Sprintf("Error %d (%s): %s", me.Number, me.SQLState, me.Message) + } + + return fmt.Sprintf("Error %d: %s", me.Number, me.Message) +} + +func (me *MySQLError) Is(err error) bool { + if merr, ok := err.(*MySQLError); ok { + return merr.Number == me.Number + } + return false +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/fields.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/fields.go new file mode 100644 index 00000000..e0654a83 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/fields.go @@ -0,0 +1,206 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2017 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "database/sql" + "reflect" +) + +func (mf *mysqlField) typeDatabaseName() string { + switch mf.fieldType { + case fieldTypeBit: + return "BIT" + case fieldTypeBLOB: + if mf.charSet != collations[binaryCollation] { + return "TEXT" + } + return "BLOB" + case fieldTypeDate: + return "DATE" + case fieldTypeDateTime: + return "DATETIME" + case fieldTypeDecimal: + return "DECIMAL" + case fieldTypeDouble: + return "DOUBLE" + case fieldTypeEnum: + return "ENUM" + case fieldTypeFloat: + return "FLOAT" + case fieldTypeGeometry: + return "GEOMETRY" + case fieldTypeInt24: + return "MEDIUMINT" + case fieldTypeJSON: + return "JSON" + case fieldTypeLong: + if mf.flags&flagUnsigned != 0 { + return "UNSIGNED INT" + } + return "INT" + case fieldTypeLongBLOB: + if mf.charSet != collations[binaryCollation] { + return "LONGTEXT" + } + return "LONGBLOB" + case fieldTypeLongLong: + if mf.flags&flagUnsigned != 0 { + return "UNSIGNED BIGINT" + } + return "BIGINT" + case fieldTypeMediumBLOB: + if mf.charSet != collations[binaryCollation] { + return "MEDIUMTEXT" + } + return "MEDIUMBLOB" + case fieldTypeNewDate: + return "DATE" + case fieldTypeNewDecimal: + return "DECIMAL" + case fieldTypeNULL: + return "NULL" + case fieldTypeSet: + return "SET" + case fieldTypeShort: + if mf.flags&flagUnsigned != 0 { + return "UNSIGNED SMALLINT" + } + return "SMALLINT" + case fieldTypeString: + if mf.charSet == collations[binaryCollation] { + return "BINARY" + } + return "CHAR" + case fieldTypeTime: + return "TIME" + case fieldTypeTimestamp: + return "TIMESTAMP" + case fieldTypeTiny: + if mf.flags&flagUnsigned != 0 { + return "UNSIGNED TINYINT" + } + return "TINYINT" + case fieldTypeTinyBLOB: + if mf.charSet != collations[binaryCollation] { + return "TINYTEXT" + } + return "TINYBLOB" + case fieldTypeVarChar: + if mf.charSet == collations[binaryCollation] { + return "VARBINARY" + } + return "VARCHAR" + case fieldTypeVarString: + if mf.charSet == collations[binaryCollation] { + return "VARBINARY" + } + return "VARCHAR" + case fieldTypeYear: + return "YEAR" + default: + return "" + } +} + +var ( + scanTypeFloat32 = reflect.TypeOf(float32(0)) + scanTypeFloat64 = reflect.TypeOf(float64(0)) + scanTypeInt8 = reflect.TypeOf(int8(0)) + scanTypeInt16 = reflect.TypeOf(int16(0)) + scanTypeInt32 = reflect.TypeOf(int32(0)) + scanTypeInt64 = reflect.TypeOf(int64(0)) + scanTypeNullFloat = reflect.TypeOf(sql.NullFloat64{}) + scanTypeNullInt = reflect.TypeOf(sql.NullInt64{}) + scanTypeNullTime = reflect.TypeOf(sql.NullTime{}) + scanTypeUint8 = reflect.TypeOf(uint8(0)) + scanTypeUint16 = reflect.TypeOf(uint16(0)) + scanTypeUint32 = reflect.TypeOf(uint32(0)) + scanTypeUint64 = reflect.TypeOf(uint64(0)) + scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{}) + scanTypeUnknown = reflect.TypeOf(new(interface{})) +) + +type mysqlField struct { + tableName string + name string + length uint32 + flags fieldFlag + fieldType fieldType + decimals byte + charSet uint8 +} + +func (mf *mysqlField) scanType() reflect.Type { + switch mf.fieldType { + case fieldTypeTiny: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint8 + } + return scanTypeInt8 + } + return scanTypeNullInt + + case fieldTypeShort, fieldTypeYear: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint16 + } + return scanTypeInt16 + } + return scanTypeNullInt + + case fieldTypeInt24, fieldTypeLong: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint32 + } + return scanTypeInt32 + } + return scanTypeNullInt + + case fieldTypeLongLong: + if mf.flags&flagNotNULL != 0 { + if mf.flags&flagUnsigned != 0 { + return scanTypeUint64 + } + return scanTypeInt64 + } + return scanTypeNullInt + + case fieldTypeFloat: + if mf.flags&flagNotNULL != 0 { + return scanTypeFloat32 + } + return scanTypeNullFloat + + case fieldTypeDouble: + if mf.flags&flagNotNULL != 0 { + return scanTypeFloat64 + } + return scanTypeNullFloat + + case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, + fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, + fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, + fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON, + fieldTypeTime: + return scanTypeRawBytes + + case fieldTypeDate, fieldTypeNewDate, + fieldTypeTimestamp, fieldTypeDateTime: + // NullTime is always returned for more consistent behavior as it can + // handle both cases of parseTime regardless if the field is nullable. + return scanTypeNullTime + + default: + return scanTypeUnknown + } +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/fuzz.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/fuzz.go new file mode 100644 index 00000000..3a4ec25a --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/fuzz.go @@ -0,0 +1,25 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package. +// +// Copyright 2020 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +//go:build gofuzz +// +build gofuzz + +package mysql + +import ( + "database/sql" +) + +func Fuzz(data []byte) int { + db, err := sql.Open("mysql", string(data)) + if err != nil { + return 0 + } + db.Close() + return 1 +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/infile.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/infile.go new file mode 100644 index 00000000..3279dcff --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/infile.go @@ -0,0 +1,182 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "fmt" + "io" + "os" + "strings" + "sync" +) + +var ( + fileRegister map[string]bool + fileRegisterLock sync.RWMutex + readerRegister map[string]func() io.Reader + readerRegisterLock sync.RWMutex +) + +// RegisterLocalFile adds the given file to the file allowlist, +// so that it can be used by "LOAD DATA LOCAL INFILE ". +// Alternatively you can allow the use of all local files with +// the DSN parameter 'allowAllFiles=true' +// +// filePath := "/home/gopher/data.csv" +// mysql.RegisterLocalFile(filePath) +// err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo") +// if err != nil { +// ... +func RegisterLocalFile(filePath string) { + fileRegisterLock.Lock() + // lazy map init + if fileRegister == nil { + fileRegister = make(map[string]bool) + } + + fileRegister[strings.Trim(filePath, `"`)] = true + fileRegisterLock.Unlock() +} + +// DeregisterLocalFile removes the given filepath from the allowlist. +func DeregisterLocalFile(filePath string) { + fileRegisterLock.Lock() + delete(fileRegister, strings.Trim(filePath, `"`)) + fileRegisterLock.Unlock() +} + +// RegisterReaderHandler registers a handler function which is used +// to receive a io.Reader. +// The Reader can be used by "LOAD DATA LOCAL INFILE Reader::". +// If the handler returns a io.ReadCloser Close() is called when the +// request is finished. +// +// mysql.RegisterReaderHandler("data", func() io.Reader { +// var csvReader io.Reader // Some Reader that returns CSV data +// ... // Open Reader here +// return csvReader +// }) +// err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo") +// if err != nil { +// ... +func RegisterReaderHandler(name string, handler func() io.Reader) { + readerRegisterLock.Lock() + // lazy map init + if readerRegister == nil { + readerRegister = make(map[string]func() io.Reader) + } + + readerRegister[name] = handler + readerRegisterLock.Unlock() +} + +// DeregisterReaderHandler removes the ReaderHandler function with +// the given name from the registry. +func DeregisterReaderHandler(name string) { + readerRegisterLock.Lock() + delete(readerRegister, name) + readerRegisterLock.Unlock() +} + +func deferredClose(err *error, closer io.Closer) { + closeErr := closer.Close() + if *err == nil { + *err = closeErr + } +} + +const defaultPacketSize = 16 * 1024 // 16KB is small enough for disk readahead and large enough for TCP + +func (mc *mysqlConn) handleInFileRequest(name string) (err error) { + var rdr io.Reader + var data []byte + packetSize := defaultPacketSize + if mc.maxWriteSize < packetSize { + packetSize = mc.maxWriteSize + } + + if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader + // The server might return an an absolute path. See issue #355. + name = name[idx+8:] + + readerRegisterLock.RLock() + handler, inMap := readerRegister[name] + readerRegisterLock.RUnlock() + + if inMap { + rdr = handler() + if rdr != nil { + if cl, ok := rdr.(io.Closer); ok { + defer deferredClose(&err, cl) + } + } else { + err = fmt.Errorf("Reader '%s' is ", name) + } + } else { + err = fmt.Errorf("Reader '%s' is not registered", name) + } + } else { // File + name = strings.Trim(name, `"`) + fileRegisterLock.RLock() + fr := fileRegister[name] + fileRegisterLock.RUnlock() + if mc.cfg.AllowAllFiles || fr { + var file *os.File + var fi os.FileInfo + + if file, err = os.Open(name); err == nil { + defer deferredClose(&err, file) + + // get file size + if fi, err = file.Stat(); err == nil { + rdr = file + if fileSize := int(fi.Size()); fileSize < packetSize { + packetSize = fileSize + } + } + } + } else { + err = fmt.Errorf("local file '%s' is not registered", name) + } + } + + // send content packets + // if packetSize == 0, the Reader contains no data + if err == nil && packetSize > 0 { + data := make([]byte, 4+packetSize) + var n int + for err == nil { + n, err = rdr.Read(data[4:]) + if n > 0 { + if ioErr := mc.writePacket(data[:4+n]); ioErr != nil { + return ioErr + } + } + } + if err == io.EOF { + err = nil + } + } + + // send empty packet (termination) + if data == nil { + data = make([]byte, 4) + } + if ioErr := mc.writePacket(data[:4]); ioErr != nil { + return ioErr + } + + // read OK packet + if err == nil { + return mc.readResultOK() + } + + mc.readPacket() + return err +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime.go new file mode 100644 index 00000000..36c8a42c --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/nulltime.go @@ -0,0 +1,71 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "database/sql" + "database/sql/driver" + "fmt" + "time" +) + +// NullTime represents a time.Time that may be NULL. +// NullTime implements the Scanner interface so +// it can be used as a scan destination: +// +// var nt NullTime +// err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt) +// ... +// if nt.Valid { +// // use nt.Time +// } else { +// // NULL value +// } +// +// # This NullTime implementation is not driver-specific +// +// Deprecated: NullTime doesn't honor the loc DSN parameter. +// NullTime.Scan interprets a time as UTC, not the loc DSN parameter. +// Use sql.NullTime instead. +type NullTime sql.NullTime + +// Scan implements the Scanner interface. +// The value type must be time.Time or string / []byte (formatted time-string), +// otherwise Scan fails. +func (nt *NullTime) Scan(value interface{}) (err error) { + if value == nil { + nt.Time, nt.Valid = time.Time{}, false + return + } + + switch v := value.(type) { + case time.Time: + nt.Time, nt.Valid = v, true + return + case []byte: + nt.Time, err = parseDateTime(v, time.UTC) + nt.Valid = (err == nil) + return + case string: + nt.Time, err = parseDateTime([]byte(v), time.UTC) + nt.Valid = (err == nil) + return + } + + nt.Valid = false + return fmt.Errorf("Can't convert %T to time.Time", value) +} + +// Value implements the driver Valuer interface. +func (nt NullTime) Value() (driver.Value, error) { + if !nt.Valid { + return nil, nil + } + return nt.Time, nil +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/packets.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/packets.go new file mode 100644 index 00000000..ee05c95a --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/packets.go @@ -0,0 +1,1349 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "bytes" + "crypto/tls" + "database/sql/driver" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "time" +) + +// Packets documentation: +// http://dev.mysql.com/doc/internals/en/client-server-protocol.html + +// Read packet to buffer 'data' +func (mc *mysqlConn) readPacket() ([]byte, error) { + var prevData []byte + for { + // read packet header + data, err := mc.buf.readNext(4) + if err != nil { + if cerr := mc.canceled.Value(); cerr != nil { + return nil, cerr + } + errLog.Print(err) + mc.Close() + return nil, ErrInvalidConn + } + + // packet length [24 bit] + pktLen := int(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16) + + // check packet sync [8 bit] + if data[3] != mc.sequence { + if data[3] > mc.sequence { + return nil, ErrPktSyncMul + } + return nil, ErrPktSync + } + mc.sequence++ + + // packets with length 0 terminate a previous packet which is a + // multiple of (2^24)-1 bytes long + if pktLen == 0 { + // there was no previous packet + if prevData == nil { + errLog.Print(ErrMalformPkt) + mc.Close() + return nil, ErrInvalidConn + } + + return prevData, nil + } + + // read packet body [pktLen bytes] + data, err = mc.buf.readNext(pktLen) + if err != nil { + if cerr := mc.canceled.Value(); cerr != nil { + return nil, cerr + } + errLog.Print(err) + mc.Close() + return nil, ErrInvalidConn + } + + // return data if this was the last packet + if pktLen < maxPacketSize { + // zero allocations for non-split packets + if prevData == nil { + return data, nil + } + + return append(prevData, data...), nil + } + + prevData = append(prevData, data...) + } +} + +// Write packet buffer 'data' +func (mc *mysqlConn) writePacket(data []byte) error { + pktLen := len(data) - 4 + + if pktLen > mc.maxAllowedPacket { + return ErrPktTooLarge + } + + // Perform a stale connection check. We only perform this check for + // the first query on a connection that has been checked out of the + // connection pool: a fresh connection from the pool is more likely + // to be stale, and it has not performed any previous writes that + // could cause data corruption, so it's safe to return ErrBadConn + // if the check fails. + if mc.reset { + mc.reset = false + conn := mc.netConn + if mc.rawConn != nil { + conn = mc.rawConn + } + var err error + if mc.cfg.CheckConnLiveness { + if mc.cfg.ReadTimeout != 0 { + err = conn.SetReadDeadline(time.Now().Add(mc.cfg.ReadTimeout)) + } + if err == nil { + err = connCheck(conn) + } + } + if err != nil { + errLog.Print("closing bad idle connection: ", err) + mc.Close() + return driver.ErrBadConn + } + } + + for { + var size int + if pktLen >= maxPacketSize { + data[0] = 0xff + data[1] = 0xff + data[2] = 0xff + size = maxPacketSize + } else { + data[0] = byte(pktLen) + data[1] = byte(pktLen >> 8) + data[2] = byte(pktLen >> 16) + size = pktLen + } + data[3] = mc.sequence + + // Write packet + if mc.writeTimeout > 0 { + if err := mc.netConn.SetWriteDeadline(time.Now().Add(mc.writeTimeout)); err != nil { + return err + } + } + + n, err := mc.netConn.Write(data[:4+size]) + if err == nil && n == 4+size { + mc.sequence++ + if size != maxPacketSize { + return nil + } + pktLen -= size + data = data[size:] + continue + } + + // Handle error + if err == nil { // n != len(data) + mc.cleanup() + errLog.Print(ErrMalformPkt) + } else { + if cerr := mc.canceled.Value(); cerr != nil { + return cerr + } + if n == 0 && pktLen == len(data)-4 { + // only for the first loop iteration when nothing was written yet + return errBadConnNoWrite + } + mc.cleanup() + errLog.Print(err) + } + return ErrInvalidConn + } +} + +/****************************************************************************** +* Initialization Process * +******************************************************************************/ + +// Handshake Initialization Packet +// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake +func (mc *mysqlConn) readHandshakePacket() (data []byte, plugin string, err error) { + data, err = mc.readPacket() + if err != nil { + // for init we can rewrite this to ErrBadConn for sql.Driver to retry, since + // in connection initialization we don't risk retrying non-idempotent actions. + if err == ErrInvalidConn { + return nil, "", driver.ErrBadConn + } + return + } + + if data[0] == iERR { + return nil, "", mc.handleErrorPacket(data) + } + + // protocol version [1 byte] + if data[0] < minProtocolVersion { + return nil, "", fmt.Errorf( + "unsupported protocol version %d. Version %d or higher is required", + data[0], + minProtocolVersion, + ) + } + + // server version [null terminated string] + // connection id [4 bytes] + pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4 + + // first part of the password cipher [8 bytes] + authData := data[pos : pos+8] + + // (filler) always 0x00 [1 byte] + pos += 8 + 1 + + // capability flags (lower 2 bytes) [2 bytes] + mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) + if mc.flags&clientProtocol41 == 0 { + return nil, "", ErrOldProtocol + } + if mc.flags&clientSSL == 0 && mc.cfg.TLS != nil { + if mc.cfg.AllowFallbackToPlaintext { + mc.cfg.TLS = nil + } else { + return nil, "", ErrNoTLS + } + } + pos += 2 + + if len(data) > pos { + // character set [1 byte] + // status flags [2 bytes] + // capability flags (upper 2 bytes) [2 bytes] + // length of auth-plugin-data [1 byte] + // reserved (all [00]) [10 bytes] + pos += 1 + 2 + 2 + 1 + 10 + + // second part of the password cipher [mininum 13 bytes], + // where len=MAX(13, length of auth-plugin-data - 8) + // + // The web documentation is ambiguous about the length. However, + // according to mysql-5.7/sql/auth/sql_authentication.cc line 538, + // the 13th byte is "\0 byte, terminating the second part of + // a scramble". So the second part of the password cipher is + // a NULL terminated string that's at least 13 bytes with the + // last byte being NULL. + // + // The official Python library uses the fixed length 12 + // which seems to work but technically could have a hidden bug. + authData = append(authData, data[pos:pos+12]...) + pos += 13 + + // EOF if version (>= 5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2) + // \NUL otherwise + if end := bytes.IndexByte(data[pos:], 0x00); end != -1 { + plugin = string(data[pos : pos+end]) + } else { + plugin = string(data[pos:]) + } + + // make a memory safe copy of the cipher slice + var b [20]byte + copy(b[:], authData) + return b[:], plugin, nil + } + + // make a memory safe copy of the cipher slice + var b [8]byte + copy(b[:], authData) + return b[:], plugin, nil +} + +// Client Authentication Packet +// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse +func (mc *mysqlConn) writeHandshakeResponsePacket(authResp []byte, plugin string) error { + // Adjust client flags based on server support + clientFlags := clientProtocol41 | + clientSecureConn | + clientLongPassword | + clientTransactions | + clientLocalFiles | + clientPluginAuth | + clientMultiResults | + mc.flags&clientLongFlag + + if mc.cfg.ClientFoundRows { + clientFlags |= clientFoundRows + } + + // To enable TLS / SSL + if mc.cfg.TLS != nil { + clientFlags |= clientSSL + } + + if mc.cfg.MultiStatements { + clientFlags |= clientMultiStatements + } + + // encode length of the auth plugin data + var authRespLEIBuf [9]byte + authRespLen := len(authResp) + authRespLEI := appendLengthEncodedInteger(authRespLEIBuf[:0], uint64(authRespLen)) + if len(authRespLEI) > 1 { + // if the length can not be written in 1 byte, it must be written as a + // length encoded integer + clientFlags |= clientPluginAuthLenEncClientData + } + + pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.User) + 1 + len(authRespLEI) + len(authResp) + 21 + 1 + + // To specify a db name + if n := len(mc.cfg.DBName); n > 0 { + clientFlags |= clientConnectWithDB + pktLen += n + 1 + } + + // Calculate packet length and get buffer with that size + data, err := mc.buf.takeSmallBuffer(pktLen + 4) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } + + // ClientFlags [32 bit] + data[4] = byte(clientFlags) + data[5] = byte(clientFlags >> 8) + data[6] = byte(clientFlags >> 16) + data[7] = byte(clientFlags >> 24) + + // MaxPacketSize [32 bit] (none) + data[8] = 0x00 + data[9] = 0x00 + data[10] = 0x00 + data[11] = 0x00 + + // Charset [1 byte] + var found bool + data[12], found = collations[mc.cfg.Collation] + if !found { + // Note possibility for false negatives: + // could be triggered although the collation is valid if the + // collations map does not contain entries the server supports. + return errors.New("unknown collation") + } + + // Filler [23 bytes] (all 0x00) + pos := 13 + for ; pos < 13+23; pos++ { + data[pos] = 0 + } + + // SSL Connection Request Packet + // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest + if mc.cfg.TLS != nil { + // Send TLS / SSL request packet + if err := mc.writePacket(data[:(4+4+1+23)+4]); err != nil { + return err + } + + // Switch to TLS + tlsConn := tls.Client(mc.netConn, mc.cfg.TLS) + if err := tlsConn.Handshake(); err != nil { + return err + } + mc.rawConn = mc.netConn + mc.netConn = tlsConn + mc.buf.nc = tlsConn + } + + // User [null terminated string] + if len(mc.cfg.User) > 0 { + pos += copy(data[pos:], mc.cfg.User) + } + data[pos] = 0x00 + pos++ + + // Auth Data [length encoded integer] + pos += copy(data[pos:], authRespLEI) + pos += copy(data[pos:], authResp) + + // Databasename [null terminated string] + if len(mc.cfg.DBName) > 0 { + pos += copy(data[pos:], mc.cfg.DBName) + data[pos] = 0x00 + pos++ + } + + pos += copy(data[pos:], plugin) + data[pos] = 0x00 + pos++ + + // Send Auth packet + return mc.writePacket(data[:pos]) +} + +// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse +func (mc *mysqlConn) writeAuthSwitchPacket(authData []byte) error { + pktLen := 4 + len(authData) + data, err := mc.buf.takeSmallBuffer(pktLen) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } + + // Add the auth data [EOF] + copy(data[4:], authData) + return mc.writePacket(data) +} + +/****************************************************************************** +* Command Packets * +******************************************************************************/ + +func (mc *mysqlConn) writeCommandPacket(command byte) error { + // Reset Packet Sequence + mc.sequence = 0 + + data, err := mc.buf.takeSmallBuffer(4 + 1) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } + + // Add command byte + data[4] = command + + // Send CMD packet + return mc.writePacket(data) +} + +func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { + // Reset Packet Sequence + mc.sequence = 0 + + pktLen := 1 + len(arg) + data, err := mc.buf.takeBuffer(pktLen + 4) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } + + // Add command byte + data[4] = command + + // Add arg + copy(data[5:], arg) + + // Send CMD packet + return mc.writePacket(data) +} + +func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error { + // Reset Packet Sequence + mc.sequence = 0 + + data, err := mc.buf.takeSmallBuffer(4 + 1 + 4) + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } + + // Add command byte + data[4] = command + + // Add arg [32 bit] + data[5] = byte(arg) + data[6] = byte(arg >> 8) + data[7] = byte(arg >> 16) + data[8] = byte(arg >> 24) + + // Send CMD packet + return mc.writePacket(data) +} + +/****************************************************************************** +* Result Packets * +******************************************************************************/ + +func (mc *mysqlConn) readAuthResult() ([]byte, string, error) { + data, err := mc.readPacket() + if err != nil { + return nil, "", err + } + + // packet indicator + switch data[0] { + + case iOK: + return nil, "", mc.handleOkPacket(data) + + case iAuthMoreData: + return data[1:], "", err + + case iEOF: + if len(data) == 1 { + // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest + return nil, "mysql_old_password", nil + } + pluginEndIndex := bytes.IndexByte(data, 0x00) + if pluginEndIndex < 0 { + return nil, "", ErrMalformPkt + } + plugin := string(data[1:pluginEndIndex]) + authData := data[pluginEndIndex+1:] + return authData, plugin, nil + + default: // Error otherwise + return nil, "", mc.handleErrorPacket(data) + } +} + +// Returns error if Packet is not an 'Result OK'-Packet +func (mc *mysqlConn) readResultOK() error { + data, err := mc.readPacket() + if err != nil { + return err + } + + if data[0] == iOK { + return mc.handleOkPacket(data) + } + return mc.handleErrorPacket(data) +} + +// Result Set Header Packet +// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::Resultset +func (mc *mysqlConn) readResultSetHeaderPacket() (int, error) { + data, err := mc.readPacket() + if err == nil { + switch data[0] { + + case iOK: + return 0, mc.handleOkPacket(data) + + case iERR: + return 0, mc.handleErrorPacket(data) + + case iLocalInFile: + return 0, mc.handleInFileRequest(string(data[1:])) + } + + // column count + num, _, n := readLengthEncodedInteger(data) + if n-len(data) == 0 { + return int(num), nil + } + + return 0, ErrMalformPkt + } + return 0, err +} + +// Error Packet +// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-ERR_Packet +func (mc *mysqlConn) handleErrorPacket(data []byte) error { + if data[0] != iERR { + return ErrMalformPkt + } + + // 0xff [1 byte] + + // Error Number [16 bit uint] + errno := binary.LittleEndian.Uint16(data[1:3]) + + // 1792: ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION + // 1290: ER_OPTION_PREVENTS_STATEMENT (returned by Aurora during failover) + if (errno == 1792 || errno == 1290) && mc.cfg.RejectReadOnly { + // Oops; we are connected to a read-only connection, and won't be able + // to issue any write statements. Since RejectReadOnly is configured, + // we throw away this connection hoping this one would have write + // permission. This is specifically for a possible race condition + // during failover (e.g. on AWS Aurora). See README.md for more. + // + // We explicitly close the connection before returning + // driver.ErrBadConn to ensure that `database/sql` purges this + // connection and initiates a new one for next statement next time. + mc.Close() + return driver.ErrBadConn + } + + me := &MySQLError{Number: errno} + + pos := 3 + + // SQL State [optional: # + 5bytes string] + if data[3] == 0x23 { + copy(me.SQLState[:], data[4:4+5]) + pos = 9 + } + + // Error Message [string] + me.Message = string(data[pos:]) + + return me +} + +func readStatus(b []byte) statusFlag { + return statusFlag(b[0]) | statusFlag(b[1])<<8 +} + +// Ok Packet +// http://dev.mysql.com/doc/internals/en/generic-response-packets.html#packet-OK_Packet +func (mc *mysqlConn) handleOkPacket(data []byte) error { + var n, m int + + // 0x00 [1 byte] + + // Affected rows [Length Coded Binary] + mc.affectedRows, _, n = readLengthEncodedInteger(data[1:]) + + // Insert id [Length Coded Binary] + mc.insertId, _, m = readLengthEncodedInteger(data[1+n:]) + + // server_status [2 bytes] + mc.status = readStatus(data[1+n+m : 1+n+m+2]) + if mc.status&statusMoreResultsExists != 0 { + return nil + } + + // warning count [2 bytes] + + return nil +} + +// Read Packets as Field Packets until EOF-Packet or an Error appears +// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnDefinition41 +func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) { + columns := make([]mysqlField, count) + + for i := 0; ; i++ { + data, err := mc.readPacket() + if err != nil { + return nil, err + } + + // EOF Packet + if data[0] == iEOF && (len(data) == 5 || len(data) == 1) { + if i == count { + return columns, nil + } + return nil, fmt.Errorf("column count mismatch n:%d len:%d", count, len(columns)) + } + + // Catalog + pos, err := skipLengthEncodedString(data) + if err != nil { + return nil, err + } + + // Database [len coded string] + n, err := skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n + + // Table [len coded string] + if mc.cfg.ColumnsWithAlias { + tableName, _, n, err := readLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n + columns[i].tableName = string(tableName) + } else { + n, err = skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n + } + + // Original table [len coded string] + n, err = skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n + + // Name [len coded string] + name, _, n, err := readLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + columns[i].name = string(name) + pos += n + + // Original name [len coded string] + n, err = skipLengthEncodedString(data[pos:]) + if err != nil { + return nil, err + } + pos += n + + // Filler [uint8] + pos++ + + // Charset [charset, collation uint8] + columns[i].charSet = data[pos] + pos += 2 + + // Length [uint32] + columns[i].length = binary.LittleEndian.Uint32(data[pos : pos+4]) + pos += 4 + + // Field type [uint8] + columns[i].fieldType = fieldType(data[pos]) + pos++ + + // Flags [uint16] + columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2])) + pos += 2 + + // Decimals [uint8] + columns[i].decimals = data[pos] + //pos++ + + // Default value [len coded binary] + //if pos < len(data) { + // defaultVal, _, err = bytesToLengthCodedBinary(data[pos:]) + //} + } +} + +// Read Packets as Field Packets until EOF-Packet or an Error appears +// http://dev.mysql.com/doc/internals/en/com-query-response.html#packet-ProtocolText::ResultsetRow +func (rows *textRows) readRow(dest []driver.Value) error { + mc := rows.mc + + if rows.rs.done { + return io.EOF + } + + data, err := mc.readPacket() + if err != nil { + return err + } + + // EOF Packet + if data[0] == iEOF && len(data) == 5 { + // server_status [2 bytes] + rows.mc.status = readStatus(data[3:]) + rows.rs.done = true + if !rows.HasNextResultSet() { + rows.mc = nil + } + return io.EOF + } + if data[0] == iERR { + rows.mc = nil + return mc.handleErrorPacket(data) + } + + // RowSet Packet + var ( + n int + isNull bool + pos int = 0 + ) + + for i := range dest { + // Read bytes and convert to string + dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) + pos += n + + if err != nil { + return err + } + + if isNull { + dest[i] = nil + continue + } + + if !mc.parseTime { + continue + } + + // Parse time field + switch rows.rs.columns[i].fieldType { + case fieldTypeTimestamp, + fieldTypeDateTime, + fieldTypeDate, + fieldTypeNewDate: + if dest[i], err = parseDateTime(dest[i].([]byte), mc.cfg.Loc); err != nil { + return err + } + } + } + + return nil +} + +// Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read +func (mc *mysqlConn) readUntilEOF() error { + for { + data, err := mc.readPacket() + if err != nil { + return err + } + + switch data[0] { + case iERR: + return mc.handleErrorPacket(data) + case iEOF: + if len(data) == 5 { + mc.status = readStatus(data[3:]) + } + return nil + } + } +} + +/****************************************************************************** +* Prepared Statements * +******************************************************************************/ + +// Prepare Result Packets +// http://dev.mysql.com/doc/internals/en/com-stmt-prepare-response.html +func (stmt *mysqlStmt) readPrepareResultPacket() (uint16, error) { + data, err := stmt.mc.readPacket() + if err == nil { + // packet indicator [1 byte] + if data[0] != iOK { + return 0, stmt.mc.handleErrorPacket(data) + } + + // statement id [4 bytes] + stmt.id = binary.LittleEndian.Uint32(data[1:5]) + + // Column count [16 bit uint] + columnCount := binary.LittleEndian.Uint16(data[5:7]) + + // Param count [16 bit uint] + stmt.paramCount = int(binary.LittleEndian.Uint16(data[7:9])) + + // Reserved [8 bit] + + // Warning count [16 bit uint] + + return columnCount, nil + } + return 0, err +} + +// http://dev.mysql.com/doc/internals/en/com-stmt-send-long-data.html +func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error { + maxLen := stmt.mc.maxAllowedPacket - 1 + pktLen := maxLen + + // After the header (bytes 0-3) follows before the data: + // 1 byte command + // 4 bytes stmtID + // 2 bytes paramID + const dataOffset = 1 + 4 + 2 + + // Cannot use the write buffer since + // a) the buffer is too small + // b) it is in use + data := make([]byte, 4+1+4+2+len(arg)) + + copy(data[4+dataOffset:], arg) + + for argLen := len(arg); argLen > 0; argLen -= pktLen - dataOffset { + if dataOffset+argLen < maxLen { + pktLen = dataOffset + argLen + } + + stmt.mc.sequence = 0 + // Add command byte [1 byte] + data[4] = comStmtSendLongData + + // Add stmtID [32 bit] + data[5] = byte(stmt.id) + data[6] = byte(stmt.id >> 8) + data[7] = byte(stmt.id >> 16) + data[8] = byte(stmt.id >> 24) + + // Add paramID [16 bit] + data[9] = byte(paramID) + data[10] = byte(paramID >> 8) + + // Send CMD packet + err := stmt.mc.writePacket(data[:4+pktLen]) + if err == nil { + data = data[pktLen-dataOffset:] + continue + } + return err + + } + + // Reset Packet Sequence + stmt.mc.sequence = 0 + return nil +} + +// Execute Prepared Statement +// http://dev.mysql.com/doc/internals/en/com-stmt-execute.html +func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { + if len(args) != stmt.paramCount { + return fmt.Errorf( + "argument count mismatch (got: %d; has: %d)", + len(args), + stmt.paramCount, + ) + } + + const minPktLen = 4 + 1 + 4 + 1 + 4 + mc := stmt.mc + + // Determine threshold dynamically to avoid packet size shortage. + longDataSize := mc.maxAllowedPacket / (stmt.paramCount + 1) + if longDataSize < 64 { + longDataSize = 64 + } + + // Reset packet-sequence + mc.sequence = 0 + + var data []byte + var err error + + if len(args) == 0 { + data, err = mc.buf.takeBuffer(minPktLen) + } else { + data, err = mc.buf.takeCompleteBuffer() + // In this case the len(data) == cap(data) which is used to optimise the flow below. + } + if err != nil { + // cannot take the buffer. Something must be wrong with the connection + errLog.Print(err) + return errBadConnNoWrite + } + + // command [1 byte] + data[4] = comStmtExecute + + // statement_id [4 bytes] + data[5] = byte(stmt.id) + data[6] = byte(stmt.id >> 8) + data[7] = byte(stmt.id >> 16) + data[8] = byte(stmt.id >> 24) + + // flags (0: CURSOR_TYPE_NO_CURSOR) [1 byte] + data[9] = 0x00 + + // iteration_count (uint32(1)) [4 bytes] + data[10] = 0x01 + data[11] = 0x00 + data[12] = 0x00 + data[13] = 0x00 + + if len(args) > 0 { + pos := minPktLen + + var nullMask []byte + if maskLen, typesLen := (len(args)+7)/8, 1+2*len(args); pos+maskLen+typesLen >= cap(data) { + // buffer has to be extended but we don't know by how much so + // we depend on append after all data with known sizes fit. + // We stop at that because we deal with a lot of columns here + // which makes the required allocation size hard to guess. + tmp := make([]byte, pos+maskLen+typesLen) + copy(tmp[:pos], data[:pos]) + data = tmp + nullMask = data[pos : pos+maskLen] + // No need to clean nullMask as make ensures that. + pos += maskLen + } else { + nullMask = data[pos : pos+maskLen] + for i := range nullMask { + nullMask[i] = 0 + } + pos += maskLen + } + + // newParameterBoundFlag 1 [1 byte] + data[pos] = 0x01 + pos++ + + // type of each parameter [len(args)*2 bytes] + paramTypes := data[pos:] + pos += len(args) * 2 + + // value of each parameter [n bytes] + paramValues := data[pos:pos] + valuesCap := cap(paramValues) + + for i, arg := range args { + // build NULL-bitmap + if arg == nil { + nullMask[i/8] |= 1 << (uint(i) & 7) + paramTypes[i+i] = byte(fieldTypeNULL) + paramTypes[i+i+1] = 0x00 + continue + } + + if v, ok := arg.(json.RawMessage); ok { + arg = []byte(v) + } + // cache types and values + switch v := arg.(type) { + case int64: + paramTypes[i+i] = byte(fieldTypeLongLong) + paramTypes[i+i+1] = 0x00 + + if cap(paramValues)-len(paramValues)-8 >= 0 { + paramValues = paramValues[:len(paramValues)+8] + binary.LittleEndian.PutUint64( + paramValues[len(paramValues)-8:], + uint64(v), + ) + } else { + paramValues = append(paramValues, + uint64ToBytes(uint64(v))..., + ) + } + + case uint64: + paramTypes[i+i] = byte(fieldTypeLongLong) + paramTypes[i+i+1] = 0x80 // type is unsigned + + if cap(paramValues)-len(paramValues)-8 >= 0 { + paramValues = paramValues[:len(paramValues)+8] + binary.LittleEndian.PutUint64( + paramValues[len(paramValues)-8:], + uint64(v), + ) + } else { + paramValues = append(paramValues, + uint64ToBytes(uint64(v))..., + ) + } + + case float64: + paramTypes[i+i] = byte(fieldTypeDouble) + paramTypes[i+i+1] = 0x00 + + if cap(paramValues)-len(paramValues)-8 >= 0 { + paramValues = paramValues[:len(paramValues)+8] + binary.LittleEndian.PutUint64( + paramValues[len(paramValues)-8:], + math.Float64bits(v), + ) + } else { + paramValues = append(paramValues, + uint64ToBytes(math.Float64bits(v))..., + ) + } + + case bool: + paramTypes[i+i] = byte(fieldTypeTiny) + paramTypes[i+i+1] = 0x00 + + if v { + paramValues = append(paramValues, 0x01) + } else { + paramValues = append(paramValues, 0x00) + } + + case []byte: + // Common case (non-nil value) first + if v != nil { + paramTypes[i+i] = byte(fieldTypeString) + paramTypes[i+i+1] = 0x00 + + if len(v) < longDataSize { + paramValues = appendLengthEncodedInteger(paramValues, + uint64(len(v)), + ) + paramValues = append(paramValues, v...) + } else { + if err := stmt.writeCommandLongData(i, v); err != nil { + return err + } + } + continue + } + + // Handle []byte(nil) as a NULL value + nullMask[i/8] |= 1 << (uint(i) & 7) + paramTypes[i+i] = byte(fieldTypeNULL) + paramTypes[i+i+1] = 0x00 + + case string: + paramTypes[i+i] = byte(fieldTypeString) + paramTypes[i+i+1] = 0x00 + + if len(v) < longDataSize { + paramValues = appendLengthEncodedInteger(paramValues, + uint64(len(v)), + ) + paramValues = append(paramValues, v...) + } else { + if err := stmt.writeCommandLongData(i, []byte(v)); err != nil { + return err + } + } + + case time.Time: + paramTypes[i+i] = byte(fieldTypeString) + paramTypes[i+i+1] = 0x00 + + var a [64]byte + var b = a[:0] + + if v.IsZero() { + b = append(b, "0000-00-00"...) + } else { + b, err = appendDateTime(b, v.In(mc.cfg.Loc)) + if err != nil { + return err + } + } + + paramValues = appendLengthEncodedInteger(paramValues, + uint64(len(b)), + ) + paramValues = append(paramValues, b...) + + default: + return fmt.Errorf("cannot convert type: %T", arg) + } + } + + // Check if param values exceeded the available buffer + // In that case we must build the data packet with the new values buffer + if valuesCap != cap(paramValues) { + data = append(data[:pos], paramValues...) + if err = mc.buf.store(data); err != nil { + errLog.Print(err) + return errBadConnNoWrite + } + } + + pos += len(paramValues) + data = data[:pos] + } + + return mc.writePacket(data) +} + +func (mc *mysqlConn) discardResults() error { + for mc.status&statusMoreResultsExists != 0 { + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return err + } + if resLen > 0 { + // columns + if err := mc.readUntilEOF(); err != nil { + return err + } + // rows + if err := mc.readUntilEOF(); err != nil { + return err + } + } + } + return nil +} + +// http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html +func (rows *binaryRows) readRow(dest []driver.Value) error { + data, err := rows.mc.readPacket() + if err != nil { + return err + } + + // packet indicator [1 byte] + if data[0] != iOK { + // EOF Packet + if data[0] == iEOF && len(data) == 5 { + rows.mc.status = readStatus(data[3:]) + rows.rs.done = true + if !rows.HasNextResultSet() { + rows.mc = nil + } + return io.EOF + } + mc := rows.mc + rows.mc = nil + + // Error otherwise + return mc.handleErrorPacket(data) + } + + // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes] + pos := 1 + (len(dest)+7+2)>>3 + nullMask := data[1:pos] + + for i := range dest { + // Field is NULL + // (byte >> bit-pos) % 2 == 1 + if ((nullMask[(i+2)>>3] >> uint((i+2)&7)) & 1) == 1 { + dest[i] = nil + continue + } + + // Convert to byte-coded string + switch rows.rs.columns[i].fieldType { + case fieldTypeNULL: + dest[i] = nil + continue + + // Numeric Types + case fieldTypeTiny: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + dest[i] = int64(data[pos]) + } else { + dest[i] = int64(int8(data[pos])) + } + pos++ + continue + + case fieldTypeShort, fieldTypeYear: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2])) + } else { + dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2]))) + } + pos += 2 + continue + + case fieldTypeInt24, fieldTypeLong: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4])) + } else { + dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4]))) + } + pos += 4 + continue + + case fieldTypeLongLong: + if rows.rs.columns[i].flags&flagUnsigned != 0 { + val := binary.LittleEndian.Uint64(data[pos : pos+8]) + if val > math.MaxInt64 { + dest[i] = uint64ToString(val) + } else { + dest[i] = int64(val) + } + } else { + dest[i] = int64(binary.LittleEndian.Uint64(data[pos : pos+8])) + } + pos += 8 + continue + + case fieldTypeFloat: + dest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])) + pos += 4 + continue + + case fieldTypeDouble: + dest[i] = math.Float64frombits(binary.LittleEndian.Uint64(data[pos : pos+8])) + pos += 8 + continue + + // Length coded Binary Strings + case fieldTypeDecimal, fieldTypeNewDecimal, fieldTypeVarChar, + fieldTypeBit, fieldTypeEnum, fieldTypeSet, fieldTypeTinyBLOB, + fieldTypeMediumBLOB, fieldTypeLongBLOB, fieldTypeBLOB, + fieldTypeVarString, fieldTypeString, fieldTypeGeometry, fieldTypeJSON: + var isNull bool + var n int + dest[i], isNull, n, err = readLengthEncodedString(data[pos:]) + pos += n + if err == nil { + if !isNull { + continue + } else { + dest[i] = nil + continue + } + } + return err + + case + fieldTypeDate, fieldTypeNewDate, // Date YYYY-MM-DD + fieldTypeTime, // Time [-][H]HH:MM:SS[.fractal] + fieldTypeTimestamp, fieldTypeDateTime: // Timestamp YYYY-MM-DD HH:MM:SS[.fractal] + + num, isNull, n := readLengthEncodedInteger(data[pos:]) + pos += n + + switch { + case isNull: + dest[i] = nil + continue + case rows.rs.columns[i].fieldType == fieldTypeTime: + // database/sql does not support an equivalent to TIME, return a string + var dstlen uint8 + switch decimals := rows.rs.columns[i].decimals; decimals { + case 0x00, 0x1f: + dstlen = 8 + case 1, 2, 3, 4, 5, 6: + dstlen = 8 + 1 + decimals + default: + return fmt.Errorf( + "protocol error, illegal decimals value %d", + rows.rs.columns[i].decimals, + ) + } + dest[i], err = formatBinaryTime(data[pos:pos+int(num)], dstlen) + case rows.mc.parseTime: + dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc) + default: + var dstlen uint8 + if rows.rs.columns[i].fieldType == fieldTypeDate { + dstlen = 10 + } else { + switch decimals := rows.rs.columns[i].decimals; decimals { + case 0x00, 0x1f: + dstlen = 19 + case 1, 2, 3, 4, 5, 6: + dstlen = 19 + 1 + decimals + default: + return fmt.Errorf( + "protocol error, illegal decimals value %d", + rows.rs.columns[i].decimals, + ) + } + } + dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen) + } + + if err == nil { + pos += int(num) + continue + } else { + return err + } + + // Please report if this happens! + default: + return fmt.Errorf("unknown field type %d", rows.rs.columns[i].fieldType) + } + } + + return nil +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/result.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/result.go new file mode 100644 index 00000000..c6438d03 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/result.go @@ -0,0 +1,22 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +type mysqlResult struct { + affectedRows int64 + insertId int64 +} + +func (res *mysqlResult) LastInsertId() (int64, error) { + return res.insertId, nil +} + +func (res *mysqlResult) RowsAffected() (int64, error) { + return res.affectedRows, nil +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/rows.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/rows.go new file mode 100644 index 00000000..888bdb5f --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/rows.go @@ -0,0 +1,223 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "database/sql/driver" + "io" + "math" + "reflect" +) + +type resultSet struct { + columns []mysqlField + columnNames []string + done bool +} + +type mysqlRows struct { + mc *mysqlConn + rs resultSet + finish func() +} + +type binaryRows struct { + mysqlRows +} + +type textRows struct { + mysqlRows +} + +func (rows *mysqlRows) Columns() []string { + if rows.rs.columnNames != nil { + return rows.rs.columnNames + } + + columns := make([]string, len(rows.rs.columns)) + if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias { + for i := range columns { + if tableName := rows.rs.columns[i].tableName; len(tableName) > 0 { + columns[i] = tableName + "." + rows.rs.columns[i].name + } else { + columns[i] = rows.rs.columns[i].name + } + } + } else { + for i := range columns { + columns[i] = rows.rs.columns[i].name + } + } + + rows.rs.columnNames = columns + return columns +} + +func (rows *mysqlRows) ColumnTypeDatabaseTypeName(i int) string { + return rows.rs.columns[i].typeDatabaseName() +} + +// func (rows *mysqlRows) ColumnTypeLength(i int) (length int64, ok bool) { +// return int64(rows.rs.columns[i].length), true +// } + +func (rows *mysqlRows) ColumnTypeNullable(i int) (nullable, ok bool) { + return rows.rs.columns[i].flags&flagNotNULL == 0, true +} + +func (rows *mysqlRows) ColumnTypePrecisionScale(i int) (int64, int64, bool) { + column := rows.rs.columns[i] + decimals := int64(column.decimals) + + switch column.fieldType { + case fieldTypeDecimal, fieldTypeNewDecimal: + if decimals > 0 { + return int64(column.length) - 2, decimals, true + } + return int64(column.length) - 1, decimals, true + case fieldTypeTimestamp, fieldTypeDateTime, fieldTypeTime: + return decimals, decimals, true + case fieldTypeFloat, fieldTypeDouble: + if decimals == 0x1f { + return math.MaxInt64, math.MaxInt64, true + } + return math.MaxInt64, decimals, true + } + + return 0, 0, false +} + +func (rows *mysqlRows) ColumnTypeScanType(i int) reflect.Type { + return rows.rs.columns[i].scanType() +} + +func (rows *mysqlRows) Close() (err error) { + if f := rows.finish; f != nil { + f() + rows.finish = nil + } + + mc := rows.mc + if mc == nil { + return nil + } + if err := mc.error(); err != nil { + return err + } + + // flip the buffer for this connection if we need to drain it. + // note that for a successful query (i.e. one where rows.next() + // has been called until it returns false), `rows.mc` will be nil + // by the time the user calls `(*Rows).Close`, so we won't reach this + // see: https://github.com/golang/go/commit/651ddbdb5056ded455f47f9c494c67b389622a47 + mc.buf.flip() + + // Remove unread packets from stream + if !rows.rs.done { + err = mc.readUntilEOF() + } + if err == nil { + if err = mc.discardResults(); err != nil { + return err + } + } + + rows.mc = nil + return err +} + +func (rows *mysqlRows) HasNextResultSet() (b bool) { + if rows.mc == nil { + return false + } + return rows.mc.status&statusMoreResultsExists != 0 +} + +func (rows *mysqlRows) nextResultSet() (int, error) { + if rows.mc == nil { + return 0, io.EOF + } + if err := rows.mc.error(); err != nil { + return 0, err + } + + // Remove unread packets from stream + if !rows.rs.done { + if err := rows.mc.readUntilEOF(); err != nil { + return 0, err + } + rows.rs.done = true + } + + if !rows.HasNextResultSet() { + rows.mc = nil + return 0, io.EOF + } + rows.rs = resultSet{} + return rows.mc.readResultSetHeaderPacket() +} + +func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) { + for { + resLen, err := rows.nextResultSet() + if err != nil { + return 0, err + } + + if resLen > 0 { + return resLen, nil + } + + rows.rs.done = true + } +} + +func (rows *binaryRows) NextResultSet() error { + resLen, err := rows.nextNotEmptyResultSet() + if err != nil { + return err + } + + rows.rs.columns, err = rows.mc.readColumns(resLen) + return err +} + +func (rows *binaryRows) Next(dest []driver.Value) error { + if mc := rows.mc; mc != nil { + if err := mc.error(); err != nil { + return err + } + + // Fetch next row from stream + return rows.readRow(dest) + } + return io.EOF +} + +func (rows *textRows) NextResultSet() (err error) { + resLen, err := rows.nextNotEmptyResultSet() + if err != nil { + return err + } + + rows.rs.columns, err = rows.mc.readColumns(resLen) + return err +} + +func (rows *textRows) Next(dest []driver.Value) error { + if mc := rows.mc; mc != nil { + if err := mc.error(); err != nil { + return err + } + + // Fetch next row from stream + return rows.readRow(dest) + } + return io.EOF +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/statement.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/statement.go new file mode 100644 index 00000000..10ece8bd --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/statement.go @@ -0,0 +1,220 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "database/sql/driver" + "encoding/json" + "fmt" + "io" + "reflect" +) + +type mysqlStmt struct { + mc *mysqlConn + id uint32 + paramCount int +} + +func (stmt *mysqlStmt) Close() error { + if stmt.mc == nil || stmt.mc.closed.Load() { + // driver.Stmt.Close can be called more than once, thus this function + // has to be idempotent. + // See also Issue #450 and golang/go#16019. + //errLog.Print(ErrInvalidConn) + return driver.ErrBadConn + } + + err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id) + stmt.mc = nil + return err +} + +func (stmt *mysqlStmt) NumInput() int { + return stmt.paramCount +} + +func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter { + return converter{} +} + +func (stmt *mysqlStmt) CheckNamedValue(nv *driver.NamedValue) (err error) { + nv.Value, err = converter{}.ConvertValue(nv.Value) + return +} + +func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { + if stmt.mc.closed.Load() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + // Send command + err := stmt.writeExecutePacket(args) + if err != nil { + return nil, stmt.mc.markBadConn(err) + } + + mc := stmt.mc + + mc.affectedRows = 0 + mc.insertId = 0 + + // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return nil, err + } + + if resLen > 0 { + // Columns + if err = mc.readUntilEOF(); err != nil { + return nil, err + } + + // Rows + if err := mc.readUntilEOF(); err != nil { + return nil, err + } + } + + if err := mc.discardResults(); err != nil { + return nil, err + } + + return &mysqlResult{ + affectedRows: int64(mc.affectedRows), + insertId: int64(mc.insertId), + }, nil +} + +func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { + return stmt.query(args) +} + +func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { + if stmt.mc.closed.Load() { + errLog.Print(ErrInvalidConn) + return nil, driver.ErrBadConn + } + // Send command + err := stmt.writeExecutePacket(args) + if err != nil { + return nil, stmt.mc.markBadConn(err) + } + + mc := stmt.mc + + // Read Result + resLen, err := mc.readResultSetHeaderPacket() + if err != nil { + return nil, err + } + + rows := new(binaryRows) + + if resLen > 0 { + rows.mc = mc + rows.rs.columns, err = mc.readColumns(resLen) + } else { + rows.rs.done = true + + switch err := rows.NextResultSet(); err { + case nil, io.EOF: + return rows, nil + default: + return nil, err + } + } + + return rows, err +} + +var jsonType = reflect.TypeOf(json.RawMessage{}) + +type converter struct{} + +// ConvertValue mirrors the reference/default converter in database/sql/driver +// with _one_ exception. We support uint64 with their high bit and the default +// implementation does not. This function should be kept in sync with +// database/sql/driver defaultConverter.ConvertValue() except for that +// deliberate difference. +func (c converter) ConvertValue(v interface{}) (driver.Value, error) { + if driver.IsValue(v) { + return v, nil + } + + if vr, ok := v.(driver.Valuer); ok { + sv, err := callValuerValue(vr) + if err != nil { + return nil, err + } + if driver.IsValue(sv) { + return sv, nil + } + // A value returned from the Valuer interface can be "a type handled by + // a database driver's NamedValueChecker interface" so we should accept + // uint64 here as well. + if u, ok := sv.(uint64); ok { + return u, nil + } + return nil, fmt.Errorf("non-Value type %T returned from Value", sv) + } + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Ptr: + // indirect pointers + if rv.IsNil() { + return nil, nil + } else { + return c.ConvertValue(rv.Elem().Interface()) + } + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rv.Int(), nil + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return rv.Uint(), nil + case reflect.Float32, reflect.Float64: + return rv.Float(), nil + case reflect.Bool: + return rv.Bool(), nil + case reflect.Slice: + switch t := rv.Type(); { + case t == jsonType: + return v, nil + case t.Elem().Kind() == reflect.Uint8: + return rv.Bytes(), nil + default: + return nil, fmt.Errorf("unsupported type %T, a slice of %s", v, t.Elem().Kind()) + } + case reflect.String: + return rv.String(), nil + } + return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) +} + +var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() + +// callValuerValue returns vr.Value(), with one exception: +// If vr.Value is an auto-generated method on a pointer type and the +// pointer is nil, it would panic at runtime in the panicwrap +// method. Treat it like nil instead. +// +// This is so people can implement driver.Value on value types and +// still use nil pointers to those types to mean nil/NULL, just like +// string/*string. +// +// This is an exact copy of the same-named unexported function from the +// database/sql package. +func callValuerValue(vr driver.Valuer) (v driver.Value, err error) { + if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Ptr && + rv.IsNil() && + rv.Type().Elem().Implements(valuerReflectType) { + return nil, nil + } + return vr.Value() +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/transaction.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/transaction.go new file mode 100644 index 00000000..4a4b6100 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/transaction.go @@ -0,0 +1,31 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +type mysqlTx struct { + mc *mysqlConn +} + +func (tx *mysqlTx) Commit() (err error) { + if tx.mc == nil || tx.mc.closed.Load() { + return ErrInvalidConn + } + err = tx.mc.exec("COMMIT") + tx.mc = nil + return +} + +func (tx *mysqlTx) Rollback() (err error) { + if tx.mc == nil || tx.mc.closed.Load() { + return ErrInvalidConn + } + err = tx.mc.exec("ROLLBACK") + tx.mc = nil + return +} diff --git a/taskman-server/vendor/github.com/go-sql-driver/mysql/utils.go b/taskman-server/vendor/github.com/go-sql-driver/mysql/utils.go new file mode 100644 index 00000000..15dbd8d1 --- /dev/null +++ b/taskman-server/vendor/github.com/go-sql-driver/mysql/utils.go @@ -0,0 +1,834 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2012 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import ( + "crypto/tls" + "database/sql" + "database/sql/driver" + "encoding/binary" + "errors" + "fmt" + "io" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +// Registry for custom tls.Configs +var ( + tlsConfigLock sync.RWMutex + tlsConfigRegistry map[string]*tls.Config +) + +// RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. +// Use the key as a value in the DSN where tls=value. +// +// Note: The provided tls.Config is exclusively owned by the driver after +// registering it. +// +// rootCertPool := x509.NewCertPool() +// pem, err := ioutil.ReadFile("/path/ca-cert.pem") +// if err != nil { +// log.Fatal(err) +// } +// if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { +// log.Fatal("Failed to append PEM.") +// } +// clientCert := make([]tls.Certificate, 0, 1) +// certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem") +// if err != nil { +// log.Fatal(err) +// } +// clientCert = append(clientCert, certs) +// mysql.RegisterTLSConfig("custom", &tls.Config{ +// RootCAs: rootCertPool, +// Certificates: clientCert, +// }) +// db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom") +func RegisterTLSConfig(key string, config *tls.Config) error { + if _, isBool := readBool(key); isBool || strings.ToLower(key) == "skip-verify" || strings.ToLower(key) == "preferred" { + return fmt.Errorf("key '%s' is reserved", key) + } + + tlsConfigLock.Lock() + if tlsConfigRegistry == nil { + tlsConfigRegistry = make(map[string]*tls.Config) + } + + tlsConfigRegistry[key] = config + tlsConfigLock.Unlock() + return nil +} + +// DeregisterTLSConfig removes the tls.Config associated with key. +func DeregisterTLSConfig(key string) { + tlsConfigLock.Lock() + if tlsConfigRegistry != nil { + delete(tlsConfigRegistry, key) + } + tlsConfigLock.Unlock() +} + +func getTLSConfigClone(key string) (config *tls.Config) { + tlsConfigLock.RLock() + if v, ok := tlsConfigRegistry[key]; ok { + config = v.Clone() + } + tlsConfigLock.RUnlock() + return +} + +// Returns the bool value of the input. +// The 2nd return value indicates if the input was a valid bool value +func readBool(input string) (value bool, valid bool) { + switch input { + case "1", "true", "TRUE", "True": + return true, true + case "0", "false", "FALSE", "False": + return false, true + } + + // Not a valid bool value + return +} + +/****************************************************************************** +* Time related utils * +******************************************************************************/ + +func parseDateTime(b []byte, loc *time.Location) (time.Time, error) { + const base = "0000-00-00 00:00:00.000000" + switch len(b) { + case 10, 19, 21, 22, 23, 24, 25, 26: // up to "YYYY-MM-DD HH:MM:SS.MMMMMM" + if string(b) == base[:len(b)] { + return time.Time{}, nil + } + + year, err := parseByteYear(b) + if err != nil { + return time.Time{}, err + } + if b[4] != '-' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[4]) + } + + m, err := parseByte2Digits(b[5], b[6]) + if err != nil { + return time.Time{}, err + } + month := time.Month(m) + + if b[7] != '-' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[7]) + } + + day, err := parseByte2Digits(b[8], b[9]) + if err != nil { + return time.Time{}, err + } + if len(b) == 10 { + return time.Date(year, month, day, 0, 0, 0, 0, loc), nil + } + + if b[10] != ' ' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[10]) + } + + hour, err := parseByte2Digits(b[11], b[12]) + if err != nil { + return time.Time{}, err + } + if b[13] != ':' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[13]) + } + + min, err := parseByte2Digits(b[14], b[15]) + if err != nil { + return time.Time{}, err + } + if b[16] != ':' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[16]) + } + + sec, err := parseByte2Digits(b[17], b[18]) + if err != nil { + return time.Time{}, err + } + if len(b) == 19 { + return time.Date(year, month, day, hour, min, sec, 0, loc), nil + } + + if b[19] != '.' { + return time.Time{}, fmt.Errorf("bad value for field: `%c`", b[19]) + } + nsec, err := parseByteNanoSec(b[20:]) + if err != nil { + return time.Time{}, err + } + return time.Date(year, month, day, hour, min, sec, nsec, loc), nil + default: + return time.Time{}, fmt.Errorf("invalid time bytes: %s", b) + } +} + +func parseByteYear(b []byte) (int, error) { + year, n := 0, 1000 + for i := 0; i < 4; i++ { + v, err := bToi(b[i]) + if err != nil { + return 0, err + } + year += v * n + n /= 10 + } + return year, nil +} + +func parseByte2Digits(b1, b2 byte) (int, error) { + d1, err := bToi(b1) + if err != nil { + return 0, err + } + d2, err := bToi(b2) + if err != nil { + return 0, err + } + return d1*10 + d2, nil +} + +func parseByteNanoSec(b []byte) (int, error) { + ns, digit := 0, 100000 // max is 6-digits + for i := 0; i < len(b); i++ { + v, err := bToi(b[i]) + if err != nil { + return 0, err + } + ns += v * digit + digit /= 10 + } + // nanoseconds has 10-digits. (needs to scale digits) + // 10 - 6 = 4, so we have to multiple 1000. + return ns * 1000, nil +} + +func bToi(b byte) (int, error) { + if b < '0' || b > '9' { + return 0, errors.New("not [0-9]") + } + return int(b - '0'), nil +} + +func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) { + switch num { + case 0: + return time.Time{}, nil + case 4: + return time.Date( + int(binary.LittleEndian.Uint16(data[:2])), // year + time.Month(data[2]), // month + int(data[3]), // day + 0, 0, 0, 0, + loc, + ), nil + case 7: + return time.Date( + int(binary.LittleEndian.Uint16(data[:2])), // year + time.Month(data[2]), // month + int(data[3]), // day + int(data[4]), // hour + int(data[5]), // minutes + int(data[6]), // seconds + 0, + loc, + ), nil + case 11: + return time.Date( + int(binary.LittleEndian.Uint16(data[:2])), // year + time.Month(data[2]), // month + int(data[3]), // day + int(data[4]), // hour + int(data[5]), // minutes + int(data[6]), // seconds + int(binary.LittleEndian.Uint32(data[7:11]))*1000, // nanoseconds + loc, + ), nil + } + return nil, fmt.Errorf("invalid DATETIME packet length %d", num) +} + +func appendDateTime(buf []byte, t time.Time) ([]byte, error) { + year, month, day := t.Date() + hour, min, sec := t.Clock() + nsec := t.Nanosecond() + + if year < 1 || year > 9999 { + return buf, errors.New("year is not in the range [1, 9999]: " + strconv.Itoa(year)) // use errors.New instead of fmt.Errorf to avoid year escape to heap + } + year100 := year / 100 + year1 := year % 100 + + var localBuf [len("2006-01-02T15:04:05.999999999")]byte // does not escape + localBuf[0], localBuf[1], localBuf[2], localBuf[3] = digits10[year100], digits01[year100], digits10[year1], digits01[year1] + localBuf[4] = '-' + localBuf[5], localBuf[6] = digits10[month], digits01[month] + localBuf[7] = '-' + localBuf[8], localBuf[9] = digits10[day], digits01[day] + + if hour == 0 && min == 0 && sec == 0 && nsec == 0 { + return append(buf, localBuf[:10]...), nil + } + + localBuf[10] = ' ' + localBuf[11], localBuf[12] = digits10[hour], digits01[hour] + localBuf[13] = ':' + localBuf[14], localBuf[15] = digits10[min], digits01[min] + localBuf[16] = ':' + localBuf[17], localBuf[18] = digits10[sec], digits01[sec] + + if nsec == 0 { + return append(buf, localBuf[:19]...), nil + } + nsec100000000 := nsec / 100000000 + nsec1000000 := (nsec / 1000000) % 100 + nsec10000 := (nsec / 10000) % 100 + nsec100 := (nsec / 100) % 100 + nsec1 := nsec % 100 + localBuf[19] = '.' + + // milli second + localBuf[20], localBuf[21], localBuf[22] = + digits01[nsec100000000], digits10[nsec1000000], digits01[nsec1000000] + // micro second + localBuf[23], localBuf[24], localBuf[25] = + digits10[nsec10000], digits01[nsec10000], digits10[nsec100] + // nano second + localBuf[26], localBuf[27], localBuf[28] = + digits01[nsec100], digits10[nsec1], digits01[nsec1] + + // trim trailing zeros + n := len(localBuf) + for n > 0 && localBuf[n-1] == '0' { + n-- + } + + return append(buf, localBuf[:n]...), nil +} + +// zeroDateTime is used in formatBinaryDateTime to avoid an allocation +// if the DATE or DATETIME has the zero value. +// It must never be changed. +// The current behavior depends on database/sql copying the result. +var zeroDateTime = []byte("0000-00-00 00:00:00.000000") + +const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" +const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999" + +func appendMicrosecs(dst, src []byte, decimals int) []byte { + if decimals <= 0 { + return dst + } + if len(src) == 0 { + return append(dst, ".000000"[:decimals+1]...) + } + + microsecs := binary.LittleEndian.Uint32(src[:4]) + p1 := byte(microsecs / 10000) + microsecs -= 10000 * uint32(p1) + p2 := byte(microsecs / 100) + microsecs -= 100 * uint32(p2) + p3 := byte(microsecs) + + switch decimals { + default: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], digits01[p2], + digits10[p3], digits01[p3], + ) + case 1: + return append(dst, '.', + digits10[p1], + ) + case 2: + return append(dst, '.', + digits10[p1], digits01[p1], + ) + case 3: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], + ) + case 4: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], digits01[p2], + ) + case 5: + return append(dst, '.', + digits10[p1], digits01[p1], + digits10[p2], digits01[p2], + digits10[p3], + ) + } +} + +func formatBinaryDateTime(src []byte, length uint8) (driver.Value, error) { + // length expects the deterministic length of the zero value, + // negative time and 100+ hours are automatically added if needed + if len(src) == 0 { + return zeroDateTime[:length], nil + } + var dst []byte // return value + var p1, p2, p3 byte // current digit pair + + switch length { + case 10, 19, 21, 22, 23, 24, 25, 26: + default: + t := "DATE" + if length > 10 { + t += "TIME" + } + return nil, fmt.Errorf("illegal %s length %d", t, length) + } + switch len(src) { + case 4, 7, 11: + default: + t := "DATE" + if length > 10 { + t += "TIME" + } + return nil, fmt.Errorf("illegal %s packet length %d", t, len(src)) + } + dst = make([]byte, 0, length) + // start with the date + year := binary.LittleEndian.Uint16(src[:2]) + pt := year / 100 + p1 = byte(year - 100*uint16(pt)) + p2, p3 = src[2], src[3] + dst = append(dst, + digits10[pt], digits01[pt], + digits10[p1], digits01[p1], '-', + digits10[p2], digits01[p2], '-', + digits10[p3], digits01[p3], + ) + if length == 10 { + return dst, nil + } + if len(src) == 4 { + return append(dst, zeroDateTime[10:length]...), nil + } + dst = append(dst, ' ') + p1 = src[4] // hour + src = src[5:] + + // p1 is 2-digit hour, src is after hour + p2, p3 = src[0], src[1] + dst = append(dst, + digits10[p1], digits01[p1], ':', + digits10[p2], digits01[p2], ':', + digits10[p3], digits01[p3], + ) + return appendMicrosecs(dst, src[2:], int(length)-20), nil +} + +func formatBinaryTime(src []byte, length uint8) (driver.Value, error) { + // length expects the deterministic length of the zero value, + // negative time and 100+ hours are automatically added if needed + if len(src) == 0 { + return zeroDateTime[11 : 11+length], nil + } + var dst []byte // return value + + switch length { + case + 8, // time (can be up to 10 when negative and 100+ hours) + 10, 11, 12, 13, 14, 15: // time with fractional seconds + default: + return nil, fmt.Errorf("illegal TIME length %d", length) + } + switch len(src) { + case 8, 12: + default: + return nil, fmt.Errorf("invalid TIME packet length %d", len(src)) + } + // +2 to enable negative time and 100+ hours + dst = make([]byte, 0, length+2) + if src[0] == 1 { + dst = append(dst, '-') + } + days := binary.LittleEndian.Uint32(src[1:5]) + hours := int64(days)*24 + int64(src[5]) + + if hours >= 100 { + dst = strconv.AppendInt(dst, hours, 10) + } else { + dst = append(dst, digits10[hours], digits01[hours]) + } + + min, sec := src[6], src[7] + dst = append(dst, ':', + digits10[min], digits01[min], ':', + digits10[sec], digits01[sec], + ) + return appendMicrosecs(dst, src[8:], int(length)-9), nil +} + +/****************************************************************************** +* Convert from and to bytes * +******************************************************************************/ + +func uint64ToBytes(n uint64) []byte { + return []byte{ + byte(n), + byte(n >> 8), + byte(n >> 16), + byte(n >> 24), + byte(n >> 32), + byte(n >> 40), + byte(n >> 48), + byte(n >> 56), + } +} + +func uint64ToString(n uint64) []byte { + var a [20]byte + i := 20 + + // U+0030 = 0 + // ... + // U+0039 = 9 + + var q uint64 + for n >= 10 { + i-- + q = n / 10 + a[i] = uint8(n-q*10) + 0x30 + n = q + } + + i-- + a[i] = uint8(n) + 0x30 + + return a[i:] +} + +// treats string value as unsigned integer representation +func stringToInt(b []byte) int { + val := 0 + for i := range b { + val *= 10 + val += int(b[i] - 0x30) + } + return val +} + +// returns the string read as a bytes slice, whether the value is NULL, +// the number of bytes read and an error, in case the string is longer than +// the input slice +func readLengthEncodedString(b []byte) ([]byte, bool, int, error) { + // Get length + num, isNull, n := readLengthEncodedInteger(b) + if num < 1 { + return b[n:n], isNull, n, nil + } + + n += int(num) + + // Check data length + if len(b) >= n { + return b[n-int(num) : n : n], false, n, nil + } + return nil, false, n, io.EOF +} + +// returns the number of bytes skipped and an error, in case the string is +// longer than the input slice +func skipLengthEncodedString(b []byte) (int, error) { + // Get length + num, _, n := readLengthEncodedInteger(b) + if num < 1 { + return n, nil + } + + n += int(num) + + // Check data length + if len(b) >= n { + return n, nil + } + return n, io.EOF +} + +// returns the number read, whether the value is NULL and the number of bytes read +func readLengthEncodedInteger(b []byte) (uint64, bool, int) { + // See issue #349 + if len(b) == 0 { + return 0, true, 1 + } + + switch b[0] { + // 251: NULL + case 0xfb: + return 0, true, 1 + + // 252: value of following 2 + case 0xfc: + return uint64(b[1]) | uint64(b[2])<<8, false, 3 + + // 253: value of following 3 + case 0xfd: + return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16, false, 4 + + // 254: value of following 8 + case 0xfe: + return uint64(b[1]) | uint64(b[2])<<8 | uint64(b[3])<<16 | + uint64(b[4])<<24 | uint64(b[5])<<32 | uint64(b[6])<<40 | + uint64(b[7])<<48 | uint64(b[8])<<56, + false, 9 + } + + // 0-250: value of first byte + return uint64(b[0]), false, 1 +} + +// encodes a uint64 value and appends it to the given bytes slice +func appendLengthEncodedInteger(b []byte, n uint64) []byte { + switch { + case n <= 250: + return append(b, byte(n)) + + case n <= 0xffff: + return append(b, 0xfc, byte(n), byte(n>>8)) + + case n <= 0xffffff: + return append(b, 0xfd, byte(n), byte(n>>8), byte(n>>16)) + } + return append(b, 0xfe, byte(n), byte(n>>8), byte(n>>16), byte(n>>24), + byte(n>>32), byte(n>>40), byte(n>>48), byte(n>>56)) +} + +// reserveBuffer checks cap(buf) and expand buffer to len(buf) + appendSize. +// If cap(buf) is not enough, reallocate new buffer. +func reserveBuffer(buf []byte, appendSize int) []byte { + newSize := len(buf) + appendSize + if cap(buf) < newSize { + // Grow buffer exponentially + newBuf := make([]byte, len(buf)*2+appendSize) + copy(newBuf, buf) + buf = newBuf + } + return buf[:newSize] +} + +// escapeBytesBackslash escapes []byte with backslashes (\) +// This escapes the contents of a string (provided as []byte) by adding backslashes before special +// characters, and turning others into specific escape sequences, such as +// turning newlines into \n and null bytes into \0. +// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932 +func escapeBytesBackslash(buf, v []byte) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) + + for _, c := range v { + switch c { + case '\x00': + buf[pos+1] = '0' + buf[pos] = '\\' + pos += 2 + case '\n': + buf[pos+1] = 'n' + buf[pos] = '\\' + pos += 2 + case '\r': + buf[pos+1] = 'r' + buf[pos] = '\\' + pos += 2 + case '\x1a': + buf[pos+1] = 'Z' + buf[pos] = '\\' + pos += 2 + case '\'': + buf[pos+1] = '\'' + buf[pos] = '\\' + pos += 2 + case '"': + buf[pos+1] = '"' + buf[pos] = '\\' + pos += 2 + case '\\': + buf[pos+1] = '\\' + buf[pos] = '\\' + pos += 2 + default: + buf[pos] = c + pos++ + } + } + + return buf[:pos] +} + +// escapeStringBackslash is similar to escapeBytesBackslash but for string. +func escapeStringBackslash(buf []byte, v string) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) + + for i := 0; i < len(v); i++ { + c := v[i] + switch c { + case '\x00': + buf[pos+1] = '0' + buf[pos] = '\\' + pos += 2 + case '\n': + buf[pos+1] = 'n' + buf[pos] = '\\' + pos += 2 + case '\r': + buf[pos+1] = 'r' + buf[pos] = '\\' + pos += 2 + case '\x1a': + buf[pos+1] = 'Z' + buf[pos] = '\\' + pos += 2 + case '\'': + buf[pos+1] = '\'' + buf[pos] = '\\' + pos += 2 + case '"': + buf[pos+1] = '"' + buf[pos] = '\\' + pos += 2 + case '\\': + buf[pos+1] = '\\' + buf[pos] = '\\' + pos += 2 + default: + buf[pos] = c + pos++ + } + } + + return buf[:pos] +} + +// escapeBytesQuotes escapes apostrophes in []byte by doubling them up. +// This escapes the contents of a string by doubling up any apostrophes that +// it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in +// effect on the server. +// https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038 +func escapeBytesQuotes(buf, v []byte) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) + + for _, c := range v { + if c == '\'' { + buf[pos+1] = '\'' + buf[pos] = '\'' + pos += 2 + } else { + buf[pos] = c + pos++ + } + } + + return buf[:pos] +} + +// escapeStringQuotes is similar to escapeBytesQuotes but for string. +func escapeStringQuotes(buf []byte, v string) []byte { + pos := len(buf) + buf = reserveBuffer(buf, len(v)*2) + + for i := 0; i < len(v); i++ { + c := v[i] + if c == '\'' { + buf[pos+1] = '\'' + buf[pos] = '\'' + pos += 2 + } else { + buf[pos] = c + pos++ + } + } + + return buf[:pos] +} + +/****************************************************************************** +* Sync utils * +******************************************************************************/ + +// noCopy may be embedded into structs which must not be copied +// after the first use. +// +// See https://github.com/golang/go/issues/8005#issuecomment-190753527 +// for details. +type noCopy struct{} + +// Lock is a no-op used by -copylocks checker from `go vet`. +func (*noCopy) Lock() {} + +// Unlock is a no-op used by -copylocks checker from `go vet`. +// noCopy should implement sync.Locker from Go 1.11 +// https://github.com/golang/go/commit/c2eba53e7f80df21d51285879d51ab81bcfbf6bc +// https://github.com/golang/go/issues/26165 +func (*noCopy) Unlock() {} + +// atomicError is a wrapper for atomically accessed error values +type atomicError struct { + _ noCopy + value atomic.Value +} + +// Set sets the error value regardless of the previous value. +// The value must not be nil +func (ae *atomicError) Set(value error) { + ae.value.Store(value) +} + +// Value returns the current error value +func (ae *atomicError) Value() error { + if v := ae.value.Load(); v != nil { + // this will panic if the value doesn't implement the error interface + return v.(error) + } + return nil +} + +func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) { + dargs := make([]driver.Value, len(named)) + for n, param := range named { + if len(param.Name) > 0 { + // TODO: support the use of Named Parameters #561 + return nil, errors.New("mysql: driver does not support the use of Named Parameters") + } + dargs[n] = param.Value + } + return dargs, nil +} + +func mapIsolationLevel(level driver.IsolationLevel) (string, error) { + switch sql.IsolationLevel(level) { + case sql.LevelRepeatableRead: + return "REPEATABLE READ", nil + case sql.LevelReadCommitted: + return "READ COMMITTED", nil + case sql.LevelReadUncommitted: + return "READ UNCOMMITTED", nil + case sql.LevelSerializable: + return "SERIALIZABLE", nil + default: + return "", fmt.Errorf("mysql: unsupported isolation level: %v", level) + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/.codecov.yml b/taskman-server/vendor/github.com/goccy/go-json/.codecov.yml new file mode 100644 index 00000000..e9813457 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/.codecov.yml @@ -0,0 +1,32 @@ +codecov: + require_ci_to_pass: yes + +coverage: + precision: 2 + round: down + range: "70...100" + + status: + project: + default: + target: 70% + threshold: 2% + patch: off + changes: no + +parsers: + gcov: + branch_detection: + conditional: yes + loop: yes + method: no + macro: no + +comment: + layout: "header,diff" + behavior: default + require_changes: no + +ignore: + - internal/encoder/vm_color + - internal/encoder/vm_color_indent diff --git a/taskman-server/vendor/github.com/goccy/go-json/.gitignore b/taskman-server/vendor/github.com/goccy/go-json/.gitignore new file mode 100644 index 00000000..37828382 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/.gitignore @@ -0,0 +1,2 @@ +cover.html +cover.out diff --git a/taskman-server/vendor/github.com/goccy/go-json/.golangci.yml b/taskman-server/vendor/github.com/goccy/go-json/.golangci.yml new file mode 100644 index 00000000..44ae40f6 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/.golangci.yml @@ -0,0 +1,75 @@ +run: + skip-files: + - encode_optype.go + - ".*_test\\.go$" + +linters-settings: + govet: + enable-all: true + disable: + - shadow + +linters: + enable-all: true + disable: + - dogsled + - dupl + - exhaustive + - exhaustivestruct + - errorlint + - forbidigo + - funlen + - gci + - gochecknoglobals + - gochecknoinits + - gocognit + - gocritic + - gocyclo + - godot + - godox + - goerr113 + - gofumpt + - gomnd + - gosec + - ifshort + - lll + - makezero + - nakedret + - nestif + - nlreturn + - paralleltest + - testpackage + - thelper + - wrapcheck + - interfacer + - lll + - nakedret + - nestif + - nlreturn + - testpackage + - wsl + +issues: + exclude-rules: + # not needed + - path: /*.go + text: "ST1003: should not use underscores in package names" + linters: + - stylecheck + - path: /*.go + text: "don't use an underscore in package name" + linters: + - golint + - path: rtype.go + linters: + - golint + - stylecheck + - path: error.go + linters: + - staticcheck + + # Maximum issues count per one linter. Set to 0 to disable. Default is 50. + max-issues-per-linter: 0 + + # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. + max-same-issues: 0 diff --git a/taskman-server/vendor/github.com/goccy/go-json/CHANGELOG.md b/taskman-server/vendor/github.com/goccy/go-json/CHANGELOG.md new file mode 100644 index 00000000..b7bc481c --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/CHANGELOG.md @@ -0,0 +1,277 @@ +# v0.8.1 - 2021/12/05 + +* Fix operation conversion from PtrHead to Head in Recursive type ( #305 ) + +# v0.8.0 - 2021/12/02 + +* Fix embedded field conflict behavior ( #300 ) +* Refactor compiler for encoder ( #301 #302 ) + +# v0.7.10 - 2021/10/16 + +* Fix conversion from pointer to uint64 ( #294 ) + +# v0.7.9 - 2021/09/28 + +* Fix encoding of nil value about interface type that has method ( #291 ) + +# v0.7.8 - 2021/09/01 + +* Fix mapassign_faststr for indirect struct type ( #283 ) +* Fix encoding of not empty interface type ( #284 ) +* Fix encoding of empty struct interface type ( #286 ) + +# v0.7.7 - 2021/08/25 + +* Fix invalid utf8 on stream decoder ( #279 ) +* Fix buffer length bug on string stream decoder ( #280 ) + +Thank you @orisano !! + +# v0.7.6 - 2021/08/13 + +* Fix nil slice assignment ( #276 ) +* Improve error message ( #277 ) + +# v0.7.5 - 2021/08/12 + +* Fix encoding of embedded struct with tags ( #265 ) +* Fix encoding of embedded struct that isn't first field ( #272 ) +* Fix decoding of binary type with escaped char ( #273 ) + +# v0.7.4 - 2021/07/06 + +* Fix encoding of indirect layout structure ( #264 ) + +# v0.7.3 - 2021/06/29 + +* Fix encoding of pointer type in empty interface ( #262 ) + +# v0.7.2 - 2021/06/26 + +### Fix decoder + +* Add decoder for func type to fix decoding of nil function value ( #257 ) +* Fix stream decoding of []byte type ( #258 ) + +### Performance + +* Improve decoding performance of map[string]interface{} type ( use `mapassign_faststr` ) ( #256 ) +* Improve encoding performance of empty interface type ( remove recursive calling of `vm.Run` ) ( #259 ) + +### Benchmark + +* Add bytedance/sonic as benchmark target ( #254 ) + +# v0.7.1 - 2021/06/18 + +### Fix decoder + +* Fix error when unmarshal empty array ( #253 ) + +# v0.7.0 - 2021/06/12 + +### Support context for MarshalJSON and UnmarshalJSON ( #248 ) + +* json.MarshalContext(context.Context, interface{}, ...json.EncodeOption) ([]byte, error) +* json.NewEncoder(io.Writer).EncodeContext(context.Context, interface{}, ...json.EncodeOption) error +* json.UnmarshalContext(context.Context, []byte, interface{}, ...json.DecodeOption) error +* json.NewDecoder(io.Reader).DecodeContext(context.Context, interface{}) error + +```go +type MarshalerContext interface { + MarshalJSON(context.Context) ([]byte, error) +} + +type UnmarshalerContext interface { + UnmarshalJSON(context.Context, []byte) error +} +``` + +### Add DecodeFieldPriorityFirstWin option ( #242 ) + +In the default behavior, go-json, like encoding/json, will reflect the result of the last evaluation when a field with the same name exists. I've added new options to allow you to change this behavior. `json.DecodeFieldPriorityFirstWin` option reflects the result of the first evaluation if a field with the same name exists. This behavior has a performance advantage as it allows the subsequent strings to be skipped if all fields have been evaluated. + +### Fix encoder + +* Fix indent number contains recursive type ( #249 ) +* Fix encoding of using empty interface as map key ( #244 ) + +### Fix decoder + +* Fix decoding fields containing escaped characters ( #237 ) + +### Refactor + +* Move some tests to subdirectory ( #243 ) +* Refactor package layout for decoder ( #238 ) + +# v0.6.1 - 2021/06/02 + +### Fix encoder + +* Fix value of totalLength for encoding ( #236 ) + +# v0.6.0 - 2021/06/01 + +### Support Colorize option for encoding (#233) + +```go +b, err := json.MarshalWithOption(v, json.Colorize(json.DefaultColorScheme)) +if err != nil { + ... +} +fmt.Println(string(b)) // print colored json +``` + +### Refactor + +* Fix opcode layout - Adjust memory layout of the opcode to 128 bytes in a 64-bit environment ( #230 ) +* Refactor encode option ( #231 ) +* Refactor escape string ( #232 ) + +# v0.5.1 - 2021/5/20 + +### Optimization + +* Add type addrShift to enable bigger encoder/decoder cache ( #213 ) + +### Fix decoder + +* Keep original reference of slice element ( #229 ) + +### Refactor + +* Refactor Debug mode for encoding ( #226 ) +* Generate VM sources for encoding ( #227 ) +* Refactor validator for null/true/false for decoding ( #221 ) + +# v0.5.0 - 2021/5/9 + +### Supports using omitempty and string tags at the same time ( #216 ) + +### Fix decoder + +* Fix stream decoder for unicode char ( #215 ) +* Fix decoding of slice element ( #219 ) +* Fix calculating of buffer length for stream decoder ( #220 ) + +### Refactor + +* replace skipWhiteSpace goto by loop ( #212 ) + +# v0.4.14 - 2021/5/4 + +### Benchmark + +* Add valyala/fastjson to benchmark ( #193 ) +* Add benchmark task for CI ( #211 ) + +### Fix decoder + +* Fix decoding of slice with unmarshal json type ( #198 ) +* Fix decoding of null value for interface type that does not implement Unmarshaler ( #205 ) +* Fix decoding of null value to []byte by json.Unmarshal ( #206 ) +* Fix decoding of backslash char at the end of string ( #207 ) +* Fix stream decoder for null/true/false value ( #208 ) +* Fix stream decoder for slow reader ( #211 ) + +### Performance + +* If cap of slice is enough, reuse slice data for compatibility with encoding/json ( #200 ) + +# v0.4.13 - 2021/4/20 + +### Fix json.Compact and json.Indent + +* Support validation the input buffer for json.Compact and json.Indent ( #189 ) +* Optimize json.Compact and json.Indent ( improve memory footprint ) ( #190 ) + +# v0.4.12 - 2021/4/15 + +### Fix encoder + +* Fix unnecessary indent for empty slice type ( #181 ) +* Fix encoding of omitempty feature for the slice or interface type ( #183 ) +* Fix encoding custom types zero values with omitempty when marshaller exists ( #187 ) + +### Fix decoder + +* Fix decoder for invalid top level value ( #184 ) +* Fix decoder for invalid number value ( #185 ) + +# v0.4.11 - 2021/4/3 + +* Improve decoder performance for interface type + +# v0.4.10 - 2021/4/2 + +### Fix encoder + +* Fixed a bug when encoding slice and map containing recursive structures +* Fixed a logic to determine if indirect reference + +# v0.4.9 - 2021/3/29 + +### Add debug mode + +If you use `json.MarshalWithOption(v, json.Debug())` and `panic` occurred in `go-json`, produces debug information to console. + +### Support a new feature to compatible with encoding/json + +- invalid UTF-8 is coerced to valid UTF-8 ( without performance down ) + +### Fix encoder + +- Fixed handling of MarshalJSON of function type + +### Fix decoding of slice of pointer type + +If there is a pointer value, go-json will use it. (This behavior is necessary to achieve the ability to prioritize pre-filled values). However, since slices are reused internally, there was a bug that referred to the previous pointer value. Therefore, it is not necessary to refer to the pointer value in advance for the slice element, so we explicitly initialize slice element by `nil`. + +# v0.4.8 - 2021/3/21 + +### Reduce memory usage at compile time + +* go-json have used about 2GB of memory at compile time, but now it can compile with about less than 550MB. + +### Fix any encoder's bug + +* Add many test cases for encoder +* Fix composite type ( slice/array/map ) +* Fix pointer types +* Fix encoding of MarshalJSON or MarshalText or json.Number type + +### Refactor encoder + +* Change package layout for reducing memory usage at compile +* Remove anonymous and only operation +* Remove root property from encodeCompileContext and opcode + +### Fix CI + +* Add Go 1.16 +* Remove Go 1.13 +* Fix `make cover` task + +### Number/Delim/Token/RawMessage use the types defined in encoding/json by type alias + +# v0.4.7 - 2021/02/22 + +### Fix decoder + +* Fix decoding of deep recursive structure +* Fix decoding of embedded unexported pointer field +* Fix invalid test case +* Fix decoding of invalid value +* Fix decoding of prefilled value +* Fix not being able to return UnmarshalTypeError when it should be returned +* Fix decoding of null value +* Fix decoding of type of null string +* Use pre allocated pointer if exists it at decoding + +### Reduce memory usage at compile + +* Integrate int/int8/int16/int32/int64 and uint/uint8/uint16/uint32/uint64 operation to reduce memory usage at compile + +### Remove unnecessary optype diff --git a/taskman-server/vendor/github.com/goccy/go-json/LICENSE b/taskman-server/vendor/github.com/goccy/go-json/LICENSE new file mode 100644 index 00000000..6449c8bf --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Masaaki Goshima + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/taskman-server/vendor/github.com/goccy/go-json/Makefile b/taskman-server/vendor/github.com/goccy/go-json/Makefile new file mode 100644 index 00000000..363563ab --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/Makefile @@ -0,0 +1,39 @@ +PKG := github.com/goccy/go-json + +BIN_DIR := $(CURDIR)/bin +PKGS := $(shell go list ./... | grep -v internal/cmd|grep -v test) +COVER_PKGS := $(foreach pkg,$(PKGS),$(subst $(PKG),.,$(pkg))) + +COMMA := , +EMPTY := +SPACE := $(EMPTY) $(EMPTY) +COVERPKG_OPT := $(subst $(SPACE),$(COMMA),$(COVER_PKGS)) + +$(BIN_DIR): + @mkdir -p $(BIN_DIR) + +.PHONY: cover +cover: + go test -coverpkg=$(COVERPKG_OPT) -coverprofile=cover.out ./... + +.PHONY: cover-html +cover-html: cover + go tool cover -html=cover.out + +.PHONY: lint +lint: golangci-lint + golangci-lint run + +golangci-lint: | $(BIN_DIR) + @{ \ + set -e; \ + GOLANGCI_LINT_TMP_DIR=$$(mktemp -d); \ + cd $$GOLANGCI_LINT_TMP_DIR; \ + go mod init tmp; \ + GOBIN=$(BIN_DIR) go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.36.0; \ + rm -rf $$GOLANGCI_LINT_TMP_DIR; \ + } + +.PHONY: generate +generate: + go generate ./internal/... diff --git a/taskman-server/vendor/github.com/goccy/go-json/README.md b/taskman-server/vendor/github.com/goccy/go-json/README.md new file mode 100644 index 00000000..8cb729f7 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/README.md @@ -0,0 +1,529 @@ +# go-json + +![Go](https://github.com/goccy/go-json/workflows/Go/badge.svg) +[![GoDoc](https://godoc.org/github.com/goccy/go-json?status.svg)](https://pkg.go.dev/github.com/goccy/go-json?tab=doc) +[![codecov](https://codecov.io/gh/goccy/go-json/branch/master/graph/badge.svg)](https://codecov.io/gh/goccy/go-json) + +Fast JSON encoder/decoder compatible with encoding/json for Go + + + +# Roadmap + +``` +* version ( expected release date ) + +* v0.8.0 + | + | while maintaining compatibility with encoding/json, we will add convenient APIs + | + v +* v1.0.0 +``` + +We are accepting requests for features that will be implemented between v0.8.0 and v.1.0.0. +If you have the API you need, please submit your issue [here](https://github.com/goccy/go-json/issues). +For example, I'm thinking of supporting `context.Context` of `json.Marshaler` and decoding using JSON Path. + +# Features + +- Drop-in replacement of `encoding/json` +- Fast ( See [Benchmark section](https://github.com/goccy/go-json#benchmarks) ) +- Flexible customization with options +- Coloring the encoded string +- Can propagate context.Context to `MarshalJSON` or `UnmarshalJSON` + +# Installation + +``` +go get github.com/goccy/go-json +``` + +# How to use + +Replace import statement from `encoding/json` to `github.com/goccy/go-json` + +``` +-import "encoding/json" ++import "github.com/goccy/go-json" +``` + +# JSON library comparison + +| name | encoder | decoder | compatible with `encoding/json` | +| :----: | :------: | :-----: | :-----------------------------: | +| encoding/json | yes | yes | N/A | +| [json-iterator/go](https://github.com/json-iterator/go) | yes | yes | partial | +| [easyjson](https://github.com/mailru/easyjson) | yes | yes | no | +| [gojay](https://github.com/francoispqt/gojay) | yes | yes | no | +| [segmentio/encoding/json](https://github.com/segmentio/encoding/tree/master/json) | yes | yes | partial | +| [jettison](https://github.com/wI2L/jettison) | yes | no | no | +| [simdjson-go](https://github.com/minio/simdjson-go) | no | yes | no | +| goccy/go-json | yes | yes | yes | + +- `json-iterator/go` isn't compatible with `encoding/json` in many ways (e.g. https://github.com/json-iterator/go/issues/229 ), but it hasn't been supported for a long time. +- `segmentio/encoding/json` is well supported for encoders, but some are not supported for decoder APIs such as `Token` ( streaming decode ) + +## Other libraries + +- [jingo](https://github.com/bet365/jingo) + +I tried the benchmark but it didn't work. +Also, it seems to panic when it receives an unexpected value because there is no error handling... + +- [ffjson](https://github.com/pquerna/ffjson) + +Benchmarking gave very slow results. +It seems that it is assumed that the user will use the buffer pool properly. +Also, development seems to have already stopped + +# Benchmarks + +``` +$ cd benchmarks +$ go test -bench . +``` + +## Encode + + + + +## Decode + + + + + + +# Fuzzing + +[go-json-fuzz](https://github.com/goccy/go-json-fuzz) is the repository for fuzzing tests. +If you run the test in this repository and find a bug, please commit to corpus to go-json-fuzz and report the issue to [go-json](https://github.com/goccy/go-json/issues). + +# How it works + +`go-json` is very fast in both encoding and decoding compared to other libraries. +It's easier to implement by using automatic code generation for performance or by using a dedicated interface, but `go-json` dares to stick to compatibility with `encoding/json` and is the simple interface. Despite this, we are developing with the aim of being the fastest library. + +Here, we explain the various speed-up techniques implemented by `go-json`. + +## Basic technique + +The techniques listed here are the ones used by most of the libraries listed above. + +### Buffer reuse + +Since the only value required for the result of `json.Marshal(interface{}) ([]byte, error)` is `[]byte`, the only value that must be allocated during encoding is the return value `[]byte` . + +Also, as the number of allocations increases, the performance will be affected, so the number of allocations should be kept as low as possible when creating `[]byte`. + +Therefore, there is a technique to reduce the number of times a new buffer must be allocated by reusing the buffer used for the previous encoding by using `sync.Pool`. + +Finally, you allocate a buffer that is as long as the resulting buffer and copy the contents into it, you only need to allocate the buffer once in theory. + +```go +type buffer struct { + data []byte +} + +var bufPool = sync.Pool{ + New: func() interface{} { + return &buffer{data: make([]byte, 0, 1024)} + }, +} + +buf := bufPool.Get().(*buffer) +data := encode(buf.data) // reuse buf.data + +newBuf := make([]byte, len(data)) +copy(newBuf, buf) + +buf.data = data +bufPool.Put(buf) +``` + +### Elimination of reflection + +As you know, the reflection operation is very slow. + +Therefore, using the fact that the address position where the type information is stored is fixed for each binary ( we call this `typeptr` ), +we can use the address in the type information to call a pre-built optimized process. + +For example, you can get the address to the type information from `interface{}` as follows and you can use that information to call a process that does not have reflection. + +To process without reflection, pass a pointer (`unsafe.Pointer`) to the value is stored. + +```go + +type emptyInterface struct { + typ unsafe.Pointer + ptr unsafe.Pointer +} + +var typeToEncoder = map[uintptr]func(unsafe.Pointer)([]byte, error){} + +func Marshal(v interface{}) ([]byte, error) { + iface := (*emptyInterface)(unsafe.Pointer(&v) + typeptr := uintptr(iface.typ) + if enc, exists := typeToEncoder[typeptr]; exists { + return enc(iface.ptr) + } + ... +} +``` + +※ In reality, `typeToEncoder` can be referenced by multiple goroutines, so exclusive control is required. + +## Unique speed-up technique + +## Encoder + +### Do not escape arguments of `Marshal` + +`json.Marshal` and `json.Unmarshal` receive `interface{}` value and they perform type determination dynamically to process. +In normal case, you need to use the `reflect` library to determine the type dynamically, but since `reflect.Type` is defined as `interface`, when you call the method of `reflect.Type`, The reflect's argument is escaped. + +Therefore, the arguments for `Marshal` and `Unmarshal` are always escape to the heap. +However, `go-json` can use the feature of `reflect.Type` while avoiding escaping. + +`reflect.Type` is defined as `interface`, but in reality `reflect.Type` is implemented only by the structure `rtype` defined in the `reflect` package. +For this reason, to date `reflect.Type` is the same as `*reflect.rtype`. + +Therefore, by directly handling `*reflect.rtype`, which is an implementation of `reflect.Type`, it is possible to avoid escaping because it changes from `interface` to using `struct`. + +The technique for working with `*reflect.rtype` directly from `go-json` is implemented at [rtype.go](https://github.com/goccy/go-json/blob/master/internal/runtime/rtype.go) + +Also, the same technique is cut out as a library ( https://github.com/goccy/go-reflect ) + +Initially this feature was the default behavior of `go-json`. +But after careful testing, I found that I passed a large value to `json.Marshal()` and if the argument could not be assigned to the stack, it could not be properly escaped to the heap (a bug in the Go compiler). + +Therefore, this feature will be provided as an **optional** until this issue is resolved. + +To use it, add `NoEscape` like `MarshalNoEscape()` + +### Encoding using opcode sequence + +I explained that you can use `typeptr` to call a pre-built process from type information. + +In other libraries, this dedicated process is processed by making it an function calling like anonymous function, but function calls are inherently slow processes and should be avoided as much as possible. + +Therefore, `go-json` adopted the Instruction-based execution processing system, which is also used to implement virtual machines for programming language. + +If it is the first type to encode, create the opcode ( instruction ) sequence required for encoding. +From the second time onward, use `typeptr` to get the cached pre-built opcode sequence and encode it based on it. An example of the opcode sequence is shown below. + +```go +json.Marshal(struct{ + X int `json:"x"` + Y string `json:"y"` +}{X: 1, Y: "hello"}) +``` + +When encoding a structure like the one above, create a sequence of opcodes like this: + +``` +- opStructFieldHead ( `{` ) +- opStructFieldInt ( `"x": 1,` ) +- opStructFieldString ( `"y": "hello"` ) +- opStructEnd ( `}` ) +- opEnd +``` + +※ When processing each operation, write the letters on the right. + +In addition, each opcode is managed by the following structure ( +Pseudo code ). + +```go +type opType int +const ( + opStructFieldHead opType = iota + opStructFieldInt + opStructFieldStirng + opStructEnd + opEnd +) +type opcode struct { + op opType + key []byte + next *opcode +} +``` + +The process of encoding using the opcode sequence is roughly implemented as follows. + +```go +func encode(code *opcode, b []byte, p unsafe.Pointer) ([]byte, error) { + for { + switch code.op { + case opStructFieldHead: + b = append(b, '{') + code = code.next + case opStructFieldInt: + b = append(b, code.key...) + b = appendInt((*int)(unsafe.Pointer(uintptr(p)+code.offset))) + code = code.next + case opStructFieldString: + b = append(b, code.key...) + b = appendString((*string)(unsafe.Pointer(uintptr(p)+code.offset))) + code = code.next + case opStructEnd: + b = append(b, '}') + code = code.next + case opEnd: + goto END + } + } +END: + return b, nil +} +``` + +In this way, the huge `switch-case` is used to encode by manipulating the linked list opcodes to avoid unnecessary function calls. + +### Opcode sequence optimization + +One of the advantages of encoding using the opcode sequence is the ease of optimization. +The opcode sequence mentioned above is actually converted into the following optimized operations and used. + +``` +- opStructFieldHeadInt ( `{"x": 1,` ) +- opStructEndString ( `"y": "hello"}` ) +- opEnd +``` + +It has been reduced from 5 opcodes to 3 opcodes ! +Reducing the number of opcodees means reducing the number of branches with `switch-case`. +In other words, the closer the number of operations is to 1, the faster the processing can be performed. + +In `go-json`, optimization to reduce the number of opcodes itself like the above and it speeds up by preparing opcodes with optimized paths. + +### Change recursive call from CALL to JMP + +Recursive processing is required during encoding if the type is defined recursively as follows: + +```go +type T struct { + X int + U *U +} + +type U struct { + T *T +} + +b, err := json.Marshal(&T{ + X: 1, + U: &U{ + T: &T{ + X: 2, + }, + }, +}) +fmt.Println(string(b)) // {"X":1,"U":{"T":{"X":2,"U":null}}} +``` + +In `go-json`, recursive processing is processed by the operation type of ` opStructFieldRecursive`. + +In this operation, after acquiring the opcode sequence used for recursive processing, the function is **not** called recursively as it is, but the necessary values ​​are saved by itself and implemented by moving to the next operation. + +The technique of implementing recursive processing with the `JMP` operation while avoiding the `CALL` operation is a famous technique for implementing a high-speed virtual machine. + +For more details, please refer to [the article](https://engineering.mercari.com/blog/entry/1599563768-081104c850) ( but Japanese only ). + +### Dispatch by typeptr from map to slice + +When retrieving the data cached from the type information by `typeptr`, we usually use map. +Map requires exclusive control, so use `sync.Map` for a naive implementation. + +However, this is slow, so it's a good idea to use the `atomic` package for exclusive control as implemented by `segmentio/encoding/json` ( https://github.com/segmentio/encoding/blob/master/json/codec.go#L41-L55 ). + +This implementation slows down the set instead of speeding up the get, but it works well because of the nature of the library, it encodes much more for the same type. + +However, as a result of profiling, I noticed that `runtime.mapaccess2` accounts for a significant percentage of the execution time. So I thought if I could change the lookup from map to slice. + +There is an API named `typelinks` defined in the `runtime` package that the `reflect` package uses internally. +This allows you to get all the type information defined in the binary at runtime. + +The fact that all type information can be acquired means that by constructing slices in advance with the acquired total number of type information, it is possible to look up with the value of `typeptr` without worrying about out-of-range access. + +However, if there is too much type information, it will use a lot of memory, so by default we will only use this optimization if the slice size fits within **2Mib** . + +If this approach is not available, it will fall back to the `atomic` based process described above. + +If you want to know more, please refer to the implementation [here](https://github.com/goccy/go-json/blob/master/internal/runtime/type.go#L36-L100) + +## Decoder + +### Dispatch by typeptr from map to slice + +Like the encoder, the decoder also uses typeptr to call the dedicated process. + +### Faster termination character inspection using NUL character + +In order to decode, you have to traverse the input buffer character by position. +At that time, if you check whether the buffer has reached the end, it will be very slow. + +`buf` : `[]byte` type variable. holds the string passed to the decoder +`cursor` : `int64` type variable. holds the current read position + +```go +buflen := len(buf) +for ; cursor < buflen; cursor++ { // compare cursor and buflen at all times, it is so slow. + switch buf[cursor] { + case ' ', '\n', '\r', '\t': + } +} +``` + +Therefore, by adding the `NUL` (`\000`) character to the end of the read buffer as shown below, it is possible to check the termination character at the same time as other characters. + +```go +for { + switch buf[cursor] { + case ' ', '\n', '\r', '\t': + case '\000': + return nil + } + cursor++ +} +``` + +### Use Boundary Check Elimination + +Due to the `NUL` character optimization, the Go compiler does a boundary check every time, even though `buf[cursor]` does not cause out-of-range access. + +Therefore, `go-json` eliminates boundary check by fetching characters for hotspot by pointer operation. For example, the following code. + +```go +func char(ptr unsafe.Pointer, offset int64) byte { + return *(*byte)(unsafe.Pointer(uintptr(ptr) + uintptr(offset))) +} + +p := (*sliceHeader)(&unsafe.Pointer(buf)).data +for { + switch char(p, cursor) { + case ' ', '\n', '\r', '\t': + case '\000': + return nil + } + cursor++ +} +``` + +### Checking the existence of fields of struct using Bitmaps + +I found by the profiling result, in the struct decode, lookup process for field was taking a long time. + +For example, consider decoding a string like `{"a":1,"b":2,"c":3}` into the following structure: + +```go +type T struct { + A int `json:"a"` + B int `json:"b"` + C int `json:"c"` +} +``` + +At this time, it was found that it takes a lot of time to acquire the decoding process corresponding to the field from the field name as shown below during the decoding process. + +```go +fieldName := decodeKey(buf, cursor) // "a" or "b" or "c" +decoder, exists := fieldToDecoderMap[fieldName] // so slow +if exists { + decoder(buf, cursor) +} else { + skipValue(buf, cursor) +} +``` + +To improve this process, `json-iterator/go` is optimized so that it can be branched by switch-case when the number of fields in the structure is 10 or less (switch-case is faster than map). However, there is a risk of hash collision because the value hashed by the FNV algorithm is used for conditional branching. Also, `gojay` processes this part at high speed by letting the library user yourself write `switch-case`. + + +`go-json` considers and implements a new approach that is different from these. I call this **bitmap field optimization**. + +The range of values ​​per character can be represented by `[256]byte`. Also, if the number of fields in the structure is 8 or less, `int8` type can represent the state of each field. +In other words, it has the following structure. + +- Base ( 8bit ): `00000000` +- Key "a": `00000001` ( assign key "a" to the first bit ) +- Key "b": `00000010` ( assign key "b" to the second bit ) +- Key "c": `00000100` ( assign key "c" to the third bit ) + +Bitmap structure is the following + +``` + | key index(0) | +------------------------ + 0 | 00000000 | + 1 | 00000000 | +~~ | | +97 (a) | 00000001 | +98 (b) | 00000010 | +99 (c) | 00000100 | +~~ | | +255 | 00000000 | +``` + +You can think of this as a Bitmap with a height of `256` and a width of the maximum string length in the field name. +In other words, it can be represented by the following type . + +```go +[maxFieldKeyLength][256]int8 +``` + +When decoding a field character, check whether the corresponding character exists by referring to the pre-built bitmap like the following. + +```go +var curBit int8 = math.MaxInt8 // 11111111 + +c := char(buf, cursor) +bit := bitmap[keyIdx][c] +curBit &= bit +if curBit == 0 { + // not found field +} +``` + +If `curBit` is not `0` until the end of the field string, then the string is +You may have hit one of the fields. +But the possibility is that if the decoded string is shorter than the field string, you will get a false hit. + +- input: `{"a":1}` +```go +type T struct { + X int `json:"abc"` +} +``` +※ Since `a` is shorter than `abc`, it can decode to the end of the field character without `curBit` being 0. + +Rest assured. In this case, it doesn't matter because you can tell if you hit by comparing the string length of `a` with the string length of `abc`. + +Finally, calculate the position of the bit where `1` is set and get the corresponding value, and you're done. + +Using this technique, field lookups are possible with only bitwise operations and access to slices. + +`go-json` uses a similar technique for fields with 9 or more and 16 or less fields. At this time, Bitmap is constructed as `[maxKeyLen][256]int16` type. + +Currently, this optimization is not performed when the maximum length of the field name is long (specifically, 64 bytes or more) in addition to the limitation of the number of fields from the viewpoint of saving memory usage. + +### Others + +I have done a lot of other optimizations. I will find time to write about them. If you have any questions about what's written here or other optimizations, please visit the `#go-json` channel on `gophers.slack.com` . + +## Reference + +Regarding the story of go-json, there are the following articles in Japanese only. + +- https://speakerdeck.com/goccy/zui-su-falsejsonraiburariwoqiu-mete +- https://engineering.mercari.com/blog/entry/1599563768-081104c850/ + +# Looking for Sponsors + +I'm looking for sponsors this library. This library is being developed as a personal project in my spare time. If you want a quick response or problem resolution when using this library in your project, please register as a [sponsor](https://github.com/sponsors/goccy). I will cooperate as much as possible. Of course, this library is developed as an MIT license, so you can use it freely for free. + +# License + +MIT diff --git a/taskman-server/vendor/github.com/goccy/go-json/color.go b/taskman-server/vendor/github.com/goccy/go-json/color.go new file mode 100644 index 00000000..e80b22b4 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/color.go @@ -0,0 +1,68 @@ +package json + +import ( + "fmt" + + "github.com/goccy/go-json/internal/encoder" +) + +type ( + ColorFormat = encoder.ColorFormat + ColorScheme = encoder.ColorScheme +) + +const escape = "\x1b" + +type colorAttr int + +//nolint:deadcode,varcheck +const ( + fgBlackColor colorAttr = iota + 30 + fgRedColor + fgGreenColor + fgYellowColor + fgBlueColor + fgMagentaColor + fgCyanColor + fgWhiteColor +) + +//nolint:deadcode,varcheck +const ( + fgHiBlackColor colorAttr = iota + 90 + fgHiRedColor + fgHiGreenColor + fgHiYellowColor + fgHiBlueColor + fgHiMagentaColor + fgHiCyanColor + fgHiWhiteColor +) + +func createColorFormat(attr colorAttr) ColorFormat { + return ColorFormat{ + Header: wrapColor(attr), + Footer: resetColor(), + } +} + +func wrapColor(attr colorAttr) string { + return fmt.Sprintf("%s[%dm", escape, attr) +} + +func resetColor() string { + return wrapColor(colorAttr(0)) +} + +var ( + DefaultColorScheme = &ColorScheme{ + Int: createColorFormat(fgHiMagentaColor), + Uint: createColorFormat(fgHiMagentaColor), + Float: createColorFormat(fgHiMagentaColor), + Bool: createColorFormat(fgHiYellowColor), + String: createColorFormat(fgHiGreenColor), + Binary: createColorFormat(fgHiRedColor), + ObjectKey: createColorFormat(fgHiCyanColor), + Null: createColorFormat(fgBlueColor), + } +) diff --git a/taskman-server/vendor/github.com/goccy/go-json/decode.go b/taskman-server/vendor/github.com/goccy/go-json/decode.go new file mode 100644 index 00000000..d99749d0 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/decode.go @@ -0,0 +1,232 @@ +package json + +import ( + "context" + "fmt" + "io" + "reflect" + "unsafe" + + "github.com/goccy/go-json/internal/decoder" + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type Decoder struct { + s *decoder.Stream +} + +const ( + nul = '\000' +) + +type emptyInterface struct { + typ *runtime.Type + ptr unsafe.Pointer +} + +func unmarshal(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { + src := make([]byte, len(data)+1) // append nul byte to the end + copy(src, data) + + header := (*emptyInterface)(unsafe.Pointer(&v)) + + if err := validateType(header.typ, uintptr(header.ptr)); err != nil { + return err + } + dec, err := decoder.CompileToGetDecoder(header.typ) + if err != nil { + return err + } + ctx := decoder.TakeRuntimeContext() + ctx.Buf = src + ctx.Option.Flags = 0 + for _, optFunc := range optFuncs { + optFunc(ctx.Option) + } + cursor, err := dec.Decode(ctx, 0, 0, header.ptr) + if err != nil { + decoder.ReleaseRuntimeContext(ctx) + return err + } + decoder.ReleaseRuntimeContext(ctx) + return validateEndBuf(src, cursor) +} + +func unmarshalContext(ctx context.Context, data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { + src := make([]byte, len(data)+1) // append nul byte to the end + copy(src, data) + + header := (*emptyInterface)(unsafe.Pointer(&v)) + + if err := validateType(header.typ, uintptr(header.ptr)); err != nil { + return err + } + dec, err := decoder.CompileToGetDecoder(header.typ) + if err != nil { + return err + } + rctx := decoder.TakeRuntimeContext() + rctx.Buf = src + rctx.Option.Flags = 0 + rctx.Option.Flags |= decoder.ContextOption + rctx.Option.Context = ctx + for _, optFunc := range optFuncs { + optFunc(rctx.Option) + } + cursor, err := dec.Decode(rctx, 0, 0, header.ptr) + if err != nil { + decoder.ReleaseRuntimeContext(rctx) + return err + } + decoder.ReleaseRuntimeContext(rctx) + return validateEndBuf(src, cursor) +} + +func unmarshalNoEscape(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { + src := make([]byte, len(data)+1) // append nul byte to the end + copy(src, data) + + header := (*emptyInterface)(unsafe.Pointer(&v)) + + if err := validateType(header.typ, uintptr(header.ptr)); err != nil { + return err + } + dec, err := decoder.CompileToGetDecoder(header.typ) + if err != nil { + return err + } + + ctx := decoder.TakeRuntimeContext() + ctx.Buf = src + ctx.Option.Flags = 0 + for _, optFunc := range optFuncs { + optFunc(ctx.Option) + } + cursor, err := dec.Decode(ctx, 0, 0, noescape(header.ptr)) + if err != nil { + decoder.ReleaseRuntimeContext(ctx) + return err + } + decoder.ReleaseRuntimeContext(ctx) + return validateEndBuf(src, cursor) +} + +func validateEndBuf(src []byte, cursor int64) error { + for { + switch src[cursor] { + case ' ', '\t', '\n', '\r': + cursor++ + continue + case nul: + return nil + } + return errors.ErrSyntax( + fmt.Sprintf("invalid character '%c' after top-level value", src[cursor]), + cursor+1, + ) + } +} + +//nolint:staticcheck +//go:nosplit +func noescape(p unsafe.Pointer) unsafe.Pointer { + x := uintptr(p) + return unsafe.Pointer(x ^ 0) +} + +func validateType(typ *runtime.Type, p uintptr) error { + if typ == nil || typ.Kind() != reflect.Ptr || p == 0 { + return &InvalidUnmarshalError{Type: runtime.RType2Type(typ)} + } + return nil +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may +// read data from r beyond the JSON values requested. +func NewDecoder(r io.Reader) *Decoder { + s := decoder.NewStream(r) + return &Decoder{ + s: s, + } +} + +// Buffered returns a reader of the data remaining in the Decoder's +// buffer. The reader is valid until the next call to Decode. +func (d *Decoder) Buffered() io.Reader { + return d.s.Buffered() +} + +// Decode reads the next JSON-encoded value from its +// input and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about +// the conversion of JSON into a Go value. +func (d *Decoder) Decode(v interface{}) error { + return d.DecodeWithOption(v) +} + +// DecodeContext reads the next JSON-encoded value from its +// input and stores it in the value pointed to by v with context.Context. +func (d *Decoder) DecodeContext(ctx context.Context, v interface{}) error { + d.s.Option.Flags |= decoder.ContextOption + d.s.Option.Context = ctx + return d.DecodeWithOption(v) +} + +func (d *Decoder) DecodeWithOption(v interface{}, optFuncs ...DecodeOptionFunc) error { + header := (*emptyInterface)(unsafe.Pointer(&v)) + typ := header.typ + ptr := uintptr(header.ptr) + typeptr := uintptr(unsafe.Pointer(typ)) + // noescape trick for header.typ ( reflect.*rtype ) + copiedType := *(**runtime.Type)(unsafe.Pointer(&typeptr)) + + if err := validateType(copiedType, ptr); err != nil { + return err + } + + dec, err := decoder.CompileToGetDecoder(typ) + if err != nil { + return err + } + if err := d.s.PrepareForDecode(); err != nil { + return err + } + s := d.s + for _, optFunc := range optFuncs { + optFunc(s.Option) + } + if err := dec.DecodeStream(s, 0, header.ptr); err != nil { + return err + } + s.Reset() + return nil +} + +func (d *Decoder) More() bool { + return d.s.More() +} + +func (d *Decoder) Token() (Token, error) { + return d.s.Token() +} + +// DisallowUnknownFields causes the Decoder to return an error when the destination +// is a struct and the input contains object keys which do not match any +// non-ignored, exported fields in the destination. +func (d *Decoder) DisallowUnknownFields() { + d.s.DisallowUnknownFields = true +} + +func (d *Decoder) InputOffset() int64 { + return d.s.TotalOffset() +} + +// UseNumber causes the Decoder to unmarshal a number into an interface{} as a +// Number instead of as a float64. +func (d *Decoder) UseNumber() { + d.s.UseNumber = true +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/docker-compose.yml b/taskman-server/vendor/github.com/goccy/go-json/docker-compose.yml new file mode 100644 index 00000000..48415e3d --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/docker-compose.yml @@ -0,0 +1,13 @@ +version: '2' +services: + go-json: + image: golang:1.17 + volumes: + - '.:/go/src/go-json' + deploy: + resources: + limits: + memory: 620M + working_dir: /go/src/go-json + command: | + sh -c "go test -c . && ls go-json.test" diff --git a/taskman-server/vendor/github.com/goccy/go-json/encode.go b/taskman-server/vendor/github.com/goccy/go-json/encode.go new file mode 100644 index 00000000..7f198bdc --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/encode.go @@ -0,0 +1,323 @@ +package json + +import ( + "context" + "io" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/encoder/vm" + "github.com/goccy/go-json/internal/encoder/vm_color" + "github.com/goccy/go-json/internal/encoder/vm_color_indent" + "github.com/goccy/go-json/internal/encoder/vm_indent" +) + +// An Encoder writes JSON values to an output stream. +type Encoder struct { + w io.Writer + enabledIndent bool + enabledHTMLEscape bool + prefix string + indentStr string +} + +// NewEncoder returns a new encoder that writes to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{w: w, enabledHTMLEscape: true} +} + +// Encode writes the JSON encoding of v to the stream, followed by a newline character. +// +// See the documentation for Marshal for details about the conversion of Go values to JSON. +func (e *Encoder) Encode(v interface{}) error { + return e.EncodeWithOption(v) +} + +// EncodeWithOption call Encode with EncodeOption. +func (e *Encoder) EncodeWithOption(v interface{}, optFuncs ...EncodeOptionFunc) error { + ctx := encoder.TakeRuntimeContext() + ctx.Option.Flag = 0 + + err := e.encodeWithOption(ctx, v, optFuncs...) + + encoder.ReleaseRuntimeContext(ctx) + return err +} + +// EncodeContext call Encode with context.Context and EncodeOption. +func (e *Encoder) EncodeContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) error { + rctx := encoder.TakeRuntimeContext() + rctx.Option.Flag = 0 + rctx.Option.Flag |= encoder.ContextOption + rctx.Option.Context = ctx + + err := e.encodeWithOption(rctx, v, optFuncs...) + + encoder.ReleaseRuntimeContext(rctx) + return err +} + +func (e *Encoder) encodeWithOption(ctx *encoder.RuntimeContext, v interface{}, optFuncs ...EncodeOptionFunc) error { + if e.enabledHTMLEscape { + ctx.Option.Flag |= encoder.HTMLEscapeOption + } + for _, optFunc := range optFuncs { + optFunc(ctx.Option) + } + var ( + buf []byte + err error + ) + if e.enabledIndent { + buf, err = encodeIndent(ctx, v, e.prefix, e.indentStr) + } else { + buf, err = encode(ctx, v) + } + if err != nil { + return err + } + if e.enabledIndent { + buf = buf[:len(buf)-2] + } else { + buf = buf[:len(buf)-1] + } + buf = append(buf, '\n') + if _, err := e.w.Write(buf); err != nil { + return err + } + return nil +} + +// SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. +// The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML. +// +// In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior. +func (e *Encoder) SetEscapeHTML(on bool) { + e.enabledHTMLEscape = on +} + +// SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). +// Calling SetIndent("", "") disables indentation. +func (e *Encoder) SetIndent(prefix, indent string) { + if prefix == "" && indent == "" { + e.enabledIndent = false + return + } + e.prefix = prefix + e.indentStr = indent + e.enabledIndent = true +} + +func marshalContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { + rctx := encoder.TakeRuntimeContext() + rctx.Option.Flag = 0 + rctx.Option.Flag = encoder.HTMLEscapeOption | encoder.ContextOption + rctx.Option.Context = ctx + for _, optFunc := range optFuncs { + optFunc(rctx.Option) + } + + buf, err := encode(rctx, v) + if err != nil { + encoder.ReleaseRuntimeContext(rctx) + return nil, err + } + + // this line exists to escape call of `runtime.makeslicecopy` . + // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`, + // dst buffer size and src buffer size are differrent. + // in this case, compiler uses `runtime.makeslicecopy`, but it is slow. + buf = buf[:len(buf)-1] + copied := make([]byte, len(buf)) + copy(copied, buf) + + encoder.ReleaseRuntimeContext(rctx) + return copied, nil +} + +func marshal(v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { + ctx := encoder.TakeRuntimeContext() + + ctx.Option.Flag = 0 + ctx.Option.Flag |= encoder.HTMLEscapeOption + for _, optFunc := range optFuncs { + optFunc(ctx.Option) + } + + buf, err := encode(ctx, v) + if err != nil { + encoder.ReleaseRuntimeContext(ctx) + return nil, err + } + + // this line exists to escape call of `runtime.makeslicecopy` . + // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`, + // dst buffer size and src buffer size are differrent. + // in this case, compiler uses `runtime.makeslicecopy`, but it is slow. + buf = buf[:len(buf)-1] + copied := make([]byte, len(buf)) + copy(copied, buf) + + encoder.ReleaseRuntimeContext(ctx) + return copied, nil +} + +func marshalNoEscape(v interface{}) ([]byte, error) { + ctx := encoder.TakeRuntimeContext() + + ctx.Option.Flag = 0 + ctx.Option.Flag |= encoder.HTMLEscapeOption + + buf, err := encodeNoEscape(ctx, v) + if err != nil { + encoder.ReleaseRuntimeContext(ctx) + return nil, err + } + + // this line exists to escape call of `runtime.makeslicecopy` . + // if use `make([]byte, len(buf)-1)` and `copy(copied, buf)`, + // dst buffer size and src buffer size are differrent. + // in this case, compiler uses `runtime.makeslicecopy`, but it is slow. + buf = buf[:len(buf)-1] + copied := make([]byte, len(buf)) + copy(copied, buf) + + encoder.ReleaseRuntimeContext(ctx) + return copied, nil +} + +func marshalIndent(v interface{}, prefix, indent string, optFuncs ...EncodeOptionFunc) ([]byte, error) { + ctx := encoder.TakeRuntimeContext() + + ctx.Option.Flag = 0 + ctx.Option.Flag |= (encoder.HTMLEscapeOption | encoder.IndentOption) + for _, optFunc := range optFuncs { + optFunc(ctx.Option) + } + + buf, err := encodeIndent(ctx, v, prefix, indent) + if err != nil { + encoder.ReleaseRuntimeContext(ctx) + return nil, err + } + + buf = buf[:len(buf)-2] + copied := make([]byte, len(buf)) + copy(copied, buf) + + encoder.ReleaseRuntimeContext(ctx) + return copied, nil +} + +func encode(ctx *encoder.RuntimeContext, v interface{}) ([]byte, error) { + b := ctx.Buf[:0] + if v == nil { + b = encoder.AppendNull(ctx, b) + b = encoder.AppendComma(ctx, b) + return b, nil + } + header := (*emptyInterface)(unsafe.Pointer(&v)) + typ := header.typ + + typeptr := uintptr(unsafe.Pointer(typ)) + codeSet, err := encoder.CompileToGetCodeSet(typeptr) + if err != nil { + return nil, err + } + + p := uintptr(header.ptr) + ctx.Init(p, codeSet.CodeLength) + ctx.KeepRefs = append(ctx.KeepRefs, header.ptr) + + buf, err := encodeRunCode(ctx, b, codeSet) + if err != nil { + return nil, err + } + ctx.Buf = buf + return buf, nil +} + +func encodeNoEscape(ctx *encoder.RuntimeContext, v interface{}) ([]byte, error) { + b := ctx.Buf[:0] + if v == nil { + b = encoder.AppendNull(ctx, b) + b = encoder.AppendComma(ctx, b) + return b, nil + } + header := (*emptyInterface)(unsafe.Pointer(&v)) + typ := header.typ + + typeptr := uintptr(unsafe.Pointer(typ)) + codeSet, err := encoder.CompileToGetCodeSet(typeptr) + if err != nil { + return nil, err + } + + p := uintptr(header.ptr) + ctx.Init(p, codeSet.CodeLength) + buf, err := encodeRunCode(ctx, b, codeSet) + if err != nil { + return nil, err + } + + ctx.Buf = buf + return buf, nil +} + +func encodeIndent(ctx *encoder.RuntimeContext, v interface{}, prefix, indent string) ([]byte, error) { + b := ctx.Buf[:0] + if v == nil { + b = encoder.AppendNull(ctx, b) + b = encoder.AppendCommaIndent(ctx, b) + return b, nil + } + header := (*emptyInterface)(unsafe.Pointer(&v)) + typ := header.typ + + typeptr := uintptr(unsafe.Pointer(typ)) + codeSet, err := encoder.CompileToGetCodeSet(typeptr) + if err != nil { + return nil, err + } + + p := uintptr(header.ptr) + ctx.Init(p, codeSet.CodeLength) + buf, err := encodeRunIndentCode(ctx, b, codeSet, prefix, indent) + + ctx.KeepRefs = append(ctx.KeepRefs, header.ptr) + + if err != nil { + return nil, err + } + + ctx.Buf = buf + return buf, nil +} + +func encodeRunCode(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + if (ctx.Option.Flag & encoder.DebugOption) != 0 { + if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { + return vm_color.DebugRun(ctx, b, codeSet) + } + return vm.DebugRun(ctx, b, codeSet) + } + if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { + return vm_color.Run(ctx, b, codeSet) + } + return vm.Run(ctx, b, codeSet) +} + +func encodeRunIndentCode(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet, prefix, indent string) ([]byte, error) { + ctx.Prefix = []byte(prefix) + ctx.IndentStr = []byte(indent) + if (ctx.Option.Flag & encoder.DebugOption) != 0 { + if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { + return vm_color_indent.DebugRun(ctx, b, codeSet) + } + return vm_indent.DebugRun(ctx, b, codeSet) + } + if (ctx.Option.Flag & encoder.ColorizeOption) != 0 { + return vm_color_indent.Run(ctx, b, codeSet) + } + return vm_indent.Run(ctx, b, codeSet) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/error.go b/taskman-server/vendor/github.com/goccy/go-json/error.go new file mode 100644 index 00000000..94c1339a --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/error.go @@ -0,0 +1,39 @@ +package json + +import ( + "github.com/goccy/go-json/internal/errors" +) + +// Before Go 1.2, an InvalidUTF8Error was returned by Marshal when +// attempting to encode a string value with invalid UTF-8 sequences. +// As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by +// replacing invalid bytes with the Unicode replacement rune U+FFFD. +// +// Deprecated: No longer used; kept for compatibility. +type InvalidUTF8Error = errors.InvalidUTF8Error + +// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. +// (The argument to Unmarshal must be a non-nil pointer.) +type InvalidUnmarshalError = errors.InvalidUnmarshalError + +// A MarshalerError represents an error from calling a MarshalJSON or MarshalText method. +type MarshalerError = errors.MarshalerError + +// A SyntaxError is a description of a JSON syntax error. +type SyntaxError = errors.SyntaxError + +// An UnmarshalFieldError describes a JSON object key that +// led to an unexported (and therefore unwritable) struct field. +// +// Deprecated: No longer used; kept for compatibility. +type UnmarshalFieldError = errors.UnmarshalFieldError + +// An UnmarshalTypeError describes a JSON value that was +// not appropriate for a value of a specific Go type. +type UnmarshalTypeError = errors.UnmarshalTypeError + +// An UnsupportedTypeError is returned by Marshal when attempting +// to encode an unsupported value type. +type UnsupportedTypeError = errors.UnsupportedTypeError + +type UnsupportedValueError = errors.UnsupportedValueError diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/anonymous_field.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/anonymous_field.go new file mode 100644 index 00000000..030cb7a9 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/anonymous_field.go @@ -0,0 +1,37 @@ +package decoder + +import ( + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +type anonymousFieldDecoder struct { + structType *runtime.Type + offset uintptr + dec Decoder +} + +func newAnonymousFieldDecoder(structType *runtime.Type, offset uintptr, dec Decoder) *anonymousFieldDecoder { + return &anonymousFieldDecoder{ + structType: structType, + offset: offset, + dec: dec, + } +} + +func (d *anonymousFieldDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + if *(*unsafe.Pointer)(p) == nil { + *(*unsafe.Pointer)(p) = unsafe_New(d.structType) + } + p = *(*unsafe.Pointer)(p) + return d.dec.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+d.offset)) +} + +func (d *anonymousFieldDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + if *(*unsafe.Pointer)(p) == nil { + *(*unsafe.Pointer)(p) = unsafe_New(d.structType) + } + p = *(*unsafe.Pointer)(p) + return d.dec.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+d.offset)) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/array.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/array.go new file mode 100644 index 00000000..21f1fd58 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/array.go @@ -0,0 +1,169 @@ +package decoder + +import ( + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type arrayDecoder struct { + elemType *runtime.Type + size uintptr + valueDecoder Decoder + alen int + structName string + fieldName string + zeroValue unsafe.Pointer +} + +func newArrayDecoder(dec Decoder, elemType *runtime.Type, alen int, structName, fieldName string) *arrayDecoder { + zeroValue := *(*unsafe.Pointer)(unsafe_New(elemType)) + return &arrayDecoder{ + valueDecoder: dec, + elemType: elemType, + size: elemType.Size(), + alen: alen, + structName: structName, + fieldName: fieldName, + zeroValue: zeroValue, + } +} + +func (d *arrayDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + + for { + switch s.char() { + case ' ', '\n', '\t', '\r': + case 'n': + if err := nullBytes(s); err != nil { + return err + } + return nil + case '[': + idx := 0 + s.cursor++ + if s.skipWhiteSpace() == ']' { + for idx < d.alen { + *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue + idx++ + } + s.cursor++ + return nil + } + for { + if idx < d.alen { + if err := d.valueDecoder.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)); err != nil { + return err + } + } else { + if err := s.skipValue(depth); err != nil { + return err + } + } + idx++ + switch s.skipWhiteSpace() { + case ']': + for idx < d.alen { + *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue + idx++ + } + s.cursor++ + return nil + case ',': + s.cursor++ + continue + case nul: + if s.read() { + s.cursor++ + continue + } + goto ERROR + default: + goto ERROR + } + } + case nul: + if s.read() { + continue + } + goto ERROR + default: + goto ERROR + } + s.cursor++ + } +ERROR: + return errors.ErrUnexpectedEndOfJSON("array", s.totalOffset()) +} + +func (d *arrayDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + + for { + switch buf[cursor] { + case ' ', '\n', '\t', '\r': + cursor++ + continue + case 'n': + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + return cursor, nil + case '[': + idx := 0 + cursor++ + cursor = skipWhiteSpace(buf, cursor) + if buf[cursor] == ']' { + for idx < d.alen { + *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue + idx++ + } + cursor++ + return cursor, nil + } + for { + if idx < d.alen { + c, err := d.valueDecoder.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+uintptr(idx)*d.size)) + if err != nil { + return 0, err + } + cursor = c + } else { + c, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + cursor = c + } + idx++ + cursor = skipWhiteSpace(buf, cursor) + switch buf[cursor] { + case ']': + for idx < d.alen { + *(*unsafe.Pointer)(unsafe.Pointer(uintptr(p) + uintptr(idx)*d.size)) = d.zeroValue + idx++ + } + cursor++ + return cursor, nil + case ',': + cursor++ + continue + default: + return 0, errors.ErrInvalidCharacter(buf[cursor], "array", cursor) + } + } + default: + return 0, errors.ErrUnexpectedEndOfJSON("array", cursor) + } + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bool.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bool.go new file mode 100644 index 00000000..455042a5 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bool.go @@ -0,0 +1,78 @@ +package decoder + +import ( + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +type boolDecoder struct { + structName string + fieldName string +} + +func newBoolDecoder(structName, fieldName string) *boolDecoder { + return &boolDecoder{structName: structName, fieldName: fieldName} +} + +func (d *boolDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + c := s.skipWhiteSpace() + for { + switch c { + case 't': + if err := trueBytes(s); err != nil { + return err + } + **(**bool)(unsafe.Pointer(&p)) = true + return nil + case 'f': + if err := falseBytes(s); err != nil { + return err + } + **(**bool)(unsafe.Pointer(&p)) = false + return nil + case 'n': + if err := nullBytes(s); err != nil { + return err + } + return nil + case nul: + if s.read() { + c = s.char() + continue + } + goto ERROR + } + break + } +ERROR: + return errors.ErrUnexpectedEndOfJSON("bool", s.totalOffset()) +} + +func (d *boolDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + cursor = skipWhiteSpace(buf, cursor) + switch buf[cursor] { + case 't': + if err := validateTrue(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + **(**bool)(unsafe.Pointer(&p)) = true + return cursor, nil + case 'f': + if err := validateFalse(buf, cursor); err != nil { + return 0, err + } + cursor += 5 + **(**bool)(unsafe.Pointer(&p)) = false + return cursor, nil + case 'n': + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + return cursor, nil + } + return 0, errors.ErrUnexpectedEndOfJSON("bool", cursor) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bytes.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bytes.go new file mode 100644 index 00000000..01a37fef --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/bytes.go @@ -0,0 +1,114 @@ +package decoder + +import ( + "encoding/base64" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type bytesDecoder struct { + typ *runtime.Type + sliceDecoder Decoder + stringDecoder *stringDecoder + structName string + fieldName string +} + +func byteUnmarshalerSliceDecoder(typ *runtime.Type, structName string, fieldName string) Decoder { + var unmarshalDecoder Decoder + switch { + case runtime.PtrTo(typ).Implements(unmarshalJSONType): + unmarshalDecoder = newUnmarshalJSONDecoder(runtime.PtrTo(typ), structName, fieldName) + case runtime.PtrTo(typ).Implements(unmarshalTextType): + unmarshalDecoder = newUnmarshalTextDecoder(runtime.PtrTo(typ), structName, fieldName) + } + if unmarshalDecoder == nil { + return nil + } + return newSliceDecoder(unmarshalDecoder, typ, 1, structName, fieldName) +} + +func newBytesDecoder(typ *runtime.Type, structName string, fieldName string) *bytesDecoder { + return &bytesDecoder{ + typ: typ, + sliceDecoder: byteUnmarshalerSliceDecoder(typ, structName, fieldName), + stringDecoder: newStringDecoder(structName, fieldName), + structName: structName, + fieldName: fieldName, + } +} + +func (d *bytesDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + bytes, err := d.decodeStreamBinary(s, depth, p) + if err != nil { + return err + } + if bytes == nil { + s.reset() + return nil + } + decodedLen := base64.StdEncoding.DecodedLen(len(bytes)) + buf := make([]byte, decodedLen) + n, err := base64.StdEncoding.Decode(buf, bytes) + if err != nil { + return err + } + *(*[]byte)(p) = buf[:n] + s.reset() + return nil +} + +func (d *bytesDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + bytes, c, err := d.decodeBinary(ctx, cursor, depth, p) + if err != nil { + return 0, err + } + if bytes == nil { + return c, nil + } + cursor = c + decodedLen := base64.StdEncoding.DecodedLen(len(bytes)) + b := make([]byte, decodedLen) + n, err := base64.StdEncoding.Decode(b, bytes) + if err != nil { + return 0, err + } + *(*[]byte)(p) = b[:n] + return cursor, nil +} + +func (d *bytesDecoder) decodeStreamBinary(s *Stream, depth int64, p unsafe.Pointer) ([]byte, error) { + c := s.skipWhiteSpace() + if c == '[' { + if d.sliceDecoder == nil { + return nil, &errors.UnmarshalTypeError{ + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + } + err := d.sliceDecoder.DecodeStream(s, depth, p) + return nil, err + } + return d.stringDecoder.decodeStreamByte(s) +} + +func (d *bytesDecoder) decodeBinary(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) ([]byte, int64, error) { + buf := ctx.Buf + cursor = skipWhiteSpace(buf, cursor) + if buf[cursor] == '[' { + if d.sliceDecoder == nil { + return nil, 0, &errors.UnmarshalTypeError{ + Type: runtime.RType2Type(d.typ), + Offset: cursor, + } + } + c, err := d.sliceDecoder.Decode(ctx, cursor, depth, p) + if err != nil { + return nil, 0, err + } + return nil, c, nil + } + return d.stringDecoder.decodeByte(buf, cursor) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile.go new file mode 100644 index 00000000..08dd044e --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile.go @@ -0,0 +1,510 @@ +package decoder + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" + "sync/atomic" + "unicode" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +var ( + jsonNumberType = reflect.TypeOf(json.Number("")) + typeAddr *runtime.TypeAddr + cachedDecoderMap unsafe.Pointer // map[uintptr]decoder + cachedDecoder []Decoder +) + +func init() { + typeAddr = runtime.AnalyzeTypeAddr() + if typeAddr == nil { + typeAddr = &runtime.TypeAddr{} + } + cachedDecoder = make([]Decoder, typeAddr.AddrRange>>typeAddr.AddrShift) +} + +func loadDecoderMap() map[uintptr]Decoder { + p := atomic.LoadPointer(&cachedDecoderMap) + return *(*map[uintptr]Decoder)(unsafe.Pointer(&p)) +} + +func storeDecoder(typ uintptr, dec Decoder, m map[uintptr]Decoder) { + newDecoderMap := make(map[uintptr]Decoder, len(m)+1) + newDecoderMap[typ] = dec + + for k, v := range m { + newDecoderMap[k] = v + } + + atomic.StorePointer(&cachedDecoderMap, *(*unsafe.Pointer)(unsafe.Pointer(&newDecoderMap))) +} + +func compileToGetDecoderSlowPath(typeptr uintptr, typ *runtime.Type) (Decoder, error) { + decoderMap := loadDecoderMap() + if dec, exists := decoderMap[typeptr]; exists { + return dec, nil + } + + dec, err := compileHead(typ, map[uintptr]Decoder{}) + if err != nil { + return nil, err + } + storeDecoder(typeptr, dec, decoderMap) + return dec, nil +} + +func compileHead(typ *runtime.Type, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + switch { + case implementsUnmarshalJSONType(runtime.PtrTo(typ)): + return newUnmarshalJSONDecoder(runtime.PtrTo(typ), "", ""), nil + case runtime.PtrTo(typ).Implements(unmarshalTextType): + return newUnmarshalTextDecoder(runtime.PtrTo(typ), "", ""), nil + } + return compile(typ.Elem(), "", "", structTypeToDecoder) +} + +func compile(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + switch { + case implementsUnmarshalJSONType(runtime.PtrTo(typ)): + return newUnmarshalJSONDecoder(runtime.PtrTo(typ), structName, fieldName), nil + case runtime.PtrTo(typ).Implements(unmarshalTextType): + return newUnmarshalTextDecoder(runtime.PtrTo(typ), structName, fieldName), nil + } + + switch typ.Kind() { + case reflect.Ptr: + return compilePtr(typ, structName, fieldName, structTypeToDecoder) + case reflect.Struct: + return compileStruct(typ, structName, fieldName, structTypeToDecoder) + case reflect.Slice: + elem := typ.Elem() + if elem.Kind() == reflect.Uint8 { + return compileBytes(elem, structName, fieldName) + } + return compileSlice(typ, structName, fieldName, structTypeToDecoder) + case reflect.Array: + return compileArray(typ, structName, fieldName, structTypeToDecoder) + case reflect.Map: + return compileMap(typ, structName, fieldName, structTypeToDecoder) + case reflect.Interface: + return compileInterface(typ, structName, fieldName) + case reflect.Uintptr: + return compileUint(typ, structName, fieldName) + case reflect.Int: + return compileInt(typ, structName, fieldName) + case reflect.Int8: + return compileInt8(typ, structName, fieldName) + case reflect.Int16: + return compileInt16(typ, structName, fieldName) + case reflect.Int32: + return compileInt32(typ, structName, fieldName) + case reflect.Int64: + return compileInt64(typ, structName, fieldName) + case reflect.Uint: + return compileUint(typ, structName, fieldName) + case reflect.Uint8: + return compileUint8(typ, structName, fieldName) + case reflect.Uint16: + return compileUint16(typ, structName, fieldName) + case reflect.Uint32: + return compileUint32(typ, structName, fieldName) + case reflect.Uint64: + return compileUint64(typ, structName, fieldName) + case reflect.String: + return compileString(typ, structName, fieldName) + case reflect.Bool: + return compileBool(structName, fieldName) + case reflect.Float32: + return compileFloat32(structName, fieldName) + case reflect.Float64: + return compileFloat64(structName, fieldName) + case reflect.Func: + return compileFunc(typ, structName, fieldName) + } + return nil, &errors.UnmarshalTypeError{ + Value: "object", + Type: runtime.RType2Type(typ), + Offset: 0, + Struct: structName, + Field: fieldName, + } +} + +func isStringTagSupportedType(typ *runtime.Type) bool { + switch { + case implementsUnmarshalJSONType(runtime.PtrTo(typ)): + return false + case runtime.PtrTo(typ).Implements(unmarshalTextType): + return false + } + switch typ.Kind() { + case reflect.Map: + return false + case reflect.Slice: + return false + case reflect.Array: + return false + case reflect.Struct: + return false + case reflect.Interface: + return false + } + return true +} + +func compileMapKey(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + if runtime.PtrTo(typ).Implements(unmarshalTextType) { + return newUnmarshalTextDecoder(runtime.PtrTo(typ), structName, fieldName), nil + } + dec, err := compile(typ, structName, fieldName, structTypeToDecoder) + if err != nil { + return nil, err + } + for { + switch t := dec.(type) { + case *stringDecoder, *interfaceDecoder: + return dec, nil + case *boolDecoder, *intDecoder, *uintDecoder, *numberDecoder: + return newWrappedStringDecoder(typ, dec, structName, fieldName), nil + case *ptrDecoder: + dec = t.dec + default: + goto ERROR + } + } +ERROR: + return nil, &errors.UnmarshalTypeError{ + Value: "object", + Type: runtime.RType2Type(typ), + Offset: 0, + Struct: structName, + Field: fieldName, + } +} + +func compilePtr(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + dec, err := compile(typ.Elem(), structName, fieldName, structTypeToDecoder) + if err != nil { + return nil, err + } + return newPtrDecoder(dec, typ.Elem(), structName, fieldName), nil +} + +func compileInt(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { + *(*int)(p) = int(v) + }), nil +} + +func compileInt8(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { + *(*int8)(p) = int8(v) + }), nil +} + +func compileInt16(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { + *(*int16)(p) = int16(v) + }), nil +} + +func compileInt32(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { + *(*int32)(p) = int32(v) + }), nil +} + +func compileInt64(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newIntDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v int64) { + *(*int64)(p) = v + }), nil +} + +func compileUint(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { + *(*uint)(p) = uint(v) + }), nil +} + +func compileUint8(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { + *(*uint8)(p) = uint8(v) + }), nil +} + +func compileUint16(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { + *(*uint16)(p) = uint16(v) + }), nil +} + +func compileUint32(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { + *(*uint32)(p) = uint32(v) + }), nil +} + +func compileUint64(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newUintDecoder(typ, structName, fieldName, func(p unsafe.Pointer, v uint64) { + *(*uint64)(p) = v + }), nil +} + +func compileFloat32(structName, fieldName string) (Decoder, error) { + return newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { + *(*float32)(p) = float32(v) + }), nil +} + +func compileFloat64(structName, fieldName string) (Decoder, error) { + return newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { + *(*float64)(p) = v + }), nil +} + +func compileString(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + if typ == runtime.Type2RType(jsonNumberType) { + return newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) { + *(*json.Number)(p) = v + }), nil + } + return newStringDecoder(structName, fieldName), nil +} + +func compileBool(structName, fieldName string) (Decoder, error) { + return newBoolDecoder(structName, fieldName), nil +} + +func compileBytes(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newBytesDecoder(typ, structName, fieldName), nil +} + +func compileSlice(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + elem := typ.Elem() + decoder, err := compile(elem, structName, fieldName, structTypeToDecoder) + if err != nil { + return nil, err + } + return newSliceDecoder(decoder, elem, elem.Size(), structName, fieldName), nil +} + +func compileArray(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + elem := typ.Elem() + decoder, err := compile(elem, structName, fieldName, structTypeToDecoder) + if err != nil { + return nil, err + } + return newArrayDecoder(decoder, elem, typ.Len(), structName, fieldName), nil +} + +func compileMap(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + keyDec, err := compileMapKey(typ.Key(), structName, fieldName, structTypeToDecoder) + if err != nil { + return nil, err + } + valueDec, err := compile(typ.Elem(), structName, fieldName, structTypeToDecoder) + if err != nil { + return nil, err + } + return newMapDecoder(typ, typ.Key(), keyDec, typ.Elem(), valueDec, structName, fieldName), nil +} + +func compileInterface(typ *runtime.Type, structName, fieldName string) (Decoder, error) { + return newInterfaceDecoder(typ, structName, fieldName), nil +} + +func compileFunc(typ *runtime.Type, strutName, fieldName string) (Decoder, error) { + return newFuncDecoder(typ, strutName, fieldName), nil +} + +func removeConflictFields(fieldMap map[string]*structFieldSet, conflictedMap map[string]struct{}, dec *structDecoder, field reflect.StructField) { + for k, v := range dec.fieldMap { + if _, exists := conflictedMap[k]; exists { + // already conflicted key + continue + } + set, exists := fieldMap[k] + if !exists { + fieldSet := &structFieldSet{ + dec: v.dec, + offset: field.Offset + v.offset, + isTaggedKey: v.isTaggedKey, + key: k, + keyLen: int64(len(k)), + } + fieldMap[k] = fieldSet + lower := strings.ToLower(k) + if _, exists := fieldMap[lower]; !exists { + fieldMap[lower] = fieldSet + } + continue + } + if set.isTaggedKey { + if v.isTaggedKey { + // conflict tag key + delete(fieldMap, k) + delete(fieldMap, strings.ToLower(k)) + conflictedMap[k] = struct{}{} + conflictedMap[strings.ToLower(k)] = struct{}{} + } + } else { + if v.isTaggedKey { + fieldSet := &structFieldSet{ + dec: v.dec, + offset: field.Offset + v.offset, + isTaggedKey: v.isTaggedKey, + key: k, + keyLen: int64(len(k)), + } + fieldMap[k] = fieldSet + lower := strings.ToLower(k) + if _, exists := fieldMap[lower]; !exists { + fieldMap[lower] = fieldSet + } + } else { + // conflict tag key + delete(fieldMap, k) + delete(fieldMap, strings.ToLower(k)) + conflictedMap[k] = struct{}{} + conflictedMap[strings.ToLower(k)] = struct{}{} + } + } + } +} + +func compileStruct(typ *runtime.Type, structName, fieldName string, structTypeToDecoder map[uintptr]Decoder) (Decoder, error) { + fieldNum := typ.NumField() + conflictedMap := map[string]struct{}{} + fieldMap := map[string]*structFieldSet{} + typeptr := uintptr(unsafe.Pointer(typ)) + if dec, exists := structTypeToDecoder[typeptr]; exists { + return dec, nil + } + structDec := newStructDecoder(structName, fieldName, fieldMap) + structTypeToDecoder[typeptr] = structDec + structName = typ.Name() + for i := 0; i < fieldNum; i++ { + field := typ.Field(i) + if runtime.IsIgnoredStructField(field) { + continue + } + isUnexportedField := unicode.IsLower([]rune(field.Name)[0]) + tag := runtime.StructTagFromField(field) + dec, err := compile(runtime.Type2RType(field.Type), structName, field.Name, structTypeToDecoder) + if err != nil { + return nil, err + } + if field.Anonymous && !tag.IsTaggedKey { + if stDec, ok := dec.(*structDecoder); ok { + if runtime.Type2RType(field.Type) == typ { + // recursive definition + continue + } + removeConflictFields(fieldMap, conflictedMap, stDec, field) + } else if pdec, ok := dec.(*ptrDecoder); ok { + contentDec := pdec.contentDecoder() + if pdec.typ == typ { + // recursive definition + continue + } + var fieldSetErr error + if isUnexportedField { + fieldSetErr = fmt.Errorf( + "json: cannot set embedded pointer to unexported struct: %v", + field.Type.Elem(), + ) + } + if dec, ok := contentDec.(*structDecoder); ok { + for k, v := range dec.fieldMap { + if _, exists := conflictedMap[k]; exists { + // already conflicted key + continue + } + set, exists := fieldMap[k] + if !exists { + fieldSet := &structFieldSet{ + dec: newAnonymousFieldDecoder(pdec.typ, v.offset, v.dec), + offset: field.Offset, + isTaggedKey: v.isTaggedKey, + key: k, + keyLen: int64(len(k)), + err: fieldSetErr, + } + fieldMap[k] = fieldSet + lower := strings.ToLower(k) + if _, exists := fieldMap[lower]; !exists { + fieldMap[lower] = fieldSet + } + continue + } + if set.isTaggedKey { + if v.isTaggedKey { + // conflict tag key + delete(fieldMap, k) + delete(fieldMap, strings.ToLower(k)) + conflictedMap[k] = struct{}{} + conflictedMap[strings.ToLower(k)] = struct{}{} + } + } else { + if v.isTaggedKey { + fieldSet := &structFieldSet{ + dec: newAnonymousFieldDecoder(pdec.typ, v.offset, v.dec), + offset: field.Offset, + isTaggedKey: v.isTaggedKey, + key: k, + keyLen: int64(len(k)), + err: fieldSetErr, + } + fieldMap[k] = fieldSet + lower := strings.ToLower(k) + if _, exists := fieldMap[lower]; !exists { + fieldMap[lower] = fieldSet + } + } else { + // conflict tag key + delete(fieldMap, k) + delete(fieldMap, strings.ToLower(k)) + conflictedMap[k] = struct{}{} + conflictedMap[strings.ToLower(k)] = struct{}{} + } + } + } + } + } + } else { + if tag.IsString && isStringTagSupportedType(runtime.Type2RType(field.Type)) { + dec = newWrappedStringDecoder(runtime.Type2RType(field.Type), dec, structName, field.Name) + } + var key string + if tag.Key != "" { + key = tag.Key + } else { + key = field.Name + } + fieldSet := &structFieldSet{ + dec: dec, + offset: field.Offset, + isTaggedKey: tag.IsTaggedKey, + key: key, + keyLen: int64(len(key)), + } + fieldMap[key] = fieldSet + lower := strings.ToLower(key) + if _, exists := fieldMap[lower]; !exists { + fieldMap[lower] = fieldSet + } + } + } + delete(structTypeToDecoder, typeptr) + structDec.tryOptimize() + return structDec, nil +} + +func implementsUnmarshalJSONType(typ *runtime.Type) bool { + return typ.Implements(unmarshalJSONType) || typ.Implements(unmarshalJSONContextType) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_norace.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_norace.go new file mode 100644 index 00000000..592f6373 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_norace.go @@ -0,0 +1,28 @@ +// +build !race + +package decoder + +import ( + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +func CompileToGetDecoder(typ *runtime.Type) (Decoder, error) { + typeptr := uintptr(unsafe.Pointer(typ)) + if typeptr > typeAddr.MaxTypeAddr { + return compileToGetDecoderSlowPath(typeptr, typ) + } + + index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift + if dec := cachedDecoder[index]; dec != nil { + return dec, nil + } + + dec, err := compileHead(typ, map[uintptr]Decoder{}) + if err != nil { + return nil, err + } + cachedDecoder[index] = dec + return dec, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_race.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_race.go new file mode 100644 index 00000000..b691bc94 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/compile_race.go @@ -0,0 +1,36 @@ +// +build race + +package decoder + +import ( + "sync" + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +var decMu sync.RWMutex + +func CompileToGetDecoder(typ *runtime.Type) (Decoder, error) { + typeptr := uintptr(unsafe.Pointer(typ)) + if typeptr > typeAddr.MaxTypeAddr { + return compileToGetDecoderSlowPath(typeptr, typ) + } + + index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift + decMu.RLock() + if dec := cachedDecoder[index]; dec != nil { + decMu.RUnlock() + return dec, nil + } + decMu.RUnlock() + + dec, err := compileHead(typ, map[uintptr]Decoder{}) + if err != nil { + return nil, err + } + decMu.Lock() + cachedDecoder[index] = dec + decMu.Unlock() + return dec, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/context.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/context.go new file mode 100644 index 00000000..cb2ffdaf --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/context.go @@ -0,0 +1,254 @@ +package decoder + +import ( + "sync" + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +type RuntimeContext struct { + Buf []byte + Option *Option +} + +var ( + runtimeContextPool = sync.Pool{ + New: func() interface{} { + return &RuntimeContext{ + Option: &Option{}, + } + }, + } +) + +func TakeRuntimeContext() *RuntimeContext { + return runtimeContextPool.Get().(*RuntimeContext) +} + +func ReleaseRuntimeContext(ctx *RuntimeContext) { + runtimeContextPool.Put(ctx) +} + +var ( + isWhiteSpace = [256]bool{} +) + +func init() { + isWhiteSpace[' '] = true + isWhiteSpace['\n'] = true + isWhiteSpace['\t'] = true + isWhiteSpace['\r'] = true +} + +func char(ptr unsafe.Pointer, offset int64) byte { + return *(*byte)(unsafe.Pointer(uintptr(ptr) + uintptr(offset))) +} + +func skipWhiteSpace(buf []byte, cursor int64) int64 { + for isWhiteSpace[buf[cursor]] { + cursor++ + } + return cursor +} + +func skipObject(buf []byte, cursor, depth int64) (int64, error) { + braceCount := 1 + for { + switch buf[cursor] { + case '{': + braceCount++ + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + case '}': + depth-- + braceCount-- + if braceCount == 0 { + return cursor + 1, nil + } + case '[': + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + case ']': + depth-- + case '"': + for { + cursor++ + switch buf[cursor] { + case '\\': + cursor++ + if buf[cursor] == nul { + return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + case '"': + goto SWITCH_OUT + case nul: + return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + } + case nul: + return 0, errors.ErrUnexpectedEndOfJSON("object of object", cursor) + } + SWITCH_OUT: + cursor++ + } +} + +func skipArray(buf []byte, cursor, depth int64) (int64, error) { + bracketCount := 1 + for { + switch buf[cursor] { + case '[': + bracketCount++ + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + case ']': + bracketCount-- + depth-- + if bracketCount == 0 { + return cursor + 1, nil + } + case '{': + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + case '}': + depth-- + case '"': + for { + cursor++ + switch buf[cursor] { + case '\\': + cursor++ + if buf[cursor] == nul { + return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + case '"': + goto SWITCH_OUT + case nul: + return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + } + case nul: + return 0, errors.ErrUnexpectedEndOfJSON("array of object", cursor) + } + SWITCH_OUT: + cursor++ + } +} + +func skipValue(buf []byte, cursor, depth int64) (int64, error) { + for { + switch buf[cursor] { + case ' ', '\t', '\n', '\r': + cursor++ + continue + case '{': + return skipObject(buf, cursor+1, depth+1) + case '[': + return skipArray(buf, cursor+1, depth+1) + case '"': + for { + cursor++ + switch buf[cursor] { + case '\\': + cursor++ + if buf[cursor] == nul { + return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + case '"': + return cursor + 1, nil + case nul: + return 0, errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + for { + cursor++ + if floatTable[buf[cursor]] { + continue + } + break + } + return cursor, nil + case 't': + if err := validateTrue(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + return cursor, nil + case 'f': + if err := validateFalse(buf, cursor); err != nil { + return 0, err + } + cursor += 5 + return cursor, nil + case 'n': + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + return cursor, nil + default: + return cursor, errors.ErrUnexpectedEndOfJSON("null", cursor) + } + } +} + +func validateTrue(buf []byte, cursor int64) error { + if cursor+3 >= int64(len(buf)) { + return errors.ErrUnexpectedEndOfJSON("true", cursor) + } + if buf[cursor+1] != 'r' { + return errors.ErrInvalidCharacter(buf[cursor+1], "true", cursor) + } + if buf[cursor+2] != 'u' { + return errors.ErrInvalidCharacter(buf[cursor+2], "true", cursor) + } + if buf[cursor+3] != 'e' { + return errors.ErrInvalidCharacter(buf[cursor+3], "true", cursor) + } + return nil +} + +func validateFalse(buf []byte, cursor int64) error { + if cursor+4 >= int64(len(buf)) { + return errors.ErrUnexpectedEndOfJSON("false", cursor) + } + if buf[cursor+1] != 'a' { + return errors.ErrInvalidCharacter(buf[cursor+1], "false", cursor) + } + if buf[cursor+2] != 'l' { + return errors.ErrInvalidCharacter(buf[cursor+2], "false", cursor) + } + if buf[cursor+3] != 's' { + return errors.ErrInvalidCharacter(buf[cursor+3], "false", cursor) + } + if buf[cursor+4] != 'e' { + return errors.ErrInvalidCharacter(buf[cursor+4], "false", cursor) + } + return nil +} + +func validateNull(buf []byte, cursor int64) error { + if cursor+3 >= int64(len(buf)) { + return errors.ErrUnexpectedEndOfJSON("null", cursor) + } + if buf[cursor+1] != 'u' { + return errors.ErrInvalidCharacter(buf[cursor+1], "null", cursor) + } + if buf[cursor+2] != 'l' { + return errors.ErrInvalidCharacter(buf[cursor+2], "null", cursor) + } + if buf[cursor+3] != 'l' { + return errors.ErrInvalidCharacter(buf[cursor+3], "null", cursor) + } + return nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/float.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/float.go new file mode 100644 index 00000000..dfb7168d --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/float.go @@ -0,0 +1,158 @@ +package decoder + +import ( + "strconv" + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +type floatDecoder struct { + op func(unsafe.Pointer, float64) + structName string + fieldName string +} + +func newFloatDecoder(structName, fieldName string, op func(unsafe.Pointer, float64)) *floatDecoder { + return &floatDecoder{op: op, structName: structName, fieldName: fieldName} +} + +var ( + floatTable = [256]bool{ + '0': true, + '1': true, + '2': true, + '3': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '9': true, + '.': true, + 'e': true, + 'E': true, + '+': true, + '-': true, + } + + validEndNumberChar = [256]bool{ + nul: true, + ' ': true, + '\t': true, + '\r': true, + '\n': true, + ',': true, + ':': true, + '}': true, + ']': true, + } +) + +func floatBytes(s *Stream) []byte { + start := s.cursor + for { + s.cursor++ + if floatTable[s.char()] { + continue + } else if s.char() == nul { + if s.read() { + s.cursor-- // for retry current character + continue + } + } + break + } + return s.buf[start:s.cursor] +} + +func (d *floatDecoder) decodeStreamByte(s *Stream) ([]byte, error) { + for { + switch s.char() { + case ' ', '\n', '\t', '\r': + s.cursor++ + continue + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return floatBytes(s), nil + case 'n': + if err := nullBytes(s); err != nil { + return nil, err + } + return nil, nil + case nul: + if s.read() { + continue + } + goto ERROR + default: + goto ERROR + } + } +ERROR: + return nil, errors.ErrUnexpectedEndOfJSON("float", s.totalOffset()) +} + +func (d *floatDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { + for { + switch buf[cursor] { + case ' ', '\n', '\t', '\r': + cursor++ + continue + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + start := cursor + cursor++ + for floatTable[buf[cursor]] { + cursor++ + } + num := buf[start:cursor] + return num, cursor, nil + case 'n': + if err := validateNull(buf, cursor); err != nil { + return nil, 0, err + } + cursor += 4 + return nil, cursor, nil + default: + return nil, 0, errors.ErrUnexpectedEndOfJSON("float", cursor) + } + } +} + +func (d *floatDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + bytes, err := d.decodeStreamByte(s) + if err != nil { + return err + } + if bytes == nil { + return nil + } + str := *(*string)(unsafe.Pointer(&bytes)) + f64, err := strconv.ParseFloat(str, 64) + if err != nil { + return errors.ErrSyntax(err.Error(), s.totalOffset()) + } + d.op(p, f64) + return nil +} + +func (d *floatDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + bytes, c, err := d.decodeByte(buf, cursor) + if err != nil { + return 0, err + } + if bytes == nil { + return c, nil + } + cursor = c + if !validEndNumberChar[buf[cursor]] { + return 0, errors.ErrUnexpectedEndOfJSON("float", cursor) + } + s := *(*string)(unsafe.Pointer(&bytes)) + f64, err := strconv.ParseFloat(s, 64) + if err != nil { + return 0, errors.ErrSyntax(err.Error(), cursor) + } + d.op(p, f64) + return cursor, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/func.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/func.go new file mode 100644 index 00000000..ee356371 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/func.go @@ -0,0 +1,141 @@ +package decoder + +import ( + "bytes" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type funcDecoder struct { + typ *runtime.Type + structName string + fieldName string +} + +func newFuncDecoder(typ *runtime.Type, structName, fieldName string) *funcDecoder { + fnDecoder := &funcDecoder{typ, structName, fieldName} + return fnDecoder +} + +func (d *funcDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + s.skipWhiteSpace() + start := s.cursor + if err := s.skipValue(depth); err != nil { + return err + } + src := s.buf[start:s.cursor] + if len(src) > 0 { + switch src[0] { + case '"': + return &errors.UnmarshalTypeError{ + Value: "string", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + case '[': + return &errors.UnmarshalTypeError{ + Value: "array", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + case '{': + return &errors.UnmarshalTypeError{ + Value: "object", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return &errors.UnmarshalTypeError{ + Value: "number", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + case 'n': + if err := nullBytes(s); err != nil { + return err + } + *(*unsafe.Pointer)(p) = nil + return nil + case 't': + if err := trueBytes(s); err == nil { + return &errors.UnmarshalTypeError{ + Value: "boolean", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + } + case 'f': + if err := falseBytes(s); err == nil { + return &errors.UnmarshalTypeError{ + Value: "boolean", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + } + } + } + return errors.ErrInvalidBeginningOfValue(s.buf[s.cursor], s.totalOffset()) +} + +func (d *funcDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + cursor = skipWhiteSpace(buf, cursor) + start := cursor + end, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + src := buf[start:end] + if len(src) > 0 { + switch src[0] { + case '"': + return 0, &errors.UnmarshalTypeError{ + Value: "string", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + case '[': + return 0, &errors.UnmarshalTypeError{ + Value: "array", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + case '{': + return 0, &errors.UnmarshalTypeError{ + Value: "object", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return 0, &errors.UnmarshalTypeError{ + Value: "number", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + case 'n': + if bytes.Equal(src, nullbytes) { + *(*unsafe.Pointer)(p) = nil + return end, nil + } + case 't': + if err := validateTrue(buf, start); err == nil { + return 0, &errors.UnmarshalTypeError{ + Value: "boolean", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + } + case 'f': + if err := validateFalse(buf, start); err == nil { + return 0, &errors.UnmarshalTypeError{ + Value: "boolean", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + } + } + } + return cursor, errors.ErrInvalidBeginningOfValue(buf[cursor], cursor) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/int.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/int.go new file mode 100644 index 00000000..7edfb041 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/int.go @@ -0,0 +1,242 @@ +package decoder + +import ( + "fmt" + "reflect" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type intDecoder struct { + typ *runtime.Type + kind reflect.Kind + op func(unsafe.Pointer, int64) + structName string + fieldName string +} + +func newIntDecoder(typ *runtime.Type, structName, fieldName string, op func(unsafe.Pointer, int64)) *intDecoder { + return &intDecoder{ + typ: typ, + kind: typ.Kind(), + op: op, + structName: structName, + fieldName: fieldName, + } +} + +func (d *intDecoder) typeError(buf []byte, offset int64) *errors.UnmarshalTypeError { + return &errors.UnmarshalTypeError{ + Value: fmt.Sprintf("number %s", string(buf)), + Type: runtime.RType2Type(d.typ), + Struct: d.structName, + Field: d.fieldName, + Offset: offset, + } +} + +var ( + pow10i64 = [...]int64{ + 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, + } + pow10i64Len = len(pow10i64) +) + +func (d *intDecoder) parseInt(b []byte) (int64, error) { + isNegative := false + if b[0] == '-' { + b = b[1:] + isNegative = true + } + maxDigit := len(b) + if maxDigit > pow10i64Len { + return 0, fmt.Errorf("invalid length of number") + } + sum := int64(0) + for i := 0; i < maxDigit; i++ { + c := int64(b[i]) - 48 + digitValue := pow10i64[maxDigit-i-1] + sum += c * digitValue + } + if isNegative { + return -1 * sum, nil + } + return sum, nil +} + +var ( + numTable = [256]bool{ + '0': true, + '1': true, + '2': true, + '3': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '9': true, + } +) + +var ( + numZeroBuf = []byte{'0'} +) + +func (d *intDecoder) decodeStreamByte(s *Stream) ([]byte, error) { + for { + switch s.char() { + case ' ', '\n', '\t', '\r': + s.cursor++ + continue + case '-': + start := s.cursor + for { + s.cursor++ + if numTable[s.char()] { + continue + } else if s.char() == nul { + if s.read() { + s.cursor-- // for retry current character + continue + } + } + break + } + num := s.buf[start:s.cursor] + if len(num) < 2 { + goto ERROR + } + return num, nil + case '0': + s.cursor++ + return numZeroBuf, nil + case '1', '2', '3', '4', '5', '6', '7', '8', '9': + start := s.cursor + for { + s.cursor++ + if numTable[s.char()] { + continue + } else if s.char() == nul { + if s.read() { + s.cursor-- // for retry current character + continue + } + } + break + } + num := s.buf[start:s.cursor] + return num, nil + case 'n': + if err := nullBytes(s); err != nil { + return nil, err + } + return nil, nil + case nul: + if s.read() { + continue + } + goto ERROR + default: + return nil, d.typeError([]byte{s.char()}, s.totalOffset()) + } + } +ERROR: + return nil, errors.ErrUnexpectedEndOfJSON("number(integer)", s.totalOffset()) +} + +func (d *intDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { + b := (*sliceHeader)(unsafe.Pointer(&buf)).data + for { + switch char(b, cursor) { + case ' ', '\n', '\t', '\r': + cursor++ + continue + case '0': + cursor++ + return numZeroBuf, cursor, nil + case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': + start := cursor + cursor++ + for numTable[char(b, cursor)] { + cursor++ + } + num := buf[start:cursor] + return num, cursor, nil + case 'n': + if err := validateNull(buf, cursor); err != nil { + return nil, 0, err + } + cursor += 4 + return nil, cursor, nil + default: + return nil, 0, d.typeError([]byte{char(b, cursor)}, cursor) + } + } +} + +func (d *intDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + bytes, err := d.decodeStreamByte(s) + if err != nil { + return err + } + if bytes == nil { + return nil + } + i64, err := d.parseInt(bytes) + if err != nil { + return d.typeError(bytes, s.totalOffset()) + } + switch d.kind { + case reflect.Int8: + if i64 <= -1*(1<<7) || (1<<7) <= i64 { + return d.typeError(bytes, s.totalOffset()) + } + case reflect.Int16: + if i64 <= -1*(1<<15) || (1<<15) <= i64 { + return d.typeError(bytes, s.totalOffset()) + } + case reflect.Int32: + if i64 <= -1*(1<<31) || (1<<31) <= i64 { + return d.typeError(bytes, s.totalOffset()) + } + } + d.op(p, i64) + s.reset() + return nil +} + +func (d *intDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + bytes, c, err := d.decodeByte(ctx.Buf, cursor) + if err != nil { + return 0, err + } + if bytes == nil { + return c, nil + } + cursor = c + + i64, err := d.parseInt(bytes) + if err != nil { + return 0, d.typeError(bytes, cursor) + } + switch d.kind { + case reflect.Int8: + if i64 <= -1*(1<<7) || (1<<7) <= i64 { + return 0, d.typeError(bytes, cursor) + } + case reflect.Int16: + if i64 <= -1*(1<<15) || (1<<15) <= i64 { + return 0, d.typeError(bytes, cursor) + } + case reflect.Int32: + if i64 <= -1*(1<<31) || (1<<31) <= i64 { + return 0, d.typeError(bytes, cursor) + } + } + d.op(p, i64) + return cursor, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/interface.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/interface.go new file mode 100644 index 00000000..4dbb4be4 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/interface.go @@ -0,0 +1,458 @@ +package decoder + +import ( + "bytes" + "encoding" + "encoding/json" + "reflect" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type interfaceDecoder struct { + typ *runtime.Type + structName string + fieldName string + sliceDecoder *sliceDecoder + mapDecoder *mapDecoder + floatDecoder *floatDecoder + numberDecoder *numberDecoder + stringDecoder *stringDecoder +} + +func newEmptyInterfaceDecoder(structName, fieldName string) *interfaceDecoder { + ifaceDecoder := &interfaceDecoder{ + typ: emptyInterfaceType, + structName: structName, + fieldName: fieldName, + floatDecoder: newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { + *(*interface{})(p) = v + }), + numberDecoder: newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) { + *(*interface{})(p) = v + }), + stringDecoder: newStringDecoder(structName, fieldName), + } + ifaceDecoder.sliceDecoder = newSliceDecoder( + ifaceDecoder, + emptyInterfaceType, + emptyInterfaceType.Size(), + structName, fieldName, + ) + ifaceDecoder.mapDecoder = newMapDecoder( + interfaceMapType, + stringType, + ifaceDecoder.stringDecoder, + interfaceMapType.Elem(), + ifaceDecoder, + structName, + fieldName, + ) + return ifaceDecoder +} + +func newInterfaceDecoder(typ *runtime.Type, structName, fieldName string) *interfaceDecoder { + emptyIfaceDecoder := newEmptyInterfaceDecoder(structName, fieldName) + stringDecoder := newStringDecoder(structName, fieldName) + return &interfaceDecoder{ + typ: typ, + structName: structName, + fieldName: fieldName, + sliceDecoder: newSliceDecoder( + emptyIfaceDecoder, + emptyInterfaceType, + emptyInterfaceType.Size(), + structName, fieldName, + ), + mapDecoder: newMapDecoder( + interfaceMapType, + stringType, + stringDecoder, + interfaceMapType.Elem(), + emptyIfaceDecoder, + structName, + fieldName, + ), + floatDecoder: newFloatDecoder(structName, fieldName, func(p unsafe.Pointer, v float64) { + *(*interface{})(p) = v + }), + numberDecoder: newNumberDecoder(structName, fieldName, func(p unsafe.Pointer, v json.Number) { + *(*interface{})(p) = v + }), + stringDecoder: stringDecoder, + } +} + +func (d *interfaceDecoder) numDecoder(s *Stream) Decoder { + if s.UseNumber { + return d.numberDecoder + } + return d.floatDecoder +} + +var ( + emptyInterfaceType = runtime.Type2RType(reflect.TypeOf((*interface{})(nil)).Elem()) + interfaceMapType = runtime.Type2RType( + reflect.TypeOf((*map[string]interface{})(nil)).Elem(), + ) + stringType = runtime.Type2RType( + reflect.TypeOf(""), + ) +) + +func decodeStreamUnmarshaler(s *Stream, depth int64, unmarshaler json.Unmarshaler) error { + start := s.cursor + if err := s.skipValue(depth); err != nil { + return err + } + src := s.buf[start:s.cursor] + dst := make([]byte, len(src)) + copy(dst, src) + + if err := unmarshaler.UnmarshalJSON(dst); err != nil { + return err + } + return nil +} + +func decodeStreamUnmarshalerContext(s *Stream, depth int64, unmarshaler unmarshalerContext) error { + start := s.cursor + if err := s.skipValue(depth); err != nil { + return err + } + src := s.buf[start:s.cursor] + dst := make([]byte, len(src)) + copy(dst, src) + + if err := unmarshaler.UnmarshalJSON(s.Option.Context, dst); err != nil { + return err + } + return nil +} + +func decodeUnmarshaler(buf []byte, cursor, depth int64, unmarshaler json.Unmarshaler) (int64, error) { + cursor = skipWhiteSpace(buf, cursor) + start := cursor + end, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + src := buf[start:end] + dst := make([]byte, len(src)) + copy(dst, src) + + if err := unmarshaler.UnmarshalJSON(dst); err != nil { + return 0, err + } + return end, nil +} + +func decodeUnmarshalerContext(ctx *RuntimeContext, buf []byte, cursor, depth int64, unmarshaler unmarshalerContext) (int64, error) { + cursor = skipWhiteSpace(buf, cursor) + start := cursor + end, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + src := buf[start:end] + dst := make([]byte, len(src)) + copy(dst, src) + + if err := unmarshaler.UnmarshalJSON(ctx.Option.Context, dst); err != nil { + return 0, err + } + return end, nil +} + +func decodeStreamTextUnmarshaler(s *Stream, depth int64, unmarshaler encoding.TextUnmarshaler, p unsafe.Pointer) error { + start := s.cursor + if err := s.skipValue(depth); err != nil { + return err + } + src := s.buf[start:s.cursor] + if bytes.Equal(src, nullbytes) { + *(*unsafe.Pointer)(p) = nil + return nil + } + + dst := make([]byte, len(src)) + copy(dst, src) + + if err := unmarshaler.UnmarshalText(dst); err != nil { + return err + } + return nil +} + +func decodeTextUnmarshaler(buf []byte, cursor, depth int64, unmarshaler encoding.TextUnmarshaler, p unsafe.Pointer) (int64, error) { + cursor = skipWhiteSpace(buf, cursor) + start := cursor + end, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + src := buf[start:end] + if bytes.Equal(src, nullbytes) { + *(*unsafe.Pointer)(p) = nil + return end, nil + } + if s, ok := unquoteBytes(src); ok { + src = s + } + if err := unmarshaler.UnmarshalText(src); err != nil { + return 0, err + } + return end, nil +} + +func (d *interfaceDecoder) decodeStreamEmptyInterface(s *Stream, depth int64, p unsafe.Pointer) error { + c := s.skipWhiteSpace() + for { + switch c { + case '{': + var v map[string]interface{} + ptr := unsafe.Pointer(&v) + if err := d.mapDecoder.DecodeStream(s, depth, ptr); err != nil { + return err + } + *(*interface{})(p) = v + return nil + case '[': + var v []interface{} + ptr := unsafe.Pointer(&v) + if err := d.sliceDecoder.DecodeStream(s, depth, ptr); err != nil { + return err + } + *(*interface{})(p) = v + return nil + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return d.numDecoder(s).DecodeStream(s, depth, p) + case '"': + s.cursor++ + start := s.cursor + for { + switch s.char() { + case '\\': + if _, err := decodeEscapeString(s, nil); err != nil { + return err + } + case '"': + literal := s.buf[start:s.cursor] + s.cursor++ + *(*interface{})(p) = string(literal) + return nil + case nul: + if s.read() { + continue + } + return errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + } + s.cursor++ + } + case 't': + if err := trueBytes(s); err != nil { + return err + } + **(**interface{})(unsafe.Pointer(&p)) = true + return nil + case 'f': + if err := falseBytes(s); err != nil { + return err + } + **(**interface{})(unsafe.Pointer(&p)) = false + return nil + case 'n': + if err := nullBytes(s); err != nil { + return err + } + *(*interface{})(p) = nil + return nil + case nul: + if s.read() { + c = s.char() + continue + } + } + break + } + return errors.ErrInvalidBeginningOfValue(c, s.totalOffset()) +} + +type emptyInterface struct { + typ *runtime.Type + ptr unsafe.Pointer +} + +func (d *interfaceDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + runtimeInterfaceValue := *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: d.typ, + ptr: p, + })) + rv := reflect.ValueOf(runtimeInterfaceValue) + if rv.NumMethod() > 0 && rv.CanInterface() { + if u, ok := rv.Interface().(unmarshalerContext); ok { + return decodeStreamUnmarshalerContext(s, depth, u) + } + if u, ok := rv.Interface().(json.Unmarshaler); ok { + return decodeStreamUnmarshaler(s, depth, u) + } + if u, ok := rv.Interface().(encoding.TextUnmarshaler); ok { + return decodeStreamTextUnmarshaler(s, depth, u, p) + } + if s.skipWhiteSpace() == 'n' { + if err := nullBytes(s); err != nil { + return err + } + *(*interface{})(p) = nil + return nil + } + return d.errUnmarshalType(rv.Type(), s.totalOffset()) + } + iface := rv.Interface() + ifaceHeader := (*emptyInterface)(unsafe.Pointer(&iface)) + typ := ifaceHeader.typ + if ifaceHeader.ptr == nil || d.typ == typ || typ == nil { + // concrete type is empty interface + return d.decodeStreamEmptyInterface(s, depth, p) + } + if typ.Kind() == reflect.Ptr && typ.Elem() == d.typ || typ.Kind() != reflect.Ptr { + return d.decodeStreamEmptyInterface(s, depth, p) + } + if s.skipWhiteSpace() == 'n' { + if err := nullBytes(s); err != nil { + return err + } + *(*interface{})(p) = nil + return nil + } + decoder, err := CompileToGetDecoder(typ) + if err != nil { + return err + } + return decoder.DecodeStream(s, depth, ifaceHeader.ptr) +} + +func (d *interfaceDecoder) errUnmarshalType(typ reflect.Type, offset int64) *errors.UnmarshalTypeError { + return &errors.UnmarshalTypeError{ + Value: typ.String(), + Type: typ, + Offset: offset, + Struct: d.structName, + Field: d.fieldName, + } +} + +func (d *interfaceDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + runtimeInterfaceValue := *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: d.typ, + ptr: p, + })) + rv := reflect.ValueOf(runtimeInterfaceValue) + if rv.NumMethod() > 0 && rv.CanInterface() { + if u, ok := rv.Interface().(unmarshalerContext); ok { + return decodeUnmarshalerContext(ctx, buf, cursor, depth, u) + } + if u, ok := rv.Interface().(json.Unmarshaler); ok { + return decodeUnmarshaler(buf, cursor, depth, u) + } + if u, ok := rv.Interface().(encoding.TextUnmarshaler); ok { + return decodeTextUnmarshaler(buf, cursor, depth, u, p) + } + cursor = skipWhiteSpace(buf, cursor) + if buf[cursor] == 'n' { + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + **(**interface{})(unsafe.Pointer(&p)) = nil + return cursor, nil + } + return 0, d.errUnmarshalType(rv.Type(), cursor) + } + + iface := rv.Interface() + ifaceHeader := (*emptyInterface)(unsafe.Pointer(&iface)) + typ := ifaceHeader.typ + if ifaceHeader.ptr == nil || d.typ == typ || typ == nil { + // concrete type is empty interface + return d.decodeEmptyInterface(ctx, cursor, depth, p) + } + if typ.Kind() == reflect.Ptr && typ.Elem() == d.typ || typ.Kind() != reflect.Ptr { + return d.decodeEmptyInterface(ctx, cursor, depth, p) + } + cursor = skipWhiteSpace(buf, cursor) + if buf[cursor] == 'n' { + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + **(**interface{})(unsafe.Pointer(&p)) = nil + return cursor, nil + } + decoder, err := CompileToGetDecoder(typ) + if err != nil { + return 0, err + } + return decoder.Decode(ctx, cursor, depth, ifaceHeader.ptr) +} + +func (d *interfaceDecoder) decodeEmptyInterface(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + cursor = skipWhiteSpace(buf, cursor) + switch buf[cursor] { + case '{': + var v map[string]interface{} + ptr := unsafe.Pointer(&v) + cursor, err := d.mapDecoder.Decode(ctx, cursor, depth, ptr) + if err != nil { + return 0, err + } + **(**interface{})(unsafe.Pointer(&p)) = v + return cursor, nil + case '[': + var v []interface{} + ptr := unsafe.Pointer(&v) + cursor, err := d.sliceDecoder.Decode(ctx, cursor, depth, ptr) + if err != nil { + return 0, err + } + **(**interface{})(unsafe.Pointer(&p)) = v + return cursor, nil + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return d.floatDecoder.Decode(ctx, cursor, depth, p) + case '"': + var v string + ptr := unsafe.Pointer(&v) + cursor, err := d.stringDecoder.Decode(ctx, cursor, depth, ptr) + if err != nil { + return 0, err + } + **(**interface{})(unsafe.Pointer(&p)) = v + return cursor, nil + case 't': + if err := validateTrue(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + **(**interface{})(unsafe.Pointer(&p)) = true + return cursor, nil + case 'f': + if err := validateFalse(buf, cursor); err != nil { + return 0, err + } + cursor += 5 + **(**interface{})(unsafe.Pointer(&p)) = false + return cursor, nil + case 'n': + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + **(**interface{})(unsafe.Pointer(&p)) = nil + return cursor, nil + } + return cursor, errors.ErrInvalidBeginningOfValue(buf[cursor], cursor) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/map.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/map.go new file mode 100644 index 00000000..bb18ef99 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/map.go @@ -0,0 +1,186 @@ +package decoder + +import ( + "reflect" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type mapDecoder struct { + mapType *runtime.Type + keyType *runtime.Type + valueType *runtime.Type + canUseAssignFaststrType bool + keyDecoder Decoder + valueDecoder Decoder + structName string + fieldName string +} + +func newMapDecoder(mapType *runtime.Type, keyType *runtime.Type, keyDec Decoder, valueType *runtime.Type, valueDec Decoder, structName, fieldName string) *mapDecoder { + return &mapDecoder{ + mapType: mapType, + keyDecoder: keyDec, + keyType: keyType, + canUseAssignFaststrType: canUseAssignFaststrType(keyType, valueType), + valueType: valueType, + valueDecoder: valueDec, + structName: structName, + fieldName: fieldName, + } +} + +const ( + mapMaxElemSize = 128 +) + +// See detail: https://github.com/goccy/go-json/pull/283 +func canUseAssignFaststrType(key *runtime.Type, value *runtime.Type) bool { + indirectElem := value.Size() > mapMaxElemSize + if indirectElem { + return false + } + return key.Kind() == reflect.String +} + +//go:linkname makemap reflect.makemap +func makemap(*runtime.Type, int) unsafe.Pointer + +//nolint:golint +//go:linkname mapassign_faststr runtime.mapassign_faststr +//go:noescape +func mapassign_faststr(t *runtime.Type, m unsafe.Pointer, s string) unsafe.Pointer + +//go:linkname mapassign reflect.mapassign +//go:noescape +func mapassign(t *runtime.Type, m unsafe.Pointer, k, v unsafe.Pointer) + +func (d *mapDecoder) mapassign(t *runtime.Type, m, k, v unsafe.Pointer) { + if d.canUseAssignFaststrType { + mapV := mapassign_faststr(t, m, *(*string)(k)) + typedmemmove(d.valueType, mapV, v) + } else { + mapassign(t, m, k, v) + } +} + +func (d *mapDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + + switch s.skipWhiteSpace() { + case 'n': + if err := nullBytes(s); err != nil { + return err + } + **(**unsafe.Pointer)(unsafe.Pointer(&p)) = nil + return nil + case '{': + default: + return errors.ErrExpected("{ character for map value", s.totalOffset()) + } + mapValue := *(*unsafe.Pointer)(p) + if mapValue == nil { + mapValue = makemap(d.mapType, 0) + } + if s.buf[s.cursor+1] == '}' { + *(*unsafe.Pointer)(p) = mapValue + s.cursor += 2 + return nil + } + for { + s.cursor++ + k := unsafe_New(d.keyType) + if err := d.keyDecoder.DecodeStream(s, depth, k); err != nil { + return err + } + s.skipWhiteSpace() + if !s.equalChar(':') { + return errors.ErrExpected("colon after object key", s.totalOffset()) + } + s.cursor++ + v := unsafe_New(d.valueType) + if err := d.valueDecoder.DecodeStream(s, depth, v); err != nil { + return err + } + d.mapassign(d.mapType, mapValue, k, v) + s.skipWhiteSpace() + if s.equalChar('}') { + **(**unsafe.Pointer)(unsafe.Pointer(&p)) = mapValue + s.cursor++ + return nil + } + if !s.equalChar(',') { + return errors.ErrExpected("comma after object value", s.totalOffset()) + } + } +} + +func (d *mapDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + + cursor = skipWhiteSpace(buf, cursor) + buflen := int64(len(buf)) + if buflen < 2 { + return 0, errors.ErrExpected("{} for map", cursor) + } + switch buf[cursor] { + case 'n': + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + **(**unsafe.Pointer)(unsafe.Pointer(&p)) = nil + return cursor, nil + case '{': + default: + return 0, errors.ErrExpected("{ character for map value", cursor) + } + cursor++ + cursor = skipWhiteSpace(buf, cursor) + mapValue := *(*unsafe.Pointer)(p) + if mapValue == nil { + mapValue = makemap(d.mapType, 0) + } + if buf[cursor] == '}' { + **(**unsafe.Pointer)(unsafe.Pointer(&p)) = mapValue + cursor++ + return cursor, nil + } + for { + k := unsafe_New(d.keyType) + keyCursor, err := d.keyDecoder.Decode(ctx, cursor, depth, k) + if err != nil { + return 0, err + } + cursor = skipWhiteSpace(buf, keyCursor) + if buf[cursor] != ':' { + return 0, errors.ErrExpected("colon after object key", cursor) + } + cursor++ + v := unsafe_New(d.valueType) + valueCursor, err := d.valueDecoder.Decode(ctx, cursor, depth, v) + if err != nil { + return 0, err + } + d.mapassign(d.mapType, mapValue, k, v) + cursor = skipWhiteSpace(buf, valueCursor) + if buf[cursor] == '}' { + **(**unsafe.Pointer)(unsafe.Pointer(&p)) = mapValue + cursor++ + return cursor, nil + } + if buf[cursor] != ',' { + return 0, errors.ErrExpected("comma after object value", cursor) + } + cursor++ + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/number.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/number.go new file mode 100644 index 00000000..bf63773e --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/number.go @@ -0,0 +1,112 @@ +package decoder + +import ( + "encoding/json" + "strconv" + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +type numberDecoder struct { + stringDecoder *stringDecoder + op func(unsafe.Pointer, json.Number) + structName string + fieldName string +} + +func newNumberDecoder(structName, fieldName string, op func(unsafe.Pointer, json.Number)) *numberDecoder { + return &numberDecoder{ + stringDecoder: newStringDecoder(structName, fieldName), + op: op, + structName: structName, + fieldName: fieldName, + } +} + +func (d *numberDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + bytes, err := d.decodeStreamByte(s) + if err != nil { + return err + } + if _, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&bytes)), 64); err != nil { + return errors.ErrSyntax(err.Error(), s.totalOffset()) + } + d.op(p, json.Number(string(bytes))) + s.reset() + return nil +} + +func (d *numberDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + bytes, c, err := d.decodeByte(ctx.Buf, cursor) + if err != nil { + return 0, err + } + if _, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&bytes)), 64); err != nil { + return 0, errors.ErrSyntax(err.Error(), c) + } + cursor = c + s := *(*string)(unsafe.Pointer(&bytes)) + d.op(p, json.Number(s)) + return cursor, nil +} + +func (d *numberDecoder) decodeStreamByte(s *Stream) ([]byte, error) { + start := s.cursor + for { + switch s.char() { + case ' ', '\n', '\t', '\r': + s.cursor++ + continue + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return floatBytes(s), nil + case 'n': + if err := nullBytes(s); err != nil { + return nil, err + } + return nil, nil + case '"': + return d.stringDecoder.decodeStreamByte(s) + case nul: + if s.read() { + continue + } + goto ERROR + default: + goto ERROR + } + } +ERROR: + if s.cursor == start { + return nil, errors.ErrInvalidBeginningOfValue(s.char(), s.totalOffset()) + } + return nil, errors.ErrUnexpectedEndOfJSON("json.Number", s.totalOffset()) +} + +func (d *numberDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { + for { + switch buf[cursor] { + case ' ', '\n', '\t', '\r': + cursor++ + continue + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + start := cursor + cursor++ + for floatTable[buf[cursor]] { + cursor++ + } + num := buf[start:cursor] + return num, cursor, nil + case 'n': + if err := validateNull(buf, cursor); err != nil { + return nil, 0, err + } + cursor += 4 + return nil, cursor, nil + case '"': + return d.stringDecoder.decodeByte(buf, cursor) + default: + return nil, 0, errors.ErrUnexpectedEndOfJSON("json.Number", cursor) + } + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/option.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/option.go new file mode 100644 index 00000000..e41f876b --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/option.go @@ -0,0 +1,15 @@ +package decoder + +import "context" + +type OptionFlags uint8 + +const ( + FirstWinOption OptionFlags = 1 << iota + ContextOption +) + +type Option struct { + Flags OptionFlags + Context context.Context +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/ptr.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/ptr.go new file mode 100644 index 00000000..2c83b9c4 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/ptr.go @@ -0,0 +1,87 @@ +package decoder + +import ( + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +type ptrDecoder struct { + dec Decoder + typ *runtime.Type + structName string + fieldName string +} + +func newPtrDecoder(dec Decoder, typ *runtime.Type, structName, fieldName string) *ptrDecoder { + return &ptrDecoder{ + dec: dec, + typ: typ, + structName: structName, + fieldName: fieldName, + } +} + +func (d *ptrDecoder) contentDecoder() Decoder { + dec, ok := d.dec.(*ptrDecoder) + if !ok { + return d.dec + } + return dec.contentDecoder() +} + +//nolint:golint +//go:linkname unsafe_New reflect.unsafe_New +func unsafe_New(*runtime.Type) unsafe.Pointer + +func (d *ptrDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + if s.skipWhiteSpace() == nul { + s.read() + } + if s.char() == 'n' { + if err := nullBytes(s); err != nil { + return err + } + *(*unsafe.Pointer)(p) = nil + return nil + } + var newptr unsafe.Pointer + if *(*unsafe.Pointer)(p) == nil { + newptr = unsafe_New(d.typ) + *(*unsafe.Pointer)(p) = newptr + } else { + newptr = *(*unsafe.Pointer)(p) + } + if err := d.dec.DecodeStream(s, depth, newptr); err != nil { + return err + } + return nil +} + +func (d *ptrDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + cursor = skipWhiteSpace(buf, cursor) + if buf[cursor] == 'n' { + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + if p != nil { + *(*unsafe.Pointer)(p) = nil + } + cursor += 4 + return cursor, nil + } + var newptr unsafe.Pointer + if *(*unsafe.Pointer)(p) == nil { + newptr = unsafe_New(d.typ) + *(*unsafe.Pointer)(p) = newptr + } else { + newptr = *(*unsafe.Pointer)(p) + } + c, err := d.dec.Decode(ctx, cursor, depth, newptr) + if err != nil { + return 0, err + } + cursor = c + return cursor, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/slice.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/slice.go new file mode 100644 index 00000000..85b6e111 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/slice.go @@ -0,0 +1,301 @@ +package decoder + +import ( + "reflect" + "sync" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +var ( + sliceType = runtime.Type2RType( + reflect.TypeOf((*sliceHeader)(nil)).Elem(), + ) + nilSlice = unsafe.Pointer(&sliceHeader{}) +) + +type sliceDecoder struct { + elemType *runtime.Type + isElemPointerType bool + valueDecoder Decoder + size uintptr + arrayPool sync.Pool + structName string + fieldName string +} + +// If use reflect.SliceHeader, data type is uintptr. +// In this case, Go compiler cannot trace reference created by newArray(). +// So, define using unsafe.Pointer as data type +type sliceHeader struct { + data unsafe.Pointer + len int + cap int +} + +const ( + defaultSliceCapacity = 2 +) + +func newSliceDecoder(dec Decoder, elemType *runtime.Type, size uintptr, structName, fieldName string) *sliceDecoder { + return &sliceDecoder{ + valueDecoder: dec, + elemType: elemType, + isElemPointerType: elemType.Kind() == reflect.Ptr || elemType.Kind() == reflect.Map, + size: size, + arrayPool: sync.Pool{ + New: func() interface{} { + return &sliceHeader{ + data: newArray(elemType, defaultSliceCapacity), + len: 0, + cap: defaultSliceCapacity, + } + }, + }, + structName: structName, + fieldName: fieldName, + } +} + +func (d *sliceDecoder) newSlice(src *sliceHeader) *sliceHeader { + slice := d.arrayPool.Get().(*sliceHeader) + if src.len > 0 { + // copy original elem + if slice.cap < src.cap { + data := newArray(d.elemType, src.cap) + slice = &sliceHeader{data: data, len: src.len, cap: src.cap} + } else { + slice.len = src.len + } + copySlice(d.elemType, *slice, *src) + } else { + slice.len = 0 + } + return slice +} + +func (d *sliceDecoder) releaseSlice(p *sliceHeader) { + d.arrayPool.Put(p) +} + +//go:linkname copySlice reflect.typedslicecopy +func copySlice(elemType *runtime.Type, dst, src sliceHeader) int + +//go:linkname newArray reflect.unsafe_NewArray +func newArray(*runtime.Type, int) unsafe.Pointer + +//go:linkname typedmemmove reflect.typedmemmove +func typedmemmove(t *runtime.Type, dst, src unsafe.Pointer) + +func (d *sliceDecoder) errNumber(offset int64) *errors.UnmarshalTypeError { + return &errors.UnmarshalTypeError{ + Value: "number", + Type: reflect.SliceOf(runtime.RType2Type(d.elemType)), + Struct: d.structName, + Field: d.fieldName, + Offset: offset, + } +} + +func (d *sliceDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + + for { + switch s.char() { + case ' ', '\n', '\t', '\r': + s.cursor++ + continue + case 'n': + if err := nullBytes(s); err != nil { + return err + } + typedmemmove(sliceType, p, nilSlice) + return nil + case '[': + s.cursor++ + if s.skipWhiteSpace() == ']' { + dst := (*sliceHeader)(p) + if dst.data == nil { + dst.data = newArray(d.elemType, 0) + } else { + dst.len = 0 + } + s.cursor++ + return nil + } + idx := 0 + slice := d.newSlice((*sliceHeader)(p)) + srcLen := slice.len + capacity := slice.cap + data := slice.data + for { + if capacity <= idx { + src := sliceHeader{data: data, len: idx, cap: capacity} + capacity *= 2 + data = newArray(d.elemType, capacity) + dst := sliceHeader{data: data, len: idx, cap: capacity} + copySlice(d.elemType, dst, src) + } + ep := unsafe.Pointer(uintptr(data) + uintptr(idx)*d.size) + + // if srcLen is greater than idx, keep the original reference + if srcLen <= idx { + if d.isElemPointerType { + **(**unsafe.Pointer)(unsafe.Pointer(&ep)) = nil // initialize elem pointer + } else { + // assign new element to the slice + typedmemmove(d.elemType, ep, unsafe_New(d.elemType)) + } + } + + if err := d.valueDecoder.DecodeStream(s, depth, ep); err != nil { + return err + } + s.skipWhiteSpace() + RETRY: + switch s.char() { + case ']': + slice.cap = capacity + slice.len = idx + 1 + slice.data = data + dst := (*sliceHeader)(p) + dst.len = idx + 1 + if dst.len > dst.cap { + dst.data = newArray(d.elemType, dst.len) + dst.cap = dst.len + } + copySlice(d.elemType, *dst, *slice) + d.releaseSlice(slice) + s.cursor++ + return nil + case ',': + idx++ + case nul: + if s.read() { + goto RETRY + } + slice.cap = capacity + slice.data = data + d.releaseSlice(slice) + goto ERROR + default: + slice.cap = capacity + slice.data = data + d.releaseSlice(slice) + goto ERROR + } + s.cursor++ + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return d.errNumber(s.totalOffset()) + case nul: + if s.read() { + continue + } + goto ERROR + default: + goto ERROR + } + } +ERROR: + return errors.ErrUnexpectedEndOfJSON("slice", s.totalOffset()) +} + +func (d *sliceDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + + for { + switch buf[cursor] { + case ' ', '\n', '\t', '\r': + cursor++ + continue + case 'n': + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + typedmemmove(sliceType, p, nilSlice) + return cursor, nil + case '[': + cursor++ + cursor = skipWhiteSpace(buf, cursor) + if buf[cursor] == ']' { + dst := (*sliceHeader)(p) + if dst.data == nil { + dst.data = newArray(d.elemType, 0) + } else { + dst.len = 0 + } + cursor++ + return cursor, nil + } + idx := 0 + slice := d.newSlice((*sliceHeader)(p)) + srcLen := slice.len + capacity := slice.cap + data := slice.data + for { + if capacity <= idx { + src := sliceHeader{data: data, len: idx, cap: capacity} + capacity *= 2 + data = newArray(d.elemType, capacity) + dst := sliceHeader{data: data, len: idx, cap: capacity} + copySlice(d.elemType, dst, src) + } + ep := unsafe.Pointer(uintptr(data) + uintptr(idx)*d.size) + // if srcLen is greater than idx, keep the original reference + if srcLen <= idx { + if d.isElemPointerType { + **(**unsafe.Pointer)(unsafe.Pointer(&ep)) = nil // initialize elem pointer + } else { + // assign new element to the slice + typedmemmove(d.elemType, ep, unsafe_New(d.elemType)) + } + } + c, err := d.valueDecoder.Decode(ctx, cursor, depth, ep) + if err != nil { + return 0, err + } + cursor = c + cursor = skipWhiteSpace(buf, cursor) + switch buf[cursor] { + case ']': + slice.cap = capacity + slice.len = idx + 1 + slice.data = data + dst := (*sliceHeader)(p) + dst.len = idx + 1 + if dst.len > dst.cap { + dst.data = newArray(d.elemType, dst.len) + dst.cap = dst.len + } + copySlice(d.elemType, *dst, *slice) + d.releaseSlice(slice) + cursor++ + return cursor, nil + case ',': + idx++ + default: + slice.cap = capacity + slice.data = data + d.releaseSlice(slice) + return 0, errors.ErrInvalidCharacter(buf[cursor], "slice", cursor) + } + cursor++ + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return 0, d.errNumber(cursor) + default: + return 0, errors.ErrUnexpectedEndOfJSON("slice", cursor) + } + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/stream.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/stream.go new file mode 100644 index 00000000..c2746834 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/stream.go @@ -0,0 +1,554 @@ +package decoder + +import ( + "bytes" + "encoding/json" + "io" + "strconv" + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +const ( + initBufSize = 512 +) + +type Stream struct { + buf []byte + bufSize int64 + length int64 + r io.Reader + offset int64 + cursor int64 + filledBuffer bool + allRead bool + UseNumber bool + DisallowUnknownFields bool + Option *Option +} + +func NewStream(r io.Reader) *Stream { + return &Stream{ + r: r, + bufSize: initBufSize, + buf: make([]byte, initBufSize), + Option: &Option{}, + } +} + +func (s *Stream) TotalOffset() int64 { + return s.totalOffset() +} + +func (s *Stream) Buffered() io.Reader { + buflen := int64(len(s.buf)) + for i := s.cursor; i < buflen; i++ { + if s.buf[i] == nul { + return bytes.NewReader(s.buf[s.cursor:i]) + } + } + return bytes.NewReader(s.buf[s.cursor:]) +} + +func (s *Stream) PrepareForDecode() error { + for { + switch s.char() { + case ' ', '\t', '\r', '\n': + s.cursor++ + continue + case ',', ':': + s.cursor++ + return nil + case nul: + if s.read() { + continue + } + return io.EOF + } + break + } + return nil +} + +func (s *Stream) totalOffset() int64 { + return s.offset + s.cursor +} + +func (s *Stream) char() byte { + return s.buf[s.cursor] +} + +func (s *Stream) equalChar(c byte) bool { + cur := s.buf[s.cursor] + if cur == nul { + s.read() + cur = s.buf[s.cursor] + } + return cur == c +} + +func (s *Stream) stat() ([]byte, int64, unsafe.Pointer) { + return s.buf, s.cursor, (*sliceHeader)(unsafe.Pointer(&s.buf)).data +} + +func (s *Stream) bufptr() unsafe.Pointer { + return (*sliceHeader)(unsafe.Pointer(&s.buf)).data +} + +func (s *Stream) statForRetry() ([]byte, int64, unsafe.Pointer) { + s.cursor-- // for retry ( because caller progress cursor position in each loop ) + return s.buf, s.cursor, (*sliceHeader)(unsafe.Pointer(&s.buf)).data +} + +func (s *Stream) Reset() { + s.reset() + s.bufSize = initBufSize +} + +func (s *Stream) More() bool { + for { + switch s.char() { + case ' ', '\n', '\r', '\t': + s.cursor++ + continue + case '}', ']': + return false + case nul: + if s.read() { + continue + } + return false + } + break + } + return true +} + +func (s *Stream) Token() (interface{}, error) { + for { + c := s.char() + switch c { + case ' ', '\n', '\r', '\t': + s.cursor++ + case '{', '[', ']', '}': + s.cursor++ + return json.Delim(c), nil + case ',', ':': + s.cursor++ + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + bytes := floatBytes(s) + s := *(*string)(unsafe.Pointer(&bytes)) + f64, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil, err + } + return f64, nil + case '"': + bytes, err := stringBytes(s) + if err != nil { + return nil, err + } + return string(bytes), nil + case 't': + if err := trueBytes(s); err != nil { + return nil, err + } + return true, nil + case 'f': + if err := falseBytes(s); err != nil { + return nil, err + } + return false, nil + case 'n': + if err := nullBytes(s); err != nil { + return nil, err + } + return nil, nil + case nul: + if s.read() { + continue + } + goto END + default: + return nil, errors.ErrInvalidCharacter(s.char(), "token", s.totalOffset()) + } + } +END: + return nil, io.EOF +} + +func (s *Stream) reset() { + s.offset += s.cursor + s.buf = s.buf[s.cursor:] + s.length -= s.cursor + s.cursor = 0 +} + +func (s *Stream) readBuf() []byte { + if s.filledBuffer { + s.bufSize *= 2 + remainBuf := s.buf + s.buf = make([]byte, s.bufSize) + copy(s.buf, remainBuf) + } + remainLen := s.length - s.cursor + remainNotNulCharNum := int64(0) + for i := int64(0); i < remainLen; i++ { + if s.buf[s.cursor+i] == nul { + break + } + remainNotNulCharNum++ + } + s.length = s.cursor + remainNotNulCharNum + return s.buf[s.cursor+remainNotNulCharNum:] +} + +func (s *Stream) read() bool { + if s.allRead { + return false + } + buf := s.readBuf() + last := len(buf) - 1 + buf[last] = nul + n, err := s.r.Read(buf[:last]) + s.length += int64(n) + if n == last { + s.filledBuffer = true + } else { + s.filledBuffer = false + } + if err == io.EOF { + s.allRead = true + } else if err != nil { + return false + } + return true +} + +func (s *Stream) skipWhiteSpace() byte { + p := s.bufptr() +LOOP: + c := char(p, s.cursor) + switch c { + case ' ', '\n', '\t', '\r': + s.cursor++ + goto LOOP + case nul: + if s.read() { + p = s.bufptr() + goto LOOP + } + } + return c +} + +func (s *Stream) skipObject(depth int64) error { + braceCount := 1 + _, cursor, p := s.stat() + for { + switch char(p, cursor) { + case '{': + braceCount++ + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + case '}': + braceCount-- + depth-- + if braceCount == 0 { + s.cursor = cursor + 1 + return nil + } + case '[': + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + case ']': + depth-- + case '"': + for { + cursor++ + switch char(p, cursor) { + case '\\': + cursor++ + if char(p, cursor) == nul { + s.cursor = cursor + if s.read() { + _, cursor, p = s.statForRetry() + continue + } + return errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + case '"': + goto SWITCH_OUT + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.statForRetry() + continue + } + return errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + } + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + return errors.ErrUnexpectedEndOfJSON("object of object", cursor) + } + SWITCH_OUT: + cursor++ + } +} + +func (s *Stream) skipArray(depth int64) error { + bracketCount := 1 + _, cursor, p := s.stat() + for { + switch char(p, cursor) { + case '[': + bracketCount++ + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + case ']': + bracketCount-- + depth-- + if bracketCount == 0 { + s.cursor = cursor + 1 + return nil + } + case '{': + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + case '}': + depth-- + case '"': + for { + cursor++ + switch char(p, cursor) { + case '\\': + cursor++ + if char(p, cursor) == nul { + s.cursor = cursor + if s.read() { + _, cursor, p = s.statForRetry() + continue + } + return errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + case '"': + goto SWITCH_OUT + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.statForRetry() + continue + } + return errors.ErrUnexpectedEndOfJSON("string of object", cursor) + } + } + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + return errors.ErrUnexpectedEndOfJSON("array of object", cursor) + } + SWITCH_OUT: + cursor++ + } +} + +func (s *Stream) skipValue(depth int64) error { + _, cursor, p := s.stat() + for { + switch char(p, cursor) { + case ' ', '\n', '\t', '\r': + cursor++ + continue + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + return errors.ErrUnexpectedEndOfJSON("value of object", s.totalOffset()) + case '{': + s.cursor = cursor + 1 + return s.skipObject(depth + 1) + case '[': + s.cursor = cursor + 1 + return s.skipArray(depth + 1) + case '"': + for { + cursor++ + switch char(p, cursor) { + case '\\': + cursor++ + if char(p, cursor) == nul { + s.cursor = cursor + if s.read() { + _, cursor, p = s.statForRetry() + continue + } + return errors.ErrUnexpectedEndOfJSON("value of string", s.totalOffset()) + } + case '"': + s.cursor = cursor + 1 + return nil + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.statForRetry() + continue + } + return errors.ErrUnexpectedEndOfJSON("value of string", s.totalOffset()) + } + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + for { + cursor++ + c := char(p, cursor) + if floatTable[c] { + continue + } else if c == nul { + if s.read() { + s.cursor-- // for retry current character + _, cursor, p = s.stat() + continue + } + } + s.cursor = cursor + return nil + } + case 't': + s.cursor = cursor + if err := trueBytes(s); err != nil { + return err + } + return nil + case 'f': + s.cursor = cursor + if err := falseBytes(s); err != nil { + return err + } + return nil + case 'n': + s.cursor = cursor + if err := nullBytes(s); err != nil { + return err + } + return nil + } + cursor++ + } +} + +func nullBytes(s *Stream) error { + // current cursor's character is 'n' + s.cursor++ + if s.char() != 'u' { + if err := retryReadNull(s); err != nil { + return err + } + } + s.cursor++ + if s.char() != 'l' { + if err := retryReadNull(s); err != nil { + return err + } + } + s.cursor++ + if s.char() != 'l' { + if err := retryReadNull(s); err != nil { + return err + } + } + s.cursor++ + return nil +} + +func retryReadNull(s *Stream) error { + if s.char() == nul && s.read() { + return nil + } + return errors.ErrInvalidCharacter(s.char(), "null", s.totalOffset()) +} + +func trueBytes(s *Stream) error { + // current cursor's character is 't' + s.cursor++ + if s.char() != 'r' { + if err := retryReadTrue(s); err != nil { + return err + } + } + s.cursor++ + if s.char() != 'u' { + if err := retryReadTrue(s); err != nil { + return err + } + } + s.cursor++ + if s.char() != 'e' { + if err := retryReadTrue(s); err != nil { + return err + } + } + s.cursor++ + return nil +} + +func retryReadTrue(s *Stream) error { + if s.char() == nul && s.read() { + return nil + } + return errors.ErrInvalidCharacter(s.char(), "bool(true)", s.totalOffset()) +} + +func falseBytes(s *Stream) error { + // current cursor's character is 'f' + s.cursor++ + if s.char() != 'a' { + if err := retryReadFalse(s); err != nil { + return err + } + } + s.cursor++ + if s.char() != 'l' { + if err := retryReadFalse(s); err != nil { + return err + } + } + s.cursor++ + if s.char() != 's' { + if err := retryReadFalse(s); err != nil { + return err + } + } + s.cursor++ + if s.char() != 'e' { + if err := retryReadFalse(s); err != nil { + return err + } + } + s.cursor++ + return nil +} + +func retryReadFalse(s *Stream) error { + if s.char() == nul && s.read() { + return nil + } + return errors.ErrInvalidCharacter(s.char(), "bool(false)", s.totalOffset()) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/string.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/string.go new file mode 100644 index 00000000..65b10048 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/string.go @@ -0,0 +1,371 @@ +package decoder + +import ( + "reflect" + "unicode" + "unicode/utf16" + "unicode/utf8" + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +type stringDecoder struct { + structName string + fieldName string +} + +func newStringDecoder(structName, fieldName string) *stringDecoder { + return &stringDecoder{ + structName: structName, + fieldName: fieldName, + } +} + +func (d *stringDecoder) errUnmarshalType(typeName string, offset int64) *errors.UnmarshalTypeError { + return &errors.UnmarshalTypeError{ + Value: typeName, + Type: reflect.TypeOf(""), + Offset: offset, + Struct: d.structName, + Field: d.fieldName, + } +} + +func (d *stringDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + bytes, err := d.decodeStreamByte(s) + if err != nil { + return err + } + if bytes == nil { + return nil + } + **(**string)(unsafe.Pointer(&p)) = *(*string)(unsafe.Pointer(&bytes)) + s.reset() + return nil +} + +func (d *stringDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + bytes, c, err := d.decodeByte(ctx.Buf, cursor) + if err != nil { + return 0, err + } + if bytes == nil { + return c, nil + } + cursor = c + **(**string)(unsafe.Pointer(&p)) = *(*string)(unsafe.Pointer(&bytes)) + return cursor, nil +} + +var ( + hexToInt = [256]int{ + '0': 0, + '1': 1, + '2': 2, + '3': 3, + '4': 4, + '5': 5, + '6': 6, + '7': 7, + '8': 8, + '9': 9, + 'A': 10, + 'B': 11, + 'C': 12, + 'D': 13, + 'E': 14, + 'F': 15, + 'a': 10, + 'b': 11, + 'c': 12, + 'd': 13, + 'e': 14, + 'f': 15, + } +) + +func unicodeToRune(code []byte) rune { + var r rune + for i := 0; i < len(code); i++ { + r = r*16 + rune(hexToInt[code[i]]) + } + return r +} + +func decodeUnicodeRune(s *Stream, p unsafe.Pointer) (rune, int64, unsafe.Pointer, error) { + const defaultOffset = 5 + const surrogateOffset = 11 + + if s.cursor+defaultOffset >= s.length { + if !s.read() { + return rune(0), 0, nil, errors.ErrInvalidCharacter(s.char(), "escaped string", s.totalOffset()) + } + p = s.bufptr() + } + + r := unicodeToRune(s.buf[s.cursor+1 : s.cursor+defaultOffset]) + if utf16.IsSurrogate(r) { + if s.cursor+surrogateOffset >= s.length { + s.read() + p = s.bufptr() + } + if s.cursor+surrogateOffset >= s.length || s.buf[s.cursor+defaultOffset] != '\\' || s.buf[s.cursor+defaultOffset+1] != 'u' { + return unicode.ReplacementChar, defaultOffset, p, nil + } + r2 := unicodeToRune(s.buf[s.cursor+defaultOffset+2 : s.cursor+surrogateOffset]) + if r := utf16.DecodeRune(r, r2); r != unicode.ReplacementChar { + return r, surrogateOffset, p, nil + } + } + return r, defaultOffset, p, nil +} + +func decodeUnicode(s *Stream, p unsafe.Pointer) (unsafe.Pointer, error) { + const backSlashAndULen = 2 // length of \u + + r, offset, pp, err := decodeUnicodeRune(s, p) + if err != nil { + return nil, err + } + unicode := []byte(string(r)) + unicodeLen := int64(len(unicode)) + s.buf = append(append(s.buf[:s.cursor-1], unicode...), s.buf[s.cursor+offset:]...) + unicodeOrgLen := offset - 1 + s.length = s.length - (backSlashAndULen + (unicodeOrgLen - unicodeLen)) + s.cursor = s.cursor - backSlashAndULen + unicodeLen + return pp, nil +} + +func decodeEscapeString(s *Stream, p unsafe.Pointer) (unsafe.Pointer, error) { + s.cursor++ +RETRY: + switch s.buf[s.cursor] { + case '"': + s.buf[s.cursor] = '"' + case '\\': + s.buf[s.cursor] = '\\' + case '/': + s.buf[s.cursor] = '/' + case 'b': + s.buf[s.cursor] = '\b' + case 'f': + s.buf[s.cursor] = '\f' + case 'n': + s.buf[s.cursor] = '\n' + case 'r': + s.buf[s.cursor] = '\r' + case 't': + s.buf[s.cursor] = '\t' + case 'u': + return decodeUnicode(s, p) + case nul: + if !s.read() { + return nil, errors.ErrInvalidCharacter(s.char(), "escaped string", s.totalOffset()) + } + goto RETRY + default: + return nil, errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + } + s.buf = append(s.buf[:s.cursor-1], s.buf[s.cursor:]...) + s.length-- + s.cursor-- + p = s.bufptr() + return p, nil +} + +var ( + runeErrBytes = []byte(string(utf8.RuneError)) + runeErrBytesLen = int64(len(runeErrBytes)) +) + +func stringBytes(s *Stream) ([]byte, error) { + _, cursor, p := s.stat() + cursor++ // skip double quote char + start := cursor + for { + switch char(p, cursor) { + case '\\': + s.cursor = cursor + pp, err := decodeEscapeString(s, p) + if err != nil { + return nil, err + } + p = pp + cursor = s.cursor + case '"': + literal := s.buf[start:cursor] + cursor++ + s.cursor = cursor + return literal, nil + case + // 0x00 is nul, 0x5c is '\\', 0x22 is '"' . + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // 0x00-0x0F + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // 0x10-0x1F + 0x20, 0x21 /*0x22,*/, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, // 0x20-0x2F + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, // 0x30-0x3F + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, // 0x40-0x4F + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B /*0x5C,*/, 0x5D, 0x5E, 0x5F, // 0x50-0x5F + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, // 0x60-0x6F + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F: // 0x70-0x7F + // character is ASCII. skip to next char + case + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, // 0x80-0x8F + 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, // 0x90-0x9F + 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, // 0xA0-0xAF + 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, // 0xB0-0xBF + 0xC0, 0xC1, // 0xC0-0xC1 + 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF: // 0xF5-0xFE + // character is invalid + s.buf = append(append(append([]byte{}, s.buf[:cursor]...), runeErrBytes...), s.buf[cursor+1:]...) + _, _, p = s.stat() + cursor += runeErrBytesLen + s.length += runeErrBytesLen + continue + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + goto ERROR + case 0xEF: + // RuneError is {0xEF, 0xBF, 0xBD} + if s.buf[cursor+1] == 0xBF && s.buf[cursor+2] == 0xBD { + // found RuneError: skip + cursor += 2 + break + } + fallthrough + default: + // multi bytes character + if !utf8.FullRune(s.buf[cursor : len(s.buf)-1]) { + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + goto ERROR + } + r, size := utf8.DecodeRune(s.buf[cursor:]) + if r == utf8.RuneError { + s.buf = append(append(append([]byte{}, s.buf[:cursor]...), runeErrBytes...), s.buf[cursor+1:]...) + cursor += runeErrBytesLen + s.length += runeErrBytesLen + _, _, p = s.stat() + } else { + cursor += int64(size) + } + continue + } + cursor++ + } +ERROR: + return nil, errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) +} + +func (d *stringDecoder) decodeStreamByte(s *Stream) ([]byte, error) { + for { + switch s.char() { + case ' ', '\n', '\t', '\r': + s.cursor++ + continue + case '[': + return nil, d.errUnmarshalType("array", s.totalOffset()) + case '{': + return nil, d.errUnmarshalType("object", s.totalOffset()) + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return nil, d.errUnmarshalType("number", s.totalOffset()) + case '"': + return stringBytes(s) + case 'n': + if err := nullBytes(s); err != nil { + return nil, err + } + return nil, nil + case nul: + if s.read() { + continue + } + } + break + } + return nil, errors.ErrInvalidBeginningOfValue(s.char(), s.totalOffset()) +} + +func (d *stringDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { + for { + switch buf[cursor] { + case ' ', '\n', '\t', '\r': + cursor++ + case '[': + return nil, 0, d.errUnmarshalType("array", cursor) + case '{': + return nil, 0, d.errUnmarshalType("object", cursor) + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return nil, 0, d.errUnmarshalType("number", cursor) + case '"': + cursor++ + start := cursor + b := (*sliceHeader)(unsafe.Pointer(&buf)).data + for { + switch char(b, cursor) { + case '\\': + cursor++ + switch char(b, cursor) { + case '"': + buf[cursor] = '"' + buf = append(buf[:cursor-1], buf[cursor:]...) + case '\\': + buf[cursor] = '\\' + buf = append(buf[:cursor-1], buf[cursor:]...) + case '/': + buf[cursor] = '/' + buf = append(buf[:cursor-1], buf[cursor:]...) + case 'b': + buf[cursor] = '\b' + buf = append(buf[:cursor-1], buf[cursor:]...) + case 'f': + buf[cursor] = '\f' + buf = append(buf[:cursor-1], buf[cursor:]...) + case 'n': + buf[cursor] = '\n' + buf = append(buf[:cursor-1], buf[cursor:]...) + case 'r': + buf[cursor] = '\r' + buf = append(buf[:cursor-1], buf[cursor:]...) + case 't': + buf[cursor] = '\t' + buf = append(buf[:cursor-1], buf[cursor:]...) + case 'u': + buflen := int64(len(buf)) + if cursor+5 >= buflen { + return nil, 0, errors.ErrUnexpectedEndOfJSON("escaped string", cursor) + } + code := unicodeToRune(buf[cursor+1 : cursor+5]) + unicode := []byte(string(code)) + buf = append(append(buf[:cursor-1], unicode...), buf[cursor+5:]...) + default: + return nil, 0, errors.ErrUnexpectedEndOfJSON("escaped string", cursor) + } + continue + case '"': + literal := buf[start:cursor] + cursor++ + return literal, cursor, nil + case nul: + return nil, 0, errors.ErrUnexpectedEndOfJSON("string", cursor) + } + cursor++ + } + case 'n': + if err := validateNull(buf, cursor); err != nil { + return nil, 0, err + } + cursor += 4 + return nil, cursor, nil + default: + return nil, 0, errors.ErrInvalidBeginningOfValue(buf[cursor], cursor) + } + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/struct.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/struct.go new file mode 100644 index 00000000..2c646804 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/struct.go @@ -0,0 +1,819 @@ +package decoder + +import ( + "fmt" + "math" + "math/bits" + "sort" + "strings" + "unicode" + "unicode/utf16" + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +type structFieldSet struct { + dec Decoder + offset uintptr + isTaggedKey bool + fieldIdx int + key string + keyLen int64 + err error +} + +type structDecoder struct { + fieldMap map[string]*structFieldSet + fieldUniqueNameNum int + stringDecoder *stringDecoder + structName string + fieldName string + isTriedOptimize bool + keyBitmapUint8 [][256]uint8 + keyBitmapUint16 [][256]uint16 + sortedFieldSets []*structFieldSet + keyDecoder func(*structDecoder, []byte, int64) (int64, *structFieldSet, error) + keyStreamDecoder func(*structDecoder, *Stream) (*structFieldSet, string, error) +} + +var ( + largeToSmallTable [256]byte +) + +func init() { + for i := 0; i < 256; i++ { + c := i + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + largeToSmallTable[i] = byte(c) + } +} + +func newStructDecoder(structName, fieldName string, fieldMap map[string]*structFieldSet) *structDecoder { + return &structDecoder{ + fieldMap: fieldMap, + stringDecoder: newStringDecoder(structName, fieldName), + structName: structName, + fieldName: fieldName, + keyDecoder: decodeKey, + keyStreamDecoder: decodeKeyStream, + } +} + +const ( + allowOptimizeMaxKeyLen = 64 + allowOptimizeMaxFieldLen = 16 +) + +func (d *structDecoder) tryOptimize() { + fieldUniqueNameMap := map[string]int{} + fieldIdx := -1 + for k, v := range d.fieldMap { + lower := strings.ToLower(k) + idx, exists := fieldUniqueNameMap[lower] + if exists { + v.fieldIdx = idx + } else { + fieldIdx++ + v.fieldIdx = fieldIdx + } + fieldUniqueNameMap[lower] = fieldIdx + } + d.fieldUniqueNameNum = len(fieldUniqueNameMap) + + if d.isTriedOptimize { + return + } + fieldMap := map[string]*structFieldSet{} + conflicted := map[string]struct{}{} + for k, v := range d.fieldMap { + key := strings.ToLower(k) + if key != k { + // already exists same key (e.g. Hello and HELLO has same lower case key + if _, exists := conflicted[key]; exists { + d.isTriedOptimize = true + return + } + conflicted[key] = struct{}{} + } + if field, exists := fieldMap[key]; exists { + if field != v { + d.isTriedOptimize = true + return + } + } + fieldMap[key] = v + } + + if len(fieldMap) > allowOptimizeMaxFieldLen { + d.isTriedOptimize = true + return + } + + var maxKeyLen int + sortedKeys := []string{} + for key := range fieldMap { + keyLen := len(key) + if keyLen > allowOptimizeMaxKeyLen { + d.isTriedOptimize = true + return + } + if maxKeyLen < keyLen { + maxKeyLen = keyLen + } + sortedKeys = append(sortedKeys, key) + } + sort.Strings(sortedKeys) + + // By allocating one extra capacity than `maxKeyLen`, + // it is possible to avoid the process of comparing the index of the key with the length of the bitmap each time. + bitmapLen := maxKeyLen + 1 + if len(sortedKeys) <= 8 { + keyBitmap := make([][256]uint8, bitmapLen) + for i, key := range sortedKeys { + for j := 0; j < len(key); j++ { + c := key[j] + keyBitmap[j][c] |= (1 << uint(i)) + } + d.sortedFieldSets = append(d.sortedFieldSets, fieldMap[key]) + } + d.keyBitmapUint8 = keyBitmap + d.keyDecoder = decodeKeyByBitmapUint8 + d.keyStreamDecoder = decodeKeyByBitmapUint8Stream + } else { + keyBitmap := make([][256]uint16, bitmapLen) + for i, key := range sortedKeys { + for j := 0; j < len(key); j++ { + c := key[j] + keyBitmap[j][c] |= (1 << uint(i)) + } + d.sortedFieldSets = append(d.sortedFieldSets, fieldMap[key]) + } + d.keyBitmapUint16 = keyBitmap + d.keyDecoder = decodeKeyByBitmapUint16 + d.keyStreamDecoder = decodeKeyByBitmapUint16Stream + } +} + +// decode from '\uXXXX' +func decodeKeyCharByUnicodeRune(buf []byte, cursor int64) ([]byte, int64) { + const defaultOffset = 4 + const surrogateOffset = 6 + + r := unicodeToRune(buf[cursor : cursor+defaultOffset]) + if utf16.IsSurrogate(r) { + cursor += defaultOffset + if cursor+surrogateOffset >= int64(len(buf)) || buf[cursor] != '\\' || buf[cursor+1] != 'u' { + return []byte(string(unicode.ReplacementChar)), cursor + defaultOffset - 1 + } + cursor += 2 + r2 := unicodeToRune(buf[cursor : cursor+defaultOffset]) + if r := utf16.DecodeRune(r, r2); r != unicode.ReplacementChar { + return []byte(string(r)), cursor + defaultOffset - 1 + } + } + return []byte(string(r)), cursor + defaultOffset - 1 +} + +func decodeKeyCharByEscapedChar(buf []byte, cursor int64) ([]byte, int64) { + c := buf[cursor] + cursor++ + switch c { + case '"': + return []byte{'"'}, cursor + case '\\': + return []byte{'\\'}, cursor + case '/': + return []byte{'/'}, cursor + case 'b': + return []byte{'\b'}, cursor + case 'f': + return []byte{'\f'}, cursor + case 'n': + return []byte{'\n'}, cursor + case 'r': + return []byte{'\r'}, cursor + case 't': + return []byte{'\t'}, cursor + case 'u': + return decodeKeyCharByUnicodeRune(buf, cursor) + } + return nil, cursor +} + +func decodeKeyByBitmapUint8(d *structDecoder, buf []byte, cursor int64) (int64, *structFieldSet, error) { + var ( + curBit uint8 = math.MaxUint8 + ) + b := (*sliceHeader)(unsafe.Pointer(&buf)).data + for { + switch char(b, cursor) { + case ' ', '\n', '\t', '\r': + cursor++ + case '"': + cursor++ + c := char(b, cursor) + switch c { + case '"': + cursor++ + return cursor, nil, nil + case nul: + return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) + } + keyIdx := 0 + bitmap := d.keyBitmapUint8 + start := cursor + for { + c := char(b, cursor) + switch c { + case '"': + fieldSetIndex := bits.TrailingZeros8(curBit) + field := d.sortedFieldSets[fieldSetIndex] + keyLen := cursor - start + cursor++ + if keyLen < field.keyLen { + // early match + return cursor, nil, nil + } + return cursor, field, nil + case nul: + return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) + case '\\': + cursor++ + chars, nextCursor := decodeKeyCharByEscapedChar(buf, cursor) + for _, c := range chars { + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + return decodeKeyNotFound(b, cursor) + } + keyIdx++ + } + cursor = nextCursor + default: + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + return decodeKeyNotFound(b, cursor) + } + keyIdx++ + } + cursor++ + } + default: + return cursor, nil, errors.ErrInvalidBeginningOfValue(char(b, cursor), cursor) + } + } +} + +func decodeKeyByBitmapUint16(d *structDecoder, buf []byte, cursor int64) (int64, *structFieldSet, error) { + var ( + curBit uint16 = math.MaxUint16 + ) + b := (*sliceHeader)(unsafe.Pointer(&buf)).data + for { + switch char(b, cursor) { + case ' ', '\n', '\t', '\r': + cursor++ + case '"': + cursor++ + c := char(b, cursor) + switch c { + case '"': + cursor++ + return cursor, nil, nil + case nul: + return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) + } + keyIdx := 0 + bitmap := d.keyBitmapUint16 + start := cursor + for { + c := char(b, cursor) + switch c { + case '"': + fieldSetIndex := bits.TrailingZeros16(curBit) + field := d.sortedFieldSets[fieldSetIndex] + keyLen := cursor - start + cursor++ + if keyLen < field.keyLen { + // early match + return cursor, nil, nil + } + return cursor, field, nil + case nul: + return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) + case '\\': + cursor++ + chars, nextCursor := decodeKeyCharByEscapedChar(buf, cursor) + for _, c := range chars { + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + return decodeKeyNotFound(b, cursor) + } + keyIdx++ + } + cursor = nextCursor + default: + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + return decodeKeyNotFound(b, cursor) + } + keyIdx++ + } + cursor++ + } + default: + return cursor, nil, errors.ErrInvalidBeginningOfValue(char(b, cursor), cursor) + } + } +} + +func decodeKeyNotFound(b unsafe.Pointer, cursor int64) (int64, *structFieldSet, error) { + for { + cursor++ + switch char(b, cursor) { + case '"': + cursor++ + return cursor, nil, nil + case '\\': + cursor++ + if char(b, cursor) == nul { + return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) + } + case nul: + return 0, nil, errors.ErrUnexpectedEndOfJSON("string", cursor) + } + } +} + +func decodeKey(d *structDecoder, buf []byte, cursor int64) (int64, *structFieldSet, error) { + key, c, err := d.stringDecoder.decodeByte(buf, cursor) + if err != nil { + return 0, nil, err + } + cursor = c + k := *(*string)(unsafe.Pointer(&key)) + field, exists := d.fieldMap[k] + if !exists { + return cursor, nil, nil + } + return cursor, field, nil +} + +func decodeKeyByBitmapUint8Stream(d *structDecoder, s *Stream) (*structFieldSet, string, error) { + var ( + curBit uint8 = math.MaxUint8 + ) + _, cursor, p := s.stat() + for { + switch char(p, cursor) { + case ' ', '\n', '\t', '\r': + cursor++ + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + return nil, "", errors.ErrInvalidBeginningOfValue(char(p, cursor), s.totalOffset()) + case '"': + cursor++ + FIRST_CHAR: + start := cursor + switch char(p, cursor) { + case '"': + cursor++ + s.cursor = cursor + return nil, "", nil + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + goto FIRST_CHAR + } + return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + } + keyIdx := 0 + bitmap := d.keyBitmapUint8 + for { + c := char(p, cursor) + switch c { + case '"': + fieldSetIndex := bits.TrailingZeros8(curBit) + field := d.sortedFieldSets[fieldSetIndex] + keyLen := cursor - start + cursor++ + s.cursor = cursor + if keyLen < field.keyLen { + // early match + return nil, field.key, nil + } + return field, field.key, nil + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + case '\\': + s.cursor = cursor + 1 // skip '\' char + chars, err := decodeKeyCharByEscapeCharStream(s) + if err != nil { + return nil, "", err + } + cursor = s.cursor + for _, c := range chars { + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + s.cursor = cursor + return decodeKeyNotFoundStream(s, start) + } + keyIdx++ + } + default: + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + s.cursor = cursor + return decodeKeyNotFoundStream(s, start) + } + keyIdx++ + } + cursor++ + } + default: + return nil, "", errors.ErrInvalidBeginningOfValue(char(p, cursor), s.totalOffset()) + } + } +} + +func decodeKeyByBitmapUint16Stream(d *structDecoder, s *Stream) (*structFieldSet, string, error) { + var ( + curBit uint16 = math.MaxUint16 + ) + _, cursor, p := s.stat() + for { + switch char(p, cursor) { + case ' ', '\n', '\t', '\r': + cursor++ + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + return nil, "", errors.ErrInvalidBeginningOfValue(char(p, cursor), s.totalOffset()) + case '"': + cursor++ + FIRST_CHAR: + start := cursor + switch char(p, cursor) { + case '"': + cursor++ + s.cursor = cursor + return nil, "", nil + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + goto FIRST_CHAR + } + return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + } + keyIdx := 0 + bitmap := d.keyBitmapUint16 + for { + c := char(p, cursor) + switch c { + case '"': + fieldSetIndex := bits.TrailingZeros16(curBit) + field := d.sortedFieldSets[fieldSetIndex] + keyLen := cursor - start + cursor++ + s.cursor = cursor + if keyLen < field.keyLen { + // early match + return nil, field.key, nil + } + return field, field.key, nil + case nul: + s.cursor = cursor + if s.read() { + _, cursor, p = s.stat() + continue + } + return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + case '\\': + s.cursor = cursor + 1 // skip '\' char + chars, err := decodeKeyCharByEscapeCharStream(s) + if err != nil { + return nil, "", err + } + cursor = s.cursor + for _, c := range chars { + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + s.cursor = cursor + return decodeKeyNotFoundStream(s, start) + } + keyIdx++ + } + default: + curBit &= bitmap[keyIdx][largeToSmallTable[c]] + if curBit == 0 { + s.cursor = cursor + return decodeKeyNotFoundStream(s, start) + } + keyIdx++ + } + cursor++ + } + default: + return nil, "", errors.ErrInvalidBeginningOfValue(char(p, cursor), s.totalOffset()) + } + } +} + +// decode from '\uXXXX' +func decodeKeyCharByUnicodeRuneStream(s *Stream) ([]byte, error) { + const defaultOffset = 4 + const surrogateOffset = 6 + + if s.cursor+defaultOffset >= s.length { + if !s.read() { + return nil, errors.ErrInvalidCharacter(s.char(), "escaped unicode char", s.totalOffset()) + } + } + + r := unicodeToRune(s.buf[s.cursor : s.cursor+defaultOffset]) + if utf16.IsSurrogate(r) { + s.cursor += defaultOffset + if s.cursor+surrogateOffset >= s.length { + s.read() + } + if s.cursor+surrogateOffset >= s.length || s.buf[s.cursor] != '\\' || s.buf[s.cursor+1] != 'u' { + s.cursor += defaultOffset - 1 + return []byte(string(unicode.ReplacementChar)), nil + } + r2 := unicodeToRune(s.buf[s.cursor+defaultOffset+2 : s.cursor+surrogateOffset]) + if r := utf16.DecodeRune(r, r2); r != unicode.ReplacementChar { + s.cursor += defaultOffset - 1 + return []byte(string(r)), nil + } + } + s.cursor += defaultOffset - 1 + return []byte(string(r)), nil +} + +func decodeKeyCharByEscapeCharStream(s *Stream) ([]byte, error) { + c := s.buf[s.cursor] + s.cursor++ +RETRY: + switch c { + case '"': + return []byte{'"'}, nil + case '\\': + return []byte{'\\'}, nil + case '/': + return []byte{'/'}, nil + case 'b': + return []byte{'\b'}, nil + case 'f': + return []byte{'\f'}, nil + case 'n': + return []byte{'\n'}, nil + case 'r': + return []byte{'\r'}, nil + case 't': + return []byte{'\t'}, nil + case 'u': + return decodeKeyCharByUnicodeRuneStream(s) + case nul: + if !s.read() { + return nil, errors.ErrInvalidCharacter(s.char(), "escaped char", s.totalOffset()) + } + goto RETRY + default: + return nil, errors.ErrUnexpectedEndOfJSON("struct field", s.totalOffset()) + } +} + +func decodeKeyNotFoundStream(s *Stream, start int64) (*structFieldSet, string, error) { + buf, cursor, p := s.stat() + for { + cursor++ + switch char(p, cursor) { + case '"': + b := buf[start:cursor] + key := *(*string)(unsafe.Pointer(&b)) + cursor++ + s.cursor = cursor + return nil, key, nil + case '\\': + cursor++ + if char(p, cursor) == nul { + s.cursor = cursor + if !s.read() { + return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + } + buf, cursor, p = s.statForRetry() + } + case nul: + s.cursor = cursor + if !s.read() { + return nil, "", errors.ErrUnexpectedEndOfJSON("string", s.totalOffset()) + } + buf, cursor, p = s.statForRetry() + } + } +} + +func decodeKeyStream(d *structDecoder, s *Stream) (*structFieldSet, string, error) { + key, err := d.stringDecoder.decodeStreamByte(s) + if err != nil { + return nil, "", err + } + k := *(*string)(unsafe.Pointer(&key)) + return d.fieldMap[k], k, nil +} + +func (d *structDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + depth++ + if depth > maxDecodeNestingDepth { + return errors.ErrExceededMaxDepth(s.char(), s.cursor) + } + + c := s.skipWhiteSpace() + switch c { + case 'n': + if err := nullBytes(s); err != nil { + return err + } + return nil + default: + if s.char() != '{' { + return errors.ErrInvalidBeginningOfValue(s.char(), s.totalOffset()) + } + } + s.cursor++ + if s.skipWhiteSpace() == '}' { + s.cursor++ + return nil + } + var ( + seenFields map[int]struct{} + seenFieldNum int + ) + firstWin := (s.Option.Flags & FirstWinOption) != 0 + if firstWin { + seenFields = make(map[int]struct{}, d.fieldUniqueNameNum) + } + for { + s.reset() + field, key, err := d.keyStreamDecoder(d, s) + if err != nil { + return err + } + if s.skipWhiteSpace() != ':' { + return errors.ErrExpected("colon after object key", s.totalOffset()) + } + s.cursor++ + if field != nil { + if field.err != nil { + return field.err + } + if firstWin { + if _, exists := seenFields[field.fieldIdx]; exists { + if err := s.skipValue(depth); err != nil { + return err + } + } else { + if err := field.dec.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+field.offset)); err != nil { + return err + } + seenFieldNum++ + if d.fieldUniqueNameNum <= seenFieldNum { + return s.skipObject(depth) + } + seenFields[field.fieldIdx] = struct{}{} + } + } else { + if err := field.dec.DecodeStream(s, depth, unsafe.Pointer(uintptr(p)+field.offset)); err != nil { + return err + } + } + } else if s.DisallowUnknownFields { + return fmt.Errorf("json: unknown field %q", key) + } else { + if err := s.skipValue(depth); err != nil { + return err + } + } + c := s.skipWhiteSpace() + if c == '}' { + s.cursor++ + return nil + } + if c != ',' { + return errors.ErrExpected("comma after object element", s.totalOffset()) + } + s.cursor++ + } +} + +func (d *structDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + depth++ + if depth > maxDecodeNestingDepth { + return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor) + } + buflen := int64(len(buf)) + cursor = skipWhiteSpace(buf, cursor) + b := (*sliceHeader)(unsafe.Pointer(&buf)).data + switch char(b, cursor) { + case 'n': + if err := validateNull(buf, cursor); err != nil { + return 0, err + } + cursor += 4 + return cursor, nil + case '{': + default: + return 0, errors.ErrInvalidBeginningOfValue(char(b, cursor), cursor) + } + cursor++ + cursor = skipWhiteSpace(buf, cursor) + if buf[cursor] == '}' { + cursor++ + return cursor, nil + } + var ( + seenFields map[int]struct{} + seenFieldNum int + ) + firstWin := (ctx.Option.Flags & FirstWinOption) != 0 + if firstWin { + seenFields = make(map[int]struct{}, d.fieldUniqueNameNum) + } + for { + c, field, err := d.keyDecoder(d, buf, cursor) + if err != nil { + return 0, err + } + cursor = skipWhiteSpace(buf, c) + if char(b, cursor) != ':' { + return 0, errors.ErrExpected("colon after object key", cursor) + } + cursor++ + if cursor >= buflen { + return 0, errors.ErrExpected("object value after colon", cursor) + } + if field != nil { + if field.err != nil { + return 0, field.err + } + if firstWin { + if _, exists := seenFields[field.fieldIdx]; exists { + c, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + cursor = c + } else { + c, err := field.dec.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+field.offset)) + if err != nil { + return 0, err + } + cursor = c + seenFieldNum++ + if d.fieldUniqueNameNum <= seenFieldNum { + return skipObject(buf, cursor, depth) + } + seenFields[field.fieldIdx] = struct{}{} + } + } else { + c, err := field.dec.Decode(ctx, cursor, depth, unsafe.Pointer(uintptr(p)+field.offset)) + if err != nil { + return 0, err + } + cursor = c + } + } else { + c, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + cursor = c + } + cursor = skipWhiteSpace(buf, cursor) + if char(b, cursor) == '}' { + cursor++ + return cursor, nil + } + if char(b, cursor) != ',' { + return 0, errors.ErrExpected("comma after object element", cursor) + } + cursor++ + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/type.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/type.go new file mode 100644 index 00000000..70e9907c --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/type.go @@ -0,0 +1,29 @@ +package decoder + +import ( + "context" + "encoding" + "encoding/json" + "reflect" + "unsafe" +) + +type Decoder interface { + Decode(*RuntimeContext, int64, int64, unsafe.Pointer) (int64, error) + DecodeStream(*Stream, int64, unsafe.Pointer) error +} + +const ( + nul = '\000' + maxDecodeNestingDepth = 10000 +) + +type unmarshalerContext interface { + UnmarshalJSON(context.Context, []byte) error +} + +var ( + unmarshalJSONType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() + unmarshalJSONContextType = reflect.TypeOf((*unmarshalerContext)(nil)).Elem() + unmarshalTextType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() +) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/uint.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/uint.go new file mode 100644 index 00000000..a62c5149 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/uint.go @@ -0,0 +1,190 @@ +package decoder + +import ( + "fmt" + "reflect" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type uintDecoder struct { + typ *runtime.Type + kind reflect.Kind + op func(unsafe.Pointer, uint64) + structName string + fieldName string +} + +func newUintDecoder(typ *runtime.Type, structName, fieldName string, op func(unsafe.Pointer, uint64)) *uintDecoder { + return &uintDecoder{ + typ: typ, + kind: typ.Kind(), + op: op, + structName: structName, + fieldName: fieldName, + } +} + +func (d *uintDecoder) typeError(buf []byte, offset int64) *errors.UnmarshalTypeError { + return &errors.UnmarshalTypeError{ + Value: fmt.Sprintf("number %s", string(buf)), + Type: runtime.RType2Type(d.typ), + Offset: offset, + } +} + +var ( + pow10u64 = [...]uint64{ + 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + } + pow10u64Len = len(pow10u64) +) + +func (d *uintDecoder) parseUint(b []byte) (uint64, error) { + maxDigit := len(b) + if maxDigit > pow10u64Len { + return 0, fmt.Errorf("invalid length of number") + } + sum := uint64(0) + for i := 0; i < maxDigit; i++ { + c := uint64(b[i]) - 48 + digitValue := pow10u64[maxDigit-i-1] + sum += c * digitValue + } + return sum, nil +} + +func (d *uintDecoder) decodeStreamByte(s *Stream) ([]byte, error) { + for { + switch s.char() { + case ' ', '\n', '\t', '\r': + s.cursor++ + continue + case '0': + s.cursor++ + return numZeroBuf, nil + case '1', '2', '3', '4', '5', '6', '7', '8', '9': + start := s.cursor + for { + s.cursor++ + if numTable[s.char()] { + continue + } else if s.char() == nul { + if s.read() { + s.cursor-- // for retry current character + continue + } + } + break + } + num := s.buf[start:s.cursor] + return num, nil + case 'n': + if err := nullBytes(s); err != nil { + return nil, err + } + return nil, nil + case nul: + if s.read() { + continue + } + default: + return nil, d.typeError([]byte{s.char()}, s.totalOffset()) + } + break + } + return nil, errors.ErrUnexpectedEndOfJSON("number(unsigned integer)", s.totalOffset()) +} + +func (d *uintDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) { + for { + switch buf[cursor] { + case ' ', '\n', '\t', '\r': + cursor++ + continue + case '0': + cursor++ + return numZeroBuf, cursor, nil + case '1', '2', '3', '4', '5', '6', '7', '8', '9': + start := cursor + cursor++ + for numTable[buf[cursor]] { + cursor++ + } + num := buf[start:cursor] + return num, cursor, nil + case 'n': + if err := validateNull(buf, cursor); err != nil { + return nil, 0, err + } + cursor += 4 + return nil, cursor, nil + default: + return nil, 0, d.typeError([]byte{buf[cursor]}, cursor) + } + } +} + +func (d *uintDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + bytes, err := d.decodeStreamByte(s) + if err != nil { + return err + } + if bytes == nil { + return nil + } + u64, err := d.parseUint(bytes) + if err != nil { + return d.typeError(bytes, s.totalOffset()) + } + switch d.kind { + case reflect.Uint8: + if (1 << 8) <= u64 { + return d.typeError(bytes, s.totalOffset()) + } + case reflect.Uint16: + if (1 << 16) <= u64 { + return d.typeError(bytes, s.totalOffset()) + } + case reflect.Uint32: + if (1 << 32) <= u64 { + return d.typeError(bytes, s.totalOffset()) + } + } + d.op(p, u64) + return nil +} + +func (d *uintDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + bytes, c, err := d.decodeByte(ctx.Buf, cursor) + if err != nil { + return 0, err + } + if bytes == nil { + return c, nil + } + cursor = c + u64, err := d.parseUint(bytes) + if err != nil { + return 0, d.typeError(bytes, cursor) + } + switch d.kind { + case reflect.Uint8: + if (1 << 8) <= u64 { + return 0, d.typeError(bytes, cursor) + } + case reflect.Uint16: + if (1 << 16) <= u64 { + return 0, d.typeError(bytes, cursor) + } + case reflect.Uint32: + if (1 << 32) <= u64 { + return 0, d.typeError(bytes, cursor) + } + } + d.op(p, u64) + return cursor, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_json.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_json.go new file mode 100644 index 00000000..d90f39cc --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_json.go @@ -0,0 +1,91 @@ +package decoder + +import ( + "encoding/json" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type unmarshalJSONDecoder struct { + typ *runtime.Type + structName string + fieldName string +} + +func newUnmarshalJSONDecoder(typ *runtime.Type, structName, fieldName string) *unmarshalJSONDecoder { + return &unmarshalJSONDecoder{ + typ: typ, + structName: structName, + fieldName: fieldName, + } +} + +func (d *unmarshalJSONDecoder) annotateError(cursor int64, err error) { + switch e := err.(type) { + case *errors.UnmarshalTypeError: + e.Struct = d.structName + e.Field = d.fieldName + case *errors.SyntaxError: + e.Offset = cursor + } +} + +func (d *unmarshalJSONDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + s.skipWhiteSpace() + start := s.cursor + if err := s.skipValue(depth); err != nil { + return err + } + src := s.buf[start:s.cursor] + dst := make([]byte, len(src)) + copy(dst, src) + + v := *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: d.typ, + ptr: p, + })) + if (s.Option.Flags & ContextOption) != 0 { + if err := v.(unmarshalerContext).UnmarshalJSON(s.Option.Context, dst); err != nil { + d.annotateError(s.cursor, err) + return err + } + } else { + if err := v.(json.Unmarshaler).UnmarshalJSON(dst); err != nil { + d.annotateError(s.cursor, err) + return err + } + } + return nil +} + +func (d *unmarshalJSONDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + cursor = skipWhiteSpace(buf, cursor) + start := cursor + end, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + src := buf[start:end] + dst := make([]byte, len(src)) + copy(dst, src) + + v := *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: d.typ, + ptr: p, + })) + if (ctx.Option.Flags & ContextOption) != 0 { + if err := v.(unmarshalerContext).UnmarshalJSON(ctx.Option.Context, dst); err != nil { + d.annotateError(cursor, err) + return 0, err + } + } else { + if err := v.(json.Unmarshaler).UnmarshalJSON(dst); err != nil { + d.annotateError(cursor, err) + return 0, err + } + } + return end, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_text.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_text.go new file mode 100644 index 00000000..1ef28778 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/unmarshal_text.go @@ -0,0 +1,280 @@ +package decoder + +import ( + "bytes" + "encoding" + "unicode" + "unicode/utf16" + "unicode/utf8" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type unmarshalTextDecoder struct { + typ *runtime.Type + structName string + fieldName string +} + +func newUnmarshalTextDecoder(typ *runtime.Type, structName, fieldName string) *unmarshalTextDecoder { + return &unmarshalTextDecoder{ + typ: typ, + structName: structName, + fieldName: fieldName, + } +} + +func (d *unmarshalTextDecoder) annotateError(cursor int64, err error) { + switch e := err.(type) { + case *errors.UnmarshalTypeError: + e.Struct = d.structName + e.Field = d.fieldName + case *errors.SyntaxError: + e.Offset = cursor + } +} + +var ( + nullbytes = []byte(`null`) +) + +func (d *unmarshalTextDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + s.skipWhiteSpace() + start := s.cursor + if err := s.skipValue(depth); err != nil { + return err + } + src := s.buf[start:s.cursor] + if len(src) > 0 { + switch src[0] { + case '[': + return &errors.UnmarshalTypeError{ + Value: "array", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + case '{': + return &errors.UnmarshalTypeError{ + Value: "object", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return &errors.UnmarshalTypeError{ + Value: "number", + Type: runtime.RType2Type(d.typ), + Offset: s.totalOffset(), + } + case 'n': + if bytes.Equal(src, nullbytes) { + *(*unsafe.Pointer)(p) = nil + return nil + } + } + } + dst := make([]byte, len(src)) + copy(dst, src) + + if b, ok := unquoteBytes(dst); ok { + dst = b + } + v := *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: d.typ, + ptr: p, + })) + if err := v.(encoding.TextUnmarshaler).UnmarshalText(dst); err != nil { + d.annotateError(s.cursor, err) + return err + } + return nil +} + +func (d *unmarshalTextDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + buf := ctx.Buf + cursor = skipWhiteSpace(buf, cursor) + start := cursor + end, err := skipValue(buf, cursor, depth) + if err != nil { + return 0, err + } + src := buf[start:end] + if len(src) > 0 { + switch src[0] { + case '[': + return 0, &errors.UnmarshalTypeError{ + Value: "array", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + case '{': + return 0, &errors.UnmarshalTypeError{ + Value: "object", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return 0, &errors.UnmarshalTypeError{ + Value: "number", + Type: runtime.RType2Type(d.typ), + Offset: start, + } + case 'n': + if bytes.Equal(src, nullbytes) { + *(*unsafe.Pointer)(p) = nil + return end, nil + } + } + } + + if s, ok := unquoteBytes(src); ok { + src = s + } + v := *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: d.typ, + ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), + })) + if err := v.(encoding.TextUnmarshaler).UnmarshalText(src); err != nil { + d.annotateError(cursor, err) + return 0, err + } + return end, nil +} + +func unquoteBytes(s []byte) (t []byte, ok bool) { + length := len(s) + if length < 2 || s[0] != '"' || s[length-1] != '"' { + return + } + s = s[1 : length-1] + length -= 2 + + // Check for unusual characters. If there are none, + // then no unquoting is needed, so return a slice of the + // original bytes. + r := 0 + for r < length { + c := s[r] + if c == '\\' || c == '"' || c < ' ' { + break + } + if c < utf8.RuneSelf { + r++ + continue + } + rr, size := utf8.DecodeRune(s[r:]) + if rr == utf8.RuneError && size == 1 { + break + } + r += size + } + if r == length { + return s, true + } + + b := make([]byte, length+2*utf8.UTFMax) + w := copy(b, s[0:r]) + for r < length { + // Out of room? Can only happen if s is full of + // malformed UTF-8 and we're replacing each + // byte with RuneError. + if w >= len(b)-2*utf8.UTFMax { + nb := make([]byte, (len(b)+utf8.UTFMax)*2) + copy(nb, b[0:w]) + b = nb + } + switch c := s[r]; { + case c == '\\': + r++ + if r >= length { + return + } + switch s[r] { + default: + return + case '"', '\\', '/', '\'': + b[w] = s[r] + r++ + w++ + case 'b': + b[w] = '\b' + r++ + w++ + case 'f': + b[w] = '\f' + r++ + w++ + case 'n': + b[w] = '\n' + r++ + w++ + case 'r': + b[w] = '\r' + r++ + w++ + case 't': + b[w] = '\t' + r++ + w++ + case 'u': + r-- + rr := getu4(s[r:]) + if rr < 0 { + return + } + r += 6 + if utf16.IsSurrogate(rr) { + rr1 := getu4(s[r:]) + if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { + // A valid pair; consume. + r += 6 + w += utf8.EncodeRune(b[w:], dec) + break + } + // Invalid surrogate; fall back to replacement rune. + rr = unicode.ReplacementChar + } + w += utf8.EncodeRune(b[w:], rr) + } + + // Quote, control characters are invalid. + case c == '"', c < ' ': + return + + // ASCII + case c < utf8.RuneSelf: + b[w] = c + r++ + w++ + + // Coerce to well-formed UTF-8. + default: + rr, size := utf8.DecodeRune(s[r:]) + r += size + w += utf8.EncodeRune(b[w:], rr) + } + } + return b[0:w], true +} + +func getu4(s []byte) rune { + if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { + return -1 + } + var r rune + for _, c := range s[2:6] { + switch { + case '0' <= c && c <= '9': + c = c - '0' + case 'a' <= c && c <= 'f': + c = c - 'a' + 10 + case 'A' <= c && c <= 'F': + c = c - 'A' + 10 + default: + return -1 + } + r = r*16 + rune(c) + } + return r +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/wrapped_string.go b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/wrapped_string.go new file mode 100644 index 00000000..66227ae0 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/decoder/wrapped_string.go @@ -0,0 +1,68 @@ +package decoder + +import ( + "reflect" + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +type wrappedStringDecoder struct { + typ *runtime.Type + dec Decoder + stringDecoder *stringDecoder + structName string + fieldName string + isPtrType bool +} + +func newWrappedStringDecoder(typ *runtime.Type, dec Decoder, structName, fieldName string) *wrappedStringDecoder { + return &wrappedStringDecoder{ + typ: typ, + dec: dec, + stringDecoder: newStringDecoder(structName, fieldName), + structName: structName, + fieldName: fieldName, + isPtrType: typ.Kind() == reflect.Ptr, + } +} + +func (d *wrappedStringDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error { + bytes, err := d.stringDecoder.decodeStreamByte(s) + if err != nil { + return err + } + if bytes == nil { + if d.isPtrType { + *(*unsafe.Pointer)(p) = nil + } + return nil + } + b := make([]byte, len(bytes)+1) + copy(b, bytes) + if _, err := d.dec.Decode(&RuntimeContext{Buf: b}, 0, depth, p); err != nil { + return err + } + return nil +} + +func (d *wrappedStringDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) { + bytes, c, err := d.stringDecoder.decodeByte(ctx.Buf, cursor) + if err != nil { + return 0, err + } + if bytes == nil { + if d.isPtrType { + *(*unsafe.Pointer)(p) = nil + } + return c, nil + } + bytes = append(bytes, nul) + oldBuf := ctx.Buf + ctx.Buf = bytes + if _, err := d.dec.Decode(ctx, 0, depth, p); err != nil { + return 0, err + } + ctx.Buf = oldBuf + return c, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/code.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/code.go new file mode 100644 index 00000000..aee01015 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/code.go @@ -0,0 +1,875 @@ +package encoder + +import ( + "fmt" + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +type Code interface { + Kind() CodeKind + ToOpcode(*compileContext) Opcodes +} + +type AnonymousCode interface { + ToAnonymousOpcode(*compileContext) Opcodes +} + +type Opcodes []*Opcode + +func (o Opcodes) First() *Opcode { + if len(o) == 0 { + return nil + } + return o[0] +} + +func (o Opcodes) Last() *Opcode { + if len(o) == 0 { + return nil + } + return o[len(o)-1] +} + +func (o Opcodes) Add(codes ...*Opcode) Opcodes { + return append(o, codes...) +} + +type CodeKind int + +const ( + CodeKindInterface CodeKind = iota + CodeKindPtr + CodeKindInt + CodeKindUint + CodeKindFloat + CodeKindString + CodeKindBool + CodeKindStruct + CodeKindMap + CodeKindSlice + CodeKindArray + CodeKindBytes + CodeKindMarshalJSON + CodeKindMarshalText + CodeKindRecursive +) + +type IntCode struct { + typ *runtime.Type + bitSize uint8 + isString bool + isPtr bool +} + +func (c *IntCode) Kind() CodeKind { + return CodeKindInt +} + +func (c *IntCode) ToOpcode(ctx *compileContext) Opcodes { + var code *Opcode + switch { + case c.isPtr: + code = newOpCode(ctx, c.typ, OpIntPtr) + case c.isString: + code = newOpCode(ctx, c.typ, OpIntString) + default: + code = newOpCode(ctx, c.typ, OpInt) + } + code.NumBitSize = c.bitSize + ctx.incIndex() + return Opcodes{code} +} + +type UintCode struct { + typ *runtime.Type + bitSize uint8 + isString bool + isPtr bool +} + +func (c *UintCode) Kind() CodeKind { + return CodeKindUint +} + +func (c *UintCode) ToOpcode(ctx *compileContext) Opcodes { + var code *Opcode + switch { + case c.isPtr: + code = newOpCode(ctx, c.typ, OpUintPtr) + case c.isString: + code = newOpCode(ctx, c.typ, OpUintString) + default: + code = newOpCode(ctx, c.typ, OpUint) + } + code.NumBitSize = c.bitSize + ctx.incIndex() + return Opcodes{code} +} + +type FloatCode struct { + typ *runtime.Type + bitSize uint8 + isPtr bool +} + +func (c *FloatCode) Kind() CodeKind { + return CodeKindFloat +} + +func (c *FloatCode) ToOpcode(ctx *compileContext) Opcodes { + var code *Opcode + switch { + case c.isPtr: + switch c.bitSize { + case 32: + code = newOpCode(ctx, c.typ, OpFloat32Ptr) + default: + code = newOpCode(ctx, c.typ, OpFloat64Ptr) + } + default: + switch c.bitSize { + case 32: + code = newOpCode(ctx, c.typ, OpFloat32) + default: + code = newOpCode(ctx, c.typ, OpFloat64) + } + } + ctx.incIndex() + return Opcodes{code} +} + +type StringCode struct { + typ *runtime.Type + isPtr bool +} + +func (c *StringCode) Kind() CodeKind { + return CodeKindString +} + +func (c *StringCode) ToOpcode(ctx *compileContext) Opcodes { + isJSONNumberType := c.typ == runtime.Type2RType(jsonNumberType) + var code *Opcode + if c.isPtr { + if isJSONNumberType { + code = newOpCode(ctx, c.typ, OpNumberPtr) + } else { + code = newOpCode(ctx, c.typ, OpStringPtr) + } + } else { + if isJSONNumberType { + code = newOpCode(ctx, c.typ, OpNumber) + } else { + code = newOpCode(ctx, c.typ, OpString) + } + } + ctx.incIndex() + return Opcodes{code} +} + +type BoolCode struct { + typ *runtime.Type + isPtr bool +} + +func (c *BoolCode) Kind() CodeKind { + return CodeKindBool +} + +func (c *BoolCode) ToOpcode(ctx *compileContext) Opcodes { + var code *Opcode + switch { + case c.isPtr: + code = newOpCode(ctx, c.typ, OpBoolPtr) + default: + code = newOpCode(ctx, c.typ, OpBool) + } + ctx.incIndex() + return Opcodes{code} +} + +type BytesCode struct { + typ *runtime.Type + isPtr bool +} + +func (c *BytesCode) Kind() CodeKind { + return CodeKindBytes +} + +func (c *BytesCode) ToOpcode(ctx *compileContext) Opcodes { + var code *Opcode + switch { + case c.isPtr: + code = newOpCode(ctx, c.typ, OpBytesPtr) + default: + code = newOpCode(ctx, c.typ, OpBytes) + } + ctx.incIndex() + return Opcodes{code} +} + +type SliceCode struct { + typ *runtime.Type + value Code +} + +func (c *SliceCode) Kind() CodeKind { + return CodeKindSlice +} + +func (c *SliceCode) ToOpcode(ctx *compileContext) Opcodes { + // header => opcode => elem => end + // ^ | + // |________| + size := c.typ.Elem().Size() + header := newSliceHeaderCode(ctx, c.typ) + ctx.incIndex() + + ctx.incIndent() + codes := c.value.ToOpcode(ctx) + ctx.decIndent() + + codes.First().Flags |= IndirectFlags + elemCode := newSliceElemCode(ctx, c.typ.Elem(), header, size) + ctx.incIndex() + end := newOpCode(ctx, c.typ, OpSliceEnd) + ctx.incIndex() + header.End = end + header.Next = codes.First() + codes.Last().Next = elemCode + elemCode.Next = codes.First() + elemCode.End = end + return Opcodes{header}.Add(codes...).Add(elemCode).Add(end) +} + +type ArrayCode struct { + typ *runtime.Type + value Code +} + +func (c *ArrayCode) Kind() CodeKind { + return CodeKindArray +} + +func (c *ArrayCode) ToOpcode(ctx *compileContext) Opcodes { + // header => opcode => elem => end + // ^ | + // |________| + elem := c.typ.Elem() + alen := c.typ.Len() + size := elem.Size() + + header := newArrayHeaderCode(ctx, c.typ, alen) + ctx.incIndex() + + ctx.incIndent() + codes := c.value.ToOpcode(ctx) + ctx.decIndent() + + codes.First().Flags |= IndirectFlags + + elemCode := newArrayElemCode(ctx, elem, header, alen, size) + ctx.incIndex() + + end := newOpCode(ctx, c.typ, OpArrayEnd) + ctx.incIndex() + + header.End = end + header.Next = codes.First() + codes.Last().Next = elemCode + elemCode.Next = codes.First() + elemCode.End = end + + return Opcodes{header}.Add(codes...).Add(elemCode).Add(end) +} + +type MapCode struct { + typ *runtime.Type + key Code + value Code +} + +func (c *MapCode) Kind() CodeKind { + return CodeKindMap +} + +func (c *MapCode) ToOpcode(ctx *compileContext) Opcodes { + // header => code => value => code => key => code => value => code => end + // ^ | + // |_______________________| + header := newMapHeaderCode(ctx, c.typ) + ctx.incIndex() + + keyCodes := c.key.ToOpcode(ctx) + + value := newMapValueCode(ctx, c.typ.Elem(), header) + ctx.incIndex() + + ctx.incIndent() + valueCodes := c.value.ToOpcode(ctx) + ctx.decIndent() + + valueCodes.First().Flags |= IndirectFlags + + key := newMapKeyCode(ctx, c.typ.Key(), header) + ctx.incIndex() + + end := newMapEndCode(ctx, c.typ, header) + ctx.incIndex() + + header.Next = keyCodes.First() + keyCodes.Last().Next = value + value.Next = valueCodes.First() + valueCodes.Last().Next = key + key.Next = keyCodes.First() + + header.End = end + key.End = end + value.End = end + return Opcodes{header}.Add(keyCodes...).Add(value).Add(valueCodes...).Add(key).Add(end) +} + +type StructCode struct { + typ *runtime.Type + fields []*StructFieldCode + isPtr bool + disableIndirectConversion bool + isIndirect bool + isRecursive bool +} + +func (c *StructCode) Kind() CodeKind { + return CodeKindStruct +} + +func (c *StructCode) lastFieldCode(field *StructFieldCode, firstField *Opcode) *Opcode { + if field.isAnonymous { + return c.lastAnonymousFieldCode(firstField) + } + lastField := firstField + for lastField.NextField != nil { + lastField = lastField.NextField + } + return lastField +} + +func (c *StructCode) lastAnonymousFieldCode(firstField *Opcode) *Opcode { + // firstField is special StructHead operation for anonymous structure. + // So, StructHead's next operation is truly struct head operation. + lastField := firstField.Next + for lastField.NextField != nil { + lastField = lastField.NextField + } + return lastField +} + +func (c *StructCode) ToOpcode(ctx *compileContext) Opcodes { + // header => code => structField => code => end + // ^ | + // |__________| + if c.isRecursive { + recursive := newRecursiveCode(ctx, c.typ, &CompiledCode{}) + recursive.Type = c.typ + ctx.incIndex() + *ctx.recursiveCodes = append(*ctx.recursiveCodes, recursive) + return Opcodes{recursive} + } + codes := Opcodes{} + var prevField *Opcode + ctx.incIndent() + for idx, field := range c.fields { + isFirstField := idx == 0 + isEndField := idx == len(c.fields)-1 + fieldCodes := field.ToOpcode(ctx, isFirstField, isEndField) + for _, code := range fieldCodes { + if c.isIndirect { + code.Flags |= IndirectFlags + } + } + firstField := fieldCodes.First() + if len(codes) > 0 { + codes.Last().Next = firstField + firstField.Idx = codes.First().Idx + } + if prevField != nil { + prevField.NextField = firstField + } + if isEndField { + endField := fieldCodes.Last() + if len(codes) > 0 { + codes.First().End = endField + } else if field.isAnonymous { + firstField.End = endField + lastField := c.lastAnonymousFieldCode(firstField) + lastField.NextField = endField + } else { + firstField.End = endField + } + codes = codes.Add(fieldCodes...) + break + } + prevField = c.lastFieldCode(field, firstField) + codes = codes.Add(fieldCodes...) + } + if len(codes) == 0 { + head := &Opcode{ + Op: OpStructHead, + Idx: opcodeOffset(ctx.ptrIndex), + Type: c.typ, + DisplayIdx: ctx.opcodeIndex, + Indent: ctx.indent, + } + ctx.incOpcodeIndex() + end := &Opcode{ + Op: OpStructEnd, + Idx: opcodeOffset(ctx.ptrIndex), + DisplayIdx: ctx.opcodeIndex, + Indent: ctx.indent, + } + head.NextField = end + head.Next = end + head.End = end + codes = codes.Add(head, end) + ctx.incIndex() + } + ctx.decIndent() + ctx.structTypeToCodes[uintptr(unsafe.Pointer(c.typ))] = codes + return codes +} + +func (c *StructCode) ToAnonymousOpcode(ctx *compileContext) Opcodes { + // header => code => structField => code => end + // ^ | + // |__________| + if c.isRecursive { + recursive := newRecursiveCode(ctx, c.typ, &CompiledCode{}) + recursive.Type = c.typ + ctx.incIndex() + *ctx.recursiveCodes = append(*ctx.recursiveCodes, recursive) + return Opcodes{recursive} + } + codes := Opcodes{} + var prevField *Opcode + for idx, field := range c.fields { + isFirstField := idx == 0 + isEndField := idx == len(c.fields)-1 + fieldCodes := field.ToAnonymousOpcode(ctx, isFirstField, isEndField) + for _, code := range fieldCodes { + if c.isIndirect { + code.Flags |= IndirectFlags + } + } + firstField := fieldCodes.First() + if len(codes) > 0 { + codes.Last().Next = firstField + firstField.Idx = codes.First().Idx + } + if prevField != nil { + prevField.NextField = firstField + } + if isEndField { + lastField := fieldCodes.Last() + if len(codes) > 0 { + codes.First().End = lastField + } else { + firstField.End = lastField + } + } + prevField = firstField + codes = codes.Add(fieldCodes...) + } + return codes +} + +func (c *StructCode) removeFieldsByTags(tags runtime.StructTags) { + fields := make([]*StructFieldCode, 0, len(c.fields)) + for _, field := range c.fields { + if field.isAnonymous { + structCode := field.getAnonymousStruct() + if structCode != nil && !structCode.isRecursive { + structCode.removeFieldsByTags(tags) + if len(structCode.fields) > 0 { + fields = append(fields, field) + } + continue + } + } + if tags.ExistsKey(field.key) { + continue + } + fields = append(fields, field) + } + c.fields = fields +} + +func (c *StructCode) enableIndirect() { + if c.isIndirect { + return + } + c.isIndirect = true + if len(c.fields) == 0 { + return + } + structCode := c.fields[0].getStruct() + if structCode == nil { + return + } + structCode.enableIndirect() +} + +type StructFieldCode struct { + typ *runtime.Type + key string + tag *runtime.StructTag + value Code + offset uintptr + isAnonymous bool + isTaggedKey bool + isNilableType bool + isNilCheck bool + isAddrForMarshaler bool + isNextOpPtrType bool +} + +func (c *StructFieldCode) getStruct() *StructCode { + value := c.value + ptr, ok := value.(*PtrCode) + if ok { + value = ptr.value + } + structCode, ok := value.(*StructCode) + if ok { + return structCode + } + return nil +} + +func (c *StructFieldCode) getAnonymousStruct() *StructCode { + if !c.isAnonymous { + return nil + } + return c.getStruct() +} + +func optimizeStructHeader(code *Opcode, tag *runtime.StructTag) OpType { + headType := code.ToHeaderType(tag.IsString) + if tag.IsOmitEmpty { + headType = headType.HeadToOmitEmptyHead() + } + return headType +} + +func optimizeStructField(code *Opcode, tag *runtime.StructTag) OpType { + fieldType := code.ToFieldType(tag.IsString) + if tag.IsOmitEmpty { + fieldType = fieldType.FieldToOmitEmptyField() + } + return fieldType +} + +func (c *StructFieldCode) headerOpcodes(ctx *compileContext, field *Opcode, valueCodes Opcodes) Opcodes { + value := valueCodes.First() + op := optimizeStructHeader(value, c.tag) + field.Op = op + field.NumBitSize = value.NumBitSize + field.PtrNum = value.PtrNum + fieldCodes := Opcodes{field} + if op.IsMultipleOpHead() { + field.Next = value + fieldCodes = fieldCodes.Add(valueCodes...) + } else { + ctx.decIndex() + } + return fieldCodes +} + +func (c *StructFieldCode) fieldOpcodes(ctx *compileContext, field *Opcode, valueCodes Opcodes) Opcodes { + value := valueCodes.First() + op := optimizeStructField(value, c.tag) + field.Op = op + field.NumBitSize = value.NumBitSize + field.PtrNum = value.PtrNum + + fieldCodes := Opcodes{field} + if op.IsMultipleOpField() { + field.Next = value + fieldCodes = fieldCodes.Add(valueCodes...) + } else { + ctx.decIndex() + } + return fieldCodes +} + +func (c *StructFieldCode) addStructEndCode(ctx *compileContext, codes Opcodes) Opcodes { + end := &Opcode{ + Op: OpStructEnd, + Idx: opcodeOffset(ctx.ptrIndex), + DisplayIdx: ctx.opcodeIndex, + Indent: ctx.indent, + } + codes.Last().Next = end + codes.First().NextField = end + codes = codes.Add(end) + ctx.incOpcodeIndex() + return codes +} + +func (c *StructFieldCode) structKey(ctx *compileContext) string { + if ctx.escapeKey { + rctx := &RuntimeContext{Option: &Option{Flag: HTMLEscapeOption}} + return fmt.Sprintf(`%s:`, string(AppendString(rctx, []byte{}, c.key))) + } + return fmt.Sprintf(`"%s":`, c.key) +} + +func (c *StructFieldCode) flags() OpFlags { + var flags OpFlags + if c.isTaggedKey { + flags |= IsTaggedKeyFlags + } + if c.isNilableType { + flags |= IsNilableTypeFlags + } + if c.isNilCheck { + flags |= NilCheckFlags + } + if c.isAddrForMarshaler { + flags |= AddrForMarshalerFlags + } + if c.isNextOpPtrType { + flags |= IsNextOpPtrTypeFlags + } + if c.isAnonymous { + flags |= AnonymousKeyFlags + } + return flags +} + +func (c *StructFieldCode) toValueOpcodes(ctx *compileContext) Opcodes { + if c.isAnonymous { + anonymCode, ok := c.value.(AnonymousCode) + if ok { + return anonymCode.ToAnonymousOpcode(ctx) + } + } + return c.value.ToOpcode(ctx) +} + +func (c *StructFieldCode) ToOpcode(ctx *compileContext, isFirstField, isEndField bool) Opcodes { + field := &Opcode{ + Idx: opcodeOffset(ctx.ptrIndex), + Flags: c.flags(), + Key: c.structKey(ctx), + Offset: uint32(c.offset), + Type: c.typ, + DisplayIdx: ctx.opcodeIndex, + Indent: ctx.indent, + DisplayKey: c.key, + } + ctx.incIndex() + valueCodes := c.toValueOpcodes(ctx) + if isFirstField { + codes := c.headerOpcodes(ctx, field, valueCodes) + if isEndField { + codes = c.addStructEndCode(ctx, codes) + } + return codes + } + codes := c.fieldOpcodes(ctx, field, valueCodes) + if isEndField { + if isEnableStructEndOptimization(c.value) { + field.Op = field.Op.FieldToEnd() + } else { + codes = c.addStructEndCode(ctx, codes) + } + } + return codes +} + +func (c *StructFieldCode) ToAnonymousOpcode(ctx *compileContext, isFirstField, isEndField bool) Opcodes { + field := &Opcode{ + Idx: opcodeOffset(ctx.ptrIndex), + Flags: c.flags() | AnonymousHeadFlags, + Key: c.structKey(ctx), + Offset: uint32(c.offset), + Type: c.typ, + DisplayIdx: ctx.opcodeIndex, + Indent: ctx.indent, + DisplayKey: c.key, + } + ctx.incIndex() + valueCodes := c.toValueOpcodes(ctx) + if isFirstField { + return c.headerOpcodes(ctx, field, valueCodes) + } + return c.fieldOpcodes(ctx, field, valueCodes) +} + +func isEnableStructEndOptimization(value Code) bool { + switch value.Kind() { + case CodeKindInt, + CodeKindUint, + CodeKindFloat, + CodeKindString, + CodeKindBool, + CodeKindBytes: + return true + case CodeKindPtr: + return isEnableStructEndOptimization(value.(*PtrCode).value) + default: + return false + } +} + +type InterfaceCode struct { + typ *runtime.Type + isPtr bool +} + +func (c *InterfaceCode) Kind() CodeKind { + return CodeKindInterface +} + +func (c *InterfaceCode) ToOpcode(ctx *compileContext) Opcodes { + var code *Opcode + switch { + case c.isPtr: + code = newOpCode(ctx, c.typ, OpInterfacePtr) + default: + code = newOpCode(ctx, c.typ, OpInterface) + } + if c.typ.NumMethod() > 0 { + code.Flags |= NonEmptyInterfaceFlags + } + ctx.incIndex() + return Opcodes{code} +} + +type MarshalJSONCode struct { + typ *runtime.Type + isAddrForMarshaler bool + isNilableType bool + isMarshalerContext bool +} + +func (c *MarshalJSONCode) Kind() CodeKind { + return CodeKindMarshalJSON +} + +func (c *MarshalJSONCode) ToOpcode(ctx *compileContext) Opcodes { + code := newOpCode(ctx, c.typ, OpMarshalJSON) + if c.isAddrForMarshaler { + code.Flags |= AddrForMarshalerFlags + } + if c.isMarshalerContext { + code.Flags |= MarshalerContextFlags + } + if c.isNilableType { + code.Flags |= IsNilableTypeFlags + } else { + code.Flags &= ^IsNilableTypeFlags + } + ctx.incIndex() + return Opcodes{code} +} + +type MarshalTextCode struct { + typ *runtime.Type + isAddrForMarshaler bool + isNilableType bool +} + +func (c *MarshalTextCode) Kind() CodeKind { + return CodeKindMarshalText +} + +func (c *MarshalTextCode) ToOpcode(ctx *compileContext) Opcodes { + code := newOpCode(ctx, c.typ, OpMarshalText) + if c.isAddrForMarshaler { + code.Flags |= AddrForMarshalerFlags + } + if c.isNilableType { + code.Flags |= IsNilableTypeFlags + } else { + code.Flags &= ^IsNilableTypeFlags + } + ctx.incIndex() + return Opcodes{code} +} + +type PtrCode struct { + typ *runtime.Type + value Code + ptrNum uint8 +} + +func (c *PtrCode) Kind() CodeKind { + return CodeKindPtr +} + +func (c *PtrCode) ToOpcode(ctx *compileContext) Opcodes { + codes := c.value.ToOpcode(ctx) + codes.First().Op = convertPtrOp(codes.First()) + codes.First().PtrNum = c.ptrNum + return codes +} + +func (c *PtrCode) ToAnonymousOpcode(ctx *compileContext) Opcodes { + var codes Opcodes + anonymCode, ok := c.value.(AnonymousCode) + if ok { + codes = anonymCode.ToAnonymousOpcode(ctx) + } else { + codes = c.value.ToOpcode(ctx) + } + codes.First().Op = convertPtrOp(codes.First()) + codes.First().PtrNum = c.ptrNum + return codes +} + +func convertPtrOp(code *Opcode) OpType { + ptrHeadOp := code.Op.HeadToPtrHead() + if code.Op != ptrHeadOp { + if code.PtrNum > 0 { + // ptr field and ptr head + code.PtrNum-- + } + return ptrHeadOp + } + switch code.Op { + case OpInt: + return OpIntPtr + case OpUint: + return OpUintPtr + case OpFloat32: + return OpFloat32Ptr + case OpFloat64: + return OpFloat64Ptr + case OpString: + return OpStringPtr + case OpBool: + return OpBoolPtr + case OpBytes: + return OpBytesPtr + case OpNumber: + return OpNumberPtr + case OpArray: + return OpArrayPtr + case OpSlice: + return OpSlicePtr + case OpMap: + return OpMapPtr + case OpMarshalJSON: + return OpMarshalJSONPtr + case OpMarshalText: + return OpMarshalTextPtr + case OpInterface: + return OpInterfacePtr + case OpRecursive: + return OpRecursivePtr + } + return code.Op +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compact.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compact.go new file mode 100644 index 00000000..0eb9545d --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compact.go @@ -0,0 +1,286 @@ +package encoder + +import ( + "bytes" + "fmt" + "strconv" + "unsafe" + + "github.com/goccy/go-json/internal/errors" +) + +var ( + isWhiteSpace = [256]bool{ + ' ': true, + '\n': true, + '\t': true, + '\r': true, + } + isHTMLEscapeChar = [256]bool{ + '<': true, + '>': true, + '&': true, + } + nul = byte('\000') +) + +func Compact(buf *bytes.Buffer, src []byte, escape bool) error { + if len(src) == 0 { + return errors.ErrUnexpectedEndOfJSON("", 0) + } + buf.Grow(len(src)) + dst := buf.Bytes() + + ctx := TakeRuntimeContext() + ctxBuf := ctx.Buf[:0] + ctxBuf = append(append(ctxBuf, src...), nul) + ctx.Buf = ctxBuf + + if err := compactAndWrite(buf, dst, ctxBuf, escape); err != nil { + ReleaseRuntimeContext(ctx) + return err + } + ReleaseRuntimeContext(ctx) + return nil +} + +func compactAndWrite(buf *bytes.Buffer, dst []byte, src []byte, escape bool) error { + dst, err := compact(dst, src, escape) + if err != nil { + return err + } + if _, err := buf.Write(dst); err != nil { + return err + } + return nil +} + +func compact(dst, src []byte, escape bool) ([]byte, error) { + buf, cursor, err := compactValue(dst, src, 0, escape) + if err != nil { + return nil, err + } + if err := validateEndBuf(src, cursor); err != nil { + return nil, err + } + return buf, nil +} + +func validateEndBuf(src []byte, cursor int64) error { + for { + switch src[cursor] { + case ' ', '\t', '\n', '\r': + cursor++ + continue + case nul: + return nil + } + return errors.ErrSyntax( + fmt.Sprintf("invalid character '%c' after top-level value", src[cursor]), + cursor+1, + ) + } +} + +func skipWhiteSpace(buf []byte, cursor int64) int64 { +LOOP: + if isWhiteSpace[buf[cursor]] { + cursor++ + goto LOOP + } + return cursor +} + +func compactValue(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { + for { + switch src[cursor] { + case ' ', '\t', '\n', '\r': + cursor++ + continue + case '{': + return compactObject(dst, src, cursor, escape) + case '}': + return nil, 0, errors.ErrSyntax("unexpected character '}'", cursor) + case '[': + return compactArray(dst, src, cursor, escape) + case ']': + return nil, 0, errors.ErrSyntax("unexpected character ']'", cursor) + case '"': + return compactString(dst, src, cursor, escape) + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return compactNumber(dst, src, cursor) + case 't': + return compactTrue(dst, src, cursor) + case 'f': + return compactFalse(dst, src, cursor) + case 'n': + return compactNull(dst, src, cursor) + default: + return nil, 0, errors.ErrSyntax(fmt.Sprintf("unexpected character '%c'", src[cursor]), cursor) + } + } +} + +func compactObject(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { + if src[cursor] == '{' { + dst = append(dst, '{') + } else { + return nil, 0, errors.ErrExpected("expected { character for object value", cursor) + } + cursor = skipWhiteSpace(src, cursor+1) + if src[cursor] == '}' { + dst = append(dst, '}') + return dst, cursor + 1, nil + } + var err error + for { + cursor = skipWhiteSpace(src, cursor) + dst, cursor, err = compactString(dst, src, cursor, escape) + if err != nil { + return nil, 0, err + } + cursor = skipWhiteSpace(src, cursor) + if src[cursor] != ':' { + return nil, 0, errors.ErrExpected("colon after object key", cursor) + } + dst = append(dst, ':') + dst, cursor, err = compactValue(dst, src, cursor+1, escape) + if err != nil { + return nil, 0, err + } + cursor = skipWhiteSpace(src, cursor) + switch src[cursor] { + case '}': + dst = append(dst, '}') + cursor++ + return dst, cursor, nil + case ',': + dst = append(dst, ',') + default: + return nil, 0, errors.ErrExpected("comma after object value", cursor) + } + cursor++ + } +} + +func compactArray(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { + if src[cursor] == '[' { + dst = append(dst, '[') + } else { + return nil, 0, errors.ErrExpected("expected [ character for array value", cursor) + } + cursor = skipWhiteSpace(src, cursor+1) + if src[cursor] == ']' { + dst = append(dst, ']') + return dst, cursor + 1, nil + } + var err error + for { + dst, cursor, err = compactValue(dst, src, cursor, escape) + if err != nil { + return nil, 0, err + } + cursor = skipWhiteSpace(src, cursor) + switch src[cursor] { + case ']': + dst = append(dst, ']') + cursor++ + return dst, cursor, nil + case ',': + dst = append(dst, ',') + default: + return nil, 0, errors.ErrExpected("comma after array value", cursor) + } + cursor++ + } +} + +func compactString(dst, src []byte, cursor int64, escape bool) ([]byte, int64, error) { + if src[cursor] != '"' { + return nil, 0, errors.ErrInvalidCharacter(src[cursor], "string", cursor) + } + start := cursor + for { + cursor++ + c := src[cursor] + if escape { + if isHTMLEscapeChar[c] { + dst = append(dst, src[start:cursor]...) + dst = append(dst, `\u00`...) + dst = append(dst, hex[c>>4], hex[c&0xF]) + start = cursor + 1 + } else if c == 0xE2 && cursor+2 < int64(len(src)) && src[cursor+1] == 0x80 && src[cursor+2]&^1 == 0xA8 { + dst = append(dst, src[start:cursor]...) + dst = append(dst, `\u202`...) + dst = append(dst, hex[src[cursor+2]&0xF]) + cursor += 2 + start = cursor + 3 + } + } + switch c { + case '\\': + cursor++ + if src[cursor] == nul { + return nil, 0, errors.ErrUnexpectedEndOfJSON("string", int64(len(src))) + } + case '"': + cursor++ + return append(dst, src[start:cursor]...), cursor, nil + case nul: + return nil, 0, errors.ErrUnexpectedEndOfJSON("string", int64(len(src))) + } + } +} + +func compactNumber(dst, src []byte, cursor int64) ([]byte, int64, error) { + start := cursor + for { + cursor++ + if floatTable[src[cursor]] { + continue + } + break + } + num := src[start:cursor] + if _, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&num)), 64); err != nil { + return nil, 0, err + } + dst = append(dst, num...) + return dst, cursor, nil +} + +func compactTrue(dst, src []byte, cursor int64) ([]byte, int64, error) { + if cursor+3 >= int64(len(src)) { + return nil, 0, errors.ErrUnexpectedEndOfJSON("true", cursor) + } + if !bytes.Equal(src[cursor:cursor+4], []byte(`true`)) { + return nil, 0, errors.ErrInvalidCharacter(src[cursor], "true", cursor) + } + dst = append(dst, "true"...) + cursor += 4 + return dst, cursor, nil +} + +func compactFalse(dst, src []byte, cursor int64) ([]byte, int64, error) { + if cursor+4 >= int64(len(src)) { + return nil, 0, errors.ErrUnexpectedEndOfJSON("false", cursor) + } + if !bytes.Equal(src[cursor:cursor+5], []byte(`false`)) { + return nil, 0, errors.ErrInvalidCharacter(src[cursor], "false", cursor) + } + dst = append(dst, "false"...) + cursor += 5 + return dst, cursor, nil +} + +func compactNull(dst, src []byte, cursor int64) ([]byte, int64, error) { + if cursor+3 >= int64(len(src)) { + return nil, 0, errors.ErrUnexpectedEndOfJSON("null", cursor) + } + if !bytes.Equal(src[cursor:cursor+4], []byte(`null`)) { + return nil, 0, errors.ErrInvalidCharacter(src[cursor], "null", cursor) + } + dst = append(dst, "null"...) + cursor += 4 + return dst, cursor, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler.go new file mode 100644 index 00000000..cbcdb65e --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler.go @@ -0,0 +1,886 @@ +package encoder + +import ( + "context" + "encoding" + "encoding/json" + "reflect" + "sync/atomic" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +type marshalerContext interface { + MarshalJSON(context.Context) ([]byte, error) +} + +var ( + marshalJSONType = reflect.TypeOf((*json.Marshaler)(nil)).Elem() + marshalJSONContextType = reflect.TypeOf((*marshalerContext)(nil)).Elem() + marshalTextType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() + jsonNumberType = reflect.TypeOf(json.Number("")) + cachedOpcodeSets []*OpcodeSet + cachedOpcodeMap unsafe.Pointer // map[uintptr]*OpcodeSet + typeAddr *runtime.TypeAddr +) + +func init() { + typeAddr = runtime.AnalyzeTypeAddr() + if typeAddr == nil { + typeAddr = &runtime.TypeAddr{} + } + cachedOpcodeSets = make([]*OpcodeSet, typeAddr.AddrRange>>typeAddr.AddrShift) +} + +func loadOpcodeMap() map[uintptr]*OpcodeSet { + p := atomic.LoadPointer(&cachedOpcodeMap) + return *(*map[uintptr]*OpcodeSet)(unsafe.Pointer(&p)) +} + +func storeOpcodeSet(typ uintptr, set *OpcodeSet, m map[uintptr]*OpcodeSet) { + newOpcodeMap := make(map[uintptr]*OpcodeSet, len(m)+1) + newOpcodeMap[typ] = set + + for k, v := range m { + newOpcodeMap[k] = v + } + + atomic.StorePointer(&cachedOpcodeMap, *(*unsafe.Pointer)(unsafe.Pointer(&newOpcodeMap))) +} + +func compileToGetCodeSetSlowPath(typeptr uintptr) (*OpcodeSet, error) { + opcodeMap := loadOpcodeMap() + if codeSet, exists := opcodeMap[typeptr]; exists { + return codeSet, nil + } + codeSet, err := newCompiler().compile(typeptr) + if err != nil { + return nil, err + } + storeOpcodeSet(typeptr, codeSet, opcodeMap) + return codeSet, nil +} + +type Compiler struct { + structTypeToCode map[uintptr]*StructCode +} + +func newCompiler() *Compiler { + return &Compiler{ + structTypeToCode: map[uintptr]*StructCode{}, + } +} + +func (c *Compiler) compile(typeptr uintptr) (*OpcodeSet, error) { + // noescape trick for header.typ ( reflect.*rtype ) + typ := *(**runtime.Type)(unsafe.Pointer(&typeptr)) + code, err := c.typeToCode(typ) + if err != nil { + return nil, err + } + noescapeKeyCode := c.codeToOpcode(&compileContext{ + structTypeToCodes: map[uintptr]Opcodes{}, + recursiveCodes: &Opcodes{}, + }, typ, code) + if err := noescapeKeyCode.Validate(); err != nil { + return nil, err + } + escapeKeyCode := c.codeToOpcode(&compileContext{ + structTypeToCodes: map[uintptr]Opcodes{}, + recursiveCodes: &Opcodes{}, + escapeKey: true, + }, typ, code) + noescapeKeyCode = copyOpcode(noescapeKeyCode) + escapeKeyCode = copyOpcode(escapeKeyCode) + setTotalLengthToInterfaceOp(noescapeKeyCode) + setTotalLengthToInterfaceOp(escapeKeyCode) + interfaceNoescapeKeyCode := copyToInterfaceOpcode(noescapeKeyCode) + interfaceEscapeKeyCode := copyToInterfaceOpcode(escapeKeyCode) + codeLength := noescapeKeyCode.TotalLength() + return &OpcodeSet{ + Type: typ, + NoescapeKeyCode: noescapeKeyCode, + EscapeKeyCode: escapeKeyCode, + InterfaceNoescapeKeyCode: interfaceNoescapeKeyCode, + InterfaceEscapeKeyCode: interfaceEscapeKeyCode, + CodeLength: codeLength, + EndCode: ToEndCode(interfaceNoescapeKeyCode), + }, nil +} + +func (c *Compiler) typeToCode(typ *runtime.Type) (Code, error) { + switch { + case c.implementsMarshalJSON(typ): + return c.marshalJSONCode(typ) + case c.implementsMarshalText(typ): + return c.marshalTextCode(typ) + } + + isPtr := false + orgType := typ + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + isPtr = true + } + switch { + case c.implementsMarshalJSON(typ): + return c.marshalJSONCode(orgType) + case c.implementsMarshalText(typ): + return c.marshalTextCode(orgType) + } + switch typ.Kind() { + case reflect.Slice: + elem := typ.Elem() + if elem.Kind() == reflect.Uint8 { + p := runtime.PtrTo(elem) + if !c.implementsMarshalJSONType(p) && !p.Implements(marshalTextType) { + return c.bytesCode(typ, isPtr) + } + } + return c.sliceCode(typ) + case reflect.Map: + if isPtr { + return c.ptrCode(runtime.PtrTo(typ)) + } + return c.mapCode(typ) + case reflect.Struct: + return c.structCode(typ, isPtr) + case reflect.Int: + return c.intCode(typ, isPtr) + case reflect.Int8: + return c.int8Code(typ, isPtr) + case reflect.Int16: + return c.int16Code(typ, isPtr) + case reflect.Int32: + return c.int32Code(typ, isPtr) + case reflect.Int64: + return c.int64Code(typ, isPtr) + case reflect.Uint, reflect.Uintptr: + return c.uintCode(typ, isPtr) + case reflect.Uint8: + return c.uint8Code(typ, isPtr) + case reflect.Uint16: + return c.uint16Code(typ, isPtr) + case reflect.Uint32: + return c.uint32Code(typ, isPtr) + case reflect.Uint64: + return c.uint64Code(typ, isPtr) + case reflect.Float32: + return c.float32Code(typ, isPtr) + case reflect.Float64: + return c.float64Code(typ, isPtr) + case reflect.String: + return c.stringCode(typ, isPtr) + case reflect.Bool: + return c.boolCode(typ, isPtr) + case reflect.Interface: + return c.interfaceCode(typ, isPtr) + default: + if isPtr && typ.Implements(marshalTextType) { + typ = orgType + } + return c.typeToCodeWithPtr(typ, isPtr) + } +} + +func (c *Compiler) typeToCodeWithPtr(typ *runtime.Type, isPtr bool) (Code, error) { + switch { + case c.implementsMarshalJSON(typ): + return c.marshalJSONCode(typ) + case c.implementsMarshalText(typ): + return c.marshalTextCode(typ) + } + switch typ.Kind() { + case reflect.Ptr: + return c.ptrCode(typ) + case reflect.Slice: + elem := typ.Elem() + if elem.Kind() == reflect.Uint8 { + p := runtime.PtrTo(elem) + if !c.implementsMarshalJSONType(p) && !p.Implements(marshalTextType) { + return c.bytesCode(typ, false) + } + } + return c.sliceCode(typ) + case reflect.Array: + return c.arrayCode(typ) + case reflect.Map: + return c.mapCode(typ) + case reflect.Struct: + return c.structCode(typ, isPtr) + case reflect.Interface: + return c.interfaceCode(typ, false) + case reflect.Int: + return c.intCode(typ, false) + case reflect.Int8: + return c.int8Code(typ, false) + case reflect.Int16: + return c.int16Code(typ, false) + case reflect.Int32: + return c.int32Code(typ, false) + case reflect.Int64: + return c.int64Code(typ, false) + case reflect.Uint: + return c.uintCode(typ, false) + case reflect.Uint8: + return c.uint8Code(typ, false) + case reflect.Uint16: + return c.uint16Code(typ, false) + case reflect.Uint32: + return c.uint32Code(typ, false) + case reflect.Uint64: + return c.uint64Code(typ, false) + case reflect.Uintptr: + return c.uintCode(typ, false) + case reflect.Float32: + return c.float32Code(typ, false) + case reflect.Float64: + return c.float64Code(typ, false) + case reflect.String: + return c.stringCode(typ, false) + case reflect.Bool: + return c.boolCode(typ, false) + } + return nil, &errors.UnsupportedTypeError{Type: runtime.RType2Type(typ)} +} + +const intSize = 32 << (^uint(0) >> 63) + +//nolint:unparam +func (c *Compiler) intCode(typ *runtime.Type, isPtr bool) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: intSize, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) int8Code(typ *runtime.Type, isPtr bool) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 8, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) int16Code(typ *runtime.Type, isPtr bool) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 16, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) int32Code(typ *runtime.Type, isPtr bool) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 32, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) int64Code(typ *runtime.Type, isPtr bool) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 64, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) uintCode(typ *runtime.Type, isPtr bool) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: intSize, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) uint8Code(typ *runtime.Type, isPtr bool) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 8, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) uint16Code(typ *runtime.Type, isPtr bool) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 16, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) uint32Code(typ *runtime.Type, isPtr bool) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 32, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) uint64Code(typ *runtime.Type, isPtr bool) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 64, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) float32Code(typ *runtime.Type, isPtr bool) (*FloatCode, error) { + return &FloatCode{typ: typ, bitSize: 32, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) float64Code(typ *runtime.Type, isPtr bool) (*FloatCode, error) { + return &FloatCode{typ: typ, bitSize: 64, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) stringCode(typ *runtime.Type, isPtr bool) (*StringCode, error) { + return &StringCode{typ: typ, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) boolCode(typ *runtime.Type, isPtr bool) (*BoolCode, error) { + return &BoolCode{typ: typ, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) intStringCode(typ *runtime.Type) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: intSize, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) int8StringCode(typ *runtime.Type) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 8, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) int16StringCode(typ *runtime.Type) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 16, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) int32StringCode(typ *runtime.Type) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 32, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) int64StringCode(typ *runtime.Type) (*IntCode, error) { + return &IntCode{typ: typ, bitSize: 64, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) uintStringCode(typ *runtime.Type) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: intSize, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) uint8StringCode(typ *runtime.Type) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 8, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) uint16StringCode(typ *runtime.Type) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 16, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) uint32StringCode(typ *runtime.Type) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 32, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) uint64StringCode(typ *runtime.Type) (*UintCode, error) { + return &UintCode{typ: typ, bitSize: 64, isString: true}, nil +} + +//nolint:unparam +func (c *Compiler) bytesCode(typ *runtime.Type, isPtr bool) (*BytesCode, error) { + return &BytesCode{typ: typ, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) interfaceCode(typ *runtime.Type, isPtr bool) (*InterfaceCode, error) { + return &InterfaceCode{typ: typ, isPtr: isPtr}, nil +} + +//nolint:unparam +func (c *Compiler) marshalJSONCode(typ *runtime.Type) (*MarshalJSONCode, error) { + return &MarshalJSONCode{ + typ: typ, + isAddrForMarshaler: c.isPtrMarshalJSONType(typ), + isNilableType: c.isNilableType(typ), + isMarshalerContext: typ.Implements(marshalJSONContextType) || runtime.PtrTo(typ).Implements(marshalJSONContextType), + }, nil +} + +//nolint:unparam +func (c *Compiler) marshalTextCode(typ *runtime.Type) (*MarshalTextCode, error) { + return &MarshalTextCode{ + typ: typ, + isAddrForMarshaler: c.isPtrMarshalTextType(typ), + isNilableType: c.isNilableType(typ), + }, nil +} + +func (c *Compiler) ptrCode(typ *runtime.Type) (*PtrCode, error) { + code, err := c.typeToCodeWithPtr(typ.Elem(), true) + if err != nil { + return nil, err + } + ptr, ok := code.(*PtrCode) + if ok { + return &PtrCode{typ: typ, value: ptr.value, ptrNum: ptr.ptrNum + 1}, nil + } + return &PtrCode{typ: typ, value: code, ptrNum: 1}, nil +} + +func (c *Compiler) sliceCode(typ *runtime.Type) (*SliceCode, error) { + elem := typ.Elem() + code, err := c.listElemCode(elem) + if err != nil { + return nil, err + } + if code.Kind() == CodeKindStruct { + structCode := code.(*StructCode) + structCode.enableIndirect() + } + return &SliceCode{typ: typ, value: code}, nil +} + +func (c *Compiler) arrayCode(typ *runtime.Type) (*ArrayCode, error) { + elem := typ.Elem() + code, err := c.listElemCode(elem) + if err != nil { + return nil, err + } + if code.Kind() == CodeKindStruct { + structCode := code.(*StructCode) + structCode.enableIndirect() + } + return &ArrayCode{typ: typ, value: code}, nil +} + +func (c *Compiler) mapCode(typ *runtime.Type) (*MapCode, error) { + keyCode, err := c.mapKeyCode(typ.Key()) + if err != nil { + return nil, err + } + valueCode, err := c.mapValueCode(typ.Elem()) + if err != nil { + return nil, err + } + if valueCode.Kind() == CodeKindStruct { + structCode := valueCode.(*StructCode) + structCode.enableIndirect() + } + return &MapCode{typ: typ, key: keyCode, value: valueCode}, nil +} + +func (c *Compiler) listElemCode(typ *runtime.Type) (Code, error) { + switch { + case c.isPtrMarshalJSONType(typ): + return c.marshalJSONCode(typ) + case !typ.Implements(marshalTextType) && runtime.PtrTo(typ).Implements(marshalTextType): + return c.marshalTextCode(typ) + case typ.Kind() == reflect.Map: + return c.ptrCode(runtime.PtrTo(typ)) + default: + code, err := c.typeToCodeWithPtr(typ, false) + if err != nil { + return nil, err + } + ptr, ok := code.(*PtrCode) + if ok { + if ptr.value.Kind() == CodeKindMap { + ptr.ptrNum++ + } + } + return code, nil + } +} + +func (c *Compiler) mapKeyCode(typ *runtime.Type) (Code, error) { + switch { + case c.implementsMarshalJSON(typ): + return c.marshalJSONCode(typ) + case c.implementsMarshalText(typ): + return c.marshalTextCode(typ) + } + switch typ.Kind() { + case reflect.Ptr: + return c.ptrCode(typ) + case reflect.String: + return c.stringCode(typ, false) + case reflect.Int: + return c.intStringCode(typ) + case reflect.Int8: + return c.int8StringCode(typ) + case reflect.Int16: + return c.int16StringCode(typ) + case reflect.Int32: + return c.int32StringCode(typ) + case reflect.Int64: + return c.int64StringCode(typ) + case reflect.Uint: + return c.uintStringCode(typ) + case reflect.Uint8: + return c.uint8StringCode(typ) + case reflect.Uint16: + return c.uint16StringCode(typ) + case reflect.Uint32: + return c.uint32StringCode(typ) + case reflect.Uint64: + return c.uint64StringCode(typ) + case reflect.Uintptr: + return c.uintStringCode(typ) + } + return nil, &errors.UnsupportedTypeError{Type: runtime.RType2Type(typ)} +} + +func (c *Compiler) mapValueCode(typ *runtime.Type) (Code, error) { + switch typ.Kind() { + case reflect.Map: + return c.ptrCode(runtime.PtrTo(typ)) + default: + code, err := c.typeToCodeWithPtr(typ, false) + if err != nil { + return nil, err + } + ptr, ok := code.(*PtrCode) + if ok { + if ptr.value.Kind() == CodeKindMap { + ptr.ptrNum++ + } + } + return code, nil + } +} + +func (c *Compiler) structCode(typ *runtime.Type, isPtr bool) (*StructCode, error) { + typeptr := uintptr(unsafe.Pointer(typ)) + if code, exists := c.structTypeToCode[typeptr]; exists { + derefCode := *code + derefCode.isRecursive = true + return &derefCode, nil + } + indirect := runtime.IfaceIndir(typ) + code := &StructCode{typ: typ, isPtr: isPtr, isIndirect: indirect} + c.structTypeToCode[typeptr] = code + + fieldNum := typ.NumField() + tags := c.typeToStructTags(typ) + fields := []*StructFieldCode{} + for i, tag := range tags { + isOnlyOneFirstField := i == 0 && fieldNum == 1 + field, err := c.structFieldCode(code, tag, isPtr, isOnlyOneFirstField) + if err != nil { + return nil, err + } + if field.isAnonymous { + structCode := field.getAnonymousStruct() + if structCode != nil { + structCode.removeFieldsByTags(tags) + if c.isAssignableIndirect(field, isPtr) { + if indirect { + structCode.isIndirect = true + } else { + structCode.isIndirect = false + } + } + } + } else { + structCode := field.getStruct() + if structCode != nil { + if indirect { + // if parent is indirect type, set child indirect property to true + structCode.isIndirect = true + } else { + // if parent is not indirect type, set child indirect property to false. + // but if parent's indirect is false and isPtr is true, then indirect must be true. + // Do this only if indirectConversion is enabled at the end of compileStruct. + structCode.isIndirect = false + } + } + } + fields = append(fields, field) + } + fieldMap := c.getFieldMap(fields) + duplicatedFieldMap := c.getDuplicatedFieldMap(fieldMap) + code.fields = c.filteredDuplicatedFields(fields, duplicatedFieldMap) + if !code.disableIndirectConversion && !indirect && isPtr { + code.enableIndirect() + } + delete(c.structTypeToCode, typeptr) + return code, nil +} + +func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTag, isPtr, isOnlyOneFirstField bool) (*StructFieldCode, error) { + field := tag.Field + fieldType := runtime.Type2RType(field.Type) + isIndirectSpecialCase := isPtr && isOnlyOneFirstField + fieldCode := &StructFieldCode{ + typ: fieldType, + key: tag.Key, + tag: tag, + offset: field.Offset, + isAnonymous: field.Anonymous && !tag.IsTaggedKey, + isTaggedKey: tag.IsTaggedKey, + isNilableType: c.isNilableType(fieldType), + isNilCheck: true, + } + switch { + case c.isMovePointerPositionFromHeadToFirstMarshalJSONFieldCase(fieldType, isIndirectSpecialCase): + code, err := c.marshalJSONCode(fieldType) + if err != nil { + return nil, err + } + fieldCode.value = code + fieldCode.isAddrForMarshaler = true + fieldCode.isNilCheck = false + structCode.isIndirect = false + structCode.disableIndirectConversion = true + case c.isMovePointerPositionFromHeadToFirstMarshalTextFieldCase(fieldType, isIndirectSpecialCase): + code, err := c.marshalTextCode(fieldType) + if err != nil { + return nil, err + } + fieldCode.value = code + fieldCode.isAddrForMarshaler = true + fieldCode.isNilCheck = false + structCode.isIndirect = false + structCode.disableIndirectConversion = true + case isPtr && c.isPtrMarshalJSONType(fieldType): + // *struct{ field T } + // func (*T) MarshalJSON() ([]byte, error) + code, err := c.marshalJSONCode(fieldType) + if err != nil { + return nil, err + } + fieldCode.value = code + fieldCode.isAddrForMarshaler = true + fieldCode.isNilCheck = false + case isPtr && c.isPtrMarshalTextType(fieldType): + // *struct{ field T } + // func (*T) MarshalText() ([]byte, error) + code, err := c.marshalTextCode(fieldType) + if err != nil { + return nil, err + } + fieldCode.value = code + fieldCode.isAddrForMarshaler = true + fieldCode.isNilCheck = false + default: + code, err := c.typeToCodeWithPtr(fieldType, isPtr) + if err != nil { + return nil, err + } + switch code.Kind() { + case CodeKindPtr, CodeKindInterface: + fieldCode.isNextOpPtrType = true + } + fieldCode.value = code + } + return fieldCode, nil +} + +func (c *Compiler) isAssignableIndirect(fieldCode *StructFieldCode, isPtr bool) bool { + if isPtr { + return false + } + codeType := fieldCode.value.Kind() + if codeType == CodeKindMarshalJSON { + return false + } + if codeType == CodeKindMarshalText { + return false + } + return true +} + +func (c *Compiler) getFieldMap(fields []*StructFieldCode) map[string][]*StructFieldCode { + fieldMap := map[string][]*StructFieldCode{} + for _, field := range fields { + if field.isAnonymous { + for k, v := range c.getAnonymousFieldMap(field) { + fieldMap[k] = append(fieldMap[k], v...) + } + continue + } + fieldMap[field.key] = append(fieldMap[field.key], field) + } + return fieldMap +} + +func (c *Compiler) getAnonymousFieldMap(field *StructFieldCode) map[string][]*StructFieldCode { + fieldMap := map[string][]*StructFieldCode{} + structCode := field.getAnonymousStruct() + if structCode == nil || structCode.isRecursive { + fieldMap[field.key] = append(fieldMap[field.key], field) + return fieldMap + } + for k, v := range c.getFieldMapFromAnonymousParent(structCode.fields) { + fieldMap[k] = append(fieldMap[k], v...) + } + return fieldMap +} + +func (c *Compiler) getFieldMapFromAnonymousParent(fields []*StructFieldCode) map[string][]*StructFieldCode { + fieldMap := map[string][]*StructFieldCode{} + for _, field := range fields { + if field.isAnonymous { + for k, v := range c.getAnonymousFieldMap(field) { + // Do not handle tagged key when embedding more than once + for _, vv := range v { + vv.isTaggedKey = false + } + fieldMap[k] = append(fieldMap[k], v...) + } + continue + } + fieldMap[field.key] = append(fieldMap[field.key], field) + } + return fieldMap +} + +func (c *Compiler) getDuplicatedFieldMap(fieldMap map[string][]*StructFieldCode) map[*StructFieldCode]struct{} { + duplicatedFieldMap := map[*StructFieldCode]struct{}{} + for _, fields := range fieldMap { + if len(fields) == 1 { + continue + } + if c.isTaggedKeyOnly(fields) { + for _, field := range fields { + if field.isTaggedKey { + continue + } + duplicatedFieldMap[field] = struct{}{} + } + } else { + for _, field := range fields { + duplicatedFieldMap[field] = struct{}{} + } + } + } + return duplicatedFieldMap +} + +func (c *Compiler) filteredDuplicatedFields(fields []*StructFieldCode, duplicatedFieldMap map[*StructFieldCode]struct{}) []*StructFieldCode { + filteredFields := make([]*StructFieldCode, 0, len(fields)) + for _, field := range fields { + if field.isAnonymous { + structCode := field.getAnonymousStruct() + if structCode != nil && !structCode.isRecursive { + structCode.fields = c.filteredDuplicatedFields(structCode.fields, duplicatedFieldMap) + if len(structCode.fields) > 0 { + filteredFields = append(filteredFields, field) + } + continue + } + } + if _, exists := duplicatedFieldMap[field]; exists { + continue + } + filteredFields = append(filteredFields, field) + } + return filteredFields +} + +func (c *Compiler) isTaggedKeyOnly(fields []*StructFieldCode) bool { + var taggedKeyFieldCount int + for _, field := range fields { + if field.isTaggedKey { + taggedKeyFieldCount++ + } + } + return taggedKeyFieldCount == 1 +} + +func (c *Compiler) typeToStructTags(typ *runtime.Type) runtime.StructTags { + tags := runtime.StructTags{} + fieldNum := typ.NumField() + for i := 0; i < fieldNum; i++ { + field := typ.Field(i) + if runtime.IsIgnoredStructField(field) { + continue + } + tags = append(tags, runtime.StructTagFromField(field)) + } + return tags +} + +// *struct{ field T } => struct { field *T } +// func (*T) MarshalJSON() ([]byte, error) +func (c *Compiler) isMovePointerPositionFromHeadToFirstMarshalJSONFieldCase(typ *runtime.Type, isIndirectSpecialCase bool) bool { + return isIndirectSpecialCase && !c.isNilableType(typ) && c.isPtrMarshalJSONType(typ) +} + +// *struct{ field T } => struct { field *T } +// func (*T) MarshalText() ([]byte, error) +func (c *Compiler) isMovePointerPositionFromHeadToFirstMarshalTextFieldCase(typ *runtime.Type, isIndirectSpecialCase bool) bool { + return isIndirectSpecialCase && !c.isNilableType(typ) && c.isPtrMarshalTextType(typ) +} + +func (c *Compiler) implementsMarshalJSON(typ *runtime.Type) bool { + if !c.implementsMarshalJSONType(typ) { + return false + } + if typ.Kind() != reflect.Ptr { + return true + } + // type kind is reflect.Ptr + if !c.implementsMarshalJSONType(typ.Elem()) { + return true + } + // needs to dereference + return false +} + +func (c *Compiler) implementsMarshalText(typ *runtime.Type) bool { + if !typ.Implements(marshalTextType) { + return false + } + if typ.Kind() != reflect.Ptr { + return true + } + // type kind is reflect.Ptr + if !typ.Elem().Implements(marshalTextType) { + return true + } + // needs to dereference + return false +} + +func (c *Compiler) isNilableType(typ *runtime.Type) bool { + switch typ.Kind() { + case reflect.Ptr: + return true + case reflect.Map: + return true + case reflect.Func: + return true + default: + return false + } +} + +func (c *Compiler) implementsMarshalJSONType(typ *runtime.Type) bool { + return typ.Implements(marshalJSONType) || typ.Implements(marshalJSONContextType) +} + +func (c *Compiler) isPtrMarshalJSONType(typ *runtime.Type) bool { + return !c.implementsMarshalJSONType(typ) && c.implementsMarshalJSONType(runtime.PtrTo(typ)) +} + +func (c *Compiler) isPtrMarshalTextType(typ *runtime.Type) bool { + return !typ.Implements(marshalTextType) && runtime.PtrTo(typ).Implements(marshalTextType) +} + +func (c *Compiler) codeToOpcode(ctx *compileContext, typ *runtime.Type, code Code) *Opcode { + codes := code.ToOpcode(ctx) + codes.Last().Next = newEndOp(ctx, typ) + c.linkRecursiveCode(ctx) + return codes.First() +} + +func (c *Compiler) linkRecursiveCode(ctx *compileContext) { + for _, recursive := range *ctx.recursiveCodes { + typeptr := uintptr(unsafe.Pointer(recursive.Type)) + codes := ctx.structTypeToCodes[typeptr] + compiled := recursive.Jmp + compiled.Code = copyOpcode(codes.First()) + code := compiled.Code + code.End.Next = newEndOp(&compileContext{}, recursive.Type) + code.Op = code.Op.PtrHeadToHead() + + beforeLastCode := code.End + lastCode := beforeLastCode.Next + + totalLength := code.TotalLength() + lastCode.Idx = uint32((totalLength + 1) * uintptrSize) + lastCode.ElemIdx = lastCode.Idx + uintptrSize + lastCode.Length = lastCode.Idx + 2*uintptrSize + code.End.Next.Op = OpRecursiveEnd + + // extend length to alloc slot for elemIdx + length + curTotalLength := uintptr(recursive.TotalLength()) + 3 + nextTotalLength := uintptr(totalLength) + 3 + compiled.CurLen = curTotalLength + compiled.NextLen = nextTotalLength + compiled.Linked = true + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_norace.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_norace.go new file mode 100644 index 00000000..afc5b662 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_norace.go @@ -0,0 +1,20 @@ +//go:build !race +// +build !race + +package encoder + +func CompileToGetCodeSet(typeptr uintptr) (*OpcodeSet, error) { + if typeptr > typeAddr.MaxTypeAddr { + return compileToGetCodeSetSlowPath(typeptr) + } + index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift + if codeSet := cachedOpcodeSets[index]; codeSet != nil { + return codeSet, nil + } + codeSet, err := newCompiler().compile(typeptr) + if err != nil { + return nil, err + } + cachedOpcodeSets[index] = codeSet + return codeSet, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_race.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_race.go new file mode 100644 index 00000000..846a898d --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/compiler_race.go @@ -0,0 +1,32 @@ +//go:build race +// +build race + +package encoder + +import ( + "sync" +) + +var setsMu sync.RWMutex + +func CompileToGetCodeSet(typeptr uintptr) (*OpcodeSet, error) { + if typeptr > typeAddr.MaxTypeAddr { + return compileToGetCodeSetSlowPath(typeptr) + } + index := (typeptr - typeAddr.BaseTypeAddr) >> typeAddr.AddrShift + setsMu.RLock() + if codeSet := cachedOpcodeSets[index]; codeSet != nil { + setsMu.RUnlock() + return codeSet, nil + } + setsMu.RUnlock() + + codeSet, err := newCompiler().compile(typeptr) + if err != nil { + return nil, err + } + setsMu.Lock() + cachedOpcodeSets[index] = codeSet + setsMu.Unlock() + return codeSet, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/context.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/context.go new file mode 100644 index 00000000..3833d0c8 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/context.go @@ -0,0 +1,105 @@ +package encoder + +import ( + "context" + "sync" + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +type compileContext struct { + opcodeIndex uint32 + ptrIndex int + indent uint32 + escapeKey bool + structTypeToCodes map[uintptr]Opcodes + recursiveCodes *Opcodes +} + +func (c *compileContext) incIndent() { + c.indent++ +} + +func (c *compileContext) decIndent() { + c.indent-- +} + +func (c *compileContext) incIndex() { + c.incOpcodeIndex() + c.incPtrIndex() +} + +func (c *compileContext) decIndex() { + c.decOpcodeIndex() + c.decPtrIndex() +} + +func (c *compileContext) incOpcodeIndex() { + c.opcodeIndex++ +} + +func (c *compileContext) decOpcodeIndex() { + c.opcodeIndex-- +} + +func (c *compileContext) incPtrIndex() { + c.ptrIndex++ +} + +func (c *compileContext) decPtrIndex() { + c.ptrIndex-- +} + +const ( + bufSize = 1024 +) + +var ( + runtimeContextPool = sync.Pool{ + New: func() interface{} { + return &RuntimeContext{ + Buf: make([]byte, 0, bufSize), + Ptrs: make([]uintptr, 128), + KeepRefs: make([]unsafe.Pointer, 0, 8), + Option: &Option{}, + } + }, + } +) + +type RuntimeContext struct { + Context context.Context + Buf []byte + MarshalBuf []byte + Ptrs []uintptr + KeepRefs []unsafe.Pointer + SeenPtr []uintptr + BaseIndent uint32 + Prefix []byte + IndentStr []byte + Option *Option +} + +func (c *RuntimeContext) Init(p uintptr, codelen int) { + if len(c.Ptrs) < codelen { + c.Ptrs = make([]uintptr, codelen) + } + c.Ptrs[0] = p + c.KeepRefs = c.KeepRefs[:0] + c.SeenPtr = c.SeenPtr[:0] + c.BaseIndent = 0 +} + +func (c *RuntimeContext) Ptr() uintptr { + header := (*runtime.SliceHeader)(unsafe.Pointer(&c.Ptrs)) + return uintptr(header.Data) +} + +func TakeRuntimeContext() *RuntimeContext { + return runtimeContextPool.Get().(*RuntimeContext) +} + +func ReleaseRuntimeContext(ctx *RuntimeContext) { + runtimeContextPool.Put(ctx) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/encoder.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/encoder.go new file mode 100644 index 00000000..b7fa99a9 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/encoder.go @@ -0,0 +1,551 @@ +package encoder + +import ( + "bytes" + "encoding" + "encoding/base64" + "encoding/json" + "fmt" + "math" + "reflect" + "strconv" + "strings" + "sync" + "unsafe" + + "github.com/goccy/go-json/internal/errors" + "github.com/goccy/go-json/internal/runtime" +) + +func (t OpType) IsMultipleOpHead() bool { + switch t { + case OpStructHead: + return true + case OpStructHeadSlice: + return true + case OpStructHeadArray: + return true + case OpStructHeadMap: + return true + case OpStructHeadStruct: + return true + case OpStructHeadOmitEmpty: + return true + case OpStructHeadOmitEmptySlice: + return true + case OpStructHeadOmitEmptyArray: + return true + case OpStructHeadOmitEmptyMap: + return true + case OpStructHeadOmitEmptyStruct: + return true + case OpStructHeadSlicePtr: + return true + case OpStructHeadOmitEmptySlicePtr: + return true + case OpStructHeadArrayPtr: + return true + case OpStructHeadOmitEmptyArrayPtr: + return true + case OpStructHeadMapPtr: + return true + case OpStructHeadOmitEmptyMapPtr: + return true + } + return false +} + +func (t OpType) IsMultipleOpField() bool { + switch t { + case OpStructField: + return true + case OpStructFieldSlice: + return true + case OpStructFieldArray: + return true + case OpStructFieldMap: + return true + case OpStructFieldStruct: + return true + case OpStructFieldOmitEmpty: + return true + case OpStructFieldOmitEmptySlice: + return true + case OpStructFieldOmitEmptyArray: + return true + case OpStructFieldOmitEmptyMap: + return true + case OpStructFieldOmitEmptyStruct: + return true + case OpStructFieldSlicePtr: + return true + case OpStructFieldOmitEmptySlicePtr: + return true + case OpStructFieldArrayPtr: + return true + case OpStructFieldOmitEmptyArrayPtr: + return true + case OpStructFieldMapPtr: + return true + case OpStructFieldOmitEmptyMapPtr: + return true + } + return false +} + +type OpcodeSet struct { + Type *runtime.Type + NoescapeKeyCode *Opcode + EscapeKeyCode *Opcode + InterfaceNoescapeKeyCode *Opcode + InterfaceEscapeKeyCode *Opcode + CodeLength int + EndCode *Opcode +} + +type CompiledCode struct { + Code *Opcode + Linked bool // whether recursive code already have linked + CurLen uintptr + NextLen uintptr +} + +const StartDetectingCyclesAfter = 1000 + +func Load(base uintptr, idx uintptr) uintptr { + addr := base + idx + return **(**uintptr)(unsafe.Pointer(&addr)) +} + +func Store(base uintptr, idx uintptr, p uintptr) { + addr := base + idx + **(**uintptr)(unsafe.Pointer(&addr)) = p +} + +func LoadNPtr(base uintptr, idx uintptr, ptrNum int) uintptr { + addr := base + idx + p := **(**uintptr)(unsafe.Pointer(&addr)) + if p == 0 { + return 0 + } + return PtrToPtr(p) + /* + for i := 0; i < ptrNum; i++ { + if p == 0 { + return p + } + p = PtrToPtr(p) + } + return p + */ +} + +func PtrToUint64(p uintptr) uint64 { return **(**uint64)(unsafe.Pointer(&p)) } +func PtrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } +func PtrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } +func PtrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } +func PtrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } +func PtrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } +func PtrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } +func PtrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } +func PtrToPtr(p uintptr) uintptr { + return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) +} +func PtrToNPtr(p uintptr, ptrNum int) uintptr { + for i := 0; i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = PtrToPtr(p) + } + return p +} + +func PtrToUnsafePtr(p uintptr) unsafe.Pointer { + return *(*unsafe.Pointer)(unsafe.Pointer(&p)) +} +func PtrToInterface(code *Opcode, p uintptr) interface{} { + return *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: code.Type, + ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), + })) +} + +func ErrUnsupportedValue(code *Opcode, ptr uintptr) *errors.UnsupportedValueError { + v := *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: code.Type, + ptr: *(*unsafe.Pointer)(unsafe.Pointer(&ptr)), + })) + return &errors.UnsupportedValueError{ + Value: reflect.ValueOf(v), + Str: fmt.Sprintf("encountered a cycle via %s", code.Type), + } +} + +func ErrUnsupportedFloat(v float64) *errors.UnsupportedValueError { + return &errors.UnsupportedValueError{ + Value: reflect.ValueOf(v), + Str: strconv.FormatFloat(v, 'g', -1, 64), + } +} + +func ErrMarshalerWithCode(code *Opcode, err error) *errors.MarshalerError { + return &errors.MarshalerError{ + Type: runtime.RType2Type(code.Type), + Err: err, + } +} + +type emptyInterface struct { + typ *runtime.Type + ptr unsafe.Pointer +} + +type MapItem struct { + Key []byte + Value []byte +} + +type Mapslice struct { + Items []MapItem +} + +func (m *Mapslice) Len() int { + return len(m.Items) +} + +func (m *Mapslice) Less(i, j int) bool { + return bytes.Compare(m.Items[i].Key, m.Items[j].Key) < 0 +} + +func (m *Mapslice) Swap(i, j int) { + m.Items[i], m.Items[j] = m.Items[j], m.Items[i] +} + +type MapContext struct { + Pos []int + Slice *Mapslice + Buf []byte +} + +var mapContextPool = sync.Pool{ + New: func() interface{} { + return &MapContext{} + }, +} + +func NewMapContext(mapLen int) *MapContext { + ctx := mapContextPool.Get().(*MapContext) + if ctx.Slice == nil { + ctx.Slice = &Mapslice{ + Items: make([]MapItem, 0, mapLen), + } + } + if cap(ctx.Pos) < (mapLen*2 + 1) { + ctx.Pos = make([]int, 0, mapLen*2+1) + ctx.Slice.Items = make([]MapItem, 0, mapLen) + } else { + ctx.Pos = ctx.Pos[:0] + ctx.Slice.Items = ctx.Slice.Items[:0] + } + ctx.Buf = ctx.Buf[:0] + return ctx +} + +func ReleaseMapContext(c *MapContext) { + mapContextPool.Put(c) +} + +//go:linkname MapIterInit reflect.mapiterinit +//go:noescape +func MapIterInit(mapType *runtime.Type, m unsafe.Pointer) unsafe.Pointer + +//go:linkname MapIterKey reflect.mapiterkey +//go:noescape +func MapIterKey(it unsafe.Pointer) unsafe.Pointer + +//go:linkname MapIterNext reflect.mapiternext +//go:noescape +func MapIterNext(it unsafe.Pointer) + +//go:linkname MapLen reflect.maplen +//go:noescape +func MapLen(m unsafe.Pointer) int + +func AppendByteSlice(_ *RuntimeContext, b []byte, src []byte) []byte { + if src == nil { + return append(b, `null`...) + } + encodedLen := base64.StdEncoding.EncodedLen(len(src)) + b = append(b, '"') + pos := len(b) + remainLen := cap(b[pos:]) + var buf []byte + if remainLen > encodedLen { + buf = b[pos : pos+encodedLen] + } else { + buf = make([]byte, encodedLen) + } + base64.StdEncoding.Encode(buf, src) + return append(append(b, buf...), '"') +} + +func AppendFloat32(_ *RuntimeContext, b []byte, v float32) []byte { + f64 := float64(v) + abs := math.Abs(f64) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + f32 := float32(abs) + if f32 < 1e-6 || f32 >= 1e21 { + fmt = 'e' + } + } + return strconv.AppendFloat(b, f64, fmt, -1, 32) +} + +func AppendFloat64(_ *RuntimeContext, b []byte, v float64) []byte { + abs := math.Abs(v) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + if abs < 1e-6 || abs >= 1e21 { + fmt = 'e' + } + } + return strconv.AppendFloat(b, v, fmt, -1, 64) +} + +func AppendBool(_ *RuntimeContext, b []byte, v bool) []byte { + if v { + return append(b, "true"...) + } + return append(b, "false"...) +} + +var ( + floatTable = [256]bool{ + '0': true, + '1': true, + '2': true, + '3': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '9': true, + '.': true, + 'e': true, + 'E': true, + '+': true, + '-': true, + } +) + +func AppendNumber(_ *RuntimeContext, b []byte, n json.Number) ([]byte, error) { + if len(n) == 0 { + return append(b, '0'), nil + } + for i := 0; i < len(n); i++ { + if !floatTable[n[i]] { + return nil, fmt.Errorf("json: invalid number literal %q", n) + } + } + b = append(b, n...) + return b, nil +} + +func AppendMarshalJSON(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { + rv := reflect.ValueOf(v) // convert by dynamic interface type + if (code.Flags & AddrForMarshalerFlags) != 0 { + if rv.CanAddr() { + rv = rv.Addr() + } else { + newV := reflect.New(rv.Type()) + newV.Elem().Set(rv) + rv = newV + } + } + v = rv.Interface() + var bb []byte + if (code.Flags & MarshalerContextFlags) != 0 { + marshaler, ok := v.(marshalerContext) + if !ok { + return AppendNull(ctx, b), nil + } + b, err := marshaler.MarshalJSON(ctx.Option.Context) + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + bb = b + } else { + marshaler, ok := v.(json.Marshaler) + if !ok { + return AppendNull(ctx, b), nil + } + b, err := marshaler.MarshalJSON() + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + bb = b + } + marshalBuf := ctx.MarshalBuf[:0] + marshalBuf = append(append(marshalBuf, bb...), nul) + compactedBuf, err := compact(b, marshalBuf, (ctx.Option.Flag&HTMLEscapeOption) != 0) + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + ctx.MarshalBuf = marshalBuf + return compactedBuf, nil +} + +func AppendMarshalJSONIndent(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { + rv := reflect.ValueOf(v) // convert by dynamic interface type + if (code.Flags & AddrForMarshalerFlags) != 0 { + if rv.CanAddr() { + rv = rv.Addr() + } else { + newV := reflect.New(rv.Type()) + newV.Elem().Set(rv) + rv = newV + } + } + v = rv.Interface() + var bb []byte + if (code.Flags & MarshalerContextFlags) != 0 { + marshaler, ok := v.(marshalerContext) + if !ok { + return AppendNull(ctx, b), nil + } + b, err := marshaler.MarshalJSON(ctx.Option.Context) + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + bb = b + } else { + marshaler, ok := v.(json.Marshaler) + if !ok { + return AppendNull(ctx, b), nil + } + b, err := marshaler.MarshalJSON() + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + bb = b + } + marshalBuf := ctx.MarshalBuf[:0] + marshalBuf = append(append(marshalBuf, bb...), nul) + indentedBuf, err := doIndent( + b, + marshalBuf, + string(ctx.Prefix)+strings.Repeat(string(ctx.IndentStr), int(ctx.BaseIndent+code.Indent)), + string(ctx.IndentStr), + (ctx.Option.Flag&HTMLEscapeOption) != 0, + ) + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + ctx.MarshalBuf = marshalBuf + return indentedBuf, nil +} + +func AppendMarshalText(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { + rv := reflect.ValueOf(v) // convert by dynamic interface type + if (code.Flags & AddrForMarshalerFlags) != 0 { + if rv.CanAddr() { + rv = rv.Addr() + } else { + newV := reflect.New(rv.Type()) + newV.Elem().Set(rv) + rv = newV + } + } + v = rv.Interface() + marshaler, ok := v.(encoding.TextMarshaler) + if !ok { + return AppendNull(ctx, b), nil + } + bytes, err := marshaler.MarshalText() + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + return AppendString(ctx, b, *(*string)(unsafe.Pointer(&bytes))), nil +} + +func AppendMarshalTextIndent(ctx *RuntimeContext, code *Opcode, b []byte, v interface{}) ([]byte, error) { + rv := reflect.ValueOf(v) // convert by dynamic interface type + if (code.Flags & AddrForMarshalerFlags) != 0 { + if rv.CanAddr() { + rv = rv.Addr() + } else { + newV := reflect.New(rv.Type()) + newV.Elem().Set(rv) + rv = newV + } + } + v = rv.Interface() + marshaler, ok := v.(encoding.TextMarshaler) + if !ok { + return AppendNull(ctx, b), nil + } + bytes, err := marshaler.MarshalText() + if err != nil { + return nil, &errors.MarshalerError{Type: reflect.TypeOf(v), Err: err} + } + return AppendString(ctx, b, *(*string)(unsafe.Pointer(&bytes))), nil +} + +func AppendNull(_ *RuntimeContext, b []byte) []byte { + return append(b, "null"...) +} + +func AppendComma(_ *RuntimeContext, b []byte) []byte { + return append(b, ',') +} + +func AppendCommaIndent(_ *RuntimeContext, b []byte) []byte { + return append(b, ',', '\n') +} + +func AppendStructEnd(_ *RuntimeContext, b []byte) []byte { + return append(b, '}', ',') +} + +func AppendStructEndIndent(ctx *RuntimeContext, code *Opcode, b []byte) []byte { + b = append(b, '\n') + b = append(b, ctx.Prefix...) + indentNum := ctx.BaseIndent + code.Indent - 1 + for i := uint32(0); i < indentNum; i++ { + b = append(b, ctx.IndentStr...) + } + return append(b, '}', ',', '\n') +} + +func AppendIndent(ctx *RuntimeContext, b []byte, indent uint32) []byte { + b = append(b, ctx.Prefix...) + indentNum := ctx.BaseIndent + indent + for i := uint32(0); i < indentNum; i++ { + b = append(b, ctx.IndentStr...) + } + return b +} + +func IsNilForMarshaler(v interface{}) bool { + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Bool: + return !rv.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rv.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return rv.Uint() == 0 + case reflect.Float32, reflect.Float64: + return math.Float64bits(rv.Float()) == 0 + case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Func: + return rv.IsNil() + case reflect.Slice: + return rv.IsNil() || rv.Len() == 0 + } + return false +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/indent.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/indent.go new file mode 100644 index 00000000..dfe04b5e --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/indent.go @@ -0,0 +1,211 @@ +package encoder + +import ( + "bytes" + "fmt" + + "github.com/goccy/go-json/internal/errors" +) + +func takeIndentSrcRuntimeContext(src []byte) (*RuntimeContext, []byte) { + ctx := TakeRuntimeContext() + buf := ctx.Buf[:0] + buf = append(append(buf, src...), nul) + ctx.Buf = buf + return ctx, buf +} + +func Indent(buf *bytes.Buffer, src []byte, prefix, indentStr string) error { + if len(src) == 0 { + return errors.ErrUnexpectedEndOfJSON("", 0) + } + + srcCtx, srcBuf := takeIndentSrcRuntimeContext(src) + dstCtx := TakeRuntimeContext() + dst := dstCtx.Buf[:0] + + dst, err := indentAndWrite(buf, dst, srcBuf, prefix, indentStr) + if err != nil { + ReleaseRuntimeContext(srcCtx) + ReleaseRuntimeContext(dstCtx) + return err + } + dstCtx.Buf = dst + ReleaseRuntimeContext(srcCtx) + ReleaseRuntimeContext(dstCtx) + return nil +} + +func indentAndWrite(buf *bytes.Buffer, dst []byte, src []byte, prefix, indentStr string) ([]byte, error) { + dst, err := doIndent(dst, src, prefix, indentStr, false) + if err != nil { + return nil, err + } + if _, err := buf.Write(dst); err != nil { + return nil, err + } + return dst, nil +} + +func doIndent(dst, src []byte, prefix, indentStr string, escape bool) ([]byte, error) { + buf, cursor, err := indentValue(dst, src, 0, 0, []byte(prefix), []byte(indentStr), escape) + if err != nil { + return nil, err + } + if err := validateEndBuf(src, cursor); err != nil { + return nil, err + } + return buf, nil +} + +func indentValue( + dst []byte, + src []byte, + indentNum int, + cursor int64, + prefix []byte, + indentBytes []byte, + escape bool) ([]byte, int64, error) { + for { + switch src[cursor] { + case ' ', '\t', '\n', '\r': + cursor++ + continue + case '{': + return indentObject(dst, src, indentNum, cursor, prefix, indentBytes, escape) + case '}': + return nil, 0, errors.ErrSyntax("unexpected character '}'", cursor) + case '[': + return indentArray(dst, src, indentNum, cursor, prefix, indentBytes, escape) + case ']': + return nil, 0, errors.ErrSyntax("unexpected character ']'", cursor) + case '"': + return compactString(dst, src, cursor, escape) + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + return compactNumber(dst, src, cursor) + case 't': + return compactTrue(dst, src, cursor) + case 'f': + return compactFalse(dst, src, cursor) + case 'n': + return compactNull(dst, src, cursor) + default: + return nil, 0, errors.ErrSyntax(fmt.Sprintf("unexpected character '%c'", src[cursor]), cursor) + } + } +} + +func indentObject( + dst []byte, + src []byte, + indentNum int, + cursor int64, + prefix []byte, + indentBytes []byte, + escape bool) ([]byte, int64, error) { + if src[cursor] == '{' { + dst = append(dst, '{') + } else { + return nil, 0, errors.ErrExpected("expected { character for object value", cursor) + } + cursor = skipWhiteSpace(src, cursor+1) + if src[cursor] == '}' { + dst = append(dst, '}') + return dst, cursor + 1, nil + } + indentNum++ + var err error + for { + dst = append(append(dst, '\n'), prefix...) + for i := 0; i < indentNum; i++ { + dst = append(dst, indentBytes...) + } + cursor = skipWhiteSpace(src, cursor) + dst, cursor, err = compactString(dst, src, cursor, escape) + if err != nil { + return nil, 0, err + } + cursor = skipWhiteSpace(src, cursor) + if src[cursor] != ':' { + return nil, 0, errors.ErrSyntax( + fmt.Sprintf("invalid character '%c' after object key", src[cursor]), + cursor+1, + ) + } + dst = append(dst, ':', ' ') + dst, cursor, err = indentValue(dst, src, indentNum, cursor+1, prefix, indentBytes, escape) + if err != nil { + return nil, 0, err + } + cursor = skipWhiteSpace(src, cursor) + switch src[cursor] { + case '}': + dst = append(append(dst, '\n'), prefix...) + for i := 0; i < indentNum-1; i++ { + dst = append(dst, indentBytes...) + } + dst = append(dst, '}') + cursor++ + return dst, cursor, nil + case ',': + dst = append(dst, ',') + default: + return nil, 0, errors.ErrSyntax( + fmt.Sprintf("invalid character '%c' after object key:value pair", src[cursor]), + cursor+1, + ) + } + cursor++ + } +} + +func indentArray( + dst []byte, + src []byte, + indentNum int, + cursor int64, + prefix []byte, + indentBytes []byte, + escape bool) ([]byte, int64, error) { + if src[cursor] == '[' { + dst = append(dst, '[') + } else { + return nil, 0, errors.ErrExpected("expected [ character for array value", cursor) + } + cursor = skipWhiteSpace(src, cursor+1) + if src[cursor] == ']' { + dst = append(dst, ']') + return dst, cursor + 1, nil + } + indentNum++ + var err error + for { + dst = append(append(dst, '\n'), prefix...) + for i := 0; i < indentNum; i++ { + dst = append(dst, indentBytes...) + } + dst, cursor, err = indentValue(dst, src, indentNum, cursor, prefix, indentBytes, escape) + if err != nil { + return nil, 0, err + } + cursor = skipWhiteSpace(src, cursor) + switch src[cursor] { + case ']': + dst = append(append(dst, '\n'), prefix...) + for i := 0; i < indentNum-1; i++ { + dst = append(dst, indentBytes...) + } + dst = append(dst, ']') + cursor++ + return dst, cursor, nil + case ',': + dst = append(dst, ',') + default: + return nil, 0, errors.ErrSyntax( + fmt.Sprintf("invalid character '%c' after array value", src[cursor]), + cursor+1, + ) + } + cursor++ + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/int.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/int.go new file mode 100644 index 00000000..85f07960 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/int.go @@ -0,0 +1,152 @@ +package encoder + +import ( + "unsafe" +) + +var endianness int + +func init() { + var b [2]byte + *(*uint16)(unsafe.Pointer(&b)) = uint16(0xABCD) + + switch b[0] { + case 0xCD: + endianness = 0 // LE + case 0xAB: + endianness = 1 // BE + default: + panic("could not determine endianness") + } +} + +// "00010203...96979899" cast to []uint16 +var intLELookup = [100]uint16{ + 0x3030, 0x3130, 0x3230, 0x3330, 0x3430, 0x3530, 0x3630, 0x3730, 0x3830, 0x3930, + 0x3031, 0x3131, 0x3231, 0x3331, 0x3431, 0x3531, 0x3631, 0x3731, 0x3831, 0x3931, + 0x3032, 0x3132, 0x3232, 0x3332, 0x3432, 0x3532, 0x3632, 0x3732, 0x3832, 0x3932, + 0x3033, 0x3133, 0x3233, 0x3333, 0x3433, 0x3533, 0x3633, 0x3733, 0x3833, 0x3933, + 0x3034, 0x3134, 0x3234, 0x3334, 0x3434, 0x3534, 0x3634, 0x3734, 0x3834, 0x3934, + 0x3035, 0x3135, 0x3235, 0x3335, 0x3435, 0x3535, 0x3635, 0x3735, 0x3835, 0x3935, + 0x3036, 0x3136, 0x3236, 0x3336, 0x3436, 0x3536, 0x3636, 0x3736, 0x3836, 0x3936, + 0x3037, 0x3137, 0x3237, 0x3337, 0x3437, 0x3537, 0x3637, 0x3737, 0x3837, 0x3937, + 0x3038, 0x3138, 0x3238, 0x3338, 0x3438, 0x3538, 0x3638, 0x3738, 0x3838, 0x3938, + 0x3039, 0x3139, 0x3239, 0x3339, 0x3439, 0x3539, 0x3639, 0x3739, 0x3839, 0x3939, +} + +var intBELookup = [100]uint16{ + 0x3030, 0x3031, 0x3032, 0x3033, 0x3034, 0x3035, 0x3036, 0x3037, 0x3038, 0x3039, + 0x3130, 0x3131, 0x3132, 0x3133, 0x3134, 0x3135, 0x3136, 0x3137, 0x3138, 0x3139, + 0x3230, 0x3231, 0x3232, 0x3233, 0x3234, 0x3235, 0x3236, 0x3237, 0x3238, 0x3239, + 0x3330, 0x3331, 0x3332, 0x3333, 0x3334, 0x3335, 0x3336, 0x3337, 0x3338, 0x3339, + 0x3430, 0x3431, 0x3432, 0x3433, 0x3434, 0x3435, 0x3436, 0x3437, 0x3438, 0x3439, + 0x3530, 0x3531, 0x3532, 0x3533, 0x3534, 0x3535, 0x3536, 0x3537, 0x3538, 0x3539, + 0x3630, 0x3631, 0x3632, 0x3633, 0x3634, 0x3635, 0x3636, 0x3637, 0x3638, 0x3639, + 0x3730, 0x3731, 0x3732, 0x3733, 0x3734, 0x3735, 0x3736, 0x3737, 0x3738, 0x3739, + 0x3830, 0x3831, 0x3832, 0x3833, 0x3834, 0x3835, 0x3836, 0x3837, 0x3838, 0x3839, + 0x3930, 0x3931, 0x3932, 0x3933, 0x3934, 0x3935, 0x3936, 0x3937, 0x3938, 0x3939, +} + +var intLookup = [2]*[100]uint16{&intLELookup, &intBELookup} + +func numMask(numBitSize uint8) uint64 { + return 1<>(code.NumBitSize-1))&1 == 1 + if !negative { + if n < 10 { + return append(out, byte(n+'0')) + } else if n < 100 { + u := intLELookup[n] + return append(out, byte(u), byte(u>>8)) + } + } else { + n = -n & mask + } + + lookup := intLookup[endianness] + + var b [22]byte + u := (*[11]uint16)(unsafe.Pointer(&b)) + i := 11 + + for n >= 100 { + j := n % 100 + n /= 100 + i-- + u[i] = lookup[j] + } + + i-- + u[i] = lookup[n] + + i *= 2 // convert to byte index + if n < 10 { + i++ // remove leading zero + } + if negative { + i-- + b[i] = '-' + } + + return append(out, b[i:]...) +} + +func AppendUint(_ *RuntimeContext, out []byte, p uintptr, code *Opcode) []byte { + var u64 uint64 + switch code.NumBitSize { + case 8: + u64 = (uint64)(**(**uint8)(unsafe.Pointer(&p))) + case 16: + u64 = (uint64)(**(**uint16)(unsafe.Pointer(&p))) + case 32: + u64 = (uint64)(**(**uint32)(unsafe.Pointer(&p))) + case 64: + u64 = **(**uint64)(unsafe.Pointer(&p)) + } + mask := numMask(code.NumBitSize) + n := u64 & mask + if n < 10 { + return append(out, byte(n+'0')) + } else if n < 100 { + u := intLELookup[n] + return append(out, byte(u), byte(u>>8)) + } + + lookup := intLookup[endianness] + + var b [22]byte + u := (*[11]uint16)(unsafe.Pointer(&b)) + i := 11 + + for n >= 100 { + j := n % 100 + n /= 100 + i-- + u[i] = lookup[j] + } + + i-- + u[i] = lookup[n] + + i *= 2 // convert to byte index + if n < 10 { + i++ // remove leading zero + } + return append(out, b[i:]...) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map112.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map112.go new file mode 100644 index 00000000..31858d00 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map112.go @@ -0,0 +1,8 @@ +// +build !go1.13 + +package encoder + +import "unsafe" + +//go:linkname MapIterValue reflect.mapitervalue +func MapIterValue(it unsafe.Pointer) unsafe.Pointer diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map113.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map113.go new file mode 100644 index 00000000..f49c27be --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/map113.go @@ -0,0 +1,8 @@ +// +build go1.13 + +package encoder + +import "unsafe" + +//go:linkname MapIterValue reflect.mapiterelem +func MapIterValue(it unsafe.Pointer) unsafe.Pointer diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/opcode.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/opcode.go new file mode 100644 index 00000000..cfd2d5a1 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/opcode.go @@ -0,0 +1,701 @@ +package encoder + +import ( + "fmt" + "strings" + "unsafe" + + "github.com/goccy/go-json/internal/runtime" +) + +const uintptrSize = 4 << (^uintptr(0) >> 63) + +type OpFlags uint16 + +const ( + AnonymousHeadFlags OpFlags = 1 << 0 + AnonymousKeyFlags OpFlags = 1 << 1 + IndirectFlags OpFlags = 1 << 2 + IsTaggedKeyFlags OpFlags = 1 << 3 + NilCheckFlags OpFlags = 1 << 4 + AddrForMarshalerFlags OpFlags = 1 << 5 + IsNextOpPtrTypeFlags OpFlags = 1 << 6 + IsNilableTypeFlags OpFlags = 1 << 7 + MarshalerContextFlags OpFlags = 1 << 8 + NonEmptyInterfaceFlags OpFlags = 1 << 9 +) + +type Opcode struct { + Op OpType // operation type + Idx uint32 // offset to access ptr + Next *Opcode // next opcode + End *Opcode // array/slice/struct/map end + NextField *Opcode // next struct field + Key string // struct field key + Offset uint32 // offset size from struct header + PtrNum uint8 // pointer number: e.g. double pointer is 2. + NumBitSize uint8 + Flags OpFlags + + Type *runtime.Type // go type + Jmp *CompiledCode // for recursive call + ElemIdx uint32 // offset to access array/slice/map elem + Length uint32 // offset to access slice/map length or array length + MapIter uint32 // offset to access map iterator + MapPos uint32 // offset to access position list for sorted map + Indent uint32 // indent number + Size uint32 // array/slice elem size + DisplayIdx uint32 // opcode index + DisplayKey string // key text to display +} + +func (c *Opcode) Validate() error { + var prevIdx uint32 + for code := c; !code.IsEnd(); { + if prevIdx != 0 { + if code.DisplayIdx != prevIdx+1 { + return fmt.Errorf( + "invalid index. previous display index is %d but next is %d. dump = %s", + prevIdx, code.DisplayIdx, c.Dump(), + ) + } + } + prevIdx = code.DisplayIdx + code = code.IterNext() + } + return nil +} + +func (c *Opcode) IterNext() *Opcode { + if c == nil { + return nil + } + switch c.Op.CodeType() { + case CodeArrayElem, CodeSliceElem, CodeMapKey: + return c.End + default: + return c.Next + } +} + +func (c *Opcode) IsEnd() bool { + if c == nil { + return true + } + return c.Op == OpEnd || c.Op == OpInterfaceEnd || c.Op == OpRecursiveEnd +} + +func (c *Opcode) MaxIdx() uint32 { + max := uint32(0) + for _, value := range []uint32{ + c.Idx, + c.ElemIdx, + c.Length, + c.MapIter, + c.MapPos, + c.Size, + } { + if max < value { + max = value + } + } + return max +} + +func (c *Opcode) ToHeaderType(isString bool) OpType { + switch c.Op { + case OpInt: + if isString { + return OpStructHeadIntString + } + return OpStructHeadInt + case OpIntPtr: + if isString { + return OpStructHeadIntPtrString + } + return OpStructHeadIntPtr + case OpUint: + if isString { + return OpStructHeadUintString + } + return OpStructHeadUint + case OpUintPtr: + if isString { + return OpStructHeadUintPtrString + } + return OpStructHeadUintPtr + case OpFloat32: + if isString { + return OpStructHeadFloat32String + } + return OpStructHeadFloat32 + case OpFloat32Ptr: + if isString { + return OpStructHeadFloat32PtrString + } + return OpStructHeadFloat32Ptr + case OpFloat64: + if isString { + return OpStructHeadFloat64String + } + return OpStructHeadFloat64 + case OpFloat64Ptr: + if isString { + return OpStructHeadFloat64PtrString + } + return OpStructHeadFloat64Ptr + case OpString: + if isString { + return OpStructHeadStringString + } + return OpStructHeadString + case OpStringPtr: + if isString { + return OpStructHeadStringPtrString + } + return OpStructHeadStringPtr + case OpNumber: + if isString { + return OpStructHeadNumberString + } + return OpStructHeadNumber + case OpNumberPtr: + if isString { + return OpStructHeadNumberPtrString + } + return OpStructHeadNumberPtr + case OpBool: + if isString { + return OpStructHeadBoolString + } + return OpStructHeadBool + case OpBoolPtr: + if isString { + return OpStructHeadBoolPtrString + } + return OpStructHeadBoolPtr + case OpBytes: + return OpStructHeadBytes + case OpBytesPtr: + return OpStructHeadBytesPtr + case OpMap: + return OpStructHeadMap + case OpMapPtr: + c.Op = OpMap + return OpStructHeadMapPtr + case OpArray: + return OpStructHeadArray + case OpArrayPtr: + c.Op = OpArray + return OpStructHeadArrayPtr + case OpSlice: + return OpStructHeadSlice + case OpSlicePtr: + c.Op = OpSlice + return OpStructHeadSlicePtr + case OpMarshalJSON: + return OpStructHeadMarshalJSON + case OpMarshalJSONPtr: + return OpStructHeadMarshalJSONPtr + case OpMarshalText: + return OpStructHeadMarshalText + case OpMarshalTextPtr: + return OpStructHeadMarshalTextPtr + } + return OpStructHead +} + +func (c *Opcode) ToFieldType(isString bool) OpType { + switch c.Op { + case OpInt: + if isString { + return OpStructFieldIntString + } + return OpStructFieldInt + case OpIntPtr: + if isString { + return OpStructFieldIntPtrString + } + return OpStructFieldIntPtr + case OpUint: + if isString { + return OpStructFieldUintString + } + return OpStructFieldUint + case OpUintPtr: + if isString { + return OpStructFieldUintPtrString + } + return OpStructFieldUintPtr + case OpFloat32: + if isString { + return OpStructFieldFloat32String + } + return OpStructFieldFloat32 + case OpFloat32Ptr: + if isString { + return OpStructFieldFloat32PtrString + } + return OpStructFieldFloat32Ptr + case OpFloat64: + if isString { + return OpStructFieldFloat64String + } + return OpStructFieldFloat64 + case OpFloat64Ptr: + if isString { + return OpStructFieldFloat64PtrString + } + return OpStructFieldFloat64Ptr + case OpString: + if isString { + return OpStructFieldStringString + } + return OpStructFieldString + case OpStringPtr: + if isString { + return OpStructFieldStringPtrString + } + return OpStructFieldStringPtr + case OpNumber: + if isString { + return OpStructFieldNumberString + } + return OpStructFieldNumber + case OpNumberPtr: + if isString { + return OpStructFieldNumberPtrString + } + return OpStructFieldNumberPtr + case OpBool: + if isString { + return OpStructFieldBoolString + } + return OpStructFieldBool + case OpBoolPtr: + if isString { + return OpStructFieldBoolPtrString + } + return OpStructFieldBoolPtr + case OpBytes: + return OpStructFieldBytes + case OpBytesPtr: + return OpStructFieldBytesPtr + case OpMap: + return OpStructFieldMap + case OpMapPtr: + c.Op = OpMap + return OpStructFieldMapPtr + case OpArray: + return OpStructFieldArray + case OpArrayPtr: + c.Op = OpArray + return OpStructFieldArrayPtr + case OpSlice: + return OpStructFieldSlice + case OpSlicePtr: + c.Op = OpSlice + return OpStructFieldSlicePtr + case OpMarshalJSON: + return OpStructFieldMarshalJSON + case OpMarshalJSONPtr: + return OpStructFieldMarshalJSONPtr + case OpMarshalText: + return OpStructFieldMarshalText + case OpMarshalTextPtr: + return OpStructFieldMarshalTextPtr + } + return OpStructField +} + +func newOpCode(ctx *compileContext, typ *runtime.Type, op OpType) *Opcode { + return newOpCodeWithNext(ctx, typ, op, newEndOp(ctx, typ)) +} + +func opcodeOffset(idx int) uint32 { + return uint32(idx) * uintptrSize +} + +func getCodeAddrByIdx(head *Opcode, idx uint32) *Opcode { + addr := uintptr(unsafe.Pointer(head)) + uintptr(idx)*unsafe.Sizeof(Opcode{}) + return *(**Opcode)(unsafe.Pointer(&addr)) +} + +func copyOpcode(code *Opcode) *Opcode { + codeNum := ToEndCode(code).DisplayIdx + 1 + codeSlice := make([]Opcode, codeNum) + head := (*Opcode)((*runtime.SliceHeader)(unsafe.Pointer(&codeSlice)).Data) + ptr := head + c := code + for { + *ptr = Opcode{ + Op: c.Op, + Key: c.Key, + PtrNum: c.PtrNum, + NumBitSize: c.NumBitSize, + Flags: c.Flags, + Idx: c.Idx, + Offset: c.Offset, + Type: c.Type, + DisplayIdx: c.DisplayIdx, + DisplayKey: c.DisplayKey, + ElemIdx: c.ElemIdx, + Length: c.Length, + MapIter: c.MapIter, + MapPos: c.MapPos, + Size: c.Size, + Indent: c.Indent, + Jmp: c.Jmp, + } + if c.End != nil { + ptr.End = getCodeAddrByIdx(head, c.End.DisplayIdx) + } + if c.NextField != nil { + ptr.NextField = getCodeAddrByIdx(head, c.NextField.DisplayIdx) + } + if c.Next != nil { + ptr.Next = getCodeAddrByIdx(head, c.Next.DisplayIdx) + } + if c.IsEnd() { + break + } + ptr = getCodeAddrByIdx(head, c.DisplayIdx+1) + c = c.IterNext() + } + return head +} + +func setTotalLengthToInterfaceOp(code *Opcode) { + for c := code; !c.IsEnd(); { + if c.Op == OpInterface { + c.Length = uint32(code.TotalLength()) + } + c = c.IterNext() + } +} + +func ToEndCode(code *Opcode) *Opcode { + c := code + for !c.IsEnd() { + c = c.IterNext() + } + return c +} + +func copyToInterfaceOpcode(code *Opcode) *Opcode { + copied := copyOpcode(code) + c := copied + c = ToEndCode(c) + c.Idx += uintptrSize + c.ElemIdx = c.Idx + uintptrSize + c.Length = c.Idx + 2*uintptrSize + c.Op = OpInterfaceEnd + return copied +} + +func newOpCodeWithNext(ctx *compileContext, typ *runtime.Type, op OpType, next *Opcode) *Opcode { + return &Opcode{ + Op: op, + Idx: opcodeOffset(ctx.ptrIndex), + Next: next, + Type: typ, + DisplayIdx: ctx.opcodeIndex, + Indent: ctx.indent, + } +} + +func newEndOp(ctx *compileContext, typ *runtime.Type) *Opcode { + return newOpCodeWithNext(ctx, typ, OpEnd, nil) +} + +func (c *Opcode) TotalLength() int { + var idx int + code := c + for !code.IsEnd() { + maxIdx := int(code.MaxIdx() / uintptrSize) + if idx < maxIdx { + idx = maxIdx + } + if code.Op == OpRecursiveEnd { + break + } + code = code.IterNext() + } + maxIdx := int(code.MaxIdx() / uintptrSize) + if idx < maxIdx { + idx = maxIdx + } + return idx + 1 +} + +func (c *Opcode) dumpHead(code *Opcode) string { + var length uint32 + if code.Op.CodeType() == CodeArrayHead { + length = code.Length + } else { + length = code.Length / uintptrSize + } + return fmt.Sprintf( + `[%03d]%s%s ([idx:%d][elemIdx:%d][length:%d])`, + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + code.ElemIdx/uintptrSize, + length, + ) +} + +func (c *Opcode) dumpMapHead(code *Opcode) string { + return fmt.Sprintf( + `[%03d]%s%s ([idx:%d][elemIdx:%d][length:%d][mapIter:%d])`, + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + code.ElemIdx/uintptrSize, + code.Length/uintptrSize, + code.MapIter/uintptrSize, + ) +} + +func (c *Opcode) dumpMapEnd(code *Opcode) string { + return fmt.Sprintf( + `[%03d]%s%s ([idx:%d][mapPos:%d][length:%d])`, + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + code.MapPos/uintptrSize, + code.Length/uintptrSize, + ) +} + +func (c *Opcode) dumpElem(code *Opcode) string { + var length uint32 + if code.Op.CodeType() == CodeArrayElem { + length = code.Length + } else { + length = code.Length / uintptrSize + } + return fmt.Sprintf( + `[%03d]%s%s ([idx:%d][elemIdx:%d][length:%d][size:%d])`, + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + code.ElemIdx/uintptrSize, + length, + code.Size, + ) +} + +func (c *Opcode) dumpField(code *Opcode) string { + return fmt.Sprintf( + `[%03d]%s%s ([idx:%d][key:%s][offset:%d])`, + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + code.DisplayKey, + code.Offset, + ) +} + +func (c *Opcode) dumpKey(code *Opcode) string { + return fmt.Sprintf( + `[%03d]%s%s ([idx:%d][elemIdx:%d][length:%d][mapIter:%d])`, + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + code.ElemIdx/uintptrSize, + code.Length/uintptrSize, + code.MapIter/uintptrSize, + ) +} + +func (c *Opcode) dumpValue(code *Opcode) string { + return fmt.Sprintf( + `[%03d]%s%s ([idx:%d][mapIter:%d])`, + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + code.MapIter/uintptrSize, + ) +} + +func (c *Opcode) Dump() string { + codes := []string{} + for code := c; !code.IsEnd(); { + switch code.Op.CodeType() { + case CodeSliceHead: + codes = append(codes, c.dumpHead(code)) + code = code.Next + case CodeMapHead: + codes = append(codes, c.dumpMapHead(code)) + code = code.Next + case CodeArrayElem, CodeSliceElem: + codes = append(codes, c.dumpElem(code)) + code = code.End + case CodeMapKey: + codes = append(codes, c.dumpKey(code)) + code = code.End + case CodeMapValue: + codes = append(codes, c.dumpValue(code)) + code = code.Next + case CodeMapEnd: + codes = append(codes, c.dumpMapEnd(code)) + code = code.Next + case CodeStructField: + codes = append(codes, c.dumpField(code)) + code = code.Next + case CodeStructEnd: + codes = append(codes, c.dumpField(code)) + code = code.Next + default: + codes = append(codes, fmt.Sprintf( + "[%03d]%s%s ([idx:%d])", + code.DisplayIdx, + strings.Repeat("-", int(code.Indent)), + code.Op, + code.Idx/uintptrSize, + )) + code = code.Next + } + } + return strings.Join(codes, "\n") +} + +func newSliceHeaderCode(ctx *compileContext, typ *runtime.Type) *Opcode { + idx := opcodeOffset(ctx.ptrIndex) + ctx.incPtrIndex() + elemIdx := opcodeOffset(ctx.ptrIndex) + ctx.incPtrIndex() + length := opcodeOffset(ctx.ptrIndex) + return &Opcode{ + Op: OpSlice, + Type: typ, + Idx: idx, + DisplayIdx: ctx.opcodeIndex, + ElemIdx: elemIdx, + Length: length, + Indent: ctx.indent, + } +} + +func newSliceElemCode(ctx *compileContext, typ *runtime.Type, head *Opcode, size uintptr) *Opcode { + return &Opcode{ + Op: OpSliceElem, + Type: typ, + Idx: head.Idx, + DisplayIdx: ctx.opcodeIndex, + ElemIdx: head.ElemIdx, + Length: head.Length, + Indent: ctx.indent, + Size: uint32(size), + } +} + +func newArrayHeaderCode(ctx *compileContext, typ *runtime.Type, alen int) *Opcode { + idx := opcodeOffset(ctx.ptrIndex) + ctx.incPtrIndex() + elemIdx := opcodeOffset(ctx.ptrIndex) + return &Opcode{ + Op: OpArray, + Type: typ, + Idx: idx, + DisplayIdx: ctx.opcodeIndex, + ElemIdx: elemIdx, + Indent: ctx.indent, + Length: uint32(alen), + } +} + +func newArrayElemCode(ctx *compileContext, typ *runtime.Type, head *Opcode, length int, size uintptr) *Opcode { + return &Opcode{ + Op: OpArrayElem, + Type: typ, + Idx: head.Idx, + DisplayIdx: ctx.opcodeIndex, + ElemIdx: head.ElemIdx, + Length: uint32(length), + Indent: ctx.indent, + Size: uint32(size), + } +} + +func newMapHeaderCode(ctx *compileContext, typ *runtime.Type) *Opcode { + idx := opcodeOffset(ctx.ptrIndex) + ctx.incPtrIndex() + elemIdx := opcodeOffset(ctx.ptrIndex) + ctx.incPtrIndex() + length := opcodeOffset(ctx.ptrIndex) + ctx.incPtrIndex() + mapIter := opcodeOffset(ctx.ptrIndex) + return &Opcode{ + Op: OpMap, + Type: typ, + Idx: idx, + DisplayIdx: ctx.opcodeIndex, + ElemIdx: elemIdx, + Length: length, + MapIter: mapIter, + Indent: ctx.indent, + } +} + +func newMapKeyCode(ctx *compileContext, typ *runtime.Type, head *Opcode) *Opcode { + return &Opcode{ + Op: OpMapKey, + Type: typ, + Idx: opcodeOffset(ctx.ptrIndex), + DisplayIdx: ctx.opcodeIndex, + ElemIdx: head.ElemIdx, + Length: head.Length, + MapIter: head.MapIter, + Indent: ctx.indent, + } +} + +func newMapValueCode(ctx *compileContext, typ *runtime.Type, head *Opcode) *Opcode { + return &Opcode{ + Op: OpMapValue, + Type: typ, + Idx: opcodeOffset(ctx.ptrIndex), + DisplayIdx: ctx.opcodeIndex, + ElemIdx: head.ElemIdx, + Length: head.Length, + MapIter: head.MapIter, + Indent: ctx.indent, + } +} + +func newMapEndCode(ctx *compileContext, typ *runtime.Type, head *Opcode) *Opcode { + mapPos := opcodeOffset(ctx.ptrIndex) + ctx.incPtrIndex() + idx := opcodeOffset(ctx.ptrIndex) + return &Opcode{ + Op: OpMapEnd, + Type: typ, + Idx: idx, + Next: newEndOp(ctx, typ), + DisplayIdx: ctx.opcodeIndex, + Length: head.Length, + MapPos: mapPos, + Indent: ctx.indent, + } +} + +func newRecursiveCode(ctx *compileContext, typ *runtime.Type, jmp *CompiledCode) *Opcode { + return &Opcode{ + Op: OpRecursive, + Type: typ, + Idx: opcodeOffset(ctx.ptrIndex), + Next: newEndOp(ctx, typ), + DisplayIdx: ctx.opcodeIndex, + Indent: ctx.indent, + Jmp: jmp, + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/option.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/option.go new file mode 100644 index 00000000..f5f1f044 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/option.go @@ -0,0 +1,41 @@ +package encoder + +import "context" + +type OptionFlag uint8 + +const ( + HTMLEscapeOption OptionFlag = 1 << iota + IndentOption + UnorderedMapOption + DebugOption + ColorizeOption + ContextOption +) + +type Option struct { + Flag OptionFlag + ColorScheme *ColorScheme + Context context.Context +} + +type EncodeFormat struct { + Header string + Footer string +} + +type EncodeFormatScheme struct { + Int EncodeFormat + Uint EncodeFormat + Float EncodeFormat + Bool EncodeFormat + String EncodeFormat + Binary EncodeFormat + ObjectKey EncodeFormat + Null EncodeFormat +} + +type ( + ColorScheme = EncodeFormatScheme + ColorFormat = EncodeFormat +) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/optype.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/optype.go new file mode 100644 index 00000000..5c1241b4 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/optype.go @@ -0,0 +1,932 @@ +// Code generated by internal/cmd/generator. DO NOT EDIT! +package encoder + +import ( + "strings" +) + +type CodeType int + +const ( + CodeOp CodeType = 0 + CodeArrayHead CodeType = 1 + CodeArrayElem CodeType = 2 + CodeSliceHead CodeType = 3 + CodeSliceElem CodeType = 4 + CodeMapHead CodeType = 5 + CodeMapKey CodeType = 6 + CodeMapValue CodeType = 7 + CodeMapEnd CodeType = 8 + CodeRecursive CodeType = 9 + CodeStructField CodeType = 10 + CodeStructEnd CodeType = 11 +) + +var opTypeStrings = [400]string{ + "End", + "Interface", + "Ptr", + "SliceElem", + "SliceEnd", + "ArrayElem", + "ArrayEnd", + "MapKey", + "MapValue", + "MapEnd", + "Recursive", + "RecursivePtr", + "RecursiveEnd", + "InterfaceEnd", + "Int", + "Uint", + "Float32", + "Float64", + "Bool", + "String", + "Bytes", + "Number", + "Array", + "Map", + "Slice", + "Struct", + "MarshalJSON", + "MarshalText", + "IntString", + "UintString", + "Float32String", + "Float64String", + "BoolString", + "StringString", + "NumberString", + "IntPtr", + "UintPtr", + "Float32Ptr", + "Float64Ptr", + "BoolPtr", + "StringPtr", + "BytesPtr", + "NumberPtr", + "ArrayPtr", + "MapPtr", + "SlicePtr", + "MarshalJSONPtr", + "MarshalTextPtr", + "InterfacePtr", + "IntPtrString", + "UintPtrString", + "Float32PtrString", + "Float64PtrString", + "BoolPtrString", + "StringPtrString", + "NumberPtrString", + "StructHeadInt", + "StructHeadOmitEmptyInt", + "StructPtrHeadInt", + "StructPtrHeadOmitEmptyInt", + "StructHeadUint", + "StructHeadOmitEmptyUint", + "StructPtrHeadUint", + "StructPtrHeadOmitEmptyUint", + "StructHeadFloat32", + "StructHeadOmitEmptyFloat32", + "StructPtrHeadFloat32", + "StructPtrHeadOmitEmptyFloat32", + "StructHeadFloat64", + "StructHeadOmitEmptyFloat64", + "StructPtrHeadFloat64", + "StructPtrHeadOmitEmptyFloat64", + "StructHeadBool", + "StructHeadOmitEmptyBool", + "StructPtrHeadBool", + "StructPtrHeadOmitEmptyBool", + "StructHeadString", + "StructHeadOmitEmptyString", + "StructPtrHeadString", + "StructPtrHeadOmitEmptyString", + "StructHeadBytes", + "StructHeadOmitEmptyBytes", + "StructPtrHeadBytes", + "StructPtrHeadOmitEmptyBytes", + "StructHeadNumber", + "StructHeadOmitEmptyNumber", + "StructPtrHeadNumber", + "StructPtrHeadOmitEmptyNumber", + "StructHeadArray", + "StructHeadOmitEmptyArray", + "StructPtrHeadArray", + "StructPtrHeadOmitEmptyArray", + "StructHeadMap", + "StructHeadOmitEmptyMap", + "StructPtrHeadMap", + "StructPtrHeadOmitEmptyMap", + "StructHeadSlice", + "StructHeadOmitEmptySlice", + "StructPtrHeadSlice", + "StructPtrHeadOmitEmptySlice", + "StructHeadStruct", + "StructHeadOmitEmptyStruct", + "StructPtrHeadStruct", + "StructPtrHeadOmitEmptyStruct", + "StructHeadMarshalJSON", + "StructHeadOmitEmptyMarshalJSON", + "StructPtrHeadMarshalJSON", + "StructPtrHeadOmitEmptyMarshalJSON", + "StructHeadMarshalText", + "StructHeadOmitEmptyMarshalText", + "StructPtrHeadMarshalText", + "StructPtrHeadOmitEmptyMarshalText", + "StructHeadIntString", + "StructHeadOmitEmptyIntString", + "StructPtrHeadIntString", + "StructPtrHeadOmitEmptyIntString", + "StructHeadUintString", + "StructHeadOmitEmptyUintString", + "StructPtrHeadUintString", + "StructPtrHeadOmitEmptyUintString", + "StructHeadFloat32String", + "StructHeadOmitEmptyFloat32String", + "StructPtrHeadFloat32String", + "StructPtrHeadOmitEmptyFloat32String", + "StructHeadFloat64String", + "StructHeadOmitEmptyFloat64String", + "StructPtrHeadFloat64String", + "StructPtrHeadOmitEmptyFloat64String", + "StructHeadBoolString", + "StructHeadOmitEmptyBoolString", + "StructPtrHeadBoolString", + "StructPtrHeadOmitEmptyBoolString", + "StructHeadStringString", + "StructHeadOmitEmptyStringString", + "StructPtrHeadStringString", + "StructPtrHeadOmitEmptyStringString", + "StructHeadNumberString", + "StructHeadOmitEmptyNumberString", + "StructPtrHeadNumberString", + "StructPtrHeadOmitEmptyNumberString", + "StructHeadIntPtr", + "StructHeadOmitEmptyIntPtr", + "StructPtrHeadIntPtr", + "StructPtrHeadOmitEmptyIntPtr", + "StructHeadUintPtr", + "StructHeadOmitEmptyUintPtr", + "StructPtrHeadUintPtr", + "StructPtrHeadOmitEmptyUintPtr", + "StructHeadFloat32Ptr", + "StructHeadOmitEmptyFloat32Ptr", + "StructPtrHeadFloat32Ptr", + "StructPtrHeadOmitEmptyFloat32Ptr", + "StructHeadFloat64Ptr", + "StructHeadOmitEmptyFloat64Ptr", + "StructPtrHeadFloat64Ptr", + "StructPtrHeadOmitEmptyFloat64Ptr", + "StructHeadBoolPtr", + "StructHeadOmitEmptyBoolPtr", + "StructPtrHeadBoolPtr", + "StructPtrHeadOmitEmptyBoolPtr", + "StructHeadStringPtr", + "StructHeadOmitEmptyStringPtr", + "StructPtrHeadStringPtr", + "StructPtrHeadOmitEmptyStringPtr", + "StructHeadBytesPtr", + "StructHeadOmitEmptyBytesPtr", + "StructPtrHeadBytesPtr", + "StructPtrHeadOmitEmptyBytesPtr", + "StructHeadNumberPtr", + "StructHeadOmitEmptyNumberPtr", + "StructPtrHeadNumberPtr", + "StructPtrHeadOmitEmptyNumberPtr", + "StructHeadArrayPtr", + "StructHeadOmitEmptyArrayPtr", + "StructPtrHeadArrayPtr", + "StructPtrHeadOmitEmptyArrayPtr", + "StructHeadMapPtr", + "StructHeadOmitEmptyMapPtr", + "StructPtrHeadMapPtr", + "StructPtrHeadOmitEmptyMapPtr", + "StructHeadSlicePtr", + "StructHeadOmitEmptySlicePtr", + "StructPtrHeadSlicePtr", + "StructPtrHeadOmitEmptySlicePtr", + "StructHeadMarshalJSONPtr", + "StructHeadOmitEmptyMarshalJSONPtr", + "StructPtrHeadMarshalJSONPtr", + "StructPtrHeadOmitEmptyMarshalJSONPtr", + "StructHeadMarshalTextPtr", + "StructHeadOmitEmptyMarshalTextPtr", + "StructPtrHeadMarshalTextPtr", + "StructPtrHeadOmitEmptyMarshalTextPtr", + "StructHeadInterfacePtr", + "StructHeadOmitEmptyInterfacePtr", + "StructPtrHeadInterfacePtr", + "StructPtrHeadOmitEmptyInterfacePtr", + "StructHeadIntPtrString", + "StructHeadOmitEmptyIntPtrString", + "StructPtrHeadIntPtrString", + "StructPtrHeadOmitEmptyIntPtrString", + "StructHeadUintPtrString", + "StructHeadOmitEmptyUintPtrString", + "StructPtrHeadUintPtrString", + "StructPtrHeadOmitEmptyUintPtrString", + "StructHeadFloat32PtrString", + "StructHeadOmitEmptyFloat32PtrString", + "StructPtrHeadFloat32PtrString", + "StructPtrHeadOmitEmptyFloat32PtrString", + "StructHeadFloat64PtrString", + "StructHeadOmitEmptyFloat64PtrString", + "StructPtrHeadFloat64PtrString", + "StructPtrHeadOmitEmptyFloat64PtrString", + "StructHeadBoolPtrString", + "StructHeadOmitEmptyBoolPtrString", + "StructPtrHeadBoolPtrString", + "StructPtrHeadOmitEmptyBoolPtrString", + "StructHeadStringPtrString", + "StructHeadOmitEmptyStringPtrString", + "StructPtrHeadStringPtrString", + "StructPtrHeadOmitEmptyStringPtrString", + "StructHeadNumberPtrString", + "StructHeadOmitEmptyNumberPtrString", + "StructPtrHeadNumberPtrString", + "StructPtrHeadOmitEmptyNumberPtrString", + "StructHead", + "StructHeadOmitEmpty", + "StructPtrHead", + "StructPtrHeadOmitEmpty", + "StructFieldInt", + "StructFieldOmitEmptyInt", + "StructEndInt", + "StructEndOmitEmptyInt", + "StructFieldUint", + "StructFieldOmitEmptyUint", + "StructEndUint", + "StructEndOmitEmptyUint", + "StructFieldFloat32", + "StructFieldOmitEmptyFloat32", + "StructEndFloat32", + "StructEndOmitEmptyFloat32", + "StructFieldFloat64", + "StructFieldOmitEmptyFloat64", + "StructEndFloat64", + "StructEndOmitEmptyFloat64", + "StructFieldBool", + "StructFieldOmitEmptyBool", + "StructEndBool", + "StructEndOmitEmptyBool", + "StructFieldString", + "StructFieldOmitEmptyString", + "StructEndString", + "StructEndOmitEmptyString", + "StructFieldBytes", + "StructFieldOmitEmptyBytes", + "StructEndBytes", + "StructEndOmitEmptyBytes", + "StructFieldNumber", + "StructFieldOmitEmptyNumber", + "StructEndNumber", + "StructEndOmitEmptyNumber", + "StructFieldArray", + "StructFieldOmitEmptyArray", + "StructEndArray", + "StructEndOmitEmptyArray", + "StructFieldMap", + "StructFieldOmitEmptyMap", + "StructEndMap", + "StructEndOmitEmptyMap", + "StructFieldSlice", + "StructFieldOmitEmptySlice", + "StructEndSlice", + "StructEndOmitEmptySlice", + "StructFieldStruct", + "StructFieldOmitEmptyStruct", + "StructEndStruct", + "StructEndOmitEmptyStruct", + "StructFieldMarshalJSON", + "StructFieldOmitEmptyMarshalJSON", + "StructEndMarshalJSON", + "StructEndOmitEmptyMarshalJSON", + "StructFieldMarshalText", + "StructFieldOmitEmptyMarshalText", + "StructEndMarshalText", + "StructEndOmitEmptyMarshalText", + "StructFieldIntString", + "StructFieldOmitEmptyIntString", + "StructEndIntString", + "StructEndOmitEmptyIntString", + "StructFieldUintString", + "StructFieldOmitEmptyUintString", + "StructEndUintString", + "StructEndOmitEmptyUintString", + "StructFieldFloat32String", + "StructFieldOmitEmptyFloat32String", + "StructEndFloat32String", + "StructEndOmitEmptyFloat32String", + "StructFieldFloat64String", + "StructFieldOmitEmptyFloat64String", + "StructEndFloat64String", + "StructEndOmitEmptyFloat64String", + "StructFieldBoolString", + "StructFieldOmitEmptyBoolString", + "StructEndBoolString", + "StructEndOmitEmptyBoolString", + "StructFieldStringString", + "StructFieldOmitEmptyStringString", + "StructEndStringString", + "StructEndOmitEmptyStringString", + "StructFieldNumberString", + "StructFieldOmitEmptyNumberString", + "StructEndNumberString", + "StructEndOmitEmptyNumberString", + "StructFieldIntPtr", + "StructFieldOmitEmptyIntPtr", + "StructEndIntPtr", + "StructEndOmitEmptyIntPtr", + "StructFieldUintPtr", + "StructFieldOmitEmptyUintPtr", + "StructEndUintPtr", + "StructEndOmitEmptyUintPtr", + "StructFieldFloat32Ptr", + "StructFieldOmitEmptyFloat32Ptr", + "StructEndFloat32Ptr", + "StructEndOmitEmptyFloat32Ptr", + "StructFieldFloat64Ptr", + "StructFieldOmitEmptyFloat64Ptr", + "StructEndFloat64Ptr", + "StructEndOmitEmptyFloat64Ptr", + "StructFieldBoolPtr", + "StructFieldOmitEmptyBoolPtr", + "StructEndBoolPtr", + "StructEndOmitEmptyBoolPtr", + "StructFieldStringPtr", + "StructFieldOmitEmptyStringPtr", + "StructEndStringPtr", + "StructEndOmitEmptyStringPtr", + "StructFieldBytesPtr", + "StructFieldOmitEmptyBytesPtr", + "StructEndBytesPtr", + "StructEndOmitEmptyBytesPtr", + "StructFieldNumberPtr", + "StructFieldOmitEmptyNumberPtr", + "StructEndNumberPtr", + "StructEndOmitEmptyNumberPtr", + "StructFieldArrayPtr", + "StructFieldOmitEmptyArrayPtr", + "StructEndArrayPtr", + "StructEndOmitEmptyArrayPtr", + "StructFieldMapPtr", + "StructFieldOmitEmptyMapPtr", + "StructEndMapPtr", + "StructEndOmitEmptyMapPtr", + "StructFieldSlicePtr", + "StructFieldOmitEmptySlicePtr", + "StructEndSlicePtr", + "StructEndOmitEmptySlicePtr", + "StructFieldMarshalJSONPtr", + "StructFieldOmitEmptyMarshalJSONPtr", + "StructEndMarshalJSONPtr", + "StructEndOmitEmptyMarshalJSONPtr", + "StructFieldMarshalTextPtr", + "StructFieldOmitEmptyMarshalTextPtr", + "StructEndMarshalTextPtr", + "StructEndOmitEmptyMarshalTextPtr", + "StructFieldInterfacePtr", + "StructFieldOmitEmptyInterfacePtr", + "StructEndInterfacePtr", + "StructEndOmitEmptyInterfacePtr", + "StructFieldIntPtrString", + "StructFieldOmitEmptyIntPtrString", + "StructEndIntPtrString", + "StructEndOmitEmptyIntPtrString", + "StructFieldUintPtrString", + "StructFieldOmitEmptyUintPtrString", + "StructEndUintPtrString", + "StructEndOmitEmptyUintPtrString", + "StructFieldFloat32PtrString", + "StructFieldOmitEmptyFloat32PtrString", + "StructEndFloat32PtrString", + "StructEndOmitEmptyFloat32PtrString", + "StructFieldFloat64PtrString", + "StructFieldOmitEmptyFloat64PtrString", + "StructEndFloat64PtrString", + "StructEndOmitEmptyFloat64PtrString", + "StructFieldBoolPtrString", + "StructFieldOmitEmptyBoolPtrString", + "StructEndBoolPtrString", + "StructEndOmitEmptyBoolPtrString", + "StructFieldStringPtrString", + "StructFieldOmitEmptyStringPtrString", + "StructEndStringPtrString", + "StructEndOmitEmptyStringPtrString", + "StructFieldNumberPtrString", + "StructFieldOmitEmptyNumberPtrString", + "StructEndNumberPtrString", + "StructEndOmitEmptyNumberPtrString", + "StructField", + "StructFieldOmitEmpty", + "StructEnd", + "StructEndOmitEmpty", +} + +type OpType uint16 + +const ( + OpEnd OpType = 0 + OpInterface OpType = 1 + OpPtr OpType = 2 + OpSliceElem OpType = 3 + OpSliceEnd OpType = 4 + OpArrayElem OpType = 5 + OpArrayEnd OpType = 6 + OpMapKey OpType = 7 + OpMapValue OpType = 8 + OpMapEnd OpType = 9 + OpRecursive OpType = 10 + OpRecursivePtr OpType = 11 + OpRecursiveEnd OpType = 12 + OpInterfaceEnd OpType = 13 + OpInt OpType = 14 + OpUint OpType = 15 + OpFloat32 OpType = 16 + OpFloat64 OpType = 17 + OpBool OpType = 18 + OpString OpType = 19 + OpBytes OpType = 20 + OpNumber OpType = 21 + OpArray OpType = 22 + OpMap OpType = 23 + OpSlice OpType = 24 + OpStruct OpType = 25 + OpMarshalJSON OpType = 26 + OpMarshalText OpType = 27 + OpIntString OpType = 28 + OpUintString OpType = 29 + OpFloat32String OpType = 30 + OpFloat64String OpType = 31 + OpBoolString OpType = 32 + OpStringString OpType = 33 + OpNumberString OpType = 34 + OpIntPtr OpType = 35 + OpUintPtr OpType = 36 + OpFloat32Ptr OpType = 37 + OpFloat64Ptr OpType = 38 + OpBoolPtr OpType = 39 + OpStringPtr OpType = 40 + OpBytesPtr OpType = 41 + OpNumberPtr OpType = 42 + OpArrayPtr OpType = 43 + OpMapPtr OpType = 44 + OpSlicePtr OpType = 45 + OpMarshalJSONPtr OpType = 46 + OpMarshalTextPtr OpType = 47 + OpInterfacePtr OpType = 48 + OpIntPtrString OpType = 49 + OpUintPtrString OpType = 50 + OpFloat32PtrString OpType = 51 + OpFloat64PtrString OpType = 52 + OpBoolPtrString OpType = 53 + OpStringPtrString OpType = 54 + OpNumberPtrString OpType = 55 + OpStructHeadInt OpType = 56 + OpStructHeadOmitEmptyInt OpType = 57 + OpStructPtrHeadInt OpType = 58 + OpStructPtrHeadOmitEmptyInt OpType = 59 + OpStructHeadUint OpType = 60 + OpStructHeadOmitEmptyUint OpType = 61 + OpStructPtrHeadUint OpType = 62 + OpStructPtrHeadOmitEmptyUint OpType = 63 + OpStructHeadFloat32 OpType = 64 + OpStructHeadOmitEmptyFloat32 OpType = 65 + OpStructPtrHeadFloat32 OpType = 66 + OpStructPtrHeadOmitEmptyFloat32 OpType = 67 + OpStructHeadFloat64 OpType = 68 + OpStructHeadOmitEmptyFloat64 OpType = 69 + OpStructPtrHeadFloat64 OpType = 70 + OpStructPtrHeadOmitEmptyFloat64 OpType = 71 + OpStructHeadBool OpType = 72 + OpStructHeadOmitEmptyBool OpType = 73 + OpStructPtrHeadBool OpType = 74 + OpStructPtrHeadOmitEmptyBool OpType = 75 + OpStructHeadString OpType = 76 + OpStructHeadOmitEmptyString OpType = 77 + OpStructPtrHeadString OpType = 78 + OpStructPtrHeadOmitEmptyString OpType = 79 + OpStructHeadBytes OpType = 80 + OpStructHeadOmitEmptyBytes OpType = 81 + OpStructPtrHeadBytes OpType = 82 + OpStructPtrHeadOmitEmptyBytes OpType = 83 + OpStructHeadNumber OpType = 84 + OpStructHeadOmitEmptyNumber OpType = 85 + OpStructPtrHeadNumber OpType = 86 + OpStructPtrHeadOmitEmptyNumber OpType = 87 + OpStructHeadArray OpType = 88 + OpStructHeadOmitEmptyArray OpType = 89 + OpStructPtrHeadArray OpType = 90 + OpStructPtrHeadOmitEmptyArray OpType = 91 + OpStructHeadMap OpType = 92 + OpStructHeadOmitEmptyMap OpType = 93 + OpStructPtrHeadMap OpType = 94 + OpStructPtrHeadOmitEmptyMap OpType = 95 + OpStructHeadSlice OpType = 96 + OpStructHeadOmitEmptySlice OpType = 97 + OpStructPtrHeadSlice OpType = 98 + OpStructPtrHeadOmitEmptySlice OpType = 99 + OpStructHeadStruct OpType = 100 + OpStructHeadOmitEmptyStruct OpType = 101 + OpStructPtrHeadStruct OpType = 102 + OpStructPtrHeadOmitEmptyStruct OpType = 103 + OpStructHeadMarshalJSON OpType = 104 + OpStructHeadOmitEmptyMarshalJSON OpType = 105 + OpStructPtrHeadMarshalJSON OpType = 106 + OpStructPtrHeadOmitEmptyMarshalJSON OpType = 107 + OpStructHeadMarshalText OpType = 108 + OpStructHeadOmitEmptyMarshalText OpType = 109 + OpStructPtrHeadMarshalText OpType = 110 + OpStructPtrHeadOmitEmptyMarshalText OpType = 111 + OpStructHeadIntString OpType = 112 + OpStructHeadOmitEmptyIntString OpType = 113 + OpStructPtrHeadIntString OpType = 114 + OpStructPtrHeadOmitEmptyIntString OpType = 115 + OpStructHeadUintString OpType = 116 + OpStructHeadOmitEmptyUintString OpType = 117 + OpStructPtrHeadUintString OpType = 118 + OpStructPtrHeadOmitEmptyUintString OpType = 119 + OpStructHeadFloat32String OpType = 120 + OpStructHeadOmitEmptyFloat32String OpType = 121 + OpStructPtrHeadFloat32String OpType = 122 + OpStructPtrHeadOmitEmptyFloat32String OpType = 123 + OpStructHeadFloat64String OpType = 124 + OpStructHeadOmitEmptyFloat64String OpType = 125 + OpStructPtrHeadFloat64String OpType = 126 + OpStructPtrHeadOmitEmptyFloat64String OpType = 127 + OpStructHeadBoolString OpType = 128 + OpStructHeadOmitEmptyBoolString OpType = 129 + OpStructPtrHeadBoolString OpType = 130 + OpStructPtrHeadOmitEmptyBoolString OpType = 131 + OpStructHeadStringString OpType = 132 + OpStructHeadOmitEmptyStringString OpType = 133 + OpStructPtrHeadStringString OpType = 134 + OpStructPtrHeadOmitEmptyStringString OpType = 135 + OpStructHeadNumberString OpType = 136 + OpStructHeadOmitEmptyNumberString OpType = 137 + OpStructPtrHeadNumberString OpType = 138 + OpStructPtrHeadOmitEmptyNumberString OpType = 139 + OpStructHeadIntPtr OpType = 140 + OpStructHeadOmitEmptyIntPtr OpType = 141 + OpStructPtrHeadIntPtr OpType = 142 + OpStructPtrHeadOmitEmptyIntPtr OpType = 143 + OpStructHeadUintPtr OpType = 144 + OpStructHeadOmitEmptyUintPtr OpType = 145 + OpStructPtrHeadUintPtr OpType = 146 + OpStructPtrHeadOmitEmptyUintPtr OpType = 147 + OpStructHeadFloat32Ptr OpType = 148 + OpStructHeadOmitEmptyFloat32Ptr OpType = 149 + OpStructPtrHeadFloat32Ptr OpType = 150 + OpStructPtrHeadOmitEmptyFloat32Ptr OpType = 151 + OpStructHeadFloat64Ptr OpType = 152 + OpStructHeadOmitEmptyFloat64Ptr OpType = 153 + OpStructPtrHeadFloat64Ptr OpType = 154 + OpStructPtrHeadOmitEmptyFloat64Ptr OpType = 155 + OpStructHeadBoolPtr OpType = 156 + OpStructHeadOmitEmptyBoolPtr OpType = 157 + OpStructPtrHeadBoolPtr OpType = 158 + OpStructPtrHeadOmitEmptyBoolPtr OpType = 159 + OpStructHeadStringPtr OpType = 160 + OpStructHeadOmitEmptyStringPtr OpType = 161 + OpStructPtrHeadStringPtr OpType = 162 + OpStructPtrHeadOmitEmptyStringPtr OpType = 163 + OpStructHeadBytesPtr OpType = 164 + OpStructHeadOmitEmptyBytesPtr OpType = 165 + OpStructPtrHeadBytesPtr OpType = 166 + OpStructPtrHeadOmitEmptyBytesPtr OpType = 167 + OpStructHeadNumberPtr OpType = 168 + OpStructHeadOmitEmptyNumberPtr OpType = 169 + OpStructPtrHeadNumberPtr OpType = 170 + OpStructPtrHeadOmitEmptyNumberPtr OpType = 171 + OpStructHeadArrayPtr OpType = 172 + OpStructHeadOmitEmptyArrayPtr OpType = 173 + OpStructPtrHeadArrayPtr OpType = 174 + OpStructPtrHeadOmitEmptyArrayPtr OpType = 175 + OpStructHeadMapPtr OpType = 176 + OpStructHeadOmitEmptyMapPtr OpType = 177 + OpStructPtrHeadMapPtr OpType = 178 + OpStructPtrHeadOmitEmptyMapPtr OpType = 179 + OpStructHeadSlicePtr OpType = 180 + OpStructHeadOmitEmptySlicePtr OpType = 181 + OpStructPtrHeadSlicePtr OpType = 182 + OpStructPtrHeadOmitEmptySlicePtr OpType = 183 + OpStructHeadMarshalJSONPtr OpType = 184 + OpStructHeadOmitEmptyMarshalJSONPtr OpType = 185 + OpStructPtrHeadMarshalJSONPtr OpType = 186 + OpStructPtrHeadOmitEmptyMarshalJSONPtr OpType = 187 + OpStructHeadMarshalTextPtr OpType = 188 + OpStructHeadOmitEmptyMarshalTextPtr OpType = 189 + OpStructPtrHeadMarshalTextPtr OpType = 190 + OpStructPtrHeadOmitEmptyMarshalTextPtr OpType = 191 + OpStructHeadInterfacePtr OpType = 192 + OpStructHeadOmitEmptyInterfacePtr OpType = 193 + OpStructPtrHeadInterfacePtr OpType = 194 + OpStructPtrHeadOmitEmptyInterfacePtr OpType = 195 + OpStructHeadIntPtrString OpType = 196 + OpStructHeadOmitEmptyIntPtrString OpType = 197 + OpStructPtrHeadIntPtrString OpType = 198 + OpStructPtrHeadOmitEmptyIntPtrString OpType = 199 + OpStructHeadUintPtrString OpType = 200 + OpStructHeadOmitEmptyUintPtrString OpType = 201 + OpStructPtrHeadUintPtrString OpType = 202 + OpStructPtrHeadOmitEmptyUintPtrString OpType = 203 + OpStructHeadFloat32PtrString OpType = 204 + OpStructHeadOmitEmptyFloat32PtrString OpType = 205 + OpStructPtrHeadFloat32PtrString OpType = 206 + OpStructPtrHeadOmitEmptyFloat32PtrString OpType = 207 + OpStructHeadFloat64PtrString OpType = 208 + OpStructHeadOmitEmptyFloat64PtrString OpType = 209 + OpStructPtrHeadFloat64PtrString OpType = 210 + OpStructPtrHeadOmitEmptyFloat64PtrString OpType = 211 + OpStructHeadBoolPtrString OpType = 212 + OpStructHeadOmitEmptyBoolPtrString OpType = 213 + OpStructPtrHeadBoolPtrString OpType = 214 + OpStructPtrHeadOmitEmptyBoolPtrString OpType = 215 + OpStructHeadStringPtrString OpType = 216 + OpStructHeadOmitEmptyStringPtrString OpType = 217 + OpStructPtrHeadStringPtrString OpType = 218 + OpStructPtrHeadOmitEmptyStringPtrString OpType = 219 + OpStructHeadNumberPtrString OpType = 220 + OpStructHeadOmitEmptyNumberPtrString OpType = 221 + OpStructPtrHeadNumberPtrString OpType = 222 + OpStructPtrHeadOmitEmptyNumberPtrString OpType = 223 + OpStructHead OpType = 224 + OpStructHeadOmitEmpty OpType = 225 + OpStructPtrHead OpType = 226 + OpStructPtrHeadOmitEmpty OpType = 227 + OpStructFieldInt OpType = 228 + OpStructFieldOmitEmptyInt OpType = 229 + OpStructEndInt OpType = 230 + OpStructEndOmitEmptyInt OpType = 231 + OpStructFieldUint OpType = 232 + OpStructFieldOmitEmptyUint OpType = 233 + OpStructEndUint OpType = 234 + OpStructEndOmitEmptyUint OpType = 235 + OpStructFieldFloat32 OpType = 236 + OpStructFieldOmitEmptyFloat32 OpType = 237 + OpStructEndFloat32 OpType = 238 + OpStructEndOmitEmptyFloat32 OpType = 239 + OpStructFieldFloat64 OpType = 240 + OpStructFieldOmitEmptyFloat64 OpType = 241 + OpStructEndFloat64 OpType = 242 + OpStructEndOmitEmptyFloat64 OpType = 243 + OpStructFieldBool OpType = 244 + OpStructFieldOmitEmptyBool OpType = 245 + OpStructEndBool OpType = 246 + OpStructEndOmitEmptyBool OpType = 247 + OpStructFieldString OpType = 248 + OpStructFieldOmitEmptyString OpType = 249 + OpStructEndString OpType = 250 + OpStructEndOmitEmptyString OpType = 251 + OpStructFieldBytes OpType = 252 + OpStructFieldOmitEmptyBytes OpType = 253 + OpStructEndBytes OpType = 254 + OpStructEndOmitEmptyBytes OpType = 255 + OpStructFieldNumber OpType = 256 + OpStructFieldOmitEmptyNumber OpType = 257 + OpStructEndNumber OpType = 258 + OpStructEndOmitEmptyNumber OpType = 259 + OpStructFieldArray OpType = 260 + OpStructFieldOmitEmptyArray OpType = 261 + OpStructEndArray OpType = 262 + OpStructEndOmitEmptyArray OpType = 263 + OpStructFieldMap OpType = 264 + OpStructFieldOmitEmptyMap OpType = 265 + OpStructEndMap OpType = 266 + OpStructEndOmitEmptyMap OpType = 267 + OpStructFieldSlice OpType = 268 + OpStructFieldOmitEmptySlice OpType = 269 + OpStructEndSlice OpType = 270 + OpStructEndOmitEmptySlice OpType = 271 + OpStructFieldStruct OpType = 272 + OpStructFieldOmitEmptyStruct OpType = 273 + OpStructEndStruct OpType = 274 + OpStructEndOmitEmptyStruct OpType = 275 + OpStructFieldMarshalJSON OpType = 276 + OpStructFieldOmitEmptyMarshalJSON OpType = 277 + OpStructEndMarshalJSON OpType = 278 + OpStructEndOmitEmptyMarshalJSON OpType = 279 + OpStructFieldMarshalText OpType = 280 + OpStructFieldOmitEmptyMarshalText OpType = 281 + OpStructEndMarshalText OpType = 282 + OpStructEndOmitEmptyMarshalText OpType = 283 + OpStructFieldIntString OpType = 284 + OpStructFieldOmitEmptyIntString OpType = 285 + OpStructEndIntString OpType = 286 + OpStructEndOmitEmptyIntString OpType = 287 + OpStructFieldUintString OpType = 288 + OpStructFieldOmitEmptyUintString OpType = 289 + OpStructEndUintString OpType = 290 + OpStructEndOmitEmptyUintString OpType = 291 + OpStructFieldFloat32String OpType = 292 + OpStructFieldOmitEmptyFloat32String OpType = 293 + OpStructEndFloat32String OpType = 294 + OpStructEndOmitEmptyFloat32String OpType = 295 + OpStructFieldFloat64String OpType = 296 + OpStructFieldOmitEmptyFloat64String OpType = 297 + OpStructEndFloat64String OpType = 298 + OpStructEndOmitEmptyFloat64String OpType = 299 + OpStructFieldBoolString OpType = 300 + OpStructFieldOmitEmptyBoolString OpType = 301 + OpStructEndBoolString OpType = 302 + OpStructEndOmitEmptyBoolString OpType = 303 + OpStructFieldStringString OpType = 304 + OpStructFieldOmitEmptyStringString OpType = 305 + OpStructEndStringString OpType = 306 + OpStructEndOmitEmptyStringString OpType = 307 + OpStructFieldNumberString OpType = 308 + OpStructFieldOmitEmptyNumberString OpType = 309 + OpStructEndNumberString OpType = 310 + OpStructEndOmitEmptyNumberString OpType = 311 + OpStructFieldIntPtr OpType = 312 + OpStructFieldOmitEmptyIntPtr OpType = 313 + OpStructEndIntPtr OpType = 314 + OpStructEndOmitEmptyIntPtr OpType = 315 + OpStructFieldUintPtr OpType = 316 + OpStructFieldOmitEmptyUintPtr OpType = 317 + OpStructEndUintPtr OpType = 318 + OpStructEndOmitEmptyUintPtr OpType = 319 + OpStructFieldFloat32Ptr OpType = 320 + OpStructFieldOmitEmptyFloat32Ptr OpType = 321 + OpStructEndFloat32Ptr OpType = 322 + OpStructEndOmitEmptyFloat32Ptr OpType = 323 + OpStructFieldFloat64Ptr OpType = 324 + OpStructFieldOmitEmptyFloat64Ptr OpType = 325 + OpStructEndFloat64Ptr OpType = 326 + OpStructEndOmitEmptyFloat64Ptr OpType = 327 + OpStructFieldBoolPtr OpType = 328 + OpStructFieldOmitEmptyBoolPtr OpType = 329 + OpStructEndBoolPtr OpType = 330 + OpStructEndOmitEmptyBoolPtr OpType = 331 + OpStructFieldStringPtr OpType = 332 + OpStructFieldOmitEmptyStringPtr OpType = 333 + OpStructEndStringPtr OpType = 334 + OpStructEndOmitEmptyStringPtr OpType = 335 + OpStructFieldBytesPtr OpType = 336 + OpStructFieldOmitEmptyBytesPtr OpType = 337 + OpStructEndBytesPtr OpType = 338 + OpStructEndOmitEmptyBytesPtr OpType = 339 + OpStructFieldNumberPtr OpType = 340 + OpStructFieldOmitEmptyNumberPtr OpType = 341 + OpStructEndNumberPtr OpType = 342 + OpStructEndOmitEmptyNumberPtr OpType = 343 + OpStructFieldArrayPtr OpType = 344 + OpStructFieldOmitEmptyArrayPtr OpType = 345 + OpStructEndArrayPtr OpType = 346 + OpStructEndOmitEmptyArrayPtr OpType = 347 + OpStructFieldMapPtr OpType = 348 + OpStructFieldOmitEmptyMapPtr OpType = 349 + OpStructEndMapPtr OpType = 350 + OpStructEndOmitEmptyMapPtr OpType = 351 + OpStructFieldSlicePtr OpType = 352 + OpStructFieldOmitEmptySlicePtr OpType = 353 + OpStructEndSlicePtr OpType = 354 + OpStructEndOmitEmptySlicePtr OpType = 355 + OpStructFieldMarshalJSONPtr OpType = 356 + OpStructFieldOmitEmptyMarshalJSONPtr OpType = 357 + OpStructEndMarshalJSONPtr OpType = 358 + OpStructEndOmitEmptyMarshalJSONPtr OpType = 359 + OpStructFieldMarshalTextPtr OpType = 360 + OpStructFieldOmitEmptyMarshalTextPtr OpType = 361 + OpStructEndMarshalTextPtr OpType = 362 + OpStructEndOmitEmptyMarshalTextPtr OpType = 363 + OpStructFieldInterfacePtr OpType = 364 + OpStructFieldOmitEmptyInterfacePtr OpType = 365 + OpStructEndInterfacePtr OpType = 366 + OpStructEndOmitEmptyInterfacePtr OpType = 367 + OpStructFieldIntPtrString OpType = 368 + OpStructFieldOmitEmptyIntPtrString OpType = 369 + OpStructEndIntPtrString OpType = 370 + OpStructEndOmitEmptyIntPtrString OpType = 371 + OpStructFieldUintPtrString OpType = 372 + OpStructFieldOmitEmptyUintPtrString OpType = 373 + OpStructEndUintPtrString OpType = 374 + OpStructEndOmitEmptyUintPtrString OpType = 375 + OpStructFieldFloat32PtrString OpType = 376 + OpStructFieldOmitEmptyFloat32PtrString OpType = 377 + OpStructEndFloat32PtrString OpType = 378 + OpStructEndOmitEmptyFloat32PtrString OpType = 379 + OpStructFieldFloat64PtrString OpType = 380 + OpStructFieldOmitEmptyFloat64PtrString OpType = 381 + OpStructEndFloat64PtrString OpType = 382 + OpStructEndOmitEmptyFloat64PtrString OpType = 383 + OpStructFieldBoolPtrString OpType = 384 + OpStructFieldOmitEmptyBoolPtrString OpType = 385 + OpStructEndBoolPtrString OpType = 386 + OpStructEndOmitEmptyBoolPtrString OpType = 387 + OpStructFieldStringPtrString OpType = 388 + OpStructFieldOmitEmptyStringPtrString OpType = 389 + OpStructEndStringPtrString OpType = 390 + OpStructEndOmitEmptyStringPtrString OpType = 391 + OpStructFieldNumberPtrString OpType = 392 + OpStructFieldOmitEmptyNumberPtrString OpType = 393 + OpStructEndNumberPtrString OpType = 394 + OpStructEndOmitEmptyNumberPtrString OpType = 395 + OpStructField OpType = 396 + OpStructFieldOmitEmpty OpType = 397 + OpStructEnd OpType = 398 + OpStructEndOmitEmpty OpType = 399 +) + +func (t OpType) String() string { + if int(t) >= 400 { + return "" + } + return opTypeStrings[int(t)] +} + +func (t OpType) CodeType() CodeType { + if strings.Contains(t.String(), "Struct") { + if strings.Contains(t.String(), "End") { + return CodeStructEnd + } + return CodeStructField + } + switch t { + case OpArray, OpArrayPtr: + return CodeArrayHead + case OpArrayElem: + return CodeArrayElem + case OpSlice, OpSlicePtr: + return CodeSliceHead + case OpSliceElem: + return CodeSliceElem + case OpMap, OpMapPtr: + return CodeMapHead + case OpMapKey: + return CodeMapKey + case OpMapValue: + return CodeMapValue + case OpMapEnd: + return CodeMapEnd + } + + return CodeOp +} + +func (t OpType) HeadToPtrHead() OpType { + if strings.Index(t.String(), "PtrHead") > 0 { + return t + } + + idx := strings.Index(t.String(), "Head") + if idx == -1 { + return t + } + suffix := "PtrHead" + t.String()[idx+len("Head"):] + + const toPtrOffset = 2 + if strings.Contains(OpType(int(t)+toPtrOffset).String(), suffix) { + return OpType(int(t) + toPtrOffset) + } + return t +} + +func (t OpType) HeadToOmitEmptyHead() OpType { + const toOmitEmptyOffset = 1 + if strings.Contains(OpType(int(t)+toOmitEmptyOffset).String(), "OmitEmpty") { + return OpType(int(t) + toOmitEmptyOffset) + } + + return t +} + +func (t OpType) PtrHeadToHead() OpType { + idx := strings.Index(t.String(), "PtrHead") + if idx == -1 { + return t + } + suffix := t.String()[idx+len("Ptr"):] + + const toPtrOffset = 2 + if strings.Contains(OpType(int(t)-toPtrOffset).String(), suffix) { + return OpType(int(t) - toPtrOffset) + } + return t +} + +func (t OpType) FieldToEnd() OpType { + idx := strings.Index(t.String(), "Field") + if idx == -1 { + return t + } + suffix := t.String()[idx+len("Field"):] + if suffix == "" || suffix == "OmitEmpty" { + return t + } + const toEndOffset = 2 + if strings.Contains(OpType(int(t)+toEndOffset).String(), "End"+suffix) { + return OpType(int(t) + toEndOffset) + } + return t +} + +func (t OpType) FieldToOmitEmptyField() OpType { + const toOmitEmptyOffset = 1 + if strings.Contains(OpType(int(t)+toOmitEmptyOffset).String(), "OmitEmpty") { + return OpType(int(t) + toOmitEmptyOffset) + } + return t +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/string.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/string.go new file mode 100644 index 00000000..a699dba1 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/string.go @@ -0,0 +1,640 @@ +package encoder + +import ( + "math/bits" + "reflect" + "unicode/utf8" + "unsafe" +) + +const ( + lsb = 0x0101010101010101 + msb = 0x8080808080808080 +) + +var needEscapeWithHTML = [256]bool{ + '"': true, + '&': true, + '<': true, + '>': true, + '\\': true, + 0x00: true, + 0x01: true, + 0x02: true, + 0x03: true, + 0x04: true, + 0x05: true, + 0x06: true, + 0x07: true, + 0x08: true, + 0x09: true, + 0x0a: true, + 0x0b: true, + 0x0c: true, + 0x0d: true, + 0x0e: true, + 0x0f: true, + 0x10: true, + 0x11: true, + 0x12: true, + 0x13: true, + 0x14: true, + 0x15: true, + 0x16: true, + 0x17: true, + 0x18: true, + 0x19: true, + 0x1a: true, + 0x1b: true, + 0x1c: true, + 0x1d: true, + 0x1e: true, + 0x1f: true, + /* 0x20 - 0x7f */ + 0x80: true, + 0x81: true, + 0x82: true, + 0x83: true, + 0x84: true, + 0x85: true, + 0x86: true, + 0x87: true, + 0x88: true, + 0x89: true, + 0x8a: true, + 0x8b: true, + 0x8c: true, + 0x8d: true, + 0x8e: true, + 0x8f: true, + 0x90: true, + 0x91: true, + 0x92: true, + 0x93: true, + 0x94: true, + 0x95: true, + 0x96: true, + 0x97: true, + 0x98: true, + 0x99: true, + 0x9a: true, + 0x9b: true, + 0x9c: true, + 0x9d: true, + 0x9e: true, + 0x9f: true, + 0xa0: true, + 0xa1: true, + 0xa2: true, + 0xa3: true, + 0xa4: true, + 0xa5: true, + 0xa6: true, + 0xa7: true, + 0xa8: true, + 0xa9: true, + 0xaa: true, + 0xab: true, + 0xac: true, + 0xad: true, + 0xae: true, + 0xaf: true, + 0xb0: true, + 0xb1: true, + 0xb2: true, + 0xb3: true, + 0xb4: true, + 0xb5: true, + 0xb6: true, + 0xb7: true, + 0xb8: true, + 0xb9: true, + 0xba: true, + 0xbb: true, + 0xbc: true, + 0xbd: true, + 0xbe: true, + 0xbf: true, + 0xc0: true, + 0xc1: true, + 0xc2: true, + 0xc3: true, + 0xc4: true, + 0xc5: true, + 0xc6: true, + 0xc7: true, + 0xc8: true, + 0xc9: true, + 0xca: true, + 0xcb: true, + 0xcc: true, + 0xcd: true, + 0xce: true, + 0xcf: true, + 0xd0: true, + 0xd1: true, + 0xd2: true, + 0xd3: true, + 0xd4: true, + 0xd5: true, + 0xd6: true, + 0xd7: true, + 0xd8: true, + 0xd9: true, + 0xda: true, + 0xdb: true, + 0xdc: true, + 0xdd: true, + 0xde: true, + 0xdf: true, + 0xe0: true, + 0xe1: true, + 0xe2: true, + 0xe3: true, + 0xe4: true, + 0xe5: true, + 0xe6: true, + 0xe7: true, + 0xe8: true, + 0xe9: true, + 0xea: true, + 0xeb: true, + 0xec: true, + 0xed: true, + 0xee: true, + 0xef: true, + 0xf0: true, + 0xf1: true, + 0xf2: true, + 0xf3: true, + 0xf4: true, + 0xf5: true, + 0xf6: true, + 0xf7: true, + 0xf8: true, + 0xf9: true, + 0xfa: true, + 0xfb: true, + 0xfc: true, + 0xfd: true, + 0xfe: true, + 0xff: true, +} + +var needEscape = [256]bool{ + '"': true, + '\\': true, + 0x00: true, + 0x01: true, + 0x02: true, + 0x03: true, + 0x04: true, + 0x05: true, + 0x06: true, + 0x07: true, + 0x08: true, + 0x09: true, + 0x0a: true, + 0x0b: true, + 0x0c: true, + 0x0d: true, + 0x0e: true, + 0x0f: true, + 0x10: true, + 0x11: true, + 0x12: true, + 0x13: true, + 0x14: true, + 0x15: true, + 0x16: true, + 0x17: true, + 0x18: true, + 0x19: true, + 0x1a: true, + 0x1b: true, + 0x1c: true, + 0x1d: true, + 0x1e: true, + 0x1f: true, + /* 0x20 - 0x7f */ + 0x80: true, + 0x81: true, + 0x82: true, + 0x83: true, + 0x84: true, + 0x85: true, + 0x86: true, + 0x87: true, + 0x88: true, + 0x89: true, + 0x8a: true, + 0x8b: true, + 0x8c: true, + 0x8d: true, + 0x8e: true, + 0x8f: true, + 0x90: true, + 0x91: true, + 0x92: true, + 0x93: true, + 0x94: true, + 0x95: true, + 0x96: true, + 0x97: true, + 0x98: true, + 0x99: true, + 0x9a: true, + 0x9b: true, + 0x9c: true, + 0x9d: true, + 0x9e: true, + 0x9f: true, + 0xa0: true, + 0xa1: true, + 0xa2: true, + 0xa3: true, + 0xa4: true, + 0xa5: true, + 0xa6: true, + 0xa7: true, + 0xa8: true, + 0xa9: true, + 0xaa: true, + 0xab: true, + 0xac: true, + 0xad: true, + 0xae: true, + 0xaf: true, + 0xb0: true, + 0xb1: true, + 0xb2: true, + 0xb3: true, + 0xb4: true, + 0xb5: true, + 0xb6: true, + 0xb7: true, + 0xb8: true, + 0xb9: true, + 0xba: true, + 0xbb: true, + 0xbc: true, + 0xbd: true, + 0xbe: true, + 0xbf: true, + 0xc0: true, + 0xc1: true, + 0xc2: true, + 0xc3: true, + 0xc4: true, + 0xc5: true, + 0xc6: true, + 0xc7: true, + 0xc8: true, + 0xc9: true, + 0xca: true, + 0xcb: true, + 0xcc: true, + 0xcd: true, + 0xce: true, + 0xcf: true, + 0xd0: true, + 0xd1: true, + 0xd2: true, + 0xd3: true, + 0xd4: true, + 0xd5: true, + 0xd6: true, + 0xd7: true, + 0xd8: true, + 0xd9: true, + 0xda: true, + 0xdb: true, + 0xdc: true, + 0xdd: true, + 0xde: true, + 0xdf: true, + 0xe0: true, + 0xe1: true, + 0xe2: true, + 0xe3: true, + 0xe4: true, + 0xe5: true, + 0xe6: true, + 0xe7: true, + 0xe8: true, + 0xe9: true, + 0xea: true, + 0xeb: true, + 0xec: true, + 0xed: true, + 0xee: true, + 0xef: true, + 0xf0: true, + 0xf1: true, + 0xf2: true, + 0xf3: true, + 0xf4: true, + 0xf5: true, + 0xf6: true, + 0xf7: true, + 0xf8: true, + 0xf9: true, + 0xfa: true, + 0xfb: true, + 0xfc: true, + 0xfd: true, + 0xfe: true, + 0xff: true, +} + +var hex = "0123456789abcdef" + +// escapeIndex finds the index of the first char in `s` that requires escaping. +// A char requires escaping if it's outside of the range of [0x20, 0x7F] or if +// it includes a double quote or backslash. +// If no chars in `s` require escaping, the return value is -1. +func escapeIndex(s string) int { + chunks := stringToUint64Slice(s) + for _, n := range chunks { + // combine masks before checking for the MSB of each byte. We include + // `n` in the mask to check whether any of the *input* byte MSBs were + // set (i.e. the byte was outside the ASCII range). + mask := n | below(n, 0x20) | contains(n, '"') | contains(n, '\\') + if (mask & msb) != 0 { + return bits.TrailingZeros64(mask&msb) / 8 + } + } + + valLen := len(s) + for i := len(chunks) * 8; i < valLen; i++ { + if needEscape[s[i]] { + return i + } + } + + return -1 +} + +// below return a mask that can be used to determine if any of the bytes +// in `n` are below `b`. If a byte's MSB is set in the mask then that byte was +// below `b`. The result is only valid if `b`, and each byte in `n`, is below +// 0x80. +func below(n uint64, b byte) uint64 { + return n - expand(b) +} + +// contains returns a mask that can be used to determine if any of the +// bytes in `n` are equal to `b`. If a byte's MSB is set in the mask then +// that byte is equal to `b`. The result is only valid if `b`, and each +// byte in `n`, is below 0x80. +func contains(n uint64, b byte) uint64 { + return (n ^ expand(b)) - lsb +} + +// expand puts the specified byte into each of the 8 bytes of a uint64. +func expand(b byte) uint64 { + return lsb * uint64(b) +} + +//nolint:govet +func stringToUint64Slice(s string) []uint64 { + return *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{ + Data: ((*reflect.StringHeader)(unsafe.Pointer(&s))).Data, + Len: len(s) / 8, + Cap: len(s) / 8, + })) +} + +func AppendString(ctx *RuntimeContext, buf []byte, s string) []byte { + if ctx.Option.Flag&HTMLEscapeOption == 0 { + return appendString(buf, s) + } + valLen := len(s) + if valLen == 0 { + return append(buf, `""`...) + } + buf = append(buf, '"') + var ( + i, j int + ) + if valLen >= 8 { + chunks := stringToUint64Slice(s) + for _, n := range chunks { + // combine masks before checking for the MSB of each byte. We include + // `n` in the mask to check whether any of the *input* byte MSBs were + // set (i.e. the byte was outside the ASCII range). + mask := n | (n - (lsb * 0x20)) | + ((n ^ (lsb * '"')) - lsb) | + ((n ^ (lsb * '\\')) - lsb) | + ((n ^ (lsb * '<')) - lsb) | + ((n ^ (lsb * '>')) - lsb) | + ((n ^ (lsb * '&')) - lsb) + if (mask & msb) != 0 { + j = bits.TrailingZeros64(mask&msb) / 8 + goto ESCAPE_END + } + } + for i := len(chunks) * 8; i < valLen; i++ { + if needEscapeWithHTML[s[i]] { + j = i + goto ESCAPE_END + } + } + // no found any escape characters. + return append(append(buf, s...), '"') + } +ESCAPE_END: + for j < valLen { + c := s[j] + + if !needEscapeWithHTML[c] { + // fast path: most of the time, printable ascii characters are used + j++ + continue + } + + switch c { + case '\\', '"': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', c) + i = j + 1 + j = j + 1 + continue + + case '\n': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', 'n') + i = j + 1 + j = j + 1 + continue + + case '\r': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', 'r') + i = j + 1 + j = j + 1 + continue + + case '\t': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', 't') + i = j + 1 + j = j + 1 + continue + + case '<', '>', '&': + buf = append(buf, s[i:j]...) + buf = append(buf, `\u00`...) + buf = append(buf, hex[c>>4], hex[c&0xF]) + i = j + 1 + j = j + 1 + continue + } + + // This encodes bytes < 0x20 except for \t, \n and \r. + if c < 0x20 { + buf = append(buf, s[i:j]...) + buf = append(buf, `\u00`...) + buf = append(buf, hex[c>>4], hex[c&0xF]) + i = j + 1 + j = j + 1 + continue + } + + r, size := utf8.DecodeRuneInString(s[j:]) + + if r == utf8.RuneError && size == 1 { + buf = append(buf, s[i:j]...) + buf = append(buf, `\ufffd`...) + i = j + size + j = j + size + continue + } + + switch r { + case '\u2028', '\u2029': + // U+2028 is LINE SEPARATOR. + // U+2029 is PARAGRAPH SEPARATOR. + // They are both technically valid characters in JSON strings, + // but don't work in JSONP, which has to be evaluated as JavaScript, + // and can lead to security holes there. It is valid JSON to + // escape them, so we do so unconditionally. + // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. + buf = append(buf, s[i:j]...) + buf = append(buf, `\u202`...) + buf = append(buf, hex[r&0xF]) + i = j + size + j = j + size + continue + } + + j += size + } + + return append(append(buf, s[i:]...), '"') +} + +func appendString(buf []byte, s string) []byte { + valLen := len(s) + if valLen == 0 { + return append(buf, `""`...) + } + buf = append(buf, '"') + var escapeIdx int + if valLen >= 8 { + if escapeIdx = escapeIndex(s); escapeIdx < 0 { + return append(append(buf, s...), '"') + } + } + + i := 0 + j := escapeIdx + for j < valLen { + c := s[j] + + if c >= 0x20 && c <= 0x7f && c != '\\' && c != '"' { + // fast path: most of the time, printable ascii characters are used + j++ + continue + } + + switch c { + case '\\', '"': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', c) + i = j + 1 + j = j + 1 + continue + + case '\n': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', 'n') + i = j + 1 + j = j + 1 + continue + + case '\r': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', 'r') + i = j + 1 + j = j + 1 + continue + + case '\t': + buf = append(buf, s[i:j]...) + buf = append(buf, '\\', 't') + i = j + 1 + j = j + 1 + continue + + case '<', '>', '&': + buf = append(buf, s[i:j]...) + buf = append(buf, `\u00`...) + buf = append(buf, hex[c>>4], hex[c&0xF]) + i = j + 1 + j = j + 1 + continue + } + + // This encodes bytes < 0x20 except for \t, \n and \r. + if c < 0x20 { + buf = append(buf, s[i:j]...) + buf = append(buf, `\u00`...) + buf = append(buf, hex[c>>4], hex[c&0xF]) + i = j + 1 + j = j + 1 + continue + } + + r, size := utf8.DecodeRuneInString(s[j:]) + + if r == utf8.RuneError && size == 1 { + buf = append(buf, s[i:j]...) + buf = append(buf, `\ufffd`...) + i = j + size + j = j + size + continue + } + + switch r { + case '\u2028', '\u2029': + // U+2028 is LINE SEPARATOR. + // U+2029 is PARAGRAPH SEPARATOR. + // They are both technically valid characters in JSON strings, + // but don't work in JSONP, which has to be evaluated as JavaScript, + // and can lead to security holes there. It is valid JSON to + // escape them, so we do so unconditionally. + // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. + buf = append(buf, s[i:j]...) + buf = append(buf, `\u202`...) + buf = append(buf, hex[r&0xF]) + i = j + size + j = j + size + continue + } + + j += size + } + + return append(append(buf, s[i:]...), '"') +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/debug_vm.go new file mode 100644 index 00000000..05509fed --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/debug_vm.go @@ -0,0 +1,34 @@ +package vm + +import ( + "fmt" + + "github.com/goccy/go-json/internal/encoder" +) + +func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + defer func() { + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + if err := recover(); err != nil { + fmt.Println("=============[DEBUG]===============") + fmt.Println("* [TYPE]") + fmt.Println(codeSet.Type) + fmt.Printf("\n") + fmt.Println("* [ALL OPCODE]") + fmt.Println(code.Dump()) + fmt.Printf("\n") + fmt.Println("* [CONTEXT]") + fmt.Printf("%+v\n", ctx) + fmt.Println("===================================") + panic(err) + } + }() + + return Run(ctx, b, codeSet) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/hack.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/hack.go new file mode 100644 index 00000000..65252b4a --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/hack.go @@ -0,0 +1,9 @@ +package vm + +import ( + // HACK: compile order + // `vm`, `vm_indent`, `vm_color`, `vm_color_indent` packages uses a lot of memory to compile, + // so forcibly make dependencies and avoid compiling in concurrent. + // dependency order: vm => vm_indent => vm_color => vm_color_indent + _ "github.com/goccy/go-json/internal/encoder/vm_indent" +) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/util.go new file mode 100644 index 00000000..86291d7b --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/util.go @@ -0,0 +1,207 @@ +package vm + +import ( + "encoding/json" + "fmt" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +const uintptrSize = 4 << (^uintptr(0) >> 63) + +var ( + appendInt = encoder.AppendInt + appendUint = encoder.AppendUint + appendFloat32 = encoder.AppendFloat32 + appendFloat64 = encoder.AppendFloat64 + appendString = encoder.AppendString + appendByteSlice = encoder.AppendByteSlice + appendNumber = encoder.AppendNumber + errUnsupportedValue = encoder.ErrUnsupportedValue + errUnsupportedFloat = encoder.ErrUnsupportedFloat + mapiterinit = encoder.MapIterInit + mapiterkey = encoder.MapIterKey + mapitervalue = encoder.MapIterValue + mapiternext = encoder.MapIterNext + maplen = encoder.MapLen +) + +type emptyInterface struct { + typ *runtime.Type + ptr unsafe.Pointer +} + +type nonEmptyInterface struct { + itab *struct { + ityp *runtime.Type // static interface type + typ *runtime.Type // dynamic concrete type + // unused fields... + } + ptr unsafe.Pointer +} + +func errUnimplementedOp(op encoder.OpType) error { + return fmt.Errorf("encoder: opcode %s has not been implemented", op) +} + +func load(base uintptr, idx uint32) uintptr { + addr := base + uintptr(idx) + return **(**uintptr)(unsafe.Pointer(&addr)) +} + +func store(base uintptr, idx uint32, p uintptr) { + addr := base + uintptr(idx) + **(**uintptr)(unsafe.Pointer(&addr)) = p +} + +func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { + addr := base + uintptr(idx) + p := **(**uintptr)(unsafe.Pointer(&addr)) + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUint64(p uintptr, bitSize uint8) uint64 { + switch bitSize { + case 8: + return (uint64)(**(**uint8)(unsafe.Pointer(&p))) + case 16: + return (uint64)(**(**uint16)(unsafe.Pointer(&p))) + case 32: + return (uint64)(**(**uint32)(unsafe.Pointer(&p))) + case 64: + return **(**uint64)(unsafe.Pointer(&p)) + } + return 0 +} +func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } +func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } +func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } +func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } +func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } +func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } +func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } +func ptrToPtr(p uintptr) uintptr { + return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) +} +func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUnsafePtr(p uintptr) unsafe.Pointer { + return *(*unsafe.Pointer)(unsafe.Pointer(&p)) +} +func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { + return *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: code.Type, + ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), + })) +} + +func appendBool(_ *encoder.RuntimeContext, b []byte, v bool) []byte { + if v { + return append(b, "true"...) + } + return append(b, "false"...) +} + +func appendNull(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, "null"...) +} + +func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, ',') +} + +func appendNullComma(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, "null,"...) +} + +func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { + last := len(b) - 1 + b[last] = ':' + return b +} + +func appendMapKeyValue(_ *encoder.RuntimeContext, _ *encoder.Opcode, b, key, value []byte) []byte { + b = append(b, key...) + b[len(b)-1] = ':' + return append(b, value...) +} + +func appendMapEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + b[len(b)-1] = '}' + b = append(b, ',') + return b +} + +func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + return encoder.AppendMarshalJSON(ctx, code, b, v) +} + +func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + return encoder.AppendMarshalText(ctx, code, b, v) +} + +func appendArrayHead(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + return append(b, '[') +} + +func appendArrayEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + b[last] = ']' + return append(b, ',') +} + +func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '[', ']', ',') +} + +func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{', '}', ',') +} + +func appendObjectEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + b[last] = '}' + return append(b, ',') +} + +func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{') +} + +func appendStructKey(_ *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + return append(b, code.Key...) +} + +func appendStructEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + return append(b, '}', ',') +} + +func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + if b[last] == ',' { + b[last] = '}' + return appendComma(ctx, b) + } + return appendStructEnd(ctx, code, b) +} + +func restoreIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, _ uintptr) {} +func storeIndent(_ uintptr, _ *encoder.Opcode, _ uintptr) {} +func appendMapKeyIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } +func appendArrayElemIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/vm.go new file mode 100644 index 00000000..b78b5eb0 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm/vm.go @@ -0,0 +1,4876 @@ +// Code generated by internal/cmd/generator. DO NOT EDIT! +package vm + +import ( + "math" + "sort" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + recursiveLevel := 0 + ptrOffset := uintptr(0) + ctxptr := ctx.Ptr() + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + for { + switch code.Op { + default: + return nil, errUnimplementedOp(code.Op) + case encoder.OpPtr: + p := load(ctxptr, code.Idx) + code = code.Next + store(ctxptr, code.Idx, ptrToPtr(p)) + case encoder.OpIntPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInt: + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpUint: + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpIntString: + b = append(b, '"') + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintString: + b = append(b, '"') + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat32Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat32: + b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat64Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat64: + v := ptrToFloat64(load(ctxptr, code.Idx)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStringPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpString: + b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBoolPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBool: + b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBytesPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBytes: + b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpNumberPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpNumber: + bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpInterfacePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInterface: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if p == seen { + return nil, errUnsupportedValue(code, p) + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, p) + var ( + typ *runtime.Type + ifacePtr unsafe.Pointer + ) + up := ptrToUnsafePtr(p) + if code.Flags&encoder.NonEmptyInterfaceFlags != 0 { + iface := (*nonEmptyInterface)(up) + ifacePtr = iface.ptr + if iface.itab != nil { + typ = iface.itab.typ + } + } else { + iface := (*emptyInterface)(up) + ifacePtr = iface.ptr + typ = iface.typ + } + if ifacePtr == nil { + b = appendNullComma(ctx, b) + code = code.Next + break + } + ctx.KeepRefs = append(ctx.KeepRefs, up) + ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(typ))) + if err != nil { + return nil, err + } + + totalLength := uintptr(code.Length) + 3 + nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 + + var c *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + c = ifaceCodeSet.InterfaceEscapeKeyCode + } else { + c = ifaceCodeSet.InterfaceNoescapeKeyCode + } + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += totalLength * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + totalLength + nextTotalLength + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + end := ifaceCodeSet.EndCode + store(ctxptr, c.Idx, uintptr(ifacePtr)) + store(ctxptr, end.Idx, oldOffset) + store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, end, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpInterfaceEnd: + recursiveLevel-- + + // restore ctxptr + offset := load(ctxptr, code.Idx) + restoreIndent(ctx, code, ctxptr) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + b = append(b, `""`...) + b = appendComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpSlicePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpSlice: + p := load(ctxptr, code.Idx) + slice := ptrToSlice(p) + if p == 0 || slice.Data == nil { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(slice.Len)) + store(ctxptr, code.Idx, uintptr(slice.Data)) + if slice.Len > 0 { + b = appendArrayHead(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, uintptr(slice.Data)) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpSliceElem: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if idx < length { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + data := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, data+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpArrayPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpArray: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + if code.Length > 0 { + b = appendArrayHead(ctx, code, b) + store(ctxptr, code.ElemIdx, 0) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpArrayElem: + idx := load(ctxptr, code.ElemIdx) + idx++ + if idx < uintptr(code.Length) { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + p := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, p+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpMapPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpMap: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + uptr := ptrToUnsafePtr(p) + mlen := maplen(uptr) + if mlen <= 0 { + b = appendEmptyObject(ctx, b) + code = code.End.Next + break + } + b = appendStructHead(ctx, b) + iter := mapiterinit(code.Type, uptr) + ctx.KeepRefs = append(ctx.KeepRefs, iter) + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(mlen)) + store(ctxptr, code.MapIter, uintptr(iter)) + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendMapKeyIndent(ctx, code.Next, b) + } else { + mapCtx := encoder.NewMapContext(mlen) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) + store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) + } + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + case encoder.OpMapKey: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + if idx < length { + b = appendMapKeyIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + b = appendObjectEnd(ctx, code, b) + code = code.End.Next + } + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + if idx < length { + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + store(ctxptr, code.ElemIdx, idx) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + code = code.End + } + } + case encoder.OpMapValue: + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendColon(ctx, b) + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + } + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + value := mapitervalue(iter) + store(ctxptr, code.Next.Idx, uintptr(value)) + mapiternext(iter) + code = code.Next + case encoder.OpMapEnd: + // this operation only used by sorted map. + length := int(load(ctxptr, code.Length)) + ptr := load(ctxptr, code.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + pos := mapCtx.Pos + for i := 0; i < length; i++ { + startKey := pos[i*2] + startValue := pos[i*2+1] + var endValue int + if i+1 < length { + endValue = pos[i*2+2] + } else { + endValue = len(b) + } + mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ + Key: b[startKey:startValue], + Value: b[startValue:endValue], + }) + } + sort.Sort(mapCtx.Slice) + buf := mapCtx.Buf + for _, item := range mapCtx.Slice.Items { + buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) + } + buf = appendMapEnd(ctx, code, buf) + b = b[:pos[0]] + b = append(b, buf...) + mapCtx.Buf = buf + encoder.ReleaseMapContext(mapCtx) + code = code.Next + case encoder.OpRecursivePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpRecursive: + ptr := load(ctxptr, code.Idx) + if ptr != 0 { + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if ptr == seen { + return nil, errUnsupportedValue(code, ptr) + } + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, ptr) + c := code.Jmp.Code + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += code.Jmp.CurLen * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + store(ctxptr, c.Idx, ptr) + store(ctxptr, c.End.Next.Idx, oldOffset) + store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpRecursiveEnd: + recursiveLevel-- + + // restore ctxptr + restoreIndent(ctx, code, ctxptr) + offset := load(ctxptr, code.Idx) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpStructPtrHead: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHead: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if len(code.Key) > 0 { + if (code.Flags&encoder.IsTaggedKeyFlags) != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + } + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + } + case encoder.OpStructPtrHeadNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructPtrHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyArray: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyArray: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptySlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptySlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + if maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructField: + if code.Flags&encoder.IsTaggedKeyFlags != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + p := load(ctxptr, code.Idx) + uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmpty: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringString: + p := load(ctxptr, code.Idx) + s := ptrToString(p + uintptr(code.Offset)) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldMarshalJSON: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalJSONPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldMarshalText: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalTextPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldArrayPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArrayPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldSlice: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlice: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldSlicePtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldMap: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMap: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldMapPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldStruct: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyStruct: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructEnd: + b = appendStructEndSkipLast(ctx, code, b) + code = code.Next + case encoder.OpStructEndInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendStructEnd(ctx, code, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + s := ptrToString(p + uintptr(code.Offset)) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytesPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + code = code.Next + case encoder.OpStructEndOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpEnd: + goto END + } + } +END: + return b, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/debug_vm.go new file mode 100644 index 00000000..6a6a33d2 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/debug_vm.go @@ -0,0 +1,34 @@ +package vm_color + +import ( + "fmt" + + "github.com/goccy/go-json/internal/encoder" +) + +func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + defer func() { + if err := recover(); err != nil { + fmt.Println("=============[DEBUG]===============") + fmt.Println("* [TYPE]") + fmt.Println(codeSet.Type) + fmt.Printf("\n") + fmt.Println("* [ALL OPCODE]") + fmt.Println(code.Dump()) + fmt.Printf("\n") + fmt.Println("* [CONTEXT]") + fmt.Printf("%+v\n", ctx) + fmt.Println("===================================") + panic(err) + } + }() + + return Run(ctx, b, codeSet) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/hack.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/hack.go new file mode 100644 index 00000000..12ec56c5 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/hack.go @@ -0,0 +1,9 @@ +package vm_color + +import ( + // HACK: compile order + // `vm`, `vm_indent`, `vm_color`, `vm_color_indent` packages uses a lot of memory to compile, + // so forcibly make dependencies and avoid compiling in concurrent. + // dependency order: vm => vm_indent => vm_color => vm_color_indent + _ "github.com/goccy/go-json/internal/encoder/vm_color_indent" +) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/util.go new file mode 100644 index 00000000..33f29aee --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/util.go @@ -0,0 +1,274 @@ +package vm_color + +import ( + "encoding/json" + "fmt" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +const uintptrSize = 4 << (^uintptr(0) >> 63) + +var ( + errUnsupportedValue = encoder.ErrUnsupportedValue + errUnsupportedFloat = encoder.ErrUnsupportedFloat + mapiterinit = encoder.MapIterInit + mapiterkey = encoder.MapIterKey + mapitervalue = encoder.MapIterValue + mapiternext = encoder.MapIterNext + maplen = encoder.MapLen +) + +type emptyInterface struct { + typ *runtime.Type + ptr unsafe.Pointer +} + +type nonEmptyInterface struct { + itab *struct { + ityp *runtime.Type // static interface type + typ *runtime.Type // dynamic concrete type + // unused fields... + } + ptr unsafe.Pointer +} + +func errUnimplementedOp(op encoder.OpType) error { + return fmt.Errorf("encoder: opcode %s has not been implemented", op) +} + +func load(base uintptr, idx uint32) uintptr { + addr := base + uintptr(idx) + return **(**uintptr)(unsafe.Pointer(&addr)) +} + +func store(base uintptr, idx uint32, p uintptr) { + addr := base + uintptr(idx) + **(**uintptr)(unsafe.Pointer(&addr)) = p +} + +func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { + addr := base + uintptr(idx) + p := **(**uintptr)(unsafe.Pointer(&addr)) + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUint64(p uintptr, bitSize uint8) uint64 { + switch bitSize { + case 8: + return (uint64)(**(**uint8)(unsafe.Pointer(&p))) + case 16: + return (uint64)(**(**uint16)(unsafe.Pointer(&p))) + case 32: + return (uint64)(**(**uint32)(unsafe.Pointer(&p))) + case 64: + return **(**uint64)(unsafe.Pointer(&p)) + } + return 0 +} +func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } +func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } +func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } +func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } +func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } +func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } +func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } +func ptrToPtr(p uintptr) uintptr { + return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) +} +func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUnsafePtr(p uintptr) unsafe.Pointer { + return *(*unsafe.Pointer)(unsafe.Pointer(&p)) +} +func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { + return *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: code.Type, + ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), + })) +} + +func appendInt(ctx *encoder.RuntimeContext, b []byte, p uintptr, code *encoder.Opcode) []byte { + format := ctx.Option.ColorScheme.Int + b = append(b, format.Header...) + b = encoder.AppendInt(ctx, b, p, code) + return append(b, format.Footer...) +} + +func appendUint(ctx *encoder.RuntimeContext, b []byte, p uintptr, code *encoder.Opcode) []byte { + format := ctx.Option.ColorScheme.Uint + b = append(b, format.Header...) + b = encoder.AppendUint(ctx, b, p, code) + return append(b, format.Footer...) +} + +func appendFloat32(ctx *encoder.RuntimeContext, b []byte, v float32) []byte { + format := ctx.Option.ColorScheme.Float + b = append(b, format.Header...) + b = encoder.AppendFloat32(ctx, b, v) + return append(b, format.Footer...) +} + +func appendFloat64(ctx *encoder.RuntimeContext, b []byte, v float64) []byte { + format := ctx.Option.ColorScheme.Float + b = append(b, format.Header...) + b = encoder.AppendFloat64(ctx, b, v) + return append(b, format.Footer...) +} + +func appendString(ctx *encoder.RuntimeContext, b []byte, v string) []byte { + format := ctx.Option.ColorScheme.String + b = append(b, format.Header...) + b = encoder.AppendString(ctx, b, v) + return append(b, format.Footer...) +} + +func appendByteSlice(ctx *encoder.RuntimeContext, b []byte, src []byte) []byte { + format := ctx.Option.ColorScheme.Binary + b = append(b, format.Header...) + b = encoder.AppendByteSlice(ctx, b, src) + return append(b, format.Footer...) +} + +func appendNumber(ctx *encoder.RuntimeContext, b []byte, n json.Number) ([]byte, error) { + format := ctx.Option.ColorScheme.Int + b = append(b, format.Header...) + bb, err := encoder.AppendNumber(ctx, b, n) + if err != nil { + return nil, err + } + return append(bb, format.Footer...), nil +} + +func appendBool(ctx *encoder.RuntimeContext, b []byte, v bool) []byte { + format := ctx.Option.ColorScheme.Bool + b = append(b, format.Header...) + if v { + b = append(b, "true"...) + } else { + b = append(b, "false"...) + } + return append(b, format.Footer...) +} + +func appendNull(ctx *encoder.RuntimeContext, b []byte) []byte { + format := ctx.Option.ColorScheme.Null + b = append(b, format.Header...) + b = append(b, "null"...) + return append(b, format.Footer...) +} + +func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, ',') +} + +func appendNullComma(ctx *encoder.RuntimeContext, b []byte) []byte { + format := ctx.Option.ColorScheme.Null + b = append(b, format.Header...) + b = append(b, "null"...) + return append(append(b, format.Footer...), ',') +} + +func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { + last := len(b) - 1 + b[last] = ':' + return b +} + +func appendMapKeyValue(_ *encoder.RuntimeContext, _ *encoder.Opcode, b, key, value []byte) []byte { + b = append(b, key[:len(key)-1]...) + b = append(b, ':') + return append(b, value...) +} + +func appendMapEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + b[last] = '}' + b = append(b, ',') + return b +} + +func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + return encoder.AppendMarshalJSON(ctx, code, b, v) +} + +func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + format := ctx.Option.ColorScheme.String + b = append(b, format.Header...) + bb, err := encoder.AppendMarshalText(ctx, code, b, v) + if err != nil { + return nil, err + } + return append(bb, format.Footer...), nil +} + +func appendArrayHead(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + return append(b, '[') +} + +func appendArrayEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + b[last] = ']' + return append(b, ',') +} + +func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '[', ']', ',') +} + +func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{', '}', ',') +} + +func appendObjectEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + b[last] = '}' + return append(b, ',') +} + +func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{') +} + +func appendStructKey(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + format := ctx.Option.ColorScheme.ObjectKey + b = append(b, format.Header...) + b = append(b, code.Key[:len(code.Key)-1]...) + b = append(b, format.Footer...) + + return append(b, ':') +} + +func appendStructEnd(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { + return append(b, '}', ',') +} + +func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + if b[last] == ',' { + b[last] = '}' + return appendComma(ctx, b) + } + return appendStructEnd(ctx, code, b) +} + +func restoreIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, _ uintptr) {} +func storeIndent(_ uintptr, _ *encoder.Opcode, _ uintptr) {} +func appendMapKeyIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } +func appendArrayElemIndent(_ *encoder.RuntimeContext, _ *encoder.Opcode, b []byte) []byte { return b } diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/vm.go new file mode 100644 index 00000000..c7c68182 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color/vm.go @@ -0,0 +1,4876 @@ +// Code generated by internal/cmd/generator. DO NOT EDIT! +package vm_color + +import ( + "math" + "sort" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + recursiveLevel := 0 + ptrOffset := uintptr(0) + ctxptr := ctx.Ptr() + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + for { + switch code.Op { + default: + return nil, errUnimplementedOp(code.Op) + case encoder.OpPtr: + p := load(ctxptr, code.Idx) + code = code.Next + store(ctxptr, code.Idx, ptrToPtr(p)) + case encoder.OpIntPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInt: + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpUint: + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpIntString: + b = append(b, '"') + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintString: + b = append(b, '"') + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat32Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat32: + b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat64Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat64: + v := ptrToFloat64(load(ctxptr, code.Idx)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStringPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpString: + b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBoolPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBool: + b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBytesPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBytes: + b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpNumberPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpNumber: + bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpInterfacePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInterface: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if p == seen { + return nil, errUnsupportedValue(code, p) + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, p) + var ( + typ *runtime.Type + ifacePtr unsafe.Pointer + ) + up := ptrToUnsafePtr(p) + if code.Flags&encoder.NonEmptyInterfaceFlags != 0 { + iface := (*nonEmptyInterface)(up) + ifacePtr = iface.ptr + if iface.itab != nil { + typ = iface.itab.typ + } + } else { + iface := (*emptyInterface)(up) + ifacePtr = iface.ptr + typ = iface.typ + } + if ifacePtr == nil { + b = appendNullComma(ctx, b) + code = code.Next + break + } + ctx.KeepRefs = append(ctx.KeepRefs, up) + ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(typ))) + if err != nil { + return nil, err + } + + totalLength := uintptr(code.Length) + 3 + nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 + + var c *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + c = ifaceCodeSet.InterfaceEscapeKeyCode + } else { + c = ifaceCodeSet.InterfaceNoescapeKeyCode + } + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += totalLength * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + totalLength + nextTotalLength + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + end := ifaceCodeSet.EndCode + store(ctxptr, c.Idx, uintptr(ifacePtr)) + store(ctxptr, end.Idx, oldOffset) + store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, end, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpInterfaceEnd: + recursiveLevel-- + + // restore ctxptr + offset := load(ctxptr, code.Idx) + restoreIndent(ctx, code, ctxptr) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + b = append(b, `""`...) + b = appendComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpSlicePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpSlice: + p := load(ctxptr, code.Idx) + slice := ptrToSlice(p) + if p == 0 || slice.Data == nil { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(slice.Len)) + store(ctxptr, code.Idx, uintptr(slice.Data)) + if slice.Len > 0 { + b = appendArrayHead(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, uintptr(slice.Data)) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpSliceElem: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if idx < length { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + data := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, data+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpArrayPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpArray: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + if code.Length > 0 { + b = appendArrayHead(ctx, code, b) + store(ctxptr, code.ElemIdx, 0) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpArrayElem: + idx := load(ctxptr, code.ElemIdx) + idx++ + if idx < uintptr(code.Length) { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + p := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, p+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpMapPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpMap: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + uptr := ptrToUnsafePtr(p) + mlen := maplen(uptr) + if mlen <= 0 { + b = appendEmptyObject(ctx, b) + code = code.End.Next + break + } + b = appendStructHead(ctx, b) + iter := mapiterinit(code.Type, uptr) + ctx.KeepRefs = append(ctx.KeepRefs, iter) + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(mlen)) + store(ctxptr, code.MapIter, uintptr(iter)) + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendMapKeyIndent(ctx, code.Next, b) + } else { + mapCtx := encoder.NewMapContext(mlen) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) + store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) + } + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + case encoder.OpMapKey: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + if idx < length { + b = appendMapKeyIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + b = appendObjectEnd(ctx, code, b) + code = code.End.Next + } + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + if idx < length { + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + store(ctxptr, code.ElemIdx, idx) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + code = code.End + } + } + case encoder.OpMapValue: + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendColon(ctx, b) + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + } + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + value := mapitervalue(iter) + store(ctxptr, code.Next.Idx, uintptr(value)) + mapiternext(iter) + code = code.Next + case encoder.OpMapEnd: + // this operation only used by sorted map. + length := int(load(ctxptr, code.Length)) + ptr := load(ctxptr, code.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + pos := mapCtx.Pos + for i := 0; i < length; i++ { + startKey := pos[i*2] + startValue := pos[i*2+1] + var endValue int + if i+1 < length { + endValue = pos[i*2+2] + } else { + endValue = len(b) + } + mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ + Key: b[startKey:startValue], + Value: b[startValue:endValue], + }) + } + sort.Sort(mapCtx.Slice) + buf := mapCtx.Buf + for _, item := range mapCtx.Slice.Items { + buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) + } + buf = appendMapEnd(ctx, code, buf) + b = b[:pos[0]] + b = append(b, buf...) + mapCtx.Buf = buf + encoder.ReleaseMapContext(mapCtx) + code = code.Next + case encoder.OpRecursivePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpRecursive: + ptr := load(ctxptr, code.Idx) + if ptr != 0 { + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if ptr == seen { + return nil, errUnsupportedValue(code, ptr) + } + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, ptr) + c := code.Jmp.Code + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += code.Jmp.CurLen * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + store(ctxptr, c.Idx, ptr) + store(ctxptr, c.End.Next.Idx, oldOffset) + store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpRecursiveEnd: + recursiveLevel-- + + // restore ctxptr + restoreIndent(ctx, code, ctxptr) + offset := load(ctxptr, code.Idx) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpStructPtrHead: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHead: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if len(code.Key) > 0 { + if (code.Flags&encoder.IsTaggedKeyFlags) != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + } + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + } + case encoder.OpStructPtrHeadNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructPtrHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyArray: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyArray: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptySlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptySlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + if maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructField: + if code.Flags&encoder.IsTaggedKeyFlags != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + p := load(ctxptr, code.Idx) + uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmpty: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringString: + p := load(ctxptr, code.Idx) + s := ptrToString(p + uintptr(code.Offset)) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldMarshalJSON: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalJSONPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldMarshalText: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalTextPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldArrayPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArrayPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldSlice: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlice: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldSlicePtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldMap: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMap: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldMapPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldStruct: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyStruct: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructEnd: + b = appendStructEndSkipLast(ctx, code, b) + code = code.Next + case encoder.OpStructEndInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendStructEnd(ctx, code, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + s := ptrToString(p + uintptr(code.Offset)) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytesPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + code = code.Next + case encoder.OpStructEndOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpEnd: + goto END + } + } +END: + return b, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/debug_vm.go new file mode 100644 index 00000000..a68bbf6b --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/debug_vm.go @@ -0,0 +1,34 @@ +package vm_color_indent + +import ( + "fmt" + + "github.com/goccy/go-json/internal/encoder" +) + +func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + defer func() { + if err := recover(); err != nil { + fmt.Println("=============[DEBUG]===============") + fmt.Println("* [TYPE]") + fmt.Println(codeSet.Type) + fmt.Printf("\n") + fmt.Println("* [ALL OPCODE]") + fmt.Println(code.Dump()) + fmt.Printf("\n") + fmt.Println("* [CONTEXT]") + fmt.Printf("%+v\n", ctx) + fmt.Println("===================================") + panic(err) + } + }() + + return Run(ctx, b, codeSet) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/util.go new file mode 100644 index 00000000..60e4a8ed --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/util.go @@ -0,0 +1,296 @@ +package vm_color_indent + +import ( + "encoding/json" + "fmt" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +const uintptrSize = 4 << (^uintptr(0) >> 63) + +var ( + appendIndent = encoder.AppendIndent + appendStructEnd = encoder.AppendStructEndIndent + errUnsupportedValue = encoder.ErrUnsupportedValue + errUnsupportedFloat = encoder.ErrUnsupportedFloat + mapiterinit = encoder.MapIterInit + mapiterkey = encoder.MapIterKey + mapitervalue = encoder.MapIterValue + mapiternext = encoder.MapIterNext + maplen = encoder.MapLen +) + +type emptyInterface struct { + typ *runtime.Type + ptr unsafe.Pointer +} + +type nonEmptyInterface struct { + itab *struct { + ityp *runtime.Type // static interface type + typ *runtime.Type // dynamic concrete type + // unused fields... + } + ptr unsafe.Pointer +} + +func errUnimplementedOp(op encoder.OpType) error { + return fmt.Errorf("encoder (indent): opcode %s has not been implemented", op) +} + +func load(base uintptr, idx uint32) uintptr { + addr := base + uintptr(idx) + return **(**uintptr)(unsafe.Pointer(&addr)) +} + +func store(base uintptr, idx uint32, p uintptr) { + addr := base + uintptr(idx) + **(**uintptr)(unsafe.Pointer(&addr)) = p +} + +func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { + addr := base + uintptr(idx) + p := **(**uintptr)(unsafe.Pointer(&addr)) + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUint64(p uintptr, bitSize uint8) uint64 { + switch bitSize { + case 8: + return (uint64)(**(**uint8)(unsafe.Pointer(&p))) + case 16: + return (uint64)(**(**uint16)(unsafe.Pointer(&p))) + case 32: + return (uint64)(**(**uint32)(unsafe.Pointer(&p))) + case 64: + return **(**uint64)(unsafe.Pointer(&p)) + } + return 0 +} + +func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } +func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } +func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } +func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } +func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } +func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } +func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } +func ptrToPtr(p uintptr) uintptr { + return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) +} +func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUnsafePtr(p uintptr) unsafe.Pointer { + return *(*unsafe.Pointer)(unsafe.Pointer(&p)) +} +func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { + return *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: code.Type, + ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), + })) +} + +func appendInt(ctx *encoder.RuntimeContext, b []byte, p uintptr, code *encoder.Opcode) []byte { + format := ctx.Option.ColorScheme.Int + b = append(b, format.Header...) + b = encoder.AppendInt(ctx, b, p, code) + return append(b, format.Footer...) +} + +func appendUint(ctx *encoder.RuntimeContext, b []byte, p uintptr, code *encoder.Opcode) []byte { + format := ctx.Option.ColorScheme.Uint + b = append(b, format.Header...) + b = encoder.AppendUint(ctx, b, p, code) + return append(b, format.Footer...) +} + +func appendFloat32(ctx *encoder.RuntimeContext, b []byte, v float32) []byte { + format := ctx.Option.ColorScheme.Float + b = append(b, format.Header...) + b = encoder.AppendFloat32(ctx, b, v) + return append(b, format.Footer...) +} + +func appendFloat64(ctx *encoder.RuntimeContext, b []byte, v float64) []byte { + format := ctx.Option.ColorScheme.Float + b = append(b, format.Header...) + b = encoder.AppendFloat64(ctx, b, v) + return append(b, format.Footer...) +} + +func appendString(ctx *encoder.RuntimeContext, b []byte, v string) []byte { + format := ctx.Option.ColorScheme.String + b = append(b, format.Header...) + b = encoder.AppendString(ctx, b, v) + return append(b, format.Footer...) +} + +func appendByteSlice(ctx *encoder.RuntimeContext, b []byte, src []byte) []byte { + format := ctx.Option.ColorScheme.Binary + b = append(b, format.Header...) + b = encoder.AppendByteSlice(ctx, b, src) + return append(b, format.Footer...) +} + +func appendNumber(ctx *encoder.RuntimeContext, b []byte, n json.Number) ([]byte, error) { + format := ctx.Option.ColorScheme.Int + b = append(b, format.Header...) + bb, err := encoder.AppendNumber(ctx, b, n) + if err != nil { + return nil, err + } + return append(bb, format.Footer...), nil +} + +func appendBool(ctx *encoder.RuntimeContext, b []byte, v bool) []byte { + format := ctx.Option.ColorScheme.Bool + b = append(b, format.Header...) + if v { + b = append(b, "true"...) + } else { + b = append(b, "false"...) + } + return append(b, format.Footer...) +} + +func appendNull(ctx *encoder.RuntimeContext, b []byte) []byte { + format := ctx.Option.ColorScheme.Null + b = append(b, format.Header...) + b = append(b, "null"...) + return append(b, format.Footer...) +} + +func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, ',', '\n') +} + +func appendNullComma(ctx *encoder.RuntimeContext, b []byte) []byte { + format := ctx.Option.ColorScheme.Null + b = append(b, format.Header...) + b = append(b, "null"...) + return append(append(b, format.Footer...), ',', '\n') +} + +func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, ':', ' ') +} + +func appendMapKeyValue(ctx *encoder.RuntimeContext, code *encoder.Opcode, b, key, value []byte) []byte { + b = appendIndent(ctx, b, code.Indent+1) + b = append(b, key...) + b[len(b)-2] = ':' + b[len(b)-1] = ' ' + return append(b, value...) +} + +func appendMapEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = b[:len(b)-2] + b = append(b, '\n') + b = appendIndent(ctx, b, code.Indent) + return append(b, '}', ',', '\n') +} + +func appendArrayHead(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = append(b, '[', '\n') + return appendIndent(ctx, b, code.Indent+1) +} + +func appendArrayEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = b[:len(b)-2] + b = append(b, '\n') + b = appendIndent(ctx, b, code.Indent) + return append(b, ']', ',', '\n') +} + +func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '[', ']', ',', '\n') +} + +func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{', '}', ',', '\n') +} + +func appendObjectEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + b[last] = '\n' + b = appendIndent(ctx, b, code.Indent-1) + return append(b, '}', ',', '\n') +} + +func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + return encoder.AppendMarshalJSONIndent(ctx, code, b, v) +} + +func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + format := ctx.Option.ColorScheme.String + b = append(b, format.Header...) + bb, err := encoder.AppendMarshalTextIndent(ctx, code, b, v) + if err != nil { + return nil, err + } + return append(bb, format.Footer...), nil +} + +func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{', '\n') +} + +func appendStructKey(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = appendIndent(ctx, b, code.Indent) + + format := ctx.Option.ColorScheme.ObjectKey + b = append(b, format.Header...) + b = append(b, code.Key[:len(code.Key)-1]...) + b = append(b, format.Footer...) + + return append(b, ':', ' ') +} + +func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + if b[last-1] == '{' { + b[last] = '}' + } else { + if b[last] == '\n' { + // to remove ',' and '\n' characters + b = b[:len(b)-2] + } + b = append(b, '\n') + b = appendIndent(ctx, b, code.Indent-1) + b = append(b, '}') + } + return appendComma(ctx, b) +} + +func restoreIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, ctxptr uintptr) { + ctx.BaseIndent = uint32(load(ctxptr, code.Length)) +} + +func storeIndent(ctxptr uintptr, code *encoder.Opcode, indent uintptr) { + store(ctxptr, code.Length, indent) +} + +func appendArrayElemIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + return appendIndent(ctx, b, code.Indent+1) +} + +func appendMapKeyIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + return appendIndent(ctx, b, code.Indent) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/vm.go new file mode 100644 index 00000000..691ffc6c --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_color_indent/vm.go @@ -0,0 +1,4876 @@ +// Code generated by internal/cmd/generator. DO NOT EDIT! +package vm_color_indent + +import ( + "math" + "sort" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + recursiveLevel := 0 + ptrOffset := uintptr(0) + ctxptr := ctx.Ptr() + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + for { + switch code.Op { + default: + return nil, errUnimplementedOp(code.Op) + case encoder.OpPtr: + p := load(ctxptr, code.Idx) + code = code.Next + store(ctxptr, code.Idx, ptrToPtr(p)) + case encoder.OpIntPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInt: + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpUint: + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpIntString: + b = append(b, '"') + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintString: + b = append(b, '"') + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat32Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat32: + b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat64Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat64: + v := ptrToFloat64(load(ctxptr, code.Idx)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStringPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpString: + b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBoolPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBool: + b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBytesPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBytes: + b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpNumberPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpNumber: + bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpInterfacePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInterface: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if p == seen { + return nil, errUnsupportedValue(code, p) + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, p) + var ( + typ *runtime.Type + ifacePtr unsafe.Pointer + ) + up := ptrToUnsafePtr(p) + if code.Flags&encoder.NonEmptyInterfaceFlags != 0 { + iface := (*nonEmptyInterface)(up) + ifacePtr = iface.ptr + if iface.itab != nil { + typ = iface.itab.typ + } + } else { + iface := (*emptyInterface)(up) + ifacePtr = iface.ptr + typ = iface.typ + } + if ifacePtr == nil { + b = appendNullComma(ctx, b) + code = code.Next + break + } + ctx.KeepRefs = append(ctx.KeepRefs, up) + ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(typ))) + if err != nil { + return nil, err + } + + totalLength := uintptr(code.Length) + 3 + nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 + + var c *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + c = ifaceCodeSet.InterfaceEscapeKeyCode + } else { + c = ifaceCodeSet.InterfaceNoescapeKeyCode + } + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += totalLength * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + totalLength + nextTotalLength + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + end := ifaceCodeSet.EndCode + store(ctxptr, c.Idx, uintptr(ifacePtr)) + store(ctxptr, end.Idx, oldOffset) + store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, end, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpInterfaceEnd: + recursiveLevel-- + + // restore ctxptr + offset := load(ctxptr, code.Idx) + restoreIndent(ctx, code, ctxptr) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + b = append(b, `""`...) + b = appendComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpSlicePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpSlice: + p := load(ctxptr, code.Idx) + slice := ptrToSlice(p) + if p == 0 || slice.Data == nil { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(slice.Len)) + store(ctxptr, code.Idx, uintptr(slice.Data)) + if slice.Len > 0 { + b = appendArrayHead(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, uintptr(slice.Data)) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpSliceElem: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if idx < length { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + data := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, data+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpArrayPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpArray: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + if code.Length > 0 { + b = appendArrayHead(ctx, code, b) + store(ctxptr, code.ElemIdx, 0) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpArrayElem: + idx := load(ctxptr, code.ElemIdx) + idx++ + if idx < uintptr(code.Length) { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + p := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, p+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpMapPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpMap: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + uptr := ptrToUnsafePtr(p) + mlen := maplen(uptr) + if mlen <= 0 { + b = appendEmptyObject(ctx, b) + code = code.End.Next + break + } + b = appendStructHead(ctx, b) + iter := mapiterinit(code.Type, uptr) + ctx.KeepRefs = append(ctx.KeepRefs, iter) + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(mlen)) + store(ctxptr, code.MapIter, uintptr(iter)) + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendMapKeyIndent(ctx, code.Next, b) + } else { + mapCtx := encoder.NewMapContext(mlen) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) + store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) + } + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + case encoder.OpMapKey: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + if idx < length { + b = appendMapKeyIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + b = appendObjectEnd(ctx, code, b) + code = code.End.Next + } + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + if idx < length { + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + store(ctxptr, code.ElemIdx, idx) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + code = code.End + } + } + case encoder.OpMapValue: + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendColon(ctx, b) + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + } + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + value := mapitervalue(iter) + store(ctxptr, code.Next.Idx, uintptr(value)) + mapiternext(iter) + code = code.Next + case encoder.OpMapEnd: + // this operation only used by sorted map. + length := int(load(ctxptr, code.Length)) + ptr := load(ctxptr, code.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + pos := mapCtx.Pos + for i := 0; i < length; i++ { + startKey := pos[i*2] + startValue := pos[i*2+1] + var endValue int + if i+1 < length { + endValue = pos[i*2+2] + } else { + endValue = len(b) + } + mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ + Key: b[startKey:startValue], + Value: b[startValue:endValue], + }) + } + sort.Sort(mapCtx.Slice) + buf := mapCtx.Buf + for _, item := range mapCtx.Slice.Items { + buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) + } + buf = appendMapEnd(ctx, code, buf) + b = b[:pos[0]] + b = append(b, buf...) + mapCtx.Buf = buf + encoder.ReleaseMapContext(mapCtx) + code = code.Next + case encoder.OpRecursivePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpRecursive: + ptr := load(ctxptr, code.Idx) + if ptr != 0 { + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if ptr == seen { + return nil, errUnsupportedValue(code, ptr) + } + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, ptr) + c := code.Jmp.Code + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += code.Jmp.CurLen * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + store(ctxptr, c.Idx, ptr) + store(ctxptr, c.End.Next.Idx, oldOffset) + store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpRecursiveEnd: + recursiveLevel-- + + // restore ctxptr + restoreIndent(ctx, code, ctxptr) + offset := load(ctxptr, code.Idx) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpStructPtrHead: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHead: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if len(code.Key) > 0 { + if (code.Flags&encoder.IsTaggedKeyFlags) != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + } + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + } + case encoder.OpStructPtrHeadNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructPtrHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyArray: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyArray: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptySlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptySlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + if maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructField: + if code.Flags&encoder.IsTaggedKeyFlags != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + p := load(ctxptr, code.Idx) + uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmpty: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringString: + p := load(ctxptr, code.Idx) + s := ptrToString(p + uintptr(code.Offset)) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldMarshalJSON: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalJSONPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldMarshalText: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalTextPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldArrayPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArrayPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldSlice: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlice: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldSlicePtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldMap: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMap: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldMapPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldStruct: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyStruct: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructEnd: + b = appendStructEndSkipLast(ctx, code, b) + code = code.Next + case encoder.OpStructEndInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendStructEnd(ctx, code, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + s := ptrToString(p + uintptr(code.Offset)) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytesPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + code = code.Next + case encoder.OpStructEndOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpEnd: + goto END + } + } +END: + return b, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/debug_vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/debug_vm.go new file mode 100644 index 00000000..4cfd17ab --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/debug_vm.go @@ -0,0 +1,34 @@ +package vm_indent + +import ( + "fmt" + + "github.com/goccy/go-json/internal/encoder" +) + +func DebugRun(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + defer func() { + if err := recover(); err != nil { + fmt.Println("=============[DEBUG]===============") + fmt.Println("* [TYPE]") + fmt.Println(codeSet.Type) + fmt.Printf("\n") + fmt.Println("* [ALL OPCODE]") + fmt.Println(code.Dump()) + fmt.Printf("\n") + fmt.Println("* [CONTEXT]") + fmt.Printf("%+v\n", ctx) + fmt.Println("===================================") + panic(err) + } + }() + + return Run(ctx, b, codeSet) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/hack.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/hack.go new file mode 100644 index 00000000..9e245bfe --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/hack.go @@ -0,0 +1,9 @@ +package vm_indent + +import ( + // HACK: compile order + // `vm`, `vm_indent`, `vm_color`, `vm_color_indent` packages uses a lot of memory to compile, + // so forcibly make dependencies and avoid compiling in concurrent. + // dependency order: vm => vm_indent => vm_color => vm_color_indent + _ "github.com/goccy/go-json/internal/encoder/vm_color" +) diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/util.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/util.go new file mode 100644 index 00000000..fca8f185 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/util.go @@ -0,0 +1,229 @@ +package vm_indent + +import ( + "encoding/json" + "fmt" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +const uintptrSize = 4 << (^uintptr(0) >> 63) + +var ( + appendInt = encoder.AppendInt + appendUint = encoder.AppendUint + appendFloat32 = encoder.AppendFloat32 + appendFloat64 = encoder.AppendFloat64 + appendString = encoder.AppendString + appendByteSlice = encoder.AppendByteSlice + appendNumber = encoder.AppendNumber + appendStructEnd = encoder.AppendStructEndIndent + appendIndent = encoder.AppendIndent + errUnsupportedValue = encoder.ErrUnsupportedValue + errUnsupportedFloat = encoder.ErrUnsupportedFloat + mapiterinit = encoder.MapIterInit + mapiterkey = encoder.MapIterKey + mapitervalue = encoder.MapIterValue + mapiternext = encoder.MapIterNext + maplen = encoder.MapLen +) + +type emptyInterface struct { + typ *runtime.Type + ptr unsafe.Pointer +} + +type nonEmptyInterface struct { + itab *struct { + ityp *runtime.Type // static interface type + typ *runtime.Type // dynamic concrete type + // unused fields... + } + ptr unsafe.Pointer +} + +func errUnimplementedOp(op encoder.OpType) error { + return fmt.Errorf("encoder (indent): opcode %s has not been implemented", op) +} + +func load(base uintptr, idx uint32) uintptr { + addr := base + uintptr(idx) + return **(**uintptr)(unsafe.Pointer(&addr)) +} + +func store(base uintptr, idx uint32, p uintptr) { + addr := base + uintptr(idx) + **(**uintptr)(unsafe.Pointer(&addr)) = p +} + +func loadNPtr(base uintptr, idx uint32, ptrNum uint8) uintptr { + addr := base + uintptr(idx) + p := **(**uintptr)(unsafe.Pointer(&addr)) + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUint64(p uintptr, bitSize uint8) uint64 { + switch bitSize { + case 8: + return (uint64)(**(**uint8)(unsafe.Pointer(&p))) + case 16: + return (uint64)(**(**uint16)(unsafe.Pointer(&p))) + case 32: + return (uint64)(**(**uint32)(unsafe.Pointer(&p))) + case 64: + return **(**uint64)(unsafe.Pointer(&p)) + } + return 0 +} +func ptrToFloat32(p uintptr) float32 { return **(**float32)(unsafe.Pointer(&p)) } +func ptrToFloat64(p uintptr) float64 { return **(**float64)(unsafe.Pointer(&p)) } +func ptrToBool(p uintptr) bool { return **(**bool)(unsafe.Pointer(&p)) } +func ptrToBytes(p uintptr) []byte { return **(**[]byte)(unsafe.Pointer(&p)) } +func ptrToNumber(p uintptr) json.Number { return **(**json.Number)(unsafe.Pointer(&p)) } +func ptrToString(p uintptr) string { return **(**string)(unsafe.Pointer(&p)) } +func ptrToSlice(p uintptr) *runtime.SliceHeader { return *(**runtime.SliceHeader)(unsafe.Pointer(&p)) } +func ptrToPtr(p uintptr) uintptr { + return uintptr(**(**unsafe.Pointer)(unsafe.Pointer(&p))) +} +func ptrToNPtr(p uintptr, ptrNum uint8) uintptr { + for i := uint8(0); i < ptrNum; i++ { + if p == 0 { + return 0 + } + p = ptrToPtr(p) + } + return p +} + +func ptrToUnsafePtr(p uintptr) unsafe.Pointer { + return *(*unsafe.Pointer)(unsafe.Pointer(&p)) +} +func ptrToInterface(code *encoder.Opcode, p uintptr) interface{} { + return *(*interface{})(unsafe.Pointer(&emptyInterface{ + typ: code.Type, + ptr: *(*unsafe.Pointer)(unsafe.Pointer(&p)), + })) +} + +func appendBool(_ *encoder.RuntimeContext, b []byte, v bool) []byte { + if v { + return append(b, "true"...) + } + return append(b, "false"...) +} + +func appendNull(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, "null"...) +} + +func appendComma(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, ',', '\n') +} + +func appendNullComma(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, "null,\n"...) +} + +func appendColon(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, ':', ' ') +} + +func appendMapKeyValue(ctx *encoder.RuntimeContext, code *encoder.Opcode, b, key, value []byte) []byte { + b = appendIndent(ctx, b, code.Indent+1) + b = append(b, key...) + b[len(b)-2] = ':' + b[len(b)-1] = ' ' + return append(b, value...) +} + +func appendMapEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = b[:len(b)-2] + b = append(b, '\n') + b = appendIndent(ctx, b, code.Indent) + return append(b, '}', ',', '\n') +} + +func appendArrayHead(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = append(b, '[', '\n') + return appendIndent(ctx, b, code.Indent+1) +} + +func appendArrayEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = b[:len(b)-2] + b = append(b, '\n') + b = appendIndent(ctx, b, code.Indent) + return append(b, ']', ',', '\n') +} + +func appendEmptyArray(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '[', ']', ',', '\n') +} + +func appendEmptyObject(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{', '}', ',', '\n') +} + +func appendObjectEnd(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + b[last] = '\n' + b = appendIndent(ctx, b, code.Indent-1) + return append(b, '}', ',', '\n') +} + +func appendMarshalJSON(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + return encoder.AppendMarshalJSONIndent(ctx, code, b, v) +} + +func appendMarshalText(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte, v interface{}) ([]byte, error) { + return encoder.AppendMarshalTextIndent(ctx, code, b, v) +} + +func appendStructHead(_ *encoder.RuntimeContext, b []byte) []byte { + return append(b, '{', '\n') +} + +func appendStructKey(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + b = appendIndent(ctx, b, code.Indent) + b = append(b, code.Key...) + return append(b, ' ') +} + +func appendStructEndSkipLast(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + last := len(b) - 1 + if b[last-1] == '{' { + b[last] = '}' + } else { + if b[last] == '\n' { + // to remove ',' and '\n' characters + b = b[:len(b)-2] + } + b = append(b, '\n') + b = appendIndent(ctx, b, code.Indent-1) + b = append(b, '}') + } + return appendComma(ctx, b) +} + +func restoreIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, ctxptr uintptr) { + ctx.BaseIndent = uint32(load(ctxptr, code.Length)) +} + +func storeIndent(ctxptr uintptr, code *encoder.Opcode, indent uintptr) { + store(ctxptr, code.Length, indent) +} + +func appendArrayElemIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + return appendIndent(ctx, b, code.Indent+1) +} + +func appendMapKeyIndent(ctx *encoder.RuntimeContext, code *encoder.Opcode, b []byte) []byte { + return appendIndent(ctx, b, code.Indent) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/vm.go b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/vm.go new file mode 100644 index 00000000..fcc3b329 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/encoder/vm_indent/vm.go @@ -0,0 +1,4876 @@ +// Code generated by internal/cmd/generator. DO NOT EDIT! +package vm_indent + +import ( + "math" + "sort" + "unsafe" + + "github.com/goccy/go-json/internal/encoder" + "github.com/goccy/go-json/internal/runtime" +) + +func Run(ctx *encoder.RuntimeContext, b []byte, codeSet *encoder.OpcodeSet) ([]byte, error) { + recursiveLevel := 0 + ptrOffset := uintptr(0) + ctxptr := ctx.Ptr() + var code *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + code = codeSet.EscapeKeyCode + } else { + code = codeSet.NoescapeKeyCode + } + + for { + switch code.Op { + default: + return nil, errUnimplementedOp(code.Op) + case encoder.OpPtr: + p := load(ctxptr, code.Idx) + code = code.Next + store(ctxptr, code.Idx, ptrToPtr(p)) + case encoder.OpIntPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInt: + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpUint: + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpIntString: + b = append(b, '"') + b = appendInt(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpUintString: + b = append(b, '"') + b = appendUint(ctx, b, load(ctxptr, code.Idx), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat32Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat32: + b = appendFloat32(ctx, b, ptrToFloat32(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpFloat64Ptr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpFloat64: + v := ptrToFloat64(load(ctxptr, code.Idx)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStringPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpString: + b = appendString(ctx, b, ptrToString(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBoolPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBool: + b = appendBool(ctx, b, ptrToBool(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpBytesPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpBytes: + b = appendByteSlice(ctx, b, ptrToBytes(load(ctxptr, code.Idx))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpNumberPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpNumber: + bb, err := appendNumber(ctx, b, ptrToNumber(load(ctxptr, code.Idx))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpInterfacePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpInterface: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if p == seen { + return nil, errUnsupportedValue(code, p) + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, p) + var ( + typ *runtime.Type + ifacePtr unsafe.Pointer + ) + up := ptrToUnsafePtr(p) + if code.Flags&encoder.NonEmptyInterfaceFlags != 0 { + iface := (*nonEmptyInterface)(up) + ifacePtr = iface.ptr + if iface.itab != nil { + typ = iface.itab.typ + } + } else { + iface := (*emptyInterface)(up) + ifacePtr = iface.ptr + typ = iface.typ + } + if ifacePtr == nil { + b = appendNullComma(ctx, b) + code = code.Next + break + } + ctx.KeepRefs = append(ctx.KeepRefs, up) + ifaceCodeSet, err := encoder.CompileToGetCodeSet(uintptr(unsafe.Pointer(typ))) + if err != nil { + return nil, err + } + + totalLength := uintptr(code.Length) + 3 + nextTotalLength := uintptr(ifaceCodeSet.CodeLength) + 3 + + var c *encoder.Opcode + if (ctx.Option.Flag & encoder.HTMLEscapeOption) != 0 { + c = ifaceCodeSet.InterfaceEscapeKeyCode + } else { + c = ifaceCodeSet.InterfaceNoescapeKeyCode + } + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += totalLength * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + totalLength + nextTotalLength + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + end := ifaceCodeSet.EndCode + store(ctxptr, c.Idx, uintptr(ifacePtr)) + store(ctxptr, end.Idx, oldOffset) + store(ctxptr, end.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, end, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpInterfaceEnd: + recursiveLevel-- + + // restore ctxptr + offset := load(ctxptr, code.Idx) + restoreIndent(ctx, code, ctxptr) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToPtr(p)) + fallthrough + case encoder.OpMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + b = append(b, `""`...) + b = appendComma(ctx, b) + code = code.Next + break + } + if (code.Flags&encoder.IsNilableTypeFlags) != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p) + } + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpSlicePtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpSlice: + p := load(ctxptr, code.Idx) + slice := ptrToSlice(p) + if p == 0 || slice.Data == nil { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(slice.Len)) + store(ctxptr, code.Idx, uintptr(slice.Data)) + if slice.Len > 0 { + b = appendArrayHead(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, uintptr(slice.Data)) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpSliceElem: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if idx < length { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + data := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, data+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpArrayPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpArray: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + if code.Length > 0 { + b = appendArrayHead(ctx, code, b) + store(ctxptr, code.ElemIdx, 0) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + b = appendEmptyArray(ctx, b) + code = code.End.Next + } + case encoder.OpArrayElem: + idx := load(ctxptr, code.ElemIdx) + idx++ + if idx < uintptr(code.Length) { + b = appendArrayElemIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + p := load(ctxptr, code.Idx) + size := uintptr(code.Size) + code = code.Next + store(ctxptr, code.Idx, p+idx*size) + } else { + b = appendArrayEnd(ctx, code, b) + code = code.End.Next + } + case encoder.OpMapPtr: + p := loadNPtr(ctxptr, code.Idx, code.PtrNum) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + store(ctxptr, code.Idx, p) + fallthrough + case encoder.OpMap: + p := load(ctxptr, code.Idx) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.End.Next + break + } + uptr := ptrToUnsafePtr(p) + mlen := maplen(uptr) + if mlen <= 0 { + b = appendEmptyObject(ctx, b) + code = code.End.Next + break + } + b = appendStructHead(ctx, b) + iter := mapiterinit(code.Type, uptr) + ctx.KeepRefs = append(ctx.KeepRefs, iter) + store(ctxptr, code.ElemIdx, 0) + store(ctxptr, code.Length, uintptr(mlen)) + store(ctxptr, code.MapIter, uintptr(iter)) + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendMapKeyIndent(ctx, code.Next, b) + } else { + mapCtx := encoder.NewMapContext(mlen) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + ctx.KeepRefs = append(ctx.KeepRefs, unsafe.Pointer(mapCtx)) + store(ctxptr, code.End.MapPos, uintptr(unsafe.Pointer(mapCtx))) + } + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + case encoder.OpMapKey: + idx := load(ctxptr, code.ElemIdx) + length := load(ctxptr, code.Length) + idx++ + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + if idx < length { + b = appendMapKeyIndent(ctx, code, b) + store(ctxptr, code.ElemIdx, idx) + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + b = appendObjectEnd(ctx, code, b) + code = code.End.Next + } + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + if idx < length { + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + store(ctxptr, code.ElemIdx, idx) + key := mapiterkey(iter) + store(ctxptr, code.Next.Idx, uintptr(key)) + code = code.Next + } else { + code = code.End + } + } + case encoder.OpMapValue: + if (ctx.Option.Flag & encoder.UnorderedMapOption) != 0 { + b = appendColon(ctx, b) + } else { + ptr := load(ctxptr, code.End.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + mapCtx.Pos = append(mapCtx.Pos, len(b)) + } + ptr := load(ctxptr, code.MapIter) + iter := ptrToUnsafePtr(ptr) + value := mapitervalue(iter) + store(ctxptr, code.Next.Idx, uintptr(value)) + mapiternext(iter) + code = code.Next + case encoder.OpMapEnd: + // this operation only used by sorted map. + length := int(load(ctxptr, code.Length)) + ptr := load(ctxptr, code.MapPos) + mapCtx := (*encoder.MapContext)(ptrToUnsafePtr(ptr)) + pos := mapCtx.Pos + for i := 0; i < length; i++ { + startKey := pos[i*2] + startValue := pos[i*2+1] + var endValue int + if i+1 < length { + endValue = pos[i*2+2] + } else { + endValue = len(b) + } + mapCtx.Slice.Items = append(mapCtx.Slice.Items, encoder.MapItem{ + Key: b[startKey:startValue], + Value: b[startValue:endValue], + }) + } + sort.Sort(mapCtx.Slice) + buf := mapCtx.Buf + for _, item := range mapCtx.Slice.Items { + buf = appendMapKeyValue(ctx, code, buf, item.Key, item.Value) + } + buf = appendMapEnd(ctx, code, buf) + b = b[:pos[0]] + b = append(b, buf...) + mapCtx.Buf = buf + encoder.ReleaseMapContext(mapCtx) + code = code.Next + case encoder.OpRecursivePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + code = code.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpRecursive: + ptr := load(ctxptr, code.Idx) + if ptr != 0 { + if recursiveLevel > encoder.StartDetectingCyclesAfter { + for _, seen := range ctx.SeenPtr { + if ptr == seen { + return nil, errUnsupportedValue(code, ptr) + } + } + } + } + ctx.SeenPtr = append(ctx.SeenPtr, ptr) + c := code.Jmp.Code + curlen := uintptr(len(ctx.Ptrs)) + offsetNum := ptrOffset / uintptrSize + oldOffset := ptrOffset + ptrOffset += code.Jmp.CurLen * uintptrSize + oldBaseIndent := ctx.BaseIndent + indentDiffFromTop := c.Indent - 1 + ctx.BaseIndent += code.Indent - indentDiffFromTop + + newLen := offsetNum + code.Jmp.CurLen + code.Jmp.NextLen + if curlen < newLen { + ctx.Ptrs = append(ctx.Ptrs, make([]uintptr, newLen-curlen)...) + } + ctxptr = ctx.Ptr() + ptrOffset // assign new ctxptr + + store(ctxptr, c.Idx, ptr) + store(ctxptr, c.End.Next.Idx, oldOffset) + store(ctxptr, c.End.Next.ElemIdx, uintptr(unsafe.Pointer(code.Next))) + storeIndent(ctxptr, c.End.Next, uintptr(oldBaseIndent)) + code = c + recursiveLevel++ + case encoder.OpRecursiveEnd: + recursiveLevel-- + + // restore ctxptr + restoreIndent(ctx, code, ctxptr) + offset := load(ctxptr, code.Idx) + ctx.SeenPtr = ctx.SeenPtr[:len(ctx.SeenPtr)-1] + + codePtr := load(ctxptr, code.ElemIdx) + code = (*encoder.Opcode)(ptrToUnsafePtr(codePtr)) + ctxptr = ctx.Ptr() + offset + ptrOffset = offset + case encoder.OpStructPtrHead: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHead: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if len(code.Key) > 0 { + if (code.Flags&encoder.IsTaggedKeyFlags) != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + } + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmpty: + p := load(ctxptr, code.Idx) + if p == 0 && ((code.Flags&encoder.IndirectFlags) != 0 || code.Next.Op == encoder.OpStructEnd) { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + if p == 0 || (ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyInt: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyInt: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyIntString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUint: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUint: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyUintString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat32(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64String: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToFloat64(p + uintptr(code.Offset)) + if v == 0 { + code = code.NextField + } else { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNull(ctx, b) + b = appendComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p+uintptr(code.Offset))))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyStringString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToString(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBool: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBool: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + } else { + code = code.NextField + } + case encoder.OpStructPtrHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytes: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyBytes: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumber: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumber: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + } + case encoder.OpStructPtrHeadNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberString: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + v := ptrToNumber(p + uintptr(code.Offset)) + if v == "" { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructPtrHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructPtrHeadArray, encoder.OpStructPtrHeadSlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadArray, encoder.OpStructHeadSlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyArray: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyArray: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptySlice: + if (code.Flags & encoder.IndirectFlags) != 0 { + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptySlice: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadArrayPtr, encoder.OpStructPtrHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadArrayPtr, encoder.OpStructHeadSlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyArrayPtr, encoder.OpStructPtrHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyArrayPtr, encoder.OpStructHeadOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructPtrHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMap: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p != 0 && (code.Flags&encoder.IndirectFlags) != 0 { + p = ptrToPtr(p + uintptr(code.Offset)) + } + if maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + break + } + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 { + code = code.NextField + } else { + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructPtrHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalJSON { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + } + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + if (code.Flags&encoder.IndirectFlags) != 0 || code.Op == encoder.OpStructPtrHeadOmitEmptyMarshalText { + p = ptrToPtr(p + uintptr(code.Offset)) + } + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructPtrHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + b = appendStructKey(ctx, code, b) + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructPtrHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + store(ctxptr, code.Idx, ptrToNPtr(p, code.PtrNum)) + fallthrough + case encoder.OpStructHeadOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + if p == 0 && (code.Flags&encoder.IndirectFlags) != 0 { + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendNullComma(ctx, b) + } + code = code.End.Next + break + } + if (code.Flags & encoder.IndirectFlags) != 0 { + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + } + if code.Flags&encoder.AnonymousHeadFlags == 0 { + b = appendStructHead(ctx, b) + } + if p == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + b = appendComma(ctx, b) + code = code.Next + } + case encoder.OpStructField: + if code.Flags&encoder.IsTaggedKeyFlags != 0 || code.Flags&encoder.AnonymousKeyFlags == 0 { + b = appendStructKey(ctx, code, b) + } + p := load(ctxptr, code.Idx) + uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmpty: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNullComma(ctx, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringString: + p := load(ctxptr, code.Idx) + s := ptrToString(p + uintptr(code.Offset)) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + b = appendStructKey(ctx, code, b) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendComma(ctx, b) + } + code = code.Next + case encoder.OpStructFieldMarshalJSON: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSON: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + iface := ptrToInterface(code, p) + if (code.Flags&encoder.NilCheckFlags) != 0 && encoder.IsNilForMarshaler(iface) { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, iface) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalJSONPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalJSONPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalJSON(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldMarshalText: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalText: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if (code.Flags & encoder.IsNilableTypeFlags) != 0 { + p = ptrToPtr(p) + } + if p == 0 && (code.Flags&encoder.NilCheckFlags) != 0 { + code = code.NextField + break + } + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + code = code.Next + case encoder.OpStructFieldMarshalTextPtr: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendComma(ctx, b) + code = code.Next + case encoder.OpStructFieldOmitEmptyMarshalTextPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendMarshalText(ctx, code, b, ptrToInterface(code, p)) + if err != nil { + return nil, err + } + b = appendComma(ctx, bb) + } + code = code.Next + case encoder.OpStructFieldArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArray: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldArrayPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyArrayPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldSlice: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlice: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + slice := ptrToSlice(p) + if slice.Len == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldSlicePtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptySlicePtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldMap: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMap: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p == 0 || maplen(ptrToUnsafePtr(p)) == 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructFieldMapPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyMapPtr: + p := load(ctxptr, code.Idx) + p = ptrToPtr(p + uintptr(code.Offset)) + if p != 0 { + p = ptrToNPtr(p, code.PtrNum) + } + if p != 0 { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } else { + code = code.NextField + } + case encoder.OpStructFieldStruct: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + code = code.Next + store(ctxptr, code.Idx, p) + case encoder.OpStructFieldOmitEmptyStruct: + p := load(ctxptr, code.Idx) + p += uintptr(code.Offset) + if ptrToPtr(p) == 0 && (code.Flags&encoder.IsNextOpPtrTypeFlags) != 0 { + code = code.NextField + } else { + b = appendStructKey(ctx, code, b) + code = code.Next + store(ctxptr, code.Idx, p) + } + case encoder.OpStructEnd: + b = appendStructEndSkipLast(ctx, code, b) + code = code.Next + case encoder.OpStructEndInt: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyInt: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendInt(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendInt(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndIntPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyIntPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendInt(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUint: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUint: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintString: + p := load(ctxptr, code.Idx) + u64 := ptrToUint64(p+uintptr(code.Offset), code.NumBitSize) + v := u64 & ((1 << code.NumBitSize) - 1) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p+uintptr(code.Offset), code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendUint(ctx, b, p, code) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendUint(ctx, b, p, code) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndUintPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyUintPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendUint(ctx, b, p, code) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32String: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32String: + p := load(ctxptr, code.Idx) + v := ptrToFloat32(p + uintptr(code.Offset)) + if v != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendFloat32(ctx, b, ptrToFloat32(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat32PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat32PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat32(ctx, b, ptrToFloat32(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64String: + p := load(ctxptr, code.Idx) + v := ptrToFloat64(p + uintptr(code.Offset)) + if v != 0 { + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64Ptr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + b = appendStructEnd(ctx, code, b) + code = code.Next + break + } + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64Ptr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndFloat64PtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = appendFloat64(ctx, b, v) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyFloat64PtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + v := ptrToFloat64(p) + if math.IsInf(v, 0) || math.IsNaN(v) { + return nil, errUnsupportedFloat(v) + } + b = append(b, '"') + b = appendFloat64(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + s := ptrToString(p + uintptr(code.Offset)) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, s))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringString: + p := load(ctxptr, code.Idx) + v := ptrToString(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, v))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, ptrToString(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, ptrToString(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndStringPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyStringPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendString(ctx, b, string(appendString(ctx, []byte{}, ptrToString(p)))) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBool: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBool: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p+uintptr(code.Offset))) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolString: + p := load(ctxptr, code.Idx) + v := ptrToBool(p + uintptr(code.Offset)) + if v { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, v) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendBool(ctx, b, ptrToBool(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendBool(ctx, b, ptrToBool(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBoolPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBoolPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + b = appendBool(ctx, b, ptrToBool(p)) + b = append(b, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytes: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p+uintptr(code.Offset))) + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytes: + p := load(ctxptr, code.Idx) + v := ptrToBytes(p + uintptr(code.Offset)) + if len(v) > 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, v) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndBytesPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = appendByteSlice(ctx, b, ptrToBytes(p)) + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyBytesPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = appendByteSlice(ctx, b, ptrToBytes(p)) + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumber: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + code = code.Next + case encoder.OpStructEndOmitEmptyNumber: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberString: + p := load(ctxptr, code.Idx) + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p+uintptr(code.Offset))) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberString: + p := load(ctxptr, code.Idx) + v := ptrToNumber(p + uintptr(code.Offset)) + if v != "" { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, v) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtr: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = bb + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtr: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = appendStructEnd(ctx, code, bb) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpStructEndNumberPtrString: + b = appendStructKey(ctx, code, b) + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p == 0 { + b = appendNull(ctx, b) + } else { + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + } + b = appendStructEnd(ctx, code, b) + code = code.Next + case encoder.OpStructEndOmitEmptyNumberPtrString: + p := load(ctxptr, code.Idx) + p = ptrToNPtr(p+uintptr(code.Offset), code.PtrNum) + if p != 0 { + b = appendStructKey(ctx, code, b) + b = append(b, '"') + bb, err := appendNumber(ctx, b, ptrToNumber(p)) + if err != nil { + return nil, err + } + b = append(bb, '"') + b = appendStructEnd(ctx, code, b) + } else { + b = appendStructEndSkipLast(ctx, code, b) + } + code = code.Next + case encoder.OpEnd: + goto END + } + } +END: + return b, nil +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/errors/error.go b/taskman-server/vendor/github.com/goccy/go-json/internal/errors/error.go new file mode 100644 index 00000000..d58e39f4 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/errors/error.go @@ -0,0 +1,164 @@ +package errors + +import ( + "fmt" + "reflect" + "strconv" +) + +type InvalidUTF8Error struct { + S string // the whole string value that caused the error +} + +func (e *InvalidUTF8Error) Error() string { + return fmt.Sprintf("json: invalid UTF-8 in string: %s", strconv.Quote(e.S)) +} + +type InvalidUnmarshalError struct { + Type reflect.Type +} + +func (e *InvalidUnmarshalError) Error() string { + if e.Type == nil { + return "json: Unmarshal(nil)" + } + + if e.Type.Kind() != reflect.Ptr { + return fmt.Sprintf("json: Unmarshal(non-pointer %s)", e.Type) + } + return fmt.Sprintf("json: Unmarshal(nil %s)", e.Type) +} + +// A MarshalerError represents an error from calling a MarshalJSON or MarshalText method. +type MarshalerError struct { + Type reflect.Type + Err error + sourceFunc string +} + +func (e *MarshalerError) Error() string { + srcFunc := e.sourceFunc + if srcFunc == "" { + srcFunc = "MarshalJSON" + } + return fmt.Sprintf("json: error calling %s for type %s: %s", srcFunc, e.Type, e.Err.Error()) +} + +// Unwrap returns the underlying error. +func (e *MarshalerError) Unwrap() error { return e.Err } + +// A SyntaxError is a description of a JSON syntax error. +type SyntaxError struct { + msg string // description of error + Offset int64 // error occurred after reading Offset bytes +} + +func (e *SyntaxError) Error() string { return e.msg } + +// An UnmarshalFieldError describes a JSON object key that +// led to an unexported (and therefore unwritable) struct field. +// +// Deprecated: No longer used; kept for compatibility. +type UnmarshalFieldError struct { + Key string + Type reflect.Type + Field reflect.StructField +} + +func (e *UnmarshalFieldError) Error() string { + return fmt.Sprintf("json: cannot unmarshal object key %s into unexported field %s of type %s", + strconv.Quote(e.Key), e.Field.Name, e.Type.String(), + ) +} + +// An UnmarshalTypeError describes a JSON value that was +// not appropriate for a value of a specific Go type. +type UnmarshalTypeError struct { + Value string // description of JSON value - "bool", "array", "number -5" + Type reflect.Type // type of Go value it could not be assigned to + Offset int64 // error occurred after reading Offset bytes + Struct string // name of the struct type containing the field + Field string // the full path from root node to the field +} + +func (e *UnmarshalTypeError) Error() string { + if e.Struct != "" || e.Field != "" { + return fmt.Sprintf("json: cannot unmarshal %s into Go struct field %s.%s of type %s", + e.Value, e.Struct, e.Field, e.Type, + ) + } + return fmt.Sprintf("json: cannot unmarshal %s into Go value of type %s", e.Value, e.Type) +} + +// An UnsupportedTypeError is returned by Marshal when attempting +// to encode an unsupported value type. +type UnsupportedTypeError struct { + Type reflect.Type +} + +func (e *UnsupportedTypeError) Error() string { + return fmt.Sprintf("json: unsupported type: %s", e.Type) +} + +type UnsupportedValueError struct { + Value reflect.Value + Str string +} + +func (e *UnsupportedValueError) Error() string { + return fmt.Sprintf("json: unsupported value: %s", e.Str) +} + +func ErrSyntax(msg string, offset int64) *SyntaxError { + return &SyntaxError{msg: msg, Offset: offset} +} + +func ErrMarshaler(typ reflect.Type, err error, msg string) *MarshalerError { + return &MarshalerError{ + Type: typ, + Err: err, + sourceFunc: msg, + } +} + +func ErrExceededMaxDepth(c byte, cursor int64) *SyntaxError { + return &SyntaxError{ + msg: fmt.Sprintf(`invalid character "%c" exceeded max depth`, c), + Offset: cursor, + } +} + +func ErrNotAtBeginningOfValue(cursor int64) *SyntaxError { + return &SyntaxError{msg: "not at beginning of value", Offset: cursor} +} + +func ErrUnexpectedEndOfJSON(msg string, cursor int64) *SyntaxError { + return &SyntaxError{ + msg: fmt.Sprintf("json: %s unexpected end of JSON input", msg), + Offset: cursor, + } +} + +func ErrExpected(msg string, cursor int64) *SyntaxError { + return &SyntaxError{msg: fmt.Sprintf("expected %s", msg), Offset: cursor} +} + +func ErrInvalidCharacter(c byte, context string, cursor int64) *SyntaxError { + if c == 0 { + return &SyntaxError{ + msg: fmt.Sprintf("json: invalid character as %s", context), + Offset: cursor, + } + } + return &SyntaxError{ + msg: fmt.Sprintf("json: invalid character %c as %s", c, context), + Offset: cursor, + } +} + +func ErrInvalidBeginningOfValue(c byte, cursor int64) *SyntaxError { + return &SyntaxError{ + msg: fmt.Sprintf("invalid character '%c' looking for beginning of value", c), + Offset: cursor, + } +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/rtype.go b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/rtype.go new file mode 100644 index 00000000..4db10deb --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/rtype.go @@ -0,0 +1,263 @@ +package runtime + +import ( + "reflect" + "unsafe" +) + +// Type representing reflect.rtype for noescape trick +type Type struct{} + +//go:linkname rtype_Align reflect.(*rtype).Align +//go:noescape +func rtype_Align(*Type) int + +func (t *Type) Align() int { + return rtype_Align(t) +} + +//go:linkname rtype_FieldAlign reflect.(*rtype).FieldAlign +//go:noescape +func rtype_FieldAlign(*Type) int + +func (t *Type) FieldAlign() int { + return rtype_FieldAlign(t) +} + +//go:linkname rtype_Method reflect.(*rtype).Method +//go:noescape +func rtype_Method(*Type, int) reflect.Method + +func (t *Type) Method(a0 int) reflect.Method { + return rtype_Method(t, a0) +} + +//go:linkname rtype_MethodByName reflect.(*rtype).MethodByName +//go:noescape +func rtype_MethodByName(*Type, string) (reflect.Method, bool) + +func (t *Type) MethodByName(a0 string) (reflect.Method, bool) { + return rtype_MethodByName(t, a0) +} + +//go:linkname rtype_NumMethod reflect.(*rtype).NumMethod +//go:noescape +func rtype_NumMethod(*Type) int + +func (t *Type) NumMethod() int { + return rtype_NumMethod(t) +} + +//go:linkname rtype_Name reflect.(*rtype).Name +//go:noescape +func rtype_Name(*Type) string + +func (t *Type) Name() string { + return rtype_Name(t) +} + +//go:linkname rtype_PkgPath reflect.(*rtype).PkgPath +//go:noescape +func rtype_PkgPath(*Type) string + +func (t *Type) PkgPath() string { + return rtype_PkgPath(t) +} + +//go:linkname rtype_Size reflect.(*rtype).Size +//go:noescape +func rtype_Size(*Type) uintptr + +func (t *Type) Size() uintptr { + return rtype_Size(t) +} + +//go:linkname rtype_String reflect.(*rtype).String +//go:noescape +func rtype_String(*Type) string + +func (t *Type) String() string { + return rtype_String(t) +} + +//go:linkname rtype_Kind reflect.(*rtype).Kind +//go:noescape +func rtype_Kind(*Type) reflect.Kind + +func (t *Type) Kind() reflect.Kind { + return rtype_Kind(t) +} + +//go:linkname rtype_Implements reflect.(*rtype).Implements +//go:noescape +func rtype_Implements(*Type, reflect.Type) bool + +func (t *Type) Implements(u reflect.Type) bool { + return rtype_Implements(t, u) +} + +//go:linkname rtype_AssignableTo reflect.(*rtype).AssignableTo +//go:noescape +func rtype_AssignableTo(*Type, reflect.Type) bool + +func (t *Type) AssignableTo(u reflect.Type) bool { + return rtype_AssignableTo(t, u) +} + +//go:linkname rtype_ConvertibleTo reflect.(*rtype).ConvertibleTo +//go:noescape +func rtype_ConvertibleTo(*Type, reflect.Type) bool + +func (t *Type) ConvertibleTo(u reflect.Type) bool { + return rtype_ConvertibleTo(t, u) +} + +//go:linkname rtype_Comparable reflect.(*rtype).Comparable +//go:noescape +func rtype_Comparable(*Type) bool + +func (t *Type) Comparable() bool { + return rtype_Comparable(t) +} + +//go:linkname rtype_Bits reflect.(*rtype).Bits +//go:noescape +func rtype_Bits(*Type) int + +func (t *Type) Bits() int { + return rtype_Bits(t) +} + +//go:linkname rtype_ChanDir reflect.(*rtype).ChanDir +//go:noescape +func rtype_ChanDir(*Type) reflect.ChanDir + +func (t *Type) ChanDir() reflect.ChanDir { + return rtype_ChanDir(t) +} + +//go:linkname rtype_IsVariadic reflect.(*rtype).IsVariadic +//go:noescape +func rtype_IsVariadic(*Type) bool + +func (t *Type) IsVariadic() bool { + return rtype_IsVariadic(t) +} + +//go:linkname rtype_Elem reflect.(*rtype).Elem +//go:noescape +func rtype_Elem(*Type) reflect.Type + +func (t *Type) Elem() *Type { + return Type2RType(rtype_Elem(t)) +} + +//go:linkname rtype_Field reflect.(*rtype).Field +//go:noescape +func rtype_Field(*Type, int) reflect.StructField + +func (t *Type) Field(i int) reflect.StructField { + return rtype_Field(t, i) +} + +//go:linkname rtype_FieldByIndex reflect.(*rtype).FieldByIndex +//go:noescape +func rtype_FieldByIndex(*Type, []int) reflect.StructField + +func (t *Type) FieldByIndex(index []int) reflect.StructField { + return rtype_FieldByIndex(t, index) +} + +//go:linkname rtype_FieldByName reflect.(*rtype).FieldByName +//go:noescape +func rtype_FieldByName(*Type, string) (reflect.StructField, bool) + +func (t *Type) FieldByName(name string) (reflect.StructField, bool) { + return rtype_FieldByName(t, name) +} + +//go:linkname rtype_FieldByNameFunc reflect.(*rtype).FieldByNameFunc +//go:noescape +func rtype_FieldByNameFunc(*Type, func(string) bool) (reflect.StructField, bool) + +func (t *Type) FieldByNameFunc(match func(string) bool) (reflect.StructField, bool) { + return rtype_FieldByNameFunc(t, match) +} + +//go:linkname rtype_In reflect.(*rtype).In +//go:noescape +func rtype_In(*Type, int) reflect.Type + +func (t *Type) In(i int) reflect.Type { + return rtype_In(t, i) +} + +//go:linkname rtype_Key reflect.(*rtype).Key +//go:noescape +func rtype_Key(*Type) reflect.Type + +func (t *Type) Key() *Type { + return Type2RType(rtype_Key(t)) +} + +//go:linkname rtype_Len reflect.(*rtype).Len +//go:noescape +func rtype_Len(*Type) int + +func (t *Type) Len() int { + return rtype_Len(t) +} + +//go:linkname rtype_NumField reflect.(*rtype).NumField +//go:noescape +func rtype_NumField(*Type) int + +func (t *Type) NumField() int { + return rtype_NumField(t) +} + +//go:linkname rtype_NumIn reflect.(*rtype).NumIn +//go:noescape +func rtype_NumIn(*Type) int + +func (t *Type) NumIn() int { + return rtype_NumIn(t) +} + +//go:linkname rtype_NumOut reflect.(*rtype).NumOut +//go:noescape +func rtype_NumOut(*Type) int + +func (t *Type) NumOut() int { + return rtype_NumOut(t) +} + +//go:linkname rtype_Out reflect.(*rtype).Out +//go:noescape +func rtype_Out(*Type, int) reflect.Type + +//go:linkname PtrTo reflect.(*rtype).ptrTo +//go:noescape +func PtrTo(*Type) *Type + +func (t *Type) Out(i int) reflect.Type { + return rtype_Out(t, i) +} + +//go:linkname IfaceIndir reflect.ifaceIndir +//go:noescape +func IfaceIndir(*Type) bool + +//go:linkname RType2Type reflect.toType +//go:noescape +func RType2Type(t *Type) reflect.Type + +//go:nolint structcheck +type emptyInterface struct { + _ *Type + ptr unsafe.Pointer +} + +func Type2RType(t reflect.Type) *Type { + return (*Type)(((*emptyInterface)(unsafe.Pointer(&t))).ptr) +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/struct_field.go b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/struct_field.go new file mode 100644 index 00000000..c321180a --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/struct_field.go @@ -0,0 +1,87 @@ +package runtime + +import ( + "reflect" + "strings" + "unicode" +) + +func getTag(field reflect.StructField) string { + return field.Tag.Get("json") +} + +func IsIgnoredStructField(field reflect.StructField) bool { + if field.PkgPath != "" { + if field.Anonymous { + if !(field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct) && field.Type.Kind() != reflect.Struct { + return true + } + } else { + // private field + return true + } + } + tag := getTag(field) + return tag == "-" +} + +type StructTag struct { + Key string + IsTaggedKey bool + IsOmitEmpty bool + IsString bool + Field reflect.StructField +} + +type StructTags []*StructTag + +func (t StructTags) ExistsKey(key string) bool { + for _, tt := range t { + if tt.Key == key { + return true + } + } + return false +} + +func isValidTag(s string) bool { + if s == "" { + return false + } + for _, c := range s { + switch { + case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): + // Backslash and quote chars are reserved, but + // otherwise any punctuation chars are allowed + // in a tag name. + case !unicode.IsLetter(c) && !unicode.IsDigit(c): + return false + } + } + return true +} + +func StructTagFromField(field reflect.StructField) *StructTag { + keyName := field.Name + tag := getTag(field) + st := &StructTag{Field: field} + opts := strings.Split(tag, ",") + if len(opts) > 0 { + if opts[0] != "" && isValidTag(opts[0]) { + keyName = opts[0] + st.IsTaggedKey = true + } + } + st.Key = keyName + if len(opts) > 1 { + for _, opt := range opts[1:] { + switch opt { + case "omitempty": + st.IsOmitEmpty = true + case "string": + st.IsString = true + } + } + } + return st +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/type.go b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/type.go new file mode 100644 index 00000000..0167cd2c --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/internal/runtime/type.go @@ -0,0 +1,100 @@ +package runtime + +import ( + "reflect" + "unsafe" +) + +type SliceHeader struct { + Data unsafe.Pointer + Len int + Cap int +} + +const ( + maxAcceptableTypeAddrRange = 1024 * 1024 * 2 // 2 Mib +) + +type TypeAddr struct { + BaseTypeAddr uintptr + MaxTypeAddr uintptr + AddrRange uintptr + AddrShift uintptr +} + +var ( + typeAddr *TypeAddr + alreadyAnalyzed bool +) + +//go:linkname typelinks reflect.typelinks +func typelinks() ([]unsafe.Pointer, [][]int32) + +//go:linkname rtypeOff reflect.rtypeOff +func rtypeOff(unsafe.Pointer, int32) unsafe.Pointer + +func AnalyzeTypeAddr() *TypeAddr { + defer func() { + alreadyAnalyzed = true + }() + if alreadyAnalyzed { + return typeAddr + } + sections, offsets := typelinks() + if len(sections) != 1 { + return nil + } + if len(offsets) != 1 { + return nil + } + section := sections[0] + offset := offsets[0] + var ( + min uintptr = uintptr(^uint(0)) + max uintptr = 0 + isAligned64 = true + isAligned32 = true + ) + for i := 0; i < len(offset); i++ { + typ := (*Type)(rtypeOff(section, offset[i])) + addr := uintptr(unsafe.Pointer(typ)) + if min > addr { + min = addr + } + if max < addr { + max = addr + } + if typ.Kind() == reflect.Ptr { + addr = uintptr(unsafe.Pointer(typ.Elem())) + if min > addr { + min = addr + } + if max < addr { + max = addr + } + } + isAligned64 = isAligned64 && (addr-min)&63 == 0 + isAligned32 = isAligned32 && (addr-min)&31 == 0 + } + addrRange := max - min + if addrRange == 0 { + return nil + } + var addrShift uintptr + if isAligned64 { + addrShift = 6 + } else if isAligned32 { + addrShift = 5 + } + cacheSize := addrRange >> addrShift + if cacheSize > maxAcceptableTypeAddrRange { + return nil + } + typeAddr = &TypeAddr{ + BaseTypeAddr: min, + MaxTypeAddr: max, + AddrRange: addrRange, + AddrShift: addrShift, + } + return typeAddr +} diff --git a/taskman-server/vendor/github.com/goccy/go-json/json.go b/taskman-server/vendor/github.com/goccy/go-json/json.go new file mode 100644 index 00000000..5c9448d8 --- /dev/null +++ b/taskman-server/vendor/github.com/goccy/go-json/json.go @@ -0,0 +1,366 @@ +package json + +import ( + "bytes" + "context" + "encoding/json" + + "github.com/goccy/go-json/internal/encoder" +) + +// Marshaler is the interface implemented by types that +// can marshal themselves into valid JSON. +type Marshaler interface { + MarshalJSON() ([]byte, error) +} + +// MarshalerContext is the interface implemented by types that +// can marshal themselves into valid JSON with context.Context. +type MarshalerContext interface { + MarshalJSON(context.Context) ([]byte, error) +} + +// Unmarshaler is the interface implemented by types +// that can unmarshal a JSON description of themselves. +// The input can be assumed to be a valid encoding of +// a JSON value. UnmarshalJSON must copy the JSON data +// if it wishes to retain the data after returning. +// +// By convention, to approximate the behavior of Unmarshal itself, +// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. +type Unmarshaler interface { + UnmarshalJSON([]byte) error +} + +// UnmarshalerContext is the interface implemented by types +// that can unmarshal with context.Context a JSON description of themselves. +type UnmarshalerContext interface { + UnmarshalJSON(context.Context, []byte) error +} + +// Marshal returns the JSON encoding of v. +// +// Marshal traverses the value v recursively. +// If an encountered value implements the Marshaler interface +// and is not a nil pointer, Marshal calls its MarshalJSON method +// to produce JSON. If no MarshalJSON method is present but the +// value implements encoding.TextMarshaler instead, Marshal calls +// its MarshalText method and encodes the result as a JSON string. +// The nil pointer exception is not strictly necessary +// but mimics a similar, necessary exception in the behavior of +// UnmarshalJSON. +// +// Otherwise, Marshal uses the following type-dependent default encodings: +// +// Boolean values encode as JSON booleans. +// +// Floating point, integer, and Number values encode as JSON numbers. +// +// String values encode as JSON strings coerced to valid UTF-8, +// replacing invalid bytes with the Unicode replacement rune. +// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" +// to keep some browsers from misinterpreting JSON output as HTML. +// Ampersand "&" is also escaped to "\u0026" for the same reason. +// This escaping can be disabled using an Encoder that had SetEscapeHTML(false) +// called on it. +// +// Array and slice values encode as JSON arrays, except that +// []byte encodes as a base64-encoded string, and a nil slice +// encodes as the null JSON value. +// +// Struct values encode as JSON objects. +// Each exported struct field becomes a member of the object, using the +// field name as the object key, unless the field is omitted for one of the +// reasons given below. +// +// The encoding of each struct field can be customized by the format string +// stored under the "json" key in the struct field's tag. +// The format string gives the name of the field, possibly followed by a +// comma-separated list of options. The name may be empty in order to +// specify options without overriding the default field name. +// +// The "omitempty" option specifies that the field should be omitted +// from the encoding if the field has an empty value, defined as +// false, 0, a nil pointer, a nil interface value, and any empty array, +// slice, map, or string. +// +// As a special case, if the field tag is "-", the field is always omitted. +// Note that a field with name "-" can still be generated using the tag "-,". +// +// Examples of struct field tags and their meanings: +// +// // Field appears in JSON as key "myName". +// Field int `json:"myName"` +// +// // Field appears in JSON as key "myName" and +// // the field is omitted from the object if its value is empty, +// // as defined above. +// Field int `json:"myName,omitempty"` +// +// // Field appears in JSON as key "Field" (the default), but +// // the field is skipped if empty. +// // Note the leading comma. +// Field int `json:",omitempty"` +// +// // Field is ignored by this package. +// Field int `json:"-"` +// +// // Field appears in JSON as key "-". +// Field int `json:"-,"` +// +// The "string" option signals that a field is stored as JSON inside a +// JSON-encoded string. It applies only to fields of string, floating point, +// integer, or boolean types. This extra level of encoding is sometimes used +// when communicating with JavaScript programs: +// +// Int64String int64 `json:",string"` +// +// The key name will be used if it's a non-empty string consisting of +// only Unicode letters, digits, and ASCII punctuation except quotation +// marks, backslash, and comma. +// +// Anonymous struct fields are usually marshaled as if their inner exported fields +// were fields in the outer struct, subject to the usual Go visibility rules amended +// as described in the next paragraph. +// An anonymous struct field with a name given in its JSON tag is treated as +// having that name, rather than being anonymous. +// An anonymous struct field of interface type is treated the same as having +// that type as its name, rather than being anonymous. +// +// The Go visibility rules for struct fields are amended for JSON when +// deciding which field to marshal or unmarshal. If there are +// multiple fields at the same level, and that level is the least +// nested (and would therefore be the nesting level selected by the +// usual Go rules), the following extra rules apply: +// +// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, +// even if there are multiple untagged fields that would otherwise conflict. +// +// 2) If there is exactly one field (tagged or not according to the first rule), that is selected. +// +// 3) Otherwise there are multiple fields, and all are ignored; no error occurs. +// +// Handling of anonymous struct fields is new in Go 1.1. +// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of +// an anonymous struct field in both current and earlier versions, give the field +// a JSON tag of "-". +// +// Map values encode as JSON objects. The map's key type must either be a +// string, an integer type, or implement encoding.TextMarshaler. The map keys +// are sorted and used as JSON object keys by applying the following rules, +// subject to the UTF-8 coercion described for string values above: +// - string keys are used directly +// - encoding.TextMarshalers are marshaled +// - integer keys are converted to strings +// +// Pointer values encode as the value pointed to. +// A nil pointer encodes as the null JSON value. +// +// Interface values encode as the value contained in the interface. +// A nil interface value encodes as the null JSON value. +// +// Channel, complex, and function values cannot be encoded in JSON. +// Attempting to encode such a value causes Marshal to return +// an UnsupportedTypeError. +// +// JSON cannot represent cyclic data structures and Marshal does not +// handle them. Passing cyclic structures to Marshal will result in +// an infinite recursion. +// +func Marshal(v interface{}) ([]byte, error) { + return MarshalWithOption(v) +} + +// MarshalNoEscape returns the JSON encoding of v and doesn't escape v. +func MarshalNoEscape(v interface{}) ([]byte, error) { + return marshalNoEscape(v) +} + +// MarshalContext returns the JSON encoding of v with context.Context and EncodeOption. +func MarshalContext(ctx context.Context, v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { + return marshalContext(ctx, v, optFuncs...) +} + +// MarshalWithOption returns the JSON encoding of v with EncodeOption. +func MarshalWithOption(v interface{}, optFuncs ...EncodeOptionFunc) ([]byte, error) { + return marshal(v, optFuncs...) +} + +// MarshalIndent is like Marshal but applies Indent to format the output. +// Each JSON element in the output will begin on a new line beginning with prefix +// followed by one or more copies of indent according to the indentation nesting. +func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + return MarshalIndentWithOption(v, prefix, indent) +} + +// MarshalIndentWithOption is like Marshal but applies Indent to format the output with EncodeOption. +func MarshalIndentWithOption(v interface{}, prefix, indent string, optFuncs ...EncodeOptionFunc) ([]byte, error) { + return marshalIndent(v, prefix, indent, optFuncs...) +} + +// Unmarshal parses the JSON-encoded data and stores the result +// in the value pointed to by v. If v is nil or not a pointer, +// Unmarshal returns an InvalidUnmarshalError. +// +// Unmarshal uses the inverse of the encodings that +// Marshal uses, allocating maps, slices, and pointers as necessary, +// with the following additional rules: +// +// To unmarshal JSON into a pointer, Unmarshal first handles the case of +// the JSON being the JSON literal null. In that case, Unmarshal sets +// the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into +// the value pointed at by the pointer. If the pointer is nil, Unmarshal +// allocates a new value for it to point to. +// +// To unmarshal JSON into a value implementing the Unmarshaler interface, +// Unmarshal calls that value's UnmarshalJSON method, including +// when the input is a JSON null. +// Otherwise, if the value implements encoding.TextUnmarshaler +// and the input is a JSON quoted string, Unmarshal calls that value's +// UnmarshalText method with the unquoted form of the string. +// +// To unmarshal JSON into a struct, Unmarshal matches incoming object +// keys to the keys used by Marshal (either the struct field name or its tag), +// preferring an exact match but also accepting a case-insensitive match. By +// default, object keys which don't have a corresponding struct field are +// ignored (see Decoder.DisallowUnknownFields for an alternative). +// +// To unmarshal JSON into an interface value, +// Unmarshal stores one of these in the interface value: +// +// bool, for JSON booleans +// float64, for JSON numbers +// string, for JSON strings +// []interface{}, for JSON arrays +// map[string]interface{}, for JSON objects +// nil for JSON null +// +// To unmarshal a JSON array into a slice, Unmarshal resets the slice length +// to zero and then appends each element to the slice. +// As a special case, to unmarshal an empty JSON array into a slice, +// Unmarshal replaces the slice with a new empty slice. +// +// To unmarshal a JSON array into a Go array, Unmarshal decodes +// JSON array elements into corresponding Go array elements. +// If the Go array is smaller than the JSON array, +// the additional JSON array elements are discarded. +// If the JSON array is smaller than the Go array, +// the additional Go array elements are set to zero values. +// +// To unmarshal a JSON object into a map, Unmarshal first establishes a map to +// use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal +// reuses the existing map, keeping existing entries. Unmarshal then stores +// key-value pairs from the JSON object into the map. The map's key type must +// either be any string type, an integer, implement json.Unmarshaler, or +// implement encoding.TextUnmarshaler. +// +// If a JSON value is not appropriate for a given target type, +// or if a JSON number overflows the target type, Unmarshal +// skips that field and completes the unmarshaling as best it can. +// If no more serious errors are encountered, Unmarshal returns +// an UnmarshalTypeError describing the earliest such error. In any +// case, it's not guaranteed that all the remaining fields following +// the problematic one will be unmarshaled into the target object. +// +// The JSON null value unmarshals into an interface, map, pointer, or slice +// by setting that Go value to nil. Because null is often used in JSON to mean +// ``not present,'' unmarshaling a JSON null into any other Go type has no effect +// on the value and produces no error. +// +// When unmarshaling quoted strings, invalid UTF-8 or +// invalid UTF-16 surrogate pairs are not treated as an error. +// Instead, they are replaced by the Unicode replacement +// character U+FFFD. +// +func Unmarshal(data []byte, v interface{}) error { + return unmarshal(data, v) +} + +// UnmarshalContext parses the JSON-encoded data and stores the result +// in the value pointed to by v. If you implement the UnmarshalerContext interface, +// call it with ctx as an argument. +func UnmarshalContext(ctx context.Context, data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { + return unmarshalContext(ctx, data, v) +} + +func UnmarshalWithOption(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { + return unmarshal(data, v, optFuncs...) +} + +func UnmarshalNoEscape(data []byte, v interface{}, optFuncs ...DecodeOptionFunc) error { + return unmarshalNoEscape(data, v, optFuncs...) +} + +// A Token holds a value of one of these types: +// +// Delim, for the four JSON delimiters [ ] { } +// bool, for JSON booleans +// float64, for JSON numbers +// Number, for JSON numbers +// string, for JSON string literals +// nil, for JSON null +// +type Token = json.Token + +// A Number represents a JSON number literal. +type Number = json.Number + +// RawMessage is a raw encoded JSON value. +// It implements Marshaler and Unmarshaler and can +// be used to delay JSON decoding or precompute a JSON encoding. +type RawMessage = json.RawMessage + +// A Delim is a JSON array or object delimiter, one of [ ] { or }. +type Delim = json.Delim + +// Compact appends to dst the JSON-encoded src with +// insignificant space characters elided. +func Compact(dst *bytes.Buffer, src []byte) error { + return encoder.Compact(dst, src, false) +} + +// Indent appends to dst an indented form of the JSON-encoded src. +// Each element in a JSON object or array begins on a new, +// indented line beginning with prefix followed by one or more +// copies of indent according to the indentation nesting. +// The data appended to dst does not begin with the prefix nor +// any indentation, to make it easier to embed inside other formatted JSON data. +// Although leading space characters (space, tab, carriage return, newline) +// at the beginning of src are dropped, trailing space characters +// at the end of src are preserved and copied to dst. +// For example, if src has no trailing spaces, neither will dst; +// if src ends in a trailing newline, so will dst. +func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { + return encoder.Indent(dst, src, prefix, indent) +} + +// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 +// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 +// so that the JSON will be safe to embed inside HTML + diff --git a/taskman-ui/src/pages/temp-management/basic-info.vue b/taskman-ui/src/pages/temp-management/basic-info.vue index 3b0b62b3..34595e56 100644 --- a/taskman-ui/src/pages/temp-management/basic-info.vue +++ b/taskman-ui/src/pages/temp-management/basic-info.vue @@ -1,92 +1,238 @@ @@ -387,3 +519,39 @@ fieldset[disabled] .ivu-input { -webkit-text-fill-color: #757575; } + diff --git a/taskman-ui/src/pages/temp-management/index-old.vue b/taskman-ui/src/pages/temp-management/index-old.vue new file mode 100644 index 00000000..b681e26f --- /dev/null +++ b/taskman-ui/src/pages/temp-management/index-old.vue @@ -0,0 +1,115 @@ + + + + + diff --git a/taskman-ui/src/pages/temp-management/index.vue b/taskman-ui/src/pages/temp-management/index.vue index b681e26f..5b064774 100644 --- a/taskman-ui/src/pages/temp-management/index.vue +++ b/taskman-ui/src/pages/temp-management/index.vue @@ -4,7 +4,7 @@ $t('back_to_template') }} - + {{ $t('basic_information_settings') }} @@ -20,7 +20,7 @@ - +