View Javadoc
1   /*
2    * Copyright (c) 2020 bahlef.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v2.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v20.html
7    * Contributors:
8    * bahlef - initial API and implementation and/or initial documentation
9    */
10  package de.funfried.netbeans.plugins.external.formatter.javascript.eclipse;
11  
12  import java.util.Map;
13  import java.util.Objects;
14  
15  import org.apache.commons.lang3.tuple.Pair;
16  import org.eclipse.jface.text.Document;
17  import org.eclipse.jface.text.IDocument;
18  import org.eclipse.text.edits.TextEdit;
19  import org.eclipse.wst.jsdt.core.ToolFactory;
20  import org.eclipse.wst.jsdt.core.formatter.CodeFormatter;
21  import org.netbeans.api.annotations.common.CheckForNull;
22  import org.netbeans.api.annotations.common.NonNull;
23  
24  import de.funfried.netbeans.plugins.external.formatter.exceptions.CannotLoadConfigurationException;
25  import de.funfried.netbeans.plugins.external.formatter.exceptions.ConfigReadException;
26  import de.funfried.netbeans.plugins.external.formatter.exceptions.FormattingFailedException;
27  import de.funfried.netbeans.plugins.external.formatter.exceptions.ProfileNotFoundException;
28  
29  /**
30   * Wrapper class to the Eclipse formatter implementation.
31   *
32   * @author bahlef
33   */
34  public final class EclipseJavascriptFormatterWrapper {
35  	/** Use to specify the kind of the code snippet to format. */
36  	private static final int FORMATTER_OPTS = CodeFormatter.K_JAVASCRIPT_UNIT;
37  
38  	/**
39  	 * Package private Constructor for creating a new instance of {@link EclipseJavascriptFormatterWrapper}.
40  	 */
41  	EclipseJavascriptFormatterWrapper() {
42  	}
43  
44  	/**
45  	 * Formats the given {@code code} with the given configurations and returns
46  	 * the formatted code.
47  	 *
48  	 * @param formatterFile the path to the formatter configuration file
49  	 * @param formatterProfile the name of the formatter configuration profile
50  	 * @param code the unformatted code
51  	 * @param lineFeed the line feed to use for formatting
52  	 * @param changedElement an optional range as a {@link Pair} object defining the offsets which should be formatted
53  	 *
54  	 * @return the formatted code
55  	 *
56  	 * @throws ConfigReadException if there is an issue parsing the formatter configuration
57  	 * @throws ProfileNotFoundException if the given {@code profile} could not be found
58  	 * @throws CannotLoadConfigurationException if there is any issue accessing or reading the formatter configuration
59  	 * @throws FormattingFailedException if the external formatter failed to format the given code
60  	 */
61  	@CheckForNull
62  	public String format(String formatterFile, String formatterProfile, String code, String lineFeed, Pair<Integer, Integer> changedElement)
63  			throws ConfigReadException, ProfileNotFoundException, CannotLoadConfigurationException, FormattingFailedException {
64  		if (code == null) {
65  			return null;
66  		}
67  
68  		Map<String, String> allConfig = EclipseFormatterConfig.parseConfig(formatterFile, formatterProfile);
69  
70  		CodeFormatter formatter = ToolFactory.createCodeFormatter(allConfig, ToolFactory.M_FORMAT_EXISTING);
71  
72  		int codeLength = code.length();
73  
74  		int offset = 0;
75  		int length = codeLength;
76  
77  		if (changedElement != null && changedElement.getLeft() != null && changedElement.getRight() != null) {
78  			offset = changedElement.getLeft();
79  			if (offset < 0) {
80  				offset = 0;
81  			}
82  
83  			length = (changedElement.getRight() - changedElement.getLeft()) + 1;
84  			if (length > codeLength) {
85  				length = codeLength;
86  			}
87  		}
88  
89  		return format(formatter, code, offset, length, lineFeed);
90  	}
91  
92  	/**
93  	 * Formats the given {@code code} with the given configurations and returns
94  	 * the formatted code.
95  	 *
96  	 * @param formatter the {@link CodeFormatter}
97  	 * @param code the unformatted code
98  	 * @param offset the offset where to start formatting the given code
99  	 * @param length the length where to stop formatting the given code
100 	 * @param lineFeed the line feed to use for formatting
101 	 *
102 	 * @return the formatted code
103 	 *
104 	 * @throws FormattingFailedException if the external formatter failed to format the given code
105 	 */
106 	@CheckForNull
107 	private String format(@NonNull CodeFormatter formatter, @NonNull String code, int offset, int length, String lineFeed) throws FormattingFailedException {
108 		String formattedCode = null;
109 
110 		try {
111 			TextEdit te = formatter.format(FORMATTER_OPTS, code, offset, length, 0, lineFeed);
112 			if (te != null && te.getChildrenSize() > 0) {
113 				IDocument dc = new Document(code);
114 				te.apply(dc);
115 
116 				formattedCode = dc.get();
117 
118 				if (Objects.equals(code, formattedCode)) {
119 					return null;
120 				}
121 			}
122 		} catch (FormattingFailedException | IllegalArgumentException ex) {
123 			throw ex;
124 		} catch (Exception ex) {
125 			throw new FormattingFailedException(ex);
126 		}
127 
128 		return formattedCode;
129 	}
130 }