Home | History | Annotate | Download | only in processors
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.google.currysrc.processors;
     17 
     18 import com.google.currysrc.api.process.Context;
     19 import com.google.currysrc.api.process.Processor;
     20 
     21 import org.eclipse.jdt.core.dom.ASTVisitor;
     22 import org.eclipse.jdt.core.dom.CompilationUnit;
     23 import org.eclipse.jdt.core.dom.StringLiteral;
     24 import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
     25 
     26 /**
     27  * Changes any string literals in the AST that start with {@code oldPrefix} to start with
     28  * {@code newPrefix} instead.
     29  */
     30 public class ModifyStringLiterals implements Processor {
     31 
     32   private final String oldString;
     33 
     34   private final String newString;
     35 
     36   public ModifyStringLiterals(String oldString, final String newString) {
     37     this.oldString = oldString;
     38     this.newString = newString;
     39   }
     40 
     41   @Override
     42   public void process(Context context, CompilationUnit cu) {
     43     final ASTRewrite rewrite = context.rewrite();
     44     ASTVisitor visitor = new ASTVisitor(false /* visitDocTags */) {
     45       @Override
     46       public boolean visit(StringLiteral node) {
     47         String literalValue = node.getLiteralValue();
     48         // TODO Replace with Pattern
     49         if (literalValue.contains(oldString)) {
     50           String newLiteralValue = literalValue.replace(oldString, newString);
     51           StringLiteral newLiteral = node.getAST().newStringLiteral();
     52           newLiteral.setLiteralValue(newLiteralValue);
     53           rewrite.replace(node, newLiteral, null /* editGorup */);
     54         }
     55         return false;
     56       }
     57     };
     58     cu.accept(visitor);
     59   }
     60 
     61   @Override
     62   public String toString() {
     63     return "ModifyStringLiterals{" +
     64         "oldString='" + oldString + '\'' +
     65         ", newString='" + newString + '\'' +
     66         '}';
     67   }
     68 }
     69