| 17 | ) |
| 18 | |
| 19 | func Completion(ctx context.Context, params *protocol.CompletionParams, manager *document.Manager, bakeDocument document.BakeHCLDocument) (*protocol.CompletionList, error) { |
| 20 | filename := string(params.TextDocument.URI) |
| 21 | |
| 22 | hclPos := parser.ConvertToHCLPosition(string(bakeDocument.Input()), int(params.Position.Line), int(params.Position.Character)) |
| 23 | candidates, err := bakeDocument.Decoder().CompletionAtPos(ctx, filename, hclPos) |
| 24 | if err != nil { |
| 25 | var rangeErr *decoder.PosOutOfRangeError |
| 26 | if errors.As(err, &rangeErr) { |
| 27 | return &protocol.CompletionList{Items: []protocol.CompletionItem{}}, nil |
| 28 | } |
| 29 | var positionalError *decoder.PositionalError |
| 30 | if !errors.As(err, &positionalError) { |
| 31 | return nil, fmt.Errorf("textDocument/completion encountered an error: %w", err) |
| 32 | } |
| 33 | } |
| 34 | body, ok := bakeDocument.File().Body.(*hclsyntax.Body) |
| 35 | if !ok { |
| 36 | return nil, errors.New("unrecognized body in HCL document") |
| 37 | } |
| 38 | |
| 39 | for _, b := range body.Blocks { |
| 40 | if b.Type == "target" && isInsideBodyRangeLines(b.Body, int(params.Position.Line)+1) { |
| 41 | attributes := b.Body.Attributes |
| 42 | if attribute, ok := attributes["inherits"]; ok && isInsideRange(attribute.Expr.Range(), params.Position) { |
| 43 | if tupleConsExpr, ok := attribute.Expr.(*hclsyntax.TupleConsExpr); ok { |
| 44 | if len(tupleConsExpr.Exprs) == 0 { |
| 45 | return createTargetBlockCompletionItems(body.Blocks, true), nil |
| 46 | } |
| 47 | |
| 48 | for _, e := range tupleConsExpr.Exprs { |
| 49 | if templateExpr, ok := e.(*hclsyntax.TemplateExpr); ok { |
| 50 | if templateExpr.IsStringLiteral() { |
| 51 | return createTargetBlockCompletionItems(body.Blocks, false), nil |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | if attribute, ok := attributes["network"]; ok && isInsideRange(attribute.Expr.Range(), params.Position) { |
| 59 | if expr, ok := attribute.Expr.(*hclsyntax.TemplateExpr); ok && len(expr.Parts) == 1 { |
| 60 | if _, ok := expr.Parts[0].(*hclsyntax.LiteralValueExpr); ok { |
| 61 | return &protocol.CompletionList{ |
| 62 | Items: []protocol.CompletionItem{ |
| 63 | {Label: "default"}, |
| 64 | {Label: "host"}, |
| 65 | {Label: "none"}, |
| 66 | }, |
| 67 | }, nil |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | if attribute, ok := attributes["dockerfile"]; ok && isInsideRange(attribute.Expr.Range(), params.Position) { |
| 73 | return fileStructureCompletionItems(bakeDocument, attribute.Expr, params.Position.Character, false) |
| 74 | } |
| 75 | |
| 76 | if attribute, ok := attributes["context"]; ok && isInsideRange(attribute.Expr.Range(), params.Position) { |