reestructurando el codigo e incorporando las librerias de active2

master
DEV 2 years ago
parent ad9e72cf4d
commit 11643decd0

@ -1,10 +1,12 @@
package main
import (
"errs/erstr"
"errs/wrap"
"fmt"
"math/rand"
"time"
"typs/strs"
)
type (
@ -28,11 +30,13 @@ func randomInt(min, max int) int {
func main() {
a := fmt.Errorf("UnError")
a := wrap.ErrCode("UnError")
//a = nil
e := wrap.WithCause(wrap.WithInfo(wrap.WithMessage(a,"Esto es un mensage")),wrap.ErrCode("cidd"))
erstr.G.Transformers = append(erstr.G.Transformers, strs.TransformFnc(erstr.RemoveLabel), strs.G.Transformers.GetOrDefault("upper"))
e := wrap.WithCause(wrap.WithInfo(wrap.WithMessage(a,"Esto es un mensage")),wrap.WithMessage(wrap.ErrCode("cidd"),"El mensaje de la causa"))
fmt.Printf(e.String())
fmt.Printf(erstr.StringifyError("",e))
}

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
import (
"reflect"

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
type (

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
import "time"

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
type (

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
import (
"errors"

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
type (

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
type (

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
type (

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
const (

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package erdata
package erinfo
import (
"fmt"

@ -27,7 +27,7 @@ import (
"bfrs"
"cdcs/cjson"
"encoding/json"
"errs/erdata"
"errs/erinfo"
"fmt"
"strings"
)
@ -63,7 +63,7 @@ func newJsonBuilder (f *JSONEncoder) *jsonBuilder {
func (b *jsonBuilder) format (err error) {
cl := erdata.NewErrorData(err)
cl := erinfo.NewErrorData(err)
cl.Collect(b.f.HasAddFields(),b.f.HasAddCauses(),b.f.HasAddTrace())
if cl.Invalid != nil {
@ -75,7 +75,7 @@ func (b *jsonBuilder) format (err error) {
}
func (b *jsonBuilder) write (coll *erdata.ErrorData, cont bool, level int) {
func (b *jsonBuilder) write (coll *erinfo.ErrorData, cont bool, level int) {
if b.invalid != nil {
return
}
@ -120,7 +120,7 @@ func (b *jsonBuilder) write (coll *erdata.ErrorData, cont bool, level int) {
if b.pretty {
b.b.WriteByte('\n')
}
b.writeField(erdata.FieldNameError,coll.ErrStr, indObj,true,false, false)
b.writeField(erinfo.FieldNameError,coll.ErrStr, indObj,true,false, false)
if b.f.HasAddTypes() {
@ -132,10 +132,10 @@ func (b *jsonBuilder) write (coll *erdata.ErrorData, cont bool, level int) {
}
if len(types) == 1 {
b.writeField(erdata.FieldNameType, types[0].String(), indObj, true, false,false)
b.writeField(erinfo.FieldNameType, types[0].String(), indObj, true, false,false)
} else {
b.writeOpen(erdata.FieldNameTypes, indObj, '[', b.pretty)
b.writeOpen(erinfo.FieldNameTypes, indObj, '[', b.pretty)
for i, t := range coll.TypesStr {
if b.pretty {
b.b.WriteString(ind2Obj)
@ -165,7 +165,7 @@ func (b *jsonBuilder) write (coll *erdata.ErrorData, cont bool, level int) {
}
coll.Fields.Sort()
b.writeOpen(erdata.FieldNameFields, indObj, '{', b.pretty)
b.writeOpen(erinfo.FieldNameFields, indObj, '{', b.pretty)
var n = 0
for _, h := range heads {
@ -201,10 +201,10 @@ func (b *jsonBuilder) write (coll *erdata.ErrorData, cont bool, level int) {
}
if len(causes) == 1 {
b.writeOpen(erdata.FieldNameCause, indObj, 0, false)
b.writeOpen(erinfo.FieldNameCause, indObj, 0, false)
b.write(&causes[0], true,level+1)
} else if len(causes) > 1 {
b.writeOpen(erdata.FieldNameCauses, indObj, '[', b.pretty)
b.writeOpen(erinfo.FieldNameCauses, indObj, '[', b.pretty)
for i, ce := range causes {
if i > 0 {
b.b.WriteByte(',')
@ -229,7 +229,7 @@ func (b *jsonBuilder) write (coll *erdata.ErrorData, cont bool, level int) {
if b.pretty {
b.b.WriteByte('\n')
}
b.writeFieldName(erdata.FieldNameTrace,indObj)
b.writeFieldName(erinfo.FieldNameTrace,indObj)
if b.encoder == nil {
b.encoder = json.NewEncoder(b.b)
@ -296,9 +296,9 @@ func (b *jsonBuilder) writeField (name, value, indent string, quote, coma, nl bo
}
func (b *jsonBuilder) writeFieldValue (fields erdata.Fields, field *erdata.FieldHead, level int) bool {
func (b *jsonBuilder) writeFieldValue (fields erinfo.Fields, field *erinfo.FieldHead, level int) bool {
switch field.Kind {
case erdata.FieldKindFloat:
case erinfo.FieldKindFloat:
n := fields.GetFieldValueFloat(field)
if n == 0 && b.f.HasIgnoreDefaults() {
@ -307,7 +307,7 @@ func (b *jsonBuilder) writeFieldValue (fields erdata.Fields, field *erdata.Field
cjson.WriteFloat(b.b,n,64,b.f.HasUseQuote())
return true
case erdata.FieldKindInt:
case erinfo.FieldKindInt:
n := fields.GetFieldValueInt(field)
if n == 0 && b.f.HasIgnoreDefaults() {
return false
@ -315,7 +315,7 @@ func (b *jsonBuilder) writeFieldValue (fields erdata.Fields, field *erdata.Field
cjson.WriteInt(b.b,int64(n),b.f.HasUseQuote())
return true
case erdata.FieldKindString:
case erinfo.FieldKindString:
s := fields.GetFieldValueString(field)
if len(s) == 0 && b.f.HasIgnoreDefaults() {
return false
@ -323,7 +323,7 @@ func (b *jsonBuilder) writeFieldValue (fields erdata.Fields, field *erdata.Field
cjson.WriteString(b.b,s,b.f.HasEscapeHTML())
return true
case erdata.FieldKindTime:
case erinfo.FieldKindTime:
d := fields.GetFieldValueDate(field)
if d.IsZero() && b.f.HasIgnoreDefaults(){
return false
@ -331,7 +331,7 @@ func (b *jsonBuilder) writeFieldValue (fields erdata.Fields, field *erdata.Field
cjson.WriteDate(b.b,d,b.f.layout.TimeLayout,true)
return true
case erdata.FieldKindDate:
case erinfo.FieldKindDate:
d := fields.GetFieldValueDate(field)
if d.IsZero() && b.f.HasIgnoreDefaults(){
return false
@ -339,7 +339,7 @@ func (b *jsonBuilder) writeFieldValue (fields erdata.Fields, field *erdata.Field
cjson.WriteDate(b.b,d,b.f.layout.DateLayout,true)
return true
case erdata.FieldKindBool:
case erinfo.FieldKindBool:
t := fields.GetFieldValueBool(field)
if !t && b.f.HasIgnoreDefaults() {
return false

@ -0,0 +1,122 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name active.go
// ✍️ Created by DEV
// 📅 Modified 04/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
package erstr
import (
"bytes"
"fmt"
"strings"
"typs/strs"
)
const (
labelError string = "error"
labelSep string = " : "
)
type (
stringer interface { String () string }
unwrapper interface { Unwrap () error }
)
var (
G = struct {
LabelSep string
LineLabelFmt string
LineErrorFmt string
Transformers strs.Transformers
}{
LabelSep : labelSep,
LineLabelFmt : "%s" + labelSep + "%s\n",
LineErrorFmt : labelError + labelSep + "%s\n",
}
)
func StringifyError (text string, err error) string {
ln := []string { "", text }
var nl string
ne := err
for ne != nil {
if st,is := ne.(stringer); is {
nl = st.String()
}
if uw,is := ne.(unwrapper); is {
ne = uw.Unwrap()
} else {
ne = nil
if strings.Index(nl,labelError) != -1 {
ln[0]= G.Transformers.Transform(nl)
break
}
}
ln = append(ln, G.Transformers.Transform(nl))
}
if len(ln[0]) == 0 {
ln[0]=G.Transformers.Transform(err.Error())
}
return strings.Join(ln,"")
}
func FormatLineError(strErr string) string {
return fmt.Sprintf(G.LineErrorFmt,strErr) }
func FormatLine (label, text string) string {
return fmt.Sprintf(G.LineLabelFmt,label,text) }
func RemoveLabel (text string) string {
if strings.Index(text,G.LabelSep) == -1 {
return text
}
l := strings.Split(text,"\n")
b := bytes.Buffer{}
for _,t := range l {
if p := strings.Index(t,G.LabelSep); p != -1 {
b.WriteString(t[p+len(G.LabelSep):])
b.WriteByte('\n')
} else {
b.WriteString(t)
}
}
return b.String()
}

@ -22,17 +22,21 @@
// limitations under the License.
// ------------------------------------------------------------------------
package strg
package erstr
type (
ErrorStringer interface {
StringError (err error) string
Stringer interface {
String (err error) string
}
StringFnc func (err error) string
)
func (f StringFnc) String(err error) string {
return f(err) }

@ -0,0 +1,121 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name stringify.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
package erstr
import (
"bytes"
"fmt"
"strings"
"typs/strs"
)
type (
Stringify struct {
LabelSep string
LineLabelFmt string
LineErrorFmt string
Transformers strs.Transformers
}
ErrorStringifyFnc func (stringify *Stringify)
)
func NewStringify (options ...ErrorStringifyFnc) *Stringify {
s := &Stringify{
LabelSep : labelSep,
LineLabelFmt : "%s" + labelSep + "%s\n",
LineErrorFmt : labelError + labelSep + "%s\n",
}
for _,o := range options {
o(s)
}
return s
}
func (s *Stringify) Stringify (text string, err error) string {
ln := []string { "", text }
var nl string
ne := err
for ne != nil {
if st,is := ne.(stringer); is {
nl = st.String()
}
if uw,is := ne.(unwrapper); is {
ne = uw.Unwrap()
} else {
ne = nil
if strings.Index(nl,labelError) != -1 {
ln[0]= s.Transformers.Transform(nl)
break
}
}
ln = append(ln, s.Transformers.Transform(nl))
}
if len(ln[0]) == 0 {
ln[0]=s.Transformers.Transform(err.Error())
}
if len(ln) == 0 {
return ln[0]
}
b := bytes.Buffer{}
for _,l := range ln {
b.WriteString(l)
}
return b.String()
}
func (s *Stringify) FormatLineError(strErr string) string {
return fmt.Sprintf(s.LineErrorFmt,strErr) }
func (s *Stringify) FormatLine (label, text string) string {
return fmt.Sprintf(s.LineLabelFmt,label,text) }
func (s *Stringify) RemoveLabel (text string) string {
if strings.Index(text,s.LabelSep) == -1 {
return text
}
l := strings.Split(text,"\n")
b := bytes.Buffer{}
for _,t := range l {
if p := strings.Index(t,s.LabelSep); p != -1 {
b.WriteString(t[p+len(s.LabelSep):])
b.WriteByte('\n')
} else {
b.WriteString(t)
}
}
return b.String()
}

@ -26,7 +26,7 @@ package ertext
import (
"aios/ansi"
"bfrs"
"errs/erdata"
"errs/erinfo"
"fmt"
"strings"
)
@ -95,7 +95,7 @@ func (b *TextBuilder) SetAnsi(ansiC ansi.Code) {
func (b *TextBuilder) format (err error) {
c := erdata.NewErrorData(err)
c := erinfo.NewErrorData(err)
if c.Collect(b.f.HasAddFields(), b.f.HasAddCauses(), b.f.HasAddTrace()); c.Invalid != nil {
//b.writeFormatError(cl.Invalid)
return
@ -103,7 +103,7 @@ func (b *TextBuilder) format (err error) {
b.write(c, 0)
}
func (b *TextBuilder) write (c *erdata.ErrorData, level int) {
func (b *TextBuilder) write (c *erinfo.ErrorData, level int) {
if b.invalid != nil {
return
}
@ -131,12 +131,12 @@ func (b *TextBuilder) write (c *erdata.ErrorData, level int) {
}(b,&d, c.Err)
f.sections.Head.begin(b)
b.writeFieldNameValue(erdata.FieldNameError, c.ErrStr, ind)
b.writeFieldNameValue(erinfo.FieldNameError, c.ErrStr, ind)
if f.HasAddTypes() {
if len(c.TypesStr) == 1 {
b.writeFieldNameValue(erdata.FieldNameType, c.TypesStr[0], ind)
b.writeFieldNameValue(erinfo.FieldNameType, c.TypesStr[0], ind)
} else {
b.writeFieldNameValue(erdata.FieldNameTypes, strings.Join(c.TypesStr, ","), ind)
b.writeFieldNameValue(erinfo.FieldNameTypes, strings.Join(c.TypesStr, ","), ind)
}
}
f.sections.Head.end(b)
@ -226,7 +226,7 @@ func (b *TextBuilder) writeFieldNameValue(name string, value string, indent stri
}
func (b *TextBuilder) writeField (fields erdata.Fields, field *erdata.FieldHead, indent string) {
func (b *TextBuilder) writeField (fields erinfo.Fields, field *erinfo.FieldHead, indent string) {
p := b.b.Len()
b.writeFieldBegin(field.Name,indent)
if !b.writeFieldValue(fields,field) {
@ -237,29 +237,29 @@ func (b *TextBuilder) writeField (fields erdata.Fields, field *erdata.FieldHead,
}
func (b *TextBuilder) writeFieldValue (fields erdata.Fields, field *erdata.FieldHead) bool {
func (b *TextBuilder) writeFieldValue (fields erinfo.Fields, field *erinfo.FieldHead) bool {
switch field.Kind {
case erdata.FieldKindFloat:
case erinfo.FieldKindFloat:
b.auxB.WriteFloatStr(fields.GetFieldValueFloat(field),'f',-1)
case erdata.FieldKindInt:
case erinfo.FieldKindInt:
b.auxB.WriteIntStr(int64(fields.GetFieldValueInt(field)),10)
case erdata.FieldKindString:
case erinfo.FieldKindString:
s := fields.GetFieldValueString(field)
if b.f.HasIgnoreEmpty() && len(s) == 0 {
return false
}
b.auxB.WriteString(fields.GetFieldValueString(field))
case erdata.FieldKindTime:
case erinfo.FieldKindTime:
b.auxB.WriteDateStr(fields.GetFieldValueDate(field), b.f.layout.TimeLayout)
case erdata.FieldKindDate:
case erinfo.FieldKindDate:
b.auxB.WriteDateStr(fields.GetFieldValueDate(field), b.f.layout.DateLayout)
case erdata.FieldKindBool:
case erinfo.FieldKindBool:
b.auxB.WriteBoolStr(fields.GetFieldValueBool(field))
default:

@ -25,7 +25,7 @@ package ertext
import (
"errs/stack"
"typs/astrings"
"typs/strs"
)
type (
@ -37,8 +37,8 @@ type (
layout Layout
sections Sections
nameTrans astrings.Transformers
valueTrans astrings.Transformers
nameTrans strs.Transformers
valueTrans strs.Transformers
onFormatError ErrorFallbackFnc
onTraceError ErrorFallbackFnc
@ -109,12 +109,12 @@ func WithOptions (set, unset Option) TextEncoderFnc {
f.Option = f.Option.Del(unset) } }
func WithNameTransformers(transformer ...astrings.Transformer) TextEncoderFnc {
func WithNameTransformers(transformer ...strs.Transformer) TextEncoderFnc {
return func(f *TextEncoder) {
f.nameTrans = append(f.nameTrans, transformer ...) } }
func WithValueTransformers(transformer ...astrings.Transformer) TextEncoderFnc {
func WithValueTransformers(transformer ...strs.Transformer) TextEncoderFnc {
return func(f *TextEncoder) {
f.valueTrans = append(f.nameTrans, transformer ...) } }

@ -24,8 +24,6 @@
package wrap
import "fmt"
const(
errNilWrapMsg string = "error trying to wrap % into a nil error"
@ -37,6 +35,7 @@ const(
labelMessage string = "message"
labelInfo string = "info"
labelDate string = "date"
labelDesc string = "desc"
labelTime string = "time"
labelHelp string = "help"
labelLink string = "link"
@ -70,17 +69,6 @@ var (
func ComposeWrappedString (str string, wrapped error) string {
type s interface { String() string }
if wrapped == nil {
return fmt.Sprintf("%s\n",str)
}
if st,is := wrapped.(s); is {
return fmt.Sprintf("%s\n%s",st.String(),str)
}
return fmt.Sprintf("%s\n%s",wrapped.Error(),str)
}
func TryWithCause(err error, cause error) error {
if err == nil && cause == nil {

@ -24,7 +24,7 @@
package wrap
import (
"errs/strg"
"errs/erstr"
)
type (
@ -36,7 +36,7 @@ type (
)
func WithCause(err error, cause error) *Cause {
if err == nil {
if err == nil {
panic(G.ErrNilWrap.WithMessageF(errNilWrapMsg, "Cause"))
}
if cause == nil {
@ -57,5 +57,4 @@ func (e Cause) Cause () error {
func (e Cause) String() string {
return ComposeWrappedString(strg.ErrorToString(e.cause),e.error)
}
return erstr.FormatLine(labelCause,e.cause.Error()) }

@ -24,7 +24,7 @@
package wrap
import "errs/erstr"
type (
@ -50,5 +50,4 @@ func (e ErrCode) WithMessageF(msgf string, params ...any) *Message {
func (e ErrCode) String () string {
return string(e)
}
return erstr.FormatLineError(e.Error()) }

@ -24,7 +24,8 @@
package wrap
import (
"fmt"
"bytes"
"errs/erstr"
"time"
)
@ -63,6 +64,13 @@ func (e Info) Unwrap () error {
func (e Info) String () string {
return ComposeWrappedString(fmt.Sprintf("date : %s",e.Date),e.error)
b := bytes.Buffer{}
if len(e.Message) > 0 { b.WriteString(erstr.FormatLine(labelMessage,e.Message)) }
if len(e.Info) > 0 { b.WriteString(erstr.FormatLine(labelInfo,e.Message)) }
if len(e.Desc) > 0 { b.WriteString(erstr.FormatLine(labelDesc,e.Desc)) }
if len(e.Link) > 0 { b.WriteString(erstr.FormatLine(labelLink,e.Link)) }
if len(e.Help) > 0 { b.WriteString(erstr.FormatLine(labelHelp,e.Help)) }
b.WriteString(erstr.FormatLine(labelDate,e.Date.String()))
return b.String()
}

@ -24,6 +24,7 @@
package wrap
import (
"errs/erstr"
"fmt"
)
@ -58,4 +59,5 @@ func (e Message) Message () string {
func (e Message) String () string {
return ComposeWrappedString(e.message,e.error) }
return erstr.FormatLine(labelMessage,e.message)
}

@ -2,9 +2,9 @@
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name stringer.go
// File name with_field.go
// ✍️ Created by DEV
// 📅 Modified 04/05/2024
// 📅 Modified 05/05/2024
//
// 🔒 Copyright 2024 activething.com
//
@ -22,22 +22,30 @@
// limitations under the License.
// ------------------------------------------------------------------------
package strg
package wrap
import "flds"
type (
Stringer interface {
String () string
Field struct {
error
field flds.Field
}
StringFnc func () string
)
func WithField (err error, field flds.Field) *Field {
if err == nil {}
if field == nil {}
return &Field{
error: err,
field: field,
}
}
func (f StringFnc) String () string {
return f() }
func WithFieldNew (err error, name string, value any, kind flds.Kind) *Field {
return WithField(err,flds.Create(name,value,kind)) }

@ -4,7 +4,7 @@
//
// File name active.go
// ✍️ Created by DEV
// 📅 Modified 04/05/2024
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
@ -22,16 +22,21 @@
// limitations under the License.
// ------------------------------------------------------------------------
package strg
package reps
func ErrorToString (err error) string {
if err == nil {
return ""
}
if st,is := err.(Stringer); is {
return st.String()
var (
G = struct {
ErrDuplicatedItem ErrCode
ErrInvalidItem ErrCode
}{
ErrDuplicatedItem : ErrCode("duplicated-repo-item"),
ErrInvalidItem : ErrCode("invalid-item"),
}
return err.Error()
}
)

@ -2,9 +2,9 @@
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name astringer.go
// File name err_code.go
// ✍️ Created by DEV
// 📅 Modified 04/05/2024
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
@ -22,20 +22,17 @@
// limitations under the License.
// ------------------------------------------------------------------------
package strg
package reps
type (
AErrorStringer struct {
useLabels bool
}
)
ErrCode string
func (s AStringer) AddString (label, str string, err error) {
}
)
func (e ErrCode) Error () string {
return string(e) }
func (e ErrCode) Code () string {
return string(e) }

@ -0,0 +1,161 @@
// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name grepo.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
package reps
import (
"sync"
"syns"
)
type (
GRepo [K comparable, V any] struct {
syns.LockerRW
items map[K]V
def V
validatorFn func(item V) bool
}
GRepoFnc[K comparable, V any] func (r *GRepo[K,V])
)
func NewGRepo [K comparable, V any](def V, safe bool, options ...GRepoFnc[K,V]) *GRepo[K,V] {
lk := syns.LockerRW (syns.NopLocker{})
if safe {
lk = &sync.RWMutex{}
}
rp := &GRepo[K,V]{
LockerRW : lk,
items : make(map[K]V),
validatorFn : func(_ V) bool { return true },
}
for _,o := range options {
o(rp)
}
return rp
}
func (r *GRepo[_,_]) Len () int {
r.RLock()
l := len(r.items)
r.RUnlock()
return l
}
func (r *GRepo[K, V]) Has (key K) bool {
r.RLock()
_,hs := r.items[key]
r.RUnlock()
return hs
}
func (r *GRepo[K, V]) Get (key K) (V,bool) {
r.RLock()
v,hs := r.items[key]
r.RUnlock()
return v,hs
}
func (r *GRepo[K, V]) GetOrDefault (key K) V {
r.RLock()
v,hs := r.items[key]
if !hs {
v = r.def
}
r.RUnlock()
return v
}
func (r *GRepo[K, V]) Reg (key K, item V) error {
r.Lock()
if r.validatorFn != nil && !r.validatorFn(item) {
r.Unlock()
return G.ErrInvalidItem
}
if _,hs := r.items[key]; hs {
r.Unlock()
return G.ErrDuplicatedItem
}
r.items[key]=item
r.Unlock()
return nil
}
func (r *GRepo[K, V]) Set (key K, item V) {
r.Lock()
if r.validatorFn != nil && !r.validatorFn(item) {
r.Unlock()
return
}
r.items[key]=item
r.Unlock()
}
func (r *GRepo[K, _]) Del (key ...K) {
r.Lock()
for _,k := range key {
delete(r.items, k)
}
r.Unlock()
}
func (r *GRepo[K,V]) GetAll (all bool, key...K) ([]V,int) {
c := 0
var l []V
for _,k := range key {
v,hs := r.items[k]
if hs {
l = append(l, v)
continue
}
if all {
return nil,-1
}
c-=1
}
return l,c
}
func RepoWithValidator[K comparable,T any] (validator func(item T) bool) GRepoFnc[K,T] {
return func(r *GRepo[K,T]) {
r.validatorFn = validator } }

@ -0,0 +1,3 @@
module reps
go 1.22

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package slices
package slcs

@ -21,11 +21,11 @@
// limitations under the License.
// ------------------------------------------------------------------------
package astrings
package strs
import (
"reps"
"strings"
"sync"
)
@ -45,69 +45,38 @@ const(
var (
G = struct {
ErrTransformerNotFound ErrAStrings
} {
ErrTransformerNotFound: ErrAStrings("transformer-not-found"),
}
g = struct {
sync.RWMutex
uppercaseAcronym map[string]string
iniTransformers sync.Once
transformers map[string]Transformer
}{
}
)
ErrTransformerNotFound ErrCode
func AddAcronym (key, value string) {
g.Lock()
g.uppercaseAcronym[key] = value
g.Unlock()
}
Transformers *reps.GRepo[string,Transformer]
func GetAcronym (key string) (string, bool) {
g.RLock()
v,h := g.uppercaseAcronym[key]
g.RUnlock()
return v,h
}
func GetTransformer (name string) Transformer {
g.iniTransformers.Do(initTransformers)
g.RLock()
t,_ := g.transformers[name]
g.RUnlock()
return t
}
func AddTransformer (name string, transformer Transformer) {
g.iniTransformers.Do(initTransformers)
if transformer != nil {
g.Lock()
g.transformers[name]=transformer
g.Unlock()
} {
ErrTransformerNotFound: ErrCode("transformer-not-found"),
Transformers : reps.NewGRepo[string,Transformer](nil,true,
reps.RepoWithValidator[string,Transformer](func (v Transformer) bool {
return v != nil
}),
func(r *reps.GRepo[string,Transformer]){
r.Set(UpperTransformer , TransformFnc(strings.ToUpper))
r.Set(LowerTransformer , TransformFnc(strings.ToLower))
r.Set(TrimTransformer , TransformFnc(strings.TrimSpace))
r.Set(TitleTransformer , TransformFnc(strings.ToTitle))
r.Set(CamelTransformer , TransformFnc(ToCamel))
r.Set(LCamelTransformer, TransformFnc(ToLowerCamel))
r.Set(SnakeTransformer , TransformFnc(ToSnake))
r.Set(USnakeTransformer, TransformFnc(ToUSnake))
r.Set(KebabTransformer , TransformFnc(ToKebab))
r.Set(UKebabTransformer, TransformFnc(ToUKebab))
}),
}
}
func initTransformers () {
g.transformers = map[string]Transformer {
UpperTransformer : TransformFnc(strings.ToUpper),
LowerTransformer : TransformFnc(strings.ToLower),
TrimTransformer : TransformFnc(strings.TrimSpace),
TitleTransformer : TransformFnc(strings.ToTitle),
CamelTransformer : TransformFnc(ToCamel),
LCamelTransformer: TransformFnc(ToLowerCamel),
SnakeTransformer : TransformFnc(ToSnake),
USnakeTransformer: TransformFnc(ToUSnake),
KebabTransformer : TransformFnc(ToKebab),
UKebabTransformer: TransformFnc(ToUKebab),
g = struct {
acronyms *reps.GRepo[string,string]
}{
acronyms: reps.NewGRepo[string,string]("",false),
}
}
)

@ -22,7 +22,7 @@
// ------------------------------------------------------------------------
// https://github.com/iancoleman/strcase/blob/v0.3.0/camel.go
package astrings
package strs
@ -36,7 +36,7 @@ func toCamelInitCase(s string, initCase bool) string {
if s == "" {
return s
}
a, hasAcronym := GetAcronym(s)
a, hasAcronym := g.acronyms.Get(s)
if hasAcronym {
s = a
}

@ -21,31 +21,23 @@
// limitations under the License.
// ------------------------------------------------------------------------
package astrings
package strs
import "errs/erdata"
type (
// ErrAStrings no puede heredar directamente de Errs.Code
// ErrCode no puede heredar directamente de Errs.Code
// ya que es utilizada por fjson y ftext lo que crea
// un ciclo de importaciones
//
ErrAStrings string
ErrCode string
)
func (e ErrAStrings) Error() string {
func (e ErrCode) Error() string {
return string(e) }
func (e ErrAStrings) Code () string {
func (e ErrCode) Code () string {
return string(e) }
func (e ErrAStrings) Collect (c erdata.Collector) {
c.AddFieldString(erdata.FieldNameCode,string(e)) }

@ -22,7 +22,7 @@
// ------------------------------------------------------------------------
// https://github.com/iancoleman/strcase/blob/v0.3.0/snake.go
package astrings
package strs
import "strings"

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package astrings
package strs
import (
"strings"

@ -21,7 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package astrings
package strs

@ -21,9 +21,7 @@
// limitations under the License.
// ------------------------------------------------------------------------
package astrings
import "errs/erfield"
package strs
type (
@ -34,16 +32,14 @@ type (
func MakeTransformers (names ...string) Transformers {
var l Transformers
for _,name := range names {
if t := GetTransformer(name); t != nil {
l = append(l, t)
continue
}
panic(erfield.NewFieldString(G.ErrTransformerNotFound,"transformer",name))
l,c := G.Transformers.GetAll(true,names ...)
if c < 0 {
panic(G.ErrTransformerNotFound)
}
return l
}
func (a Transformers) Transform (value string) string {
if len(a) == 0 {
return value

@ -19,6 +19,8 @@ use (
./core/crns
./core/rsls
./core/ctxs
core/bfrs
./core/bfrs
./core/reps
./core
)

Loading…
Cancel
Save

Powered by TurnKey Linux.