github.com/Odesyuk/pop@v4.13.1+incompatible/fix/auto_timestamps_off.go (about)

     1  package fix
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/gobuffalo/plush/ast"
     7  	"github.com/gobuffalo/plush/parser"
     8  )
     9  
    10  // AutoTimestampsOff adds a t.Timestamps() statement to fizz migrations
    11  // when they still use the implicit auto-timestamp old fizz feature.
    12  func AutoTimestampsOff(content string) (string, error) {
    13  	var p *ast.Program
    14  	var err error
    15  	if p, err = parser.Parse("<% " + content + "%>"); err != nil {
    16  		return "", err
    17  	}
    18  
    19  	var pt *ast.Program
    20  	if pt, err = parser.Parse("<% t.Timestamps() %>"); err != nil {
    21  		return "", err
    22  	}
    23  	ts := pt.Statements[0].(*ast.ExpressionStatement)
    24  
    25  	for _, s := range p.Statements {
    26  		stmt := s.(*ast.ExpressionStatement)
    27  		if function, ok := stmt.Expression.(*ast.CallExpression); ok {
    28  			if function.Function.TokenLiteral() == "create_table" {
    29  				args := function.Arguments
    30  				enableTimestamps := true
    31  				if len(args) > 1 {
    32  					if v, ok := args[1].(*ast.HashLiteral); ok {
    33  						if strings.Contains(v.String(), `"timestamps": false`) {
    34  							enableTimestamps = false
    35  						}
    36  					}
    37  				}
    38  				for _, bs := range function.Block.Statements {
    39  					bstmt := bs.(*ast.ExpressionStatement)
    40  					if f, ok := bstmt.Expression.(*ast.CallExpression); ok {
    41  						fs := f.Function.String()
    42  						if fs == "t.DisableTimestamps" || fs == "t.Timestamps" {
    43  							enableTimestamps = false
    44  						}
    45  					}
    46  				}
    47  				if enableTimestamps {
    48  					function.Block.Statements = append(function.Block.Statements, ts)
    49  				}
    50  			}
    51  		}
    52  	}
    53  
    54  	return p.String(), nil
    55  }