下面列出了怎么用com.intellij.psi.javadoc.PsiDocTag的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 构建作者
*
* @param elements 元素
* @return {@link java.lang.String}
*/
private String buildAuthor(List<PsiElement> elements) {
boolean isInsert = true;
for (Iterator<PsiElement> iterator = elements.iterator(); iterator.hasNext(); ) {
PsiElement element = iterator.next();
if (!"PsiDocTag:@author".equalsIgnoreCase(element.toString())) {
continue;
}
PsiDocTagValue value = ((PsiDocTag)element).getValueElement();
if (value == null || StringUtils.isBlank(value.getText())) {
iterator.remove();
} else {
isInsert = false;
}
}
if (isInsert) {
return "@author " + config.getAuthor() + "\n";
} else {
return null;
}
}
/**
* 构建返回
*
* @param elements 元素
* @param returnName 返回名称
* @return {@link java.lang.String}
*/
private String buildReturn(List<PsiElement> elements, String returnName) {
boolean isInsert = true;
for (Iterator<PsiElement> iterator = elements.iterator(); iterator.hasNext(); ) {
PsiElement element = iterator.next();
if (!"PsiDocTag:@return".equalsIgnoreCase(element.toString())) {
continue;
}
PsiDocTagValue value = ((PsiDocTag) element).getValueElement();
if (value == null || StringUtils.isBlank(value.getText())) {
iterator.remove();
} else if (returnName.length() <= 0 || "void".equals(returnName)) {
iterator.remove();
} else {
isInsert = false;
}
}
if (isInsert && returnName.length() > 0 && !"void".equals(returnName)) {
if (Consts.BASE_TYPE_SET.contains(returnName)) {
return "@return " + returnName + "\n";
} else {
return "@return {@link " + returnName + "}\n";
}
}
return null;
}
/**
* 构建日期
*
* @param elements 元素
* @return {@link java.lang.String}
*/
private String buildDate(List<PsiElement> elements) {
String dateString;
try {
dateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern(config.getDateFormat()));
} catch (Exception e) {
LOGGER.error("您输入的日期格式不正确,请到配置中修改类相关日期格式!");
dateString = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern(EasyJavadocConfigComponent.DEFAULT_DATE_FORMAT));
}
boolean isInsert = true;
for (Iterator<PsiElement> iterator = elements.iterator(); iterator.hasNext(); ) {
PsiElement element = iterator.next();
if (!"PsiDocTag:@date".equalsIgnoreCase(element.toString())) {
continue;
}
PsiDocTagValue value = ((PsiDocTag)element).getValueElement();
if (value == null || StringUtils.isBlank(value.getText())) {
iterator.remove();
} else {
isInsert = false;
}
}
if (isInsert) {
return "@date " + dateString + "\n";
} else {
return null;
}
}
private String generateTestSuite(StringBuilder sb, StringBuilder sbDev, PsiClass clazz) {
boolean classInstanciated = false;
for (PsiMethod method : clazz.getAllMethods()) {
boolean ignore = false;
PsiDocComment comment = method.getDocComment();
if (comment != null) {
PsiDocTag[] tags = comment.getTags();
if (tags != null) {
for (PsiDocTag tag : tags) {
if (tag.getName().equals(DocTagTranslator.IGNORE) && tag.getValueElement() != null && tag.getValueElement().getText().equals(DocTagTranslator.TS)) {
ignore = true;
}
}
}
}
if (!ignore) {
PsiAnnotation testAnnot = method.getModifierList().findAnnotation("Test");
if (testAnnot != null) {
if (!classInstanciated) {
sb.append(instanciateClass(clazz));
sbDev.append(instanciateClassDev(clazz));
classInstanciated = true;
}
generateTestCall(sb, clazz, method);
generateTestCallDev(sbDev, clazz, method);
}
}
}
if (classInstanciated) {
sb.append("});\n\n");
sbDev.append("} catch(err) {\n" +
"\tconsole.error(err.stack);\n" +
"}\n\n");
}
return sb.toString();
}
private void renderSimpleTag(MarkdownDoclet doclet, StringBuilder tagBlock, PsiDocTag docTag, boolean stripFirstWord) {
tagBlock.append("\[email protected]").append(docTag.getName()).append(' ');
String firstWord = null;
String text = toString(docTag, false);
if ( stripFirstWord ) {
String[] stripped = stripFirstWord(text);
firstWord = stripped[0];
text = stripped[1].trim();
}
text = TagRendering.simplifySingleParagraph(doclet.toHtml(text, false));
if ( firstWord != null ) {
tagBlock.append(firstWord).append(' ');
}
tagBlock.append(text).append('\n');
}
/**
* Convert a given `PsiDocTag` to a string.
*
* @param docTag The `PsiDocTag` to be converted to a string.
* @param stripFirstWord `true`, if the first word should be stripped (e.g. the
* parameter name of a `@param` tag.
*
* @return The `PsiDocTag` as string.
*/
private static String toString(PsiDocTag docTag, boolean stripFirstWord) {
String tagText = stripLead(docTag.getText());
tagText = stripFirstWord(tagText)[1]; // remove the tag itself
if ( stripFirstWord ) {
String[] stripped = stripFirstWord(tagText);
return stripped[0] + " " + stripped[1].trim();
}
else {
return tagText.trim();
}
}
private void inheritanceHierarchyMatchingWithStaticTypes(TypeCheckElimination typeCheckElimination,
CompleteInheritanceDetection inheritanceDetection) {
List<PsiField> staticFields = typeCheckElimination.getStaticFields();
String abstractClassType = typeCheckElimination.getAbstractClassType();
InheritanceTree tree = null;
if (abstractClassType != null) {
tree = inheritanceDetection.getTree(abstractClassType);
}
if (tree != null) {
DefaultMutableTreeNode rootNode = tree.getRootNode();
DefaultMutableTreeNode leaf = rootNode.getFirstLeaf();
List<String> inheritanceHierarchySubclassNames = new ArrayList<>();
while (leaf != null) {
inheritanceHierarchySubclassNames.add((String) leaf.getUserObject());
leaf = leaf.getNextLeaf();
}
int matchCounter = 0;
for (PsiField staticField : staticFields) {
for (String subclassName : inheritanceHierarchySubclassNames) {
ClassObject classObject = getClassObject(subclassName);
PsiElement abstractTypeDeclaration = classObject.getAbstractTypeDeclaration();
if (abstractTypeDeclaration instanceof PsiClass) {
PsiClass typeDeclaration = (PsiClass) abstractTypeDeclaration;
PsiDocComment javadoc = typeDeclaration.getDocComment();
if (javadoc != null) {
PsiDocTag[] tagElements = javadoc.getTags();
for (PsiDocTag tagElement : tagElements) {
tagElement.getName();
if ("see".equals(tagElement.getName())) {
PsiElement[] fragments = tagElement.getDataElements();
for (PsiElement fragment : fragments) {
if (!(fragment instanceof PsiDocMethodOrFieldRef)) {
continue;
}
PsiReference memberRef = fragment.getReference();
if (memberRef == null) {
continue;
}
PsiElement resolvedRef = memberRef.resolve();
if (staticField.equals(resolvedRef)) {
typeCheckElimination.putStaticFieldSubclassTypeMapping(staticField, subclassName);
matchCounter++;
break;
}
}
}
}
}
}
}
}
if (matchCounter == staticFields.size()) {
typeCheckElimination.setInheritanceTreeMatchingWithStaticTypes(tree);
}
}
}
public void generate(File sourceDir, File targetDir) {
try {
StringBuilder sb = new StringBuilder();
StringBuilder sbDev = new StringBuilder();
if (headers != null) {
for (String s : headers) {
sb.append(s + "\n");
sbDev.append(s + "\n");
}
}
JavaAnalyzer javaAnalyzer = new JavaAnalyzer();
PsiDirectory parsedDir = javaAnalyzer.analyze(sourceDir);
parsedDir.acceptChildren(new PsiElementVisitor() {
@Override
public void visitElement(PsiElement element) {
boolean ignore = false;
if (element instanceof PsiClass) {
PsiClass clazz = (PsiClass) element;
PsiDocComment comment = clazz.getDocComment();
if (comment != null) {
PsiDocTag[] tags = comment.getTags();
if (tags != null) {
for (PsiDocTag tag : tags) {
if (tag.getName().equals(DocTagTranslator.IGNORE) && tag.getValueElement() != null && tag.getValueElement().getText().equals(DocTagTranslator.TS)) {
ignore = true;
}
}
}
}
if (!ignore && !clazz.isInterface() && !clazz.hasModifierProperty(PsiModifier.ABSTRACT)) {
generateTestSuite(sb, sbDev, clazz);
}
} else {
element.acceptChildren(this);
}
}
});
targetDir.mkdirs();
File generatedTS = new File(targetDir, "testsRunner.js");
FileUtil.writeToFile(generatedTS, sb.toString().getBytes());
File generatedDevTS = new File(targetDir, "testsRunnerDev.js");
FileUtil.writeToFile(generatedDevTS, sbDev.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private void renderSeeTag(MarkdownDoclet doclet, StringBuilder tagBlock, PsiDocTag docTag) {
final String seeText = toString(docTag, false);
if ( seeText.startsWith("\"") ) {
SeeTag tag = new SeeTag() {
@Override
public String label() {
return null;
}
@Override
public PackageDoc referencedPackage() {
return null;
}
@Override
public String referencedClassName() {
return null;
}
@Override
public ClassDoc referencedClass() {
return null;
}
@Override
public String referencedMemberName() {
return null;
}
@Override
public MemberDoc referencedMember() {
return null;
}
@Override
public String name() {
return "@see";
}
@Override
public Doc holder() {
return null;
}
@Override
public String kind() {
return "@see";
}
@Override
public String text() {
return seeText;
}
@Override
public Tag[] inlineTags() {
return new Tag[0];
}
@Override
public Tag[] firstSentenceTags() {
return new Tag[0];
}
@Override
public SourcePosition position() {
return null;
}
};
SeeTagRenderer.INSTANCE.render(tag, tagBlock, doclet);
}
else {
tagBlock.append("\[email protected]").append(docTag.getName());
tagBlock.append(' ').append(seeText);
}
}
private void renderTodoTag(MarkdownDoclet doclet, StringBuilder tagBlock, PsiDocTag docTag) {
tagBlock.append("\n<DL style=\"border:solid 1px;padding:5px;\"><DT><B>To Do</B></DT><DD>");
tagBlock.append(toString(docTag, false));
tagBlock.append("\n</DD></DL>");
}
@Override
public void visitElement(PsiElement element) {
if ( element instanceof PsiDocTag ) {
PsiDocTag tag = (PsiDocTag)element;
String tagName = null;
switch ( tag.getName() ) {
case "link":
case "linkplain":
case "see":
// todo: @ssee
tagName = tag.getName();
}
if ( tagName != null ) {
int inlineOffset = (tag instanceof PsiInlineDocTag) ? 1 : 0;
String linkText = tag.getText().substring(inlineOffset + 1 + tagName.length(), tag.getTextLength() - inlineOffset).trim();
if ( !linkText.startsWith("#") ) {
return;
}
StringBuilder newLink = new StringBuilder(100);
if ( inlineOffset > 0 ) {
newLink.append('{');
}
newLink.append('@').append(tagName).append(' ');
int refEndIndex = JavaDocUtil.extractReference(linkText);
String refText = linkText.substring(0, refEndIndex);
PsiElement target = JavaDocUtil.findReferenceTarget(docContext.getManager(), refText, docContext, true);
if ( target == null ) {
return;
}
newLink.append(JavaDocUtil.getReferenceText(project, target)).append(' ');
String labelText = linkText.substring(refEndIndex).trim();
if ( labelText.isEmpty() ) {
labelText = JavaDocUtil.getLabelText(project, docContext.getManager(), refText, docContext);
}
newLink.append(labelText);
if ( inlineOffset > 0 ) {
newLink.append('}');
}
int start = getStartOffsetInComment(element);
if ( buffer == null ) {
buffer = new StringBuilder(docText.length() + 100);
}
buffer.append(docText, docTextPosition, start);
buffer.append(newLink);
docTextPosition += start - docTextPosition + element.getTextLength();
}
}
element.acceptChildren(this);
}