Best Gauge code snippet using refactor.Info
iworkstepservice.go
Source:iworkstepservice.go
...15 "isoft/isoft_iwork_web/models"16 "strings"17 "time"18)19func LoadResourceInfo() *iworkmodels.ParamOutputSchema {20 pos := &iworkmodels.ParamOutputSchema{21 ParamOutputSchemaItems: []iworkmodels.ParamOutputSchemaItem{},22 }23 resources := models.QueryAllResource()24 for _, resource := range resources {25 pos.ParamOutputSchemaItems = append(pos.ParamOutputSchemaItems, iworkmodels.ParamOutputSchemaItem{26 ParamName: resource.ResourceName,27 })28 }29 return pos30}31func LoadWorkInfo() *iworkmodels.ParamOutputSchema {32 pos := &iworkmodels.ParamOutputSchema{33 ParamOutputSchemaItems: []iworkmodels.ParamOutputSchemaItem{},34 }35 works := models.QueryAllWorkInfo(orm.NewOrm())36 for _, work := range works {37 pos.ParamOutputSchemaItems = append(pos.ParamOutputSchemaItems, iworkmodels.ParamOutputSchemaItem{38 ParamName: work.WorkName,39 })40 }41 return pos42}43func LoadGlobalVarInfo() *iworkmodels.ParamOutputSchema {44 pos := &iworkmodels.ParamOutputSchema{45 ParamOutputSchemaItems: []iworkmodels.ParamOutputSchemaItem{},46 }47 globalVars := models.QueryAllGlobalVar()48 for _, globalVar := range globalVars {49 pos.ParamOutputSchemaItems = append(pos.ParamOutputSchemaItems, iworkmodels.ParamOutputSchemaItem{50 ParamName: globalVar.Name,51 })52 }53 return pos54}55func LoadErrorInfo() *iworkmodels.ParamOutputSchema {56 pos := &iworkmodels.ParamOutputSchema{57 ParamOutputSchemaItems: []iworkmodels.ParamOutputSchemaItem{},58 }59 pos.ParamOutputSchemaItems = append(pos.ParamOutputSchemaItems, iworkmodels.ParamOutputSchemaItem{ParamName: "isError"})60 pos.ParamOutputSchemaItems = append(pos.ParamOutputSchemaItems, iworkmodels.ParamOutputSchemaItem{ParamName: "isNoError"})61 pos.ParamOutputSchemaItems = append(pos.ParamOutputSchemaItems, iworkmodels.ParamOutputSchemaItem{ParamName: "errorMsg"})62 pos.ParamOutputSchemaItems = append(pos.ParamOutputSchemaItems, iworkmodels.ParamOutputSchemaItem{ParamName: "insensitiveErrorMsg"})63 return pos64}65// å è½½åç½®èç¹è¾åºåæ°66func LoadPreNodeOutputService(serviceArgs map[string]interface{}) (result map[string]interface{}, err error) {67 result = make(map[string]interface{}, 0)68 work_id := serviceArgs["work_id"].(int64)69 work_step_id := serviceArgs["work_step_id"].(int64)70 o := serviceArgs["o"].(orm.Ormer)71 prePosTreeNodeArr := make([]*iworkmodels.TreeNode, 0)72 // å è½½ resource åæ°73 pos := LoadResourceInfo()74 prePosTreeNodeArr = append(prePosTreeNodeArr, pos.RenderToTreeNodes("$RESOURCE"))75 // å è½½ work å76 pos = LoadWorkInfo()77 prePosTreeNodeArr = append(prePosTreeNodeArr, pos.RenderToTreeNodes("$WORK"))78 // å è½½ error åæ°79 pos = LoadErrorInfo()80 prePosTreeNodeArr = append(prePosTreeNodeArr, pos.RenderToTreeNodes("$Error"))81 // å è½½ globalVar åæ°82 pos = LoadGlobalVarInfo()83 prePosTreeNodeArr = append(prePosTreeNodeArr, pos.RenderToTreeNodes("$Global"))84 // å è½½åç½®æ¥éª¤è¾åº85 if steps, err := models.QueryAllPreStepInfo(work_id, work_step_id, o); err == nil {86 // å½åæ¥éª¤ä¿¡æ¯87 currentWorkStep, _ := models.QueryWorkStepInfo(work_id, work_step_id, orm.NewOrm())88 // æææ¥éª¤ä¿¡æ¯89 allSteps, _ := models.QueryAllWorkStepInfo(work_id, orm.NewOrm())90 parser := &block.BlockParser{Steps: allSteps}91 _, blockStepMapper := parser.ParseToBlockSteps()92 currentBlockStep := blockStepMapper[currentWorkStep.WorkStepId]93 for _, step := range steps {94 // å¤æåç½® step å¨åèå´å
æ¯å¦æ¯å¯è®¿é®ç,ä¸æ¯å¦é defer æ¥éª¤95 if block.CheckBlockAccessble(currentBlockStep, step.WorkStepId) && step.IsDefer != "true" {96 pos := node.GetCacheParamOutputSchema(&step)97 prePosTreeNodeArr = append(prePosTreeNodeArr, pos.RenderToTreeNodes("$"+step.WorkStepName))98 }99 }100 }101 // è¿åç»æ102 result["prePosTreeNodeArr"] = prePosTreeNodeArr103 return104}105func GetAllWorkStepInfoService(serviceArgs map[string]interface{}) (result map[string]interface{}, err error) {106 result = make(map[string]interface{}, 0)107 work_id := serviceArgs["work_id"].(int64)108 o := serviceArgs["o"].(orm.Ormer)109 steps, err := models.QueryAllWorkStepInfo(work_id, o)110 if err != nil {111 return nil, err112 }113 result["steps"] = steps114 return115}116func LoadWorkStepInfoService(serviceArgs map[string]interface{}) (result map[string]interface{}, err error) {117 result = make(map[string]interface{}, 0)118 work_id := serviceArgs["work_id"].(int64)119 work_step_id := serviceArgs["work_step_id"].(int64)120 o := serviceArgs["o"].(orm.Ormer)121 // 读å work_step ä¿¡æ¯122 step, err := models.QueryWorkStepInfo(work_id, work_step_id, o)123 if err != nil {124 return nil, err125 }126 var paramMappingsArr []iworkmodels.ParamMapping127 json.Unmarshal([]byte(step.WorkStepParamMapping), ¶mMappingsArr)128 result["step"] = step129 result["paramInputSchema"] = node.GetCacheParamInputSchema(&step)130 result["paramOutputSchema"] = node.GetCacheParamOutputSchema(&step)131 result["paramOutputSchemaTreeNode"] = node.GetCacheParamOutputSchema(&step).RenderToTreeNodes("output")132 result["paramMappings"] = paramMappingsArr133 return134}135func CopyWorkStepByWorkStepIdService(serviceArgs map[string]interface{}) error {136 work_id := serviceArgs["work_id"].(int64)137 work_step_id := serviceArgs["work_step_id"].(int64)138 o := serviceArgs["o"].(orm.Ormer)139 step, err := models.QueryOneWorkStep(work_id, work_step_id, o)140 if err != nil {141 return err142 }143 step.Id = 0144 step.WorkStepId = step.WorkStepId + 1145 step.WorkStepName = step.WorkStepName + "_copy"146 return insertWorkStepAfter(work_id, work_step_id, &step, o)147}148func insertWorkStepAfter(work_id, work_step_id int64, step *models.WorkStep, o orm.Ormer) error {149 // å° work_step_id ä¹åçææèç¹å移ä¸ä½150 if err := models.BatchChangeWorkStepIdOrder(work_id, work_step_id, "+", o); err != nil {151 return err152 }153 _, err := models.InsertOrUpdateWorkStep(step, o)154 return err155}156func DeleteWorkStepByWorkStepIdService(serviceArgs map[string]interface{}) error {157 work_id := serviceArgs["work_id"].(int64)158 work_step_id := serviceArgs["work_step_id"].(int64)159 o := serviceArgs["o"].(orm.Ormer)160 if step, err := models.QueryWorkStepInfo(work_id, work_step_id, o); err == nil {161 if step.WorkStepType == "work_start" || step.WorkStepType == "work_end" {162 return errors.New("start èç¹å end èç¹ä¸è½è¢«å é¤!")163 }164 }165 if err := models.DeleteWorkStepByWorkStepId(work_id, work_step_id, o); err != nil {166 return err167 }168 return nil169}170func WorkStepListService(serviceArgs map[string]interface{}) (result map[string]interface{}, err error) {171 result = make(map[string]interface{}, 0)172 condArr := make(map[string]interface{})173 condArr["work_id"] = serviceArgs["work_id"].(int64)174 o := serviceArgs["o"].(orm.Ormer)175 worksteps, err := models.QueryWorkStep(condArr, o)176 if err != nil {177 return nil, err178 }179 result["worksteps"] = worksteps180 return181}182func AddWorkStepService(serviceArgs map[string]interface{}) error {183 work_id := serviceArgs["work_id"].(int64)184 work_step_id := serviceArgs["work_step_id"].(int64)185 work_step_meta := serviceArgs["work_step_meta"].(string)186 o := serviceArgs["o"].(orm.Ormer)187 // end èç¹ä¹åä¸è½æ·»å èç¹188 if step, err := models.QueryWorkStepInfo(work_id, work_step_id, o); err == nil {189 if step.WorkStepType == "work_end" {190 return errors.New("ä¸è½å end èç¹åé¢æ·»å èç¹!")191 }192 }193 if strings.HasPrefix(work_step_meta, "work_type__") {194 work_step_type := strings.TrimPrefix(work_step_meta, "work_type__")195 step := models.WorkStep{196 WorkId: work_id,197 WorkStepName: work_step_type + "_" + fmt.Sprintf("%v", time.Now().Unix()),198 WorkStepType: work_step_type,199 WorkStepDesc: "",200 IsDefer: "false", // é»è®¤ä¸å»¶è¿æ§è¡201 WorkStepIndent: 0, // é»è®¤ç¼©è¿çº§å«ä¸º 0202 WorkStepId: work_step_id + 1,203 CreatedBy: "SYSTEM",204 CreatedTime: time.Now(),205 LastUpdatedBy: "SYSTEM",206 LastUpdatedTime: time.Now(),207 }208 return insertWorkStepAfter(work_id, work_step_id, &step, o)209 } else if strings.HasPrefix(work_step_meta, "work_name__") {210 subWorkName := strings.TrimPrefix(work_step_meta, "work_name__")211 workStepName := strings.Join([]string{iworkconst.NODE_TYPE_WORK_SUB, subWorkName,212 fmt.Sprintf("%v", time.Now().Unix())}, "_")213 step := models.WorkStep{214 WorkId: work_id,215 WorkStepName: workStepName,216 WorkStepType: iworkconst.NODE_TYPE_WORK_SUB,217 WorkStepInput: framework.PrepareEmptyInputForWorkSub(subWorkName).RenderToJson(),218 WorkStepDesc: "",219 IsDefer: "false", // é»è®¤ä¸å»¶è¿æ§è¡220 WorkStepIndent: 0, // é»è®¤ç¼©è¿çº§å«ä¸º 0221 WorkStepId: work_step_id + 1,222 CreatedBy: "SYSTEM",223 CreatedTime: time.Now(),224 LastUpdatedBy: "SYSTEM",225 LastUpdatedTime: time.Now(),226 }227 if err := insertWorkStepAfter(work_id, work_step_id, &step, o); err == nil {228 // å¨ææ建è¾å
¥è¾åº229 BuildDynamic(work_id, step.WorkStepId, step, o)230 } else {231 return err232 }233 }234 return nil235}236// æ´æ¹é»è¿ä¸¤ä¸ªèç¹ç顺åº237func changeNearWorkStepOrder(work_id, work_step_id int64, o orm.Ormer, nearStepLength int64) error {238 // è·åå½åæ¥éª¤239 step, err := models.QueryOneWorkStep(work_id, work_step_id, o)240 if err != nil {241 return err242 }243 // è·åé»è¿æ¥éª¤244 nearStep, err := models.QueryOneWorkStep(work_id, work_step_id-nearStepLength, o)245 if err != nil {246 return err247 }248 if nearStep.WorkStepType == "work_start" || nearStep.WorkStepType == "work_end" {249 return errors.New("start èç¹å end èç¹ä¸è½ç§»å¨ä½ç½®!")250 }251 nearStep.WorkStepId = nearStep.WorkStepId + nearStepLength252 step.WorkStepId = step.WorkStepId - nearStepLength253 // æ´æ°é»è¿æ¥éª¤254 if _, err := models.InsertOrUpdateWorkStep(&nearStep, o); err != nil {255 return err256 }257 // æ´æ°å½åæ¥éª¤258 if _, err := models.InsertOrUpdateWorkStep(&step, o); err != nil {259 return err260 }261 return nil262}263func ChangeWorkStepOrderService(serviceArgs map[string]interface{}) error {264 work_id := serviceArgs["work_id"].(int64)265 work_step_id := serviceArgs["work_step_id"].(int64)266 _type := serviceArgs["_type"].(string)267 o := serviceArgs["o"].(orm.Ormer)268 if _type == "up" {269 return changeNearWorkStepOrder(work_id, work_step_id, o, 1)270 } else {271 return changeNearWorkStepOrder(work_id, work_step_id, o, -1)272 }273 return nil274}275func EditWorkStepBaseInfoService(serviceArgs map[string]interface{}) error {276 o := serviceArgs["o"].(orm.Ormer)277 step, err := models.QueryOneWorkStep(serviceArgs["work_id"].(int64), serviceArgs["work_step_id"].(int64), o)278 if err != nil {279 return err280 }281 old_work_step_name := step.WorkStepName282 old_work_step_type := step.WorkStepType283 // æ¿æ¢ææ°å¼284 step.WorkStepName = serviceArgs["work_step_name"].(string)285 step.WorkStepType = serviceArgs["work_step_type"].(string)286 step.WorkStepDesc = serviceArgs["work_step_desc"].(string)287 step.IsDefer = serviceArgs["is_defer"].(string)288 // åæ´ç±»åéè¦ç½®ç©º input å output åæ°289 if step.WorkStepType != old_work_step_type {290 step.WorkStepInput = ""291 step.WorkStepOutput = ""292 }293 if _, err := models.InsertOrUpdateWorkStep(&step, o); err != nil {294 return err295 }296 // 级èæ´æ¹ç¸å
³èçæ¥éª¤å称297 if err := ChangeReferencesWorkStepName(step.WorkId, old_work_step_name, step.WorkStepName, o); err != nil {298 return err299 }300 return nil301}302func ChangeReferencesWorkStepName(work_id int64, oldWorkStepName, workStepName string, o orm.Ormer) error {303 if oldWorkStepName == workStepName {304 return nil305 }306 steps, err := models.QueryAllWorkStepInfo(work_id, o)307 if err != nil {308 return err309 }310 for _, step := range steps {311 step.WorkStepInput = strings.Replace(step.WorkStepInput, "$"+oldWorkStepName, "$"+workStepName, -1)312 _, err := models.InsertOrUpdateWorkStep(&step, o)313 if err != nil {314 return err315 }316 }317 return nil318}319func createSubWork(refactor_worksub_name string, o orm.Ormer) (int64, error) {320 // å建åæµç¨321 subWork := &models.Work{322 WorkName: refactor_worksub_name,323 WorkDesc: "refactor worksub",324 CreatedBy: "SYSTEM",325 CreatedTime: time.Now(),326 LastUpdatedBy: "SYSTEM",327 LastUpdatedTime: time.Now(),328 }329 if _, err := models.InsertOrUpdateWork(subWork, o); err != nil {330 return -1, err331 }332 // 为åæµç¨æ·»å å¼å§åç»æèç¹333 if err := InsertStartEndWorkStepNode(subWork.Id, o); err != nil {334 return -1, err335 }336 return subWork.Id, nil337}338func getRefactorWorkStep(work_id, work_step_id int64, o orm.Ormer) (step models.WorkStep, err error) {339 step, err = models.QueryWorkStepInfo(work_id, int64(work_step_id), o)340 if err != nil {341 return342 }343 if step.WorkStepType == "work_start" || step.WorkStepType == "work_end" {344 return step, errors.New("start å end èç¹ä¸è½éæï¼")345 }346 return step, nil347}348func refactorSubWork(refactorStep models.WorkStep, subWorkId int64, o orm.Ormer) error {349 // å°åæµç¨ start èç¹åé¢ææçæ¥éª¤ id é¡ºåº + 1350 err := models.BatchChangeWorkStepIdOrder(subWorkId, 1, "+", o)351 if err != nil {352 return err353 }354 newStep := models.CopyWorkStepInfo(refactorStep)355 newStep.WorkId = subWorkId356 newStep.WorkStepId = 2357 // å¨ 2 å·æ¥éª¤ä½ç½®æå
¥å½åæ¥éª¤358 if _, err := models.InsertOrUpdateWorkStep(newStep, o); err != nil {359 return err360 }361 return nil362}363func refactorCurrentWorkByDelete(refactorStep models.WorkStep, o orm.Ormer) error {364 _serviceArgs := map[string]interface{}{"work_id": refactorStep.WorkId, "work_step_id": refactorStep.WorkStepId, "o": o}365 return DeleteWorkStepByWorkStepIdService(_serviceArgs)366}367func refactorCurrentWorkByChangeToWorkSub(subWorkId int64, refactor_worksub_name string, refactorStep models.WorkStep, o orm.Ormer) error {368 // ä¿®æ¹ refactorStep çç±»å369 refactorStep.WorkStepType = "work_sub"370 // ä¿®æ¹ refactorStep ç subWorkId371 refactorStep.WorkSubId = subWorkId372 // ä¿®æ¹ refactorStep ç WorkStepInput373 factory := node.WorkStepFactory{WorkStep: &refactorStep}374 inputSchema := factory.GetDefaultParamInputSchema()375 for index, item := range inputSchema.ParamInputSchemaItems {376 if item.ParamName == iworkconst.STRING_PREFIX+"work_sub" {377 item.ParamValue = fmt.Sprintf("$WORK.%s;", refactor_worksub_name)378 inputSchema.ParamInputSchemaItems[index] = item379 break380 }381 }382 refactorStep.WorkStepOutput = (&iworkmodels.ParamOutputSchema{}).RenderToJson() // è¾åºç½®ç©º383 refactorStep.WorkStepInput = inputSchema.RenderToJson()384 if _, err := models.InsertOrUpdateWorkStep(&refactorStep, o); err != nil {385 return err386 }387 return nil388}389func BatchChangeIndentService(serviceArgs map[string]interface{}) error {390 work_id := serviceArgs["work_id"].(int64)391 mod := serviceArgs["mod"].(string)392 indent_work_step_ids := serviceArgs["indent_work_step_ids"].(string)393 o := serviceArgs["o"].(orm.Ormer)394 var indent_work_step_id_arr []int395 json.Unmarshal([]byte(indent_work_step_ids), &indent_work_step_id_arr)396 for _, work_step_id := range indent_work_step_id_arr {397 if step, err := models.QueryWorkStepInfo(work_id, int64(work_step_id), o); err == nil {398 if mod == "left" && step.WorkStepIndent > 0 {399 step.WorkStepIndent -= 1400 } else if mod == "right" {401 step.WorkStepIndent += 1402 }403 if _, err := models.InsertOrUpdateWorkStep(&step, o); err != nil {404 return err405 }406 }407 }408 return nil409}410func RefactorWorkStepInfoService(serviceArgs map[string]interface{}) error {411 // è·ååæ°412 work_id := serviceArgs["work_id"].(int64)413 refactor_worksub_name := serviceArgs["refactor_worksub_name"].(string)414 refactor_work_step_ids := serviceArgs["refactor_work_step_ids"].(string)415 o := serviceArgs["o"].(orm.Ormer)416 var refactor_work_step_id_arr []int417 json.Unmarshal([]byte(refactor_work_step_ids), &refactor_work_step_id_arr)418 // æ ¡éª refactor_work_step_id_arr æ¯å¦è¿ç»419 if refactor_work_step_id_arr[len(refactor_work_step_id_arr)-1]-refactor_work_step_id_arr[0] != len(refactor_work_step_id_arr)-1 {420 return errors.New("refactor workStepId å¿
é¡»æ¯è¿ç»ç!")421 }422 // å建åæµç¨423 subWorkId, err := createSubWork(refactor_worksub_name, o)424 if err != nil {425 return err426 }427 // 循ç¯ç§»å¨åæ¥éª¤,移å¨ä¸ä¸ªå é¤ä¸ä¸ª,å转slice,ä» id 大çå¼å§æ§è¡428 for index, work_step_id := range datatypeutil.ReverseSlice(refactor_work_step_id_arr).([]int) {429 refactorStep, err := getRefactorWorkStep(work_id, int64(work_step_id), o)430 if err != nil {431 return err432 }433 if err := refactorSubWork(refactorStep, subWorkId, o); err != nil {434 return err435 }436 if index == len(refactor_work_step_id_arr)-1 {437 // æåä¸æ¬¡æä½ä¸åæ¯å é¤,èæ¯æ¿æ¢æåèç¹438 if err := refactorCurrentWorkByChangeToWorkSub(subWorkId, refactor_worksub_name, refactorStep, o); err != nil {439 return err440 }441 } else {442 // å é¤èç¹443 if err := refactorCurrentWorkByDelete(refactorStep, o); err != nil {444 return err445 }446 }447 }448 return nil449}450func formatChecker(paramInputSchema *iworkmodels.ParamInputSchema) error {451 for _, item := range paramInputSchema.ParamInputSchemaItems {452 formatChecker := iworkvalid.ParamValueFormatChecker{453 ParamName: item.ParamName,454 PureText: item.PureText,455 ParamValue: item.ParamValue,456 }457 if ok, err := formatChecker.Check(); !ok && err != nil {458 return err459 }460 }461 return nil462}463func EditWorkStepParamInfo(serviceArgs map[string]interface{}) error {464 var (465 step models.WorkStep466 err error467 )468 work_id := serviceArgs["work_id"].(int64)469 work_step_id := serviceArgs["work_step_id"].(int64)470 paramInputSchemaStr := serviceArgs["paramInputSchemaStr"].(string)471 o := serviceArgs["o"].(orm.Ormer)472 if step, err = models.QueryOneWorkStep(work_id, work_step_id, o); err != nil {473 return err474 }475 paramInputSchema, _ := iworkmodels.ParseToParamInputSchema(paramInputSchemaStr)476 if err = formatChecker(paramInputSchema); err != nil {477 return err478 }479 // ä¿åå®éæåæ°åèªå¨æ建è·å¨æåæ°å¹¶ä¿å480 BuildDynamic(work_id, work_step_id, step, o)481 // ç¼è¾å¼å§æç»æèç¹æ¶éè¦éç¥è°åº¦æµç¨éæ° BuildDynamic482 if step.WorkStepType == iworkconst.NODE_TYPE_WORK_START || step.WorkStepType == iworkconst.NODE_TYPE_WORK_END {483 BuildParentWork(work_id, step, o)484 }485 return nil486}487func BuildParentWork(work_id int64, step models.WorkStep, o orm.Ormer) {488 if workSteps, _, _, err := models.QueryParentWorks(work_id, o); err == nil {489 for _, workStep := range workSteps {490 BuildDynamic(workStep.WorkId, workStep.WorkStepId, step, o)491 }492 }493}494// æ建å¨æå¼,æ¯æ¬¡ build ä¹åéè¦é读 step ä¿¡æ¯495func BuildDynamic(work_id int64, work_step_id int64, step models.WorkStep, o orm.Ormer) {496 step, _ = models.QueryWorkStepInfo(work_id, work_step_id, o)497 // èªå¨å建åæµç¨498 iworkbuild.BuildAutoCreateSubWork(step, o, InsertStartEndWorkStepNode)499 step, _ = models.QueryWorkStepInfo(work_id, work_step_id, o)500 // æ建å¨æè¾å
¥å¼501 iworkbuild.BuildDynamicInput(step, o)502 step, _ = models.QueryWorkStepInfo(work_id, work_step_id, o)503 // æ建å¨æè¾åºå¼504 iworkbuild.BuildDynamicOutput(step, o)505}...
mvcode.go
Source:mvcode.go
...24 if !ok {25 return26 }27 _, havePkgDot := stack[1].(*ast.SelectorExpr)28 obj := srcPkg.TypesInfo.Uses[id]29 if obj == nil {30 return31 }32 objPkg := obj.Pkg()33 if objPkg == nil {34 return35 }36 if obj.Parent() != objPkg.Scope() {37 // Not a package-scope variable.38 return39 }40 if mp := moves[obj]; mp != nil {41 objPkg = mp.Types42 }43 if havePkgDot {44 ed.Delete(stack[1].Pos(), id.Pos())45 }46 if objPkg == dstPkg.Types {47 // Need to remove qualifier if any, make sure name is not shadowed.48 // (For moving globals, shadowed would mean a duplicate definition,49 // which should be caught earlier but may not be.)50 if found := snap.LookupAt(id.Name, dst); found != nil && found != obj {51 snap.ErrorAt(dst, "%s is already declared\n\t%s: previous declaration", id.Name, snap.Addr(found.Pos()))52 }53 } else {54 name := snap.NeedImport(dst, "", objPkg)55 ed.Insert(id.Pos(), name+".")56 }57 })58 return ed.String()59}60// mvCode moves the code described by srcs into dst.61func mvCode(snap *refactor.Snapshot, srcs []*refactor.Item, dst *refactor.Item, dstPkg *refactor.Package) (anyExported bool) {62 // Build list of what's moving.63 // Keep a list of the objects in files separately, so that we can avoid moving them twice.64 moves := make(map[types.Object]*refactor.Package)65 inFiles := make(map[types.Object]*refactor.Package)66 for _, src := range srcs {67 if src.Obj != nil {68 for _, obj := range declObjs(snap, src.Obj) {69 moves[obj] = dstPkg70 }71 continue72 }73 switch src.Kind {74 default:75 panic(fmt.Sprintf("unexpected src %v", src))76 case refactor.ItemFile:77 srcPkg, srcFile := snap.FileByName(src.Name)78 if srcFile == nil {79 snap.ErrorAt(token.NoPos, "cannot find file %s", src.Name)80 continue81 }82 recordFileMoves(srcPkg, srcFile, dstPkg, inFiles)83 case refactor.ItemDir:84 panic("mv dir not implemented")85 }86 }87 for obj, dst := range inFiles {88 moves[obj] = dst89 }90 remap := make(map[refactor.QualName]refactor.QualName)91 for obj, dst := range moves {92 path := obj.Pkg().Path()93 var src *refactor.Package94 for _, pp := range snap.Packages() {95 if pp.PkgPath == path {96 src = pp97 }98 }99 if src == nil {100 panic("LOST SRC: " + path)101 }102 name := obj.Name()103 if f, ok := obj.(*types.Func); ok && f.Type().(*types.Signature).Recv() != nil {104 typ := f.Type().(*types.Signature).Recv().Type()105 if ptr, ok := typ.(*types.Pointer); ok {106 typ = ptr.Elem()107 }108 name = typ.(*types.Named).Obj().Name() + "." + name109 }110 remap[refactor.QualName{src, name}] = refactor.QualName{dst, name}111 }112 g := snap.DepsGraph(refactor.SymRefs).Map(remap)113 if err := snap.CheckImportCycle(g); err != nil {114 snap.ErrorAt(token.NoPos, "mv ... %s: %v", dstPkg.PkgPath, err)115 return116 }117 done := make(map[types.Object]bool)118 for _, src := range srcs {119 if inFiles[src.Obj] != nil || done[src.Obj] {120 continue121 }122 if src.Obj != nil {123 srcPkg, srcFile := snap.FileAt(src.Obj.Pos())124 pos, end := declRange(snap, src.Obj)125 moveCode(snap, srcPkg, srcFile, pos, end, dst, dstPkg, moves)126 }127 switch src.Kind {128 case refactor.ItemFile:129 srcPkg, srcFile := snap.FileByName(src.Name)130 moveCode(snap, srcPkg, srcFile, 0, 0, dst, dstPkg, moves)131 case refactor.ItemDir:132 panic("mv dir not implemented")133 }134 }135 if dstPkg != snap.Target() {136 var structs []types.Type137 for obj := range moves {138 if obj, ok := obj.(*types.TypeName); ok {139 typ := obj.Type()140 if _, ok := typ.Underlying().(*types.Struct); ok {141 structs = append(structs, typ)142 }143 }144 }145 if len(structs) > 0 {146 keyLiterals(snap, structs)147 }148 }149 rewritePkgRefs(snap, moves)150 return true // TODO: better151}152func recordFileMoves(srcPkg *refactor.Package, file *ast.File, dstPkg *refactor.Package, moves map[types.Object]*refactor.Package) {153 for _, d := range file.Decls {154 switch d := d.(type) {155 default:156 panic(fmt.Sprintf("unexpected decl %T", d))157 case *ast.GenDecl:158 for _, spec := range d.Specs {159 switch spec := spec.(type) {160 default:161 panic(fmt.Sprintf("unexpected spec %T", spec))162 case *ast.ImportSpec:163 // ignore164 case *ast.ValueSpec:165 for _, id := range spec.Names {166 obj := srcPkg.TypesInfo.Defs[id]167 if obj == nil {168 panic("no obj for var/const")169 }170 moves[obj] = dstPkg171 }172 case *ast.TypeSpec:173 obj := srcPkg.TypesInfo.Defs[spec.Name]174 if obj == nil {175 panic("no obj for type")176 }177 moves[obj] = dstPkg178 }179 }180 case *ast.FuncDecl:181 obj := srcPkg.TypesInfo.Defs[d.Name]182 if obj == nil {183 panic("no obj for func")184 }185 moves[obj] = dstPkg186 }187 }188}189func moveCode(snap *refactor.Snapshot,190 srcPkg *refactor.Package, srcFile *ast.File,191 srcPos, srcEnd token.Pos,192 dst *refactor.Item, dstPkg *refactor.Package,193 moves map[types.Object]*refactor.Package) {194 // Decide destination file.195 if dst.Kind == refactor.ItemDir {196 // Reduce to file case.197 dst0 := *dst198 dst = &dst0199 dst.Kind = refactor.ItemFile200 dst.Name = filepath.Base(snap.Position(srcFile.Package).Filename)201 }202 if dst.Kind != refactor.ItemFile {203 panic("moveFile")204 }205 srcSplit := srcFile.Name.End() // just after package declaration206 srcHdrEnd := srcFile.Name.End()207 if len(srcFile.Imports) > 0 {208 srcHdrEnd = srcFile.Decls[0].Pos()209 for i := 0; i < len(srcFile.Decls) && isImportDecl(srcFile.Decls[i]); i++ {210 srcSplit = srcFile.Decls[i].End()211 }212 }213 srcStart, srcEOF := snap.FileRange(srcFile.Package)214 if srcPos == token.NoPos {215 srcPos = srcSplit216 srcEnd = srcEOF217 }218 var dstFile *ast.File219 for _, file := range dstPkg.Files {220 if file.Syntax == nil {221 // File was deleted.222 continue223 }224 if filepath.Base(snap.Position(file.Syntax.Pos()).Filename) == dst.Name {225 dstFile = file.Syntax226 break227 }228 }229 if dstFile == nil {230 text := string(snap.Text(srcStart, srcHdrEnd))231 text = text[:srcFile.Name.Pos()-srcStart] + dstPkg.Name + text[srcFile.Name.End()-srcStart:]232 dstFile = snap.CreateFile(dstPkg, dst.Name, text)233 }234 _, dstPos := snap.FileRange(dstFile.Package)235 snap.InsertAt(dstPos, "\n\n"+236 transplant(snap, string(snap.Text(srcPos, srcEnd)), srcPos, dstPos, moves))237 if srcPos == srcSplit && srcEnd == srcEOF {238 snap.DeleteFile(srcPos)239 } else {240 snap.ForceDeleteAt(srcPos, srcEnd)241 }242}243func rewritePkgRefs(snap *refactor.Snapshot, moves map[types.Object]*refactor.Package) {244 snap.ForEachFile(func(pkg *refactor.Package, file *ast.File) {245 refactor.Walk(file, func(stack []ast.Node) {246 id, ok := stack[0].(*ast.Ident)247 if !ok {248 return249 }250 obj := pkg.TypesInfo.Uses[id]251 if f, ok := obj.(*types.Func); ok && f.Type().(*types.Signature).Recv() != nil {252 return253 }254 newPkg := moves[obj]255 if newPkg == nil || newPkg.Types == obj.Pkg() {256 return257 }258 // obj is moving to a new package.259 if sel, ok := stack[1].(*ast.SelectorExpr); ok && sel.Sel == id {260 // obj is already otherPkg.Name; update to newPkg.Name.261 if newPkg == pkg {262 // Delete the no-longer-needed package qualifier.263 if xobj := snap.LookupAt(id.Name, id.Pos()); xobj != nil && xobj != obj {264 snap.ErrorAt(id.Pos(), "%s is shadowed at new unqualified use", id.Name)265 }266 snap.DeleteAt(sel.Pos(), id.Pos())267 } else {268 name := snap.NeedImport(id.Pos(), "", newPkg.Types)269 snap.ReplaceNode(sel.X, name)270 }271 } else if newPkg == pkg {272 // obj is moving to pkg but is already referred to in pkg without a qualifier.273 // Can happen if pkg imports the old location with a dot import.274 // Can't be shadowed or the reference wouldn't be to obj.275 // Do nothing.276 } else {277 // obj is moving to a new package and needs a qualified import.278 name := snap.NeedImport(id.Pos(), "", newPkg.Types)279 snap.InsertAt(id.Pos(), name+".")280 }281 })282 })283}284func isImportDecl(decl ast.Decl) bool {285 d, ok := decl.(*ast.GenDecl)286 return ok && d.Tok == token.IMPORT287}288func declRange(snap *refactor.Snapshot, obj types.Object) (pos, end token.Pos) {289 _, srcFile := snap.FileAt(obj.Pos())290 startFile, endFile := snap.FileRange(obj.Pos())291 text := snap.Text(startFile, endFile)292 pos = srcFile.Name.End()293 if int(pos-startFile) < len(text) && text[pos-startFile] == '\n' {294 pos++295 }296 d := codeDecl(snap, obj)297 pastEOL := func(pos token.Pos) token.Pos {298 p := pos299 for int(p-startFile) < len(text) && text[p-startFile] == ' ' {300 p++301 }302 if int(p-startFile)+2 <= len(text) && text[p-startFile] == '/' && text[p-startFile+1] == '/' {303 for int(p-startFile) < len(text) && text[p-startFile] != '\n' {304 p++305 }306 }307 if int(p-startFile) == len(text) {308 return p309 }310 if int(p-startFile) < len(text) && text[p-startFile] == '\n' {311 return p + 1312 }313 return pos314 }315 for i := 0; i < len(srcFile.Decls); i++ {316 if srcFile.Decls[i] == d {317 break318 }319 pos = pastEOL(srcFile.Decls[i].End())320 if int(pos-startFile) < len(text) && text[pos-startFile] == '\n' {321 pos++322 }323 }324 end = pastEOL(d.End())325 if int(end-startFile) < len(text) && text[end-startFile] == '\n' {326 end++327 }328 return pos, end329}330func declObjs(snap *refactor.Snapshot, obj types.Object) []types.Object {331 srcPkg, _ := snap.FileAt(obj.Pos())332 defs := srcPkg.TypesInfo.Defs333 var objs []types.Object334 switch d := codeDecl(snap, obj).(type) {335 default:336 panic(fmt.Sprintf("unexpected codeDecl %T", d))337 case *ast.GenDecl:338 for _, spec := range d.Specs {339 switch spec := spec.(type) {340 case *ast.ValueSpec:341 for _, id := range spec.Names {342 objs = append(objs, defs[id])343 }344 case *ast.TypeSpec:345 objs = append(objs, defs[spec.Name])346 }...
inject.go
Source:inject.go
...86 id, ok := stack[0].(*ast.Ident)87 if !ok || len(stack) < 2 {88 return89 }90 obj := pkg.TypesInfo.Uses[id]91 if converting[obj] == "" {92 return93 }94 if call, ok := stack[1].(*ast.CallExpr); ok && call.Fun == id {95 // ok96 return97 } else if sel, ok := stack[1].(*ast.SelectorExpr); ok && sel.Sel == id {98 if call, ok := stack[2].(*ast.CallExpr); ok && call.Fun == stack[1] {99 // ok100 return101 }102 }103 // snap.ErrorAt(id.Pos(), "%v not called - skipping conversion", obj)104 delete(converting, obj)105 })106 })107 snap.ForEachFile(func(pkg *refactor.Package, file *ast.File) {108 for _, decl := range file.Decls {109 if fn, ok := decl.(*ast.FuncDecl); ok {110 obj := pkg.TypesInfo.Defs[fn.Name]111 if obj == nil {112 fmt.Printf("MISSING %v\n", fn.Name)113 }114 if converting[obj] == "" {115 continue116 }117 // Determine a name for the parameter.118 uses := make(map[string]bool)119 refactor.Walk(fn.Body, func(stack []ast.Node) {120 if id, ok := stack[0].(*ast.Ident); ok {121 if sel, ok := stack[1].(*ast.SelectorExpr); ok && sel.Sel == id {122 return123 }124 if kv, ok := stack[1].(*ast.KeyValueExpr); ok && kv.Key == id {125 return126 }127 uses[id.Name] = true128 }129 })130 dst := fn.Type.Params.Opening + 1131 name := targetName132 for uses[name] {133 name += "_"134 }135 converting[obj] = name136 var b bytes.Buffer137 fmt.Fprintf(&b, "%s ", name)138 printType(&b, snap, targetObj.Pos(), dst, targetObj.Type())139 if len(fn.Type.Params.List) > 0 {140 b.WriteString(", ")141 }142 snap.InsertAt(dst, b.String())143 }144 }145 })146 snap.ForEachFile(func(pkg *refactor.Package, file *ast.File) {147 refactor.Walk(file, func(stack []ast.Node) {148 id, ok := stack[0].(*ast.Ident)149 if !ok || len(stack) < 2 {150 return151 }152 obj := pkg.TypesInfo.Uses[id]153 if converting[obj] == "" && obj != targetObj {154 return155 }156 // If inside a function body, stack[len-1] = *ast.File, stack[len-2] = *ast.FuncDecl.157 name := ""158 if fn, ok := stack[len(stack)-2].(*ast.FuncDecl); ok {159 fnobj := pkg.TypesInfo.Defs[fn.Name]160 name = converting[fnobj]161 }162 if obj == targetObj {163 if name != "" {164 pos := ast.Node(id)165 if sel, ok := stack[1].(*ast.SelectorExpr); ok && sel.Sel == id {166 pos = sel167 }168 snap.ReplaceNode(pos, name)169 }170 return171 }172 fixName := func() {173 if name == "" {...
Info
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 refactor.Info()5}6import "fmt"7func Info() {8 fmt.Println("Info")9}
Info
Using AI Code Generation
1import (2func main() {3 refactor.Info("This is an info message")4}5import "fmt"6func Info(message string) {7 fmt.Println(message)8}9import "fmt"10func Info(message string) {11 fmt.Println(message)12}13func main() {14 Info("This is an info message")15}
Info
Using AI Code Generation
1import (2func main() {3 refactor.Info()4 fmt.Println("Hello")5}6import "fmt"7func Info() {8 fmt.Println("This is refactor package")9}10import (11func main() {12 fmt.Printf("Now you have %g problems.", math.Nextafter(2, 3))13}14The import keyword is used to import packages in Go. The import keyword is used to import
Info
Using AI Code Generation
1import (2func main() {3refactor := new(Refactor)4refactor.Info()5}6import (7func main() {8refactor := new(Refactor)9refactor.Info()10}11import (12func main() {13refactor := new(Refactor)14refactor.Info()15}16import (17type Info interface {18GetInfo() string19}20type Refactor struct {21}22func (refactor *Refactor) GetInfo() string {23}24import (25func main() {26refactor := new(Refactor)27fmt.Println(refactor.GetInfo())28}29import (30func main() {31refactor := new(Refactor)32fmt.Println(refactor.GetInfo())33}34import (35func main() {36refactor := new(Refactor)37fmt.Println(refactor.GetInfo())38}
Info
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4 fmt.Println(x)5}6type Info struct {7}8import (9func TestInfo(t *testing.T) {10 if x.Name != "Name" {11 t.Errorf("Name is not set")12 }13 if x.Age != 10 {14 t.Errorf("Age is not set")15 }16}17{Name 10}
Info
Using AI Code Generation
1import (2func main() {3 fmt.Println("I am in main")4 r := refactor.New()5 r.Info()6}7import (8func main() {9 fmt.Println("I am in main")10 r := refactor.New()11 r.Info()12}13import (14func main() {15 fmt.Println("I am in main")16 r := refactor.New()17 r.Info()18}19import (20func main() {21 fmt.Println("I am in main")22 r := refactor.New()23 r.Info()24}25import (26func main() {27 fmt.Println("I am in main")28 r := refactor.New()29 r.Info()30}31import (32func main() {33 fmt.Println("I am in main")34 r := refactor.New()35 r.Info()36}37import (38func main() {39 fmt.Println("I am in main")40 r := refactor.New()41 r.Info()42}43import (44func main() {45 fmt.Println("I am in
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!