func pluralize(c int, s string, format bool) string { if c == 1 { if format { return fmt.Sprintf("1 %s", inflect.Singularize(s)) } return fmt.Sprintf("%s", inflect.Singularize(s)) } if format { return fmt.Sprintf("%d %s", c, inflect.Pluralize(s)) } return fmt.Sprintf("%s", inflect.Pluralize(s)) }
func (s *Site) RenderLists() error { for section, data := range s.Sections { n := s.NewNode() n.Title = strings.Title(inflect.Pluralize(section)) n.Url = helpers.Urlize(section + "/" + "index.html") n.Permalink = permalink(s, n.Url) n.RSSlink = permalink(s, section+".xml") n.Date = data[0].Page.Date n.Data["Pages"] = data.Pages() layout := "indexes/" + section + ".html" err := s.render(n, section, layout, "_default/indexes.html") if err != nil { return err } if a := s.Tmpl.Lookup("rss.xml"); a != nil { // XML Feed n.Url = helpers.Urlize(section + ".xml") n.Permalink = template.HTML(string(n.Site.BaseUrl) + n.Url) err = s.render(n, section+".xml", "rss.xml") if err != nil { return err } } } return nil }
func (s *Site) RenderLists() error { for section, data := range s.Sections { n := s.NewNode() n.Title = strings.Title(inflect.Pluralize(section)) n.Url = Urlize(section + "/" + "index.html") n.Permalink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(n.Url))) n.RSSlink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(section+".xml"))) n.Date = data[0].Date n.Data["Pages"] = data layout := "indexes" + slash + section + ".html" x, err := s.RenderThing(n, layout) if err != nil { return err } s.WritePublic(section+slash+"index.html", x.Bytes()) if a := s.Tmpl.Lookup("rss.xml"); a != nil { // XML Feed if s.Config.UglyUrls { n.Url = Urlize(section + ".xml") } else { n.Url = Urlize(section + "/" + "index.xml") } n.Permalink = template.HTML(string(n.Site.BaseUrl) + n.Url) y := s.NewXMLBuffer() s.Tmpl.ExecuteTemplate(y, "rss.xml", n) s.WritePublic(section+slash+"index.xml", y.Bytes()) } } return nil }
func plural(qty int, singular string) string { s := singular if qty != 1 { s = inflect.Pluralize(s) } return fmt.Sprintf("%d %s", qty, s) }
func (s *Site) RenderLists() error { for section, data := range s.Sections { n := s.NewNode() n.Title = strings.Title(inflect.Pluralize(section)) s.setUrls(n, section) n.Date = data[0].Page.Date n.Data["Pages"] = data.Pages() layout := "indexes/" + section + ".html" err := s.render(n, section, layout, "_default/indexes.html") if err != nil { return err } if a := s.Tmpl.Lookup("rss.xml"); a != nil { // XML Feed s.setUrls(n, section+".xml") err = s.render(n, section+".xml", "rss.xml") if err != nil { return err } } } return nil }
// Render a page for each section func (s *Site) RenderSectionLists() error { for section, data := range s.Sections { n := s.NewNode() if viper.GetBool("PluralizeListTitles") { n.Title = strings.Title(inflect.Pluralize(section)) } else { n.Title = strings.Title(section) } s.setUrls(n, section) n.Date = data[0].Page.Date n.Data["Pages"] = data.Pages() layouts := []string{"section/" + section + ".html", "_default/section.html", "_default/list.html", "indexes/" + section + ".html", "_default/indexes.html"} err := s.render(n, section, s.appendThemeTemplates(layouts)...) if err != nil { return err } if !viper.GetBool("DisableRSS") { // XML Feed rssLayouts := []string{"section/" + section + ".rss.xml", "_default/rss.xml", "rss.xml", "_internal/_default/rss.xml"} s.setUrls(n, section+".xml") err = s.render(n, section+".xml", s.appendThemeTemplates(rssLayouts)...) if err != nil { return err } } } return nil }
func (fm *ForceMetadata) CreateCustomObject(object string) (err error) { fld := "" fld = strings.ToUpper(object) fld = fld[0:1] soap := ` <metadata xsi:type="CustomObject" xmlns:cmd="http://soap.sforce.com/2006/04/metadata"> <fullName>%s__c</fullName> <label>%s</label> <pluralLabel>%s</pluralLabel> <deploymentStatus>Deployed</deploymentStatus> <sharingModel>ReadWrite</sharingModel> <nameField> <label>%s Name</label> <type>AutoNumber</type> <displayFormat>%s-{00000}</displayFormat> <startingNumber>1</startingNumber> </nameField> </metadata> ` body, err := fm.soapExecute("create", fmt.Sprintf(soap, object, object, inflect.Pluralize(object), object, fld)) if err != nil { return err } var status struct { Id string `xml:"Body>createResponse>result>id"` } if err = xml.Unmarshal(body, &status); err != nil { return } if err = fm.CheckStatus(status.Id); err != nil { return } return }
//NewBuilder creates a build instance using the JSON schema data from the given filename. If modelName and/or pkgName //are left empty the title-attribute of the JSON schema is used for: // => struct-name (singular, camelcase e.g contact => Contact) // => package name (pluralize, lowercased e.g. payment_reminder => paymentreminders) func NewBuilder(inputFile string, modelName string, pkgName string) (builder Builder) { builder = Builder{} // try to read input file raw, err := ioutil.ReadFile(inputFile) if err != nil { msg := fmt.Sprintf("File error: %s", err) builder.Errors = append(builder.Errors, msg) return } builder.InputFile = inputFile builder.SchemaRaw = raw // try parsing json if err := json.Unmarshal(builder.SchemaRaw, &builder.SchemaJSON); err != nil { msg := fmt.Sprintf("JSON error: %s", err) builder.Errors = append(builder.Errors, msg) return } // defer model name from schema.title if not given as argument, schema['title'] MUST be set if len(modelName) > 0 { builder.ModelName = modelName } else { builder.ModelName = inflect.Typeify(builder.SchemaJSON["title"].(string)) } // defer package name from schema.title if not given as argument if len(pkgName) > 0 { builder.PkgName = pkgName } else { //Pluralize no underscores builder.PkgName = strings.ToLower(inflect.Camelize(inflect.Pluralize(builder.SchemaJSON["title"].(string)))) } return }
// pluralize returns the plural form of a single word. func pluralize(in interface{}) (string, error) { word, err := cast.ToStringE(in) if err != nil { return "", err } return inflect.Pluralize(word), nil }
func (s *Service) ResourceNames() []string { l := make([]string, len(s.Resources)) i := 0 for _, r := range s.Resources { l[i] = inflect.Pluralize(r.Name) i++ } sort.Strings(l) return l }
func (s *Site) newSectionListNode(section string, data WeightedPages) *Node { n := s.NewNode() if viper.GetBool("PluralizeListTitles") { n.Title = strings.Title(inflect.Pluralize(section)) } else { n.Title = strings.Title(section) } s.setUrls(n, section) n.Date = data[0].Page.Date n.Data["Pages"] = data.Pages() return n }
// HasMany signifies a relationship between this model and a // set of Children. The Parent has the children, and the Children belong // to the Parent. The first parameter becomes the name of the // field in the model struct, the second parameter is the name // of the child model. The Child model will have a ParentID field // appended to the field list. The Parent model definition will use // the first parameter as the field name in the struct definition. // Usage: HasMany("Orders", "Order") // Struct field definition: Children []Child func HasMany(name, child string) { if r, ok := relationalModelDefinition(false); ok { field := &gorma.RelationalFieldDefinition{ Name: codegen.Goify(name, true), HasMany: child, Description: "has many " + inflect.Pluralize(child), Datatype: gorma.HasMany, Parent: r, } r.RelationalFields[field.Name] = field var model *gorma.RelationalModelDefinition model, ok := r.Parent.RelationalModels[child] if ok { r.HasMany[child] = model // create the fk field f := &gorma.RelationalFieldDefinition{ Name: codegen.Goify(inflect.Singularize(r.Name), true) + "ID", HasMany: child, Description: "has many " + child, Datatype: gorma.HasManyKey, Parent: model, DatabaseFieldName: SanitizeDBFieldName(codegen.Goify(inflect.Singularize(r.Name), true) + "ID"), } model.RelationalFields[f.Name] = f } else { model = &gorma.RelationalModelDefinition{ Name: child, Parent: r.Parent, RelationalFields: make(map[string]*gorma.RelationalFieldDefinition), BelongsTo: make(map[string]*gorma.RelationalModelDefinition), HasMany: make(map[string]*gorma.RelationalModelDefinition), HasOne: make(map[string]*gorma.RelationalModelDefinition), ManyToMany: make(map[string]*gorma.ManyToManyDefinition), } r.HasMany[child] = model // create the fk field f := &gorma.RelationalFieldDefinition{ Name: codegen.Goify(inflect.Singularize(r.Name), true) + "ID", HasMany: child, Description: "has many " + child, Datatype: gorma.HasManyKey, Parent: model, DatabaseFieldName: SanitizeDBFieldName(codegen.Goify(inflect.Singularize(r.Name), true) + "ID"), } model.RelationalFields[f.Name] = f } } }
func runBigObjectCreate(args []string) { var fieldObjects = make([]BigObjectField, len(fields)) for i, field := range fields { fieldObjects[i] = parseField(field) } var object = BigObject{deploymentStatus, objectLabel, pluralLabel, fieldObjects} if len(object.Label) == 0 { ErrorAndExit("Please provide a label for your big object using the -l flag.") } if len(object.PluralLabel) == 0 { object.PluralLabel = inflect.Pluralize(object.Label) } force, _ := ActiveForce() if err := force.Metadata.CreateBigObject(object); err != nil { ErrorAndExit(err.Error()) } fmt.Println("Big object created") }
// ManyToMany creates a join table to store the intersection relationship // between this model and another model. For example, in retail an Order can // contain many products, and a product can belong to many orders. To express // this relationship use the following syntax: // Model("Order", func(){ // ManyToMany("Product", "order_lines") // }) // This specifies that the Order and Product tables have a "junction" table // called `order_lines` that contains the order and product information. // The generated model will have a field called `Products` that will // be an array of type `product.Product`. func ManyToMany(other, tablename string) { if r, ok := relationalModelDefinition(false); ok { field := &gorma.RelationalFieldDefinition{ Name: inflect.Pluralize(other), Many2Many: other, Description: "many to many " + r.Name + "/" + strings.Title(other), Parent: r, } r.RelationalFields[field.Name] = field var model *gorma.RelationalModelDefinition model, ok := r.Parent.RelationalModels[other] var m2m *gorma.ManyToManyDefinition if ok { m2m = &gorma.ManyToManyDefinition{ Left: r, Right: model, DatabaseField: tablename, } r.ManyToMany[other] = m2m } else { model = &gorma.RelationalModelDefinition{ Name: other, Parent: r.Parent, RelationalFields: make(map[string]*gorma.RelationalFieldDefinition), BelongsTo: make(map[string]*gorma.RelationalModelDefinition), HasMany: make(map[string]*gorma.RelationalModelDefinition), HasOne: make(map[string]*gorma.RelationalModelDefinition), ManyToMany: make(map[string]*gorma.ManyToManyDefinition), } m2m = &gorma.ManyToManyDefinition{ Left: r, Right: model, DatabaseField: tablename, } r.ManyToMany[other] = m2m } } }
func (e Element) Field(plural bool) *ast.Field { omitempty := false if e.MinOccurs == "0" { omitempty = true } if e.MaxOccurs == "unbounded" { plural = true } if e.GoType() == "" { e.Type = e.Name defer func() { e.Type = "" }() } doc := "" if e.Annotation.Documentation != "" { doc = e.Annotation.Documentation } if plural { pluralName := inflect.Pluralize(e.GoName()) pluralType := "[]" + e.GoType() return &ast.Field{ Names: []*ast.Ident{{Name: pluralName}}, Type: &ast.Ident{Name: pluralType}, Tag: tag(XMLTag{Name: e.Name, Omitempty: omitempty}.String()), Doc: comment(doc), } } typ := e.GoType() if e.MinOccurs == "0" { typ = omitType(typ) } return &ast.Field{ Names: []*ast.Ident{{Name: e.GoName()}}, Type: &ast.Ident{Name: typ}, Tag: tag(XMLTag{Name: e.Name, Omitempty: omitempty}.String()), Doc: comment(doc), } }
func (s *Site) RenderLists() { for section, data := range s.Sections { n := s.NewNode() n.Title = strings.Title(inflect.Pluralize(section)) n.Url = Urlize(section + "/index.html") n.Permalink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(n.Url))) n.RSSlink = template.HTML(MakePermalink(string(n.Site.BaseUrl), string(section+"/index.xml"))) n.Date = data[0].Date n.Data["Pages"] = data layout := "indexes/" + section + ".html" x := s.RenderThing(n, layout) s.WritePublic(section, "index.html", x.Bytes()) if a := s.Tmpl.Lookup("rss.xml"); a != nil { // XML Feed n.Url = Urlize(section + "/index.xml") n.Permalink = template.HTML(string(n.Site.BaseUrl) + section + "/index.xml") y := s.NewXMLBuffer() s.Tmpl.ExecuteTemplate(y, "rss.xml", n) s.WritePublic(section, "index.xml", y.Bytes()) } } }
func (proc *postgresqlSchemaProcessor) RetrieveTableMetaData(databaseName string, schemaName string) ([]Table, error) { // fetch the schema tables dbTables, err := proc.schemaLoader.GetTables(databaseName, schemaName) if err != nil { log.Fatalln(err) return nil, err } tables := []Table{} for _, dbTable := range dbTables { sanitisedModelName := toCapitalCase(dbTable.TableName) sanitisedModelNameLowerCase := strings.ToLower(sanitisedModelName) pluralisedModelName := inflect.Pluralize(sanitisedModelNameLowerCase) table := Table{ DatabaseName: dbTable.TableCatalog, SchemaName: dbTable.TableSchema, TableName: dbTable.TableName, ModelName: sanitisedModelName, ModelNameLowerCase: sanitisedModelNameLowerCase, // sanitised tableName ModelNameLowerCasePlural: pluralisedModelName, // pluralised sanitised tableName Columns: []*Column{}, ForeignKeys: []*ForeignKey{}, InsertColumns: []*Column{}, UpdateColumns: []*Column{}, PrimaryKeyColumns: []*Column{}, } // fetch the schema columns dbColumns, err := proc.schemaLoader.GetColumns(databaseName, schemaName, dbTable.TableName) if err != nil { log.Fatalln(err) return nil, err } // get the foreign key information var currentFk *ForeignKey dbForeignKeys, err := proc.schemaLoader.GetForeignKeys(databaseName, schemaName, dbTable.TableName) for _, fk := range dbForeignKeys { if currentFk == nil { currentFk = proc.populateFk(&table, fk) table.ForeignKeys = append(table.ForeignKeys, currentFk) } else { if currentFk.DatabaseName == fk.UqTableCatalog && currentFk.SchemaName == fk.UqTableSchema && currentFk.TableName == fk.UqTableName { currentFk.FkColumns = append(currentFk.FkColumns, fk.FkColumnName) currentFk.UkColumns = append(currentFk.UkColumns, fk.UqColumnName) } else { currentFk = proc.populateFk(&table, fk) table.ForeignKeys = append(table.ForeignKeys, currentFk) } } } for _, dbColumn := range dbColumns { // get the primay and unique key column usage keyColumns, err := proc.schemaLoader.GetColumnKeyUsage(databaseName, schemaName, dbTable.TableName, dbColumn.ColumnName) if err != nil { log.Fatalln(err) return nil, err } sanitisedColumnName := toCapitalCase(dbColumn.ColumnName) sanitisedColumnNameLowerCase := strings.ToLower(sanitisedColumnName) column := Column{ ColumnName: dbColumn.ColumnName, FieldName: sanitisedColumnName, FieldNameLowerCase: sanitisedColumnNameLowerCase, FieldType: dataType(dbColumn.DataType), DataType: dbColumn.DataType, IsNullable: false, IsPrimaryKeyColumn: false, HasDefault: false, } if dbColumn.CharacterMaximumLength.Valid { column.DataTypeSize = dbColumn.CharacterMaximumLength.Int64 } if dbColumn.IsNullable.Valid && dbColumn.IsNullable.String == "YES" { column.IsNullable = true } if dbColumn.ColumnDefault.Valid { column.HasDefault = true } for _, colKey := range keyColumns { if colKey.ConstraintType == "PRIMARY KEY" { column.IsPrimaryKeyColumn = true table.PrimaryKeyColumns = append(table.PrimaryKeyColumns, &column) } if colKey.ConstraintType == "UNIQUE" { column.IsUnique = true } } // assumption about sequence columns on postgres, if it has a default, is not nullable and is a primary key assume it is a sequence if column.HasDefault && column.IsPrimaryKeyColumn && !column.IsNullable { column.IsAutoIncrementColumn = true if column.DataType == "integer" { column.AutoIncrementDataType = "serial" table.SerialPrimaryKeyFieldType = "int" } else if column.DataType == "bigint" { column.AutoIncrementDataType = "bigserial" table.SerialPrimaryKeyFieldType = "int64" } table.SerialPrimaryKey = column.ColumnName table.SerialPrimaryKeyFieldName = column.FieldName } table.Columns = append(table.Columns, &column) if !column.IsAutoIncrementColumn { table.InsertColumns = append(table.InsertColumns, &column) table.UpdateColumns = append(table.UpdateColumns, &column) } } if len(table.PrimaryKeyColumns) > 0 { table.HasPrimaryKeys = true } tables = append(tables, table) } return tables, err }
// RightNamePlural returns the pluralized version // of the "child" of the m2m relationship. func (m *ManyToManyDefinition) RightNamePlural() string { return inflect.Pluralize(m.Right.ModelName) }
func (m *ManyToManyDefinition) LeftNamePlural() string { return inflect.Pluralize(m.Left.Name) }
// TableName returns the TableName of the struct. func (f RelationalModelDefinition) TableName() string { return inflect.Underscore(inflect.Pluralize(f.ModelName)) }
func init() { funcMap = template.FuncMap{ "urlize": helpers.URLize, "sanitizeURL": helpers.SanitizeURL, "sanitizeurl": helpers.SanitizeURL, "eq": Eq, "ne": Ne, "gt": Gt, "ge": Ge, "lt": Lt, "le": Le, "dict": Dictionary, "in": In, "slicestr": Slicestr, "substr": Substr, "split": Split, "intersect": Intersect, "isSet": IsSet, "isset": IsSet, "echoParam": ReturnWhenSet, "safeHTML": SafeHTML, "safeCSS": SafeCSS, "safeURL": SafeURL, "absURL": func(a string) template.HTML { return template.HTML(helpers.AbsURL(a)) }, "relURL": func(a string) template.HTML { return template.HTML(helpers.RelURL(a)) }, "markdownify": Markdownify, "first": First, "last": Last, "after": After, "where": Where, "delimit": Delimit, "sort": Sort, "highlight": Highlight, "add": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '+') }, "sub": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '-') }, "div": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '/') }, "mod": Mod, "mul": func(a, b interface{}) (interface{}, error) { return doArithmetic(a, b, '*') }, "modBool": ModBool, "lower": func(a string) string { return strings.ToLower(a) }, "upper": func(a string) string { return strings.ToUpper(a) }, "title": func(a string) string { return strings.Title(a) }, "partial": Partial, "ref": Ref, "relref": RelRef, "apply": Apply, "chomp": Chomp, "replace": Replace, "trim": Trim, "dateFormat": DateFormat, "getJSON": GetJSON, "getCSV": GetCSV, "readDir": ReadDir, "seq": helpers.Seq, "getenv": func(varName string) string { return os.Getenv(varName) }, "base64Decode": Base64Decode, "base64Encode": Base64Encode, "pluralize": func(in interface{}) (string, error) { word, err := cast.ToStringE(in) if err != nil { return "", err } return inflect.Pluralize(word), nil }, "singularize": func(in interface{}) (string, error) { word, err := cast.ToStringE(in) if err != nil { return "", err } return inflect.Singularize(word), nil }, } }
func doTestSectionNaming(t *testing.T, canonify, uglify, pluralize bool) { hugofs.DestinationFS = new(afero.MemMapFs) viper.Reset() defer viper.Reset() viper.Set("baseurl", "http://auth/sub/") viper.Set("DefaultExtension", "html") viper.Set("UglyURLs", uglify) viper.Set("PluralizeListTitles", pluralize) viper.Set("CanonifyURLs", canonify) var expectedPathSuffix string if uglify { expectedPathSuffix = ".html" } else { expectedPathSuffix = "/index.html" } sources := []source.ByteSource{ {filepath.FromSlash("sect/doc1.html"), []byte("doc1")}, {filepath.FromSlash("Fish and Chips/doc2.html"), []byte("doc2")}, {filepath.FromSlash("ラーメン/doc3.html"), []byte("doc3")}, } s := &Site{ Source: &source.InMemorySource{ByteSource: sources}, Targets: targetList{Page: &target.PagePub{UglyURLs: uglify}}, } s.initializeSiteInfo() templatePrep(s) must(s.addTemplate("_default/single.html", "{{.Content}}")) must(s.addTemplate("_default/list.html", "{{ .Title }}")) createAndRenderPages(t, s) s.RenderSectionLists() tests := []struct { doc string pluralAware bool expected string }{ {filepath.FromSlash(fmt.Sprintf("sect/doc1%s", expectedPathSuffix)), false, "doc1"}, {filepath.FromSlash(fmt.Sprintf("sect%s", expectedPathSuffix)), true, "Sect"}, {filepath.FromSlash(fmt.Sprintf("fish-and-chips/doc2%s", expectedPathSuffix)), false, "doc2"}, {filepath.FromSlash(fmt.Sprintf("fish-and-chips%s", expectedPathSuffix)), true, "Fish and Chips"}, {filepath.FromSlash(fmt.Sprintf("ラーメン/doc3%s", expectedPathSuffix)), false, "doc3"}, {filepath.FromSlash(fmt.Sprintf("ラーメン%s", expectedPathSuffix)), true, "ラーメン"}, } for _, test := range tests { file, err := hugofs.DestinationFS.Open(test.doc) if err != nil { t.Fatalf("Did not find %s in target: %s", test.doc, err) } content := helpers.ReaderToString(file) if test.pluralAware && pluralize { test.expected = inflect.Pluralize(test.expected) } if content != test.expected { t.Errorf("%s content expected:\n%q\ngot:\n%q", test.doc, test.expected, content) } } }
var FuncMap template.FuncMap = map[string]interface{}{ "pascalize": func(arg string) string { if len(arg) == 0 || arg[0] > '9' { return swag.ToGoName(arg) } return swag.ToGoName("Nr " + arg) }, "camelize": swag.ToJSONName, "humanize": swag.ToHumanNameLower, "snakize": swag.ToFileName, "dasherize": swag.ToCommandName, "pluralizeFirstWord": func(arg string) string { sentence := strings.Split(arg, " ") if len(sentence) == 1 { return inflect.Pluralize(arg) } return inflect.Pluralize(sentence[0]) + " " + strings.Join(sentence[1:], " ") }, "json": asJSON, "hasInsecure": func(arg []string) bool { return swag.ContainsStringsCI(arg, "http") || swag.ContainsStringsCI(arg, "ws") }, "hasSecure": func(arg []string) bool { return swag.ContainsStringsCI(arg, "https") || swag.ContainsStringsCI(arg, "wss") }, "stripPackage": func(str, pkg string) string { parts := strings.Split(str, ".") strlen := len(parts) if strlen > 0 {
func (p *Parser) Parse(info types.Info) (err error) { for ident, obj := range info.Defs { if ident.Obj == nil { continue } switch ident.Obj.Kind { case ast.Con: p.Consts[obj.Name()], err = strconv.Unquote(info.Types[ident.Obj.Decl.(*ast.ValueSpec).Values[0]].Value.String()) if err != nil { return } case ast.Typ: struc, ok := obj.Type().Underlying().(*types.Struct) if !ok { continue } var table Table // table.struc = node table.Name = ident.Name table.RefName = strings.ToLower(ident.Name[:1]) table.VarName = strings.ToLower(ident.Name[:1]) + ident.Name[1:] table.ColName = inflect.Pluralize(table.Name) table.ColRefName = inflect.Pluralize(table.RefName) table.ColVarName = inflect.Pluralize(table.VarName) table.SQLName = inflect.Pluralize(toSnake(table.Name)) + TableNameSuffix for i := 0; i < struc.NumFields(); i++ { field := struc.Field(i) flags := strings.Split(reflect.StructTag(struc.Tag(i)).Get("go2sql"), ",") var column Column column.Name = field.Name() column.field = field column.flags = flags column.Table = &table column.parser = p if len(flags) > 0 && flags[0] != "" { if flags[0] == FlagIgnore { continue } column.SQLName = flags[0] } else { column.SQLName = toSnake(column.Name) } _, column.IsPointer = field.Type().(*types.Pointer) if contains(flags, FlagID) { table.IDColumn = &column } if contains(flags, FlagPK) { column.IsPrimaryKey = true table.PrimaryKeys = append(table.PrimaryKeys, &column) } column.Type = types.TypeString(field.Type(), p.Qualifier) column.IsTable, column.TableType, column.Relationship = p.IsTable(field.Type()) if column.IsTable && contains(flags, FlagInline) { column.IsTable = false } table.Columns = append(table.Columns, &column) } p.Tables[table.Name] = &table } } for _, host := range p.Tables { if name, ok := p.Consts[host.Name+TableNameSuffix]; ok { host.HasCustomSQLName = true host.SQLName = name } for _, hostc := range host.Columns { if !hostc.IsTable { continue } guest := p.Tables[hostc.TableType] if guest == nil { log.Printf("can't found struct %s\n", hostc.TableType) continue } hostc.TypeTable = guest if hostc.Relationship == RelationshipHasOne { // reanalyze if it's a valid belongs-to belongsTo := true for _, pk := range guest.PrimaryKeys { // TODO: custome primary key naming belongsTo = belongsTo && host.HasColumn(hostc.Name+pk.Name) } if belongsTo { hostc.Relationship = RelationshipBelongsTo continue } // reanalyze if it's a valid has-one hasOne := true for _, pk := range host.PrimaryKeys { // TODO: custome primary key naming hasOne = hasOne && guest.HasColumn(host.Name+pk.Name) } if !hasOne { hostc.Relationship = RelationshipNone } } else if hostc.Relationship == RelationshipHasMany { hasMany := true for _, pk := range host.PrimaryKeys { // TODO: custome primary key naming hasMany = hasMany && guest.HasColumn(host.Name+pk.Name) } if !hasMany { hostc.Relationship = RelationshipNone continue } many2Many := true for _, pk := range guest.PrimaryKeys { // TODO: custome primary key naming many2Many = many2Many && host.HasColumn(guest.Name+pk.Name) } if many2Many { hostc.Relationship = RelationshipManyToMany } } } } return }
func (c *collector) needPlural(name string) { c.add(pluralType{ Name: inflect.Pluralize(name), Type: name, }) }
func (s *Site) newSectionListNode(sectionName, section string, data WeightedPages) *Node { n := s.NewNode() sectionName = helpers.FirstUpper(sectionName) if viper.GetBool("PluralizeListTitles") { n.Title = inflect.Pluralize(sectionName) } else { n.Title = sectionName } s.setURLs(n, section) n.Date = data[0].Page.Date n.Lastmod = data[0].Page.Lastmod n.Data["Pages"] = data.Pages() return n }