1
0
mirror of https://github.com/1C-Company/v8-code-style.git synced 2024-11-24 16:53:51 +02:00

Merge pull request #1419 from 1C-Company/feature/1418-bsl-doc-domment-format

Контекстная команда форматирования документирующего комментария #1418
This commit is contained in:
Dmitriy Marmyshev 2024-03-06 21:02:30 -08:00 committed by GitHub
commit 1bf7477377
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 478 additions and 5 deletions

View File

@ -28,6 +28,7 @@
### Прочие изменения
- Контекстная команда форматирования документирующего комментария в редакторе модуля #1418
### Исправленные ошибки

View File

@ -22,6 +22,7 @@ Import-Package: com._1c.g5.ides.ui.texteditor.xtext.embedded;version="[6.0.0,7.0
com._1c.g5.v8.dt.bsl.comment;version="[3.0.0,4.0.0)",
com._1c.g5.v8.dt.bsl.common;version="[6.0.0,7.0.0)",
com._1c.g5.v8.dt.bsl.documentation.comment;version="[4.0.0,5.0.0)",
com._1c.g5.v8.dt.bsl.formatting;version="[3.0.0,4.0.0)",
com._1c.g5.v8.dt.bsl.model;version="[5.0.0,6.0.0)",
com._1c.g5.v8.dt.bsl.services;version="[7.0.0,8.0.0)",
com._1c.g5.v8.dt.bsl.ui;version="[9.0.0,10.0.0)",
@ -34,6 +35,7 @@ Import-Package: com._1c.g5.ides.ui.texteditor.xtext.embedded;version="[6.0.0,7.0
com._1c.g5.v8.dt.core.filesystem;version="[6.0.0,7.0.0)",
com._1c.g5.v8.dt.core.model;version="[6.0.0,7.0.0)",
com._1c.g5.v8.dt.core.platform;version="[11.0.0,12.0.0)",
com._1c.g5.v8.dt.lcore.nodemodel.util;version="[1.0.0,2.0.0)",
com._1c.g5.v8.dt.lcore.ui.texteditor;version="[1.1.0,2.0.0)",
com._1c.g5.v8.dt.mcore;version="[7.0.0,8.0.0)",
com._1c.g5.v8.dt.metadata.mdclass;version="[9.0.0,10.0.0)",

View File

@ -15,6 +15,8 @@
command.enableStrictTypes.mnemonic = E
command.enableStrictTypes.name = Enable @strict-types in modules
command.formatDocComment.mnemonic = F
command.formatDocComment.name = Format Method Documentation Comment
menu.label = Source

View File

@ -237,6 +237,10 @@
id="com.e1c.v8codestyle.bsl.ui.commands.addStrictTypesAnnotationCommand"
name="%command.enableStrictTypes.name">
</command>
<command
id="com.e1c.v8codestyle.bsl.ui.commands.formatDocCommentCommand"
name="%command.formatDocComment.name">
</command>
</extension>
<extension
point="org.eclipse.ui.menus">
@ -330,6 +334,16 @@
</reference>
</visibleWhen>
</command>
<command
commandId="com.e1c.v8codestyle.bsl.ui.commands.formatDocCommentCommand"
style="push">
<visibleWhen
checkEnabled="false">
<reference
definitionId="com._1c.g5.v8.dt.bsl.Bsl.Editor.editable">
</reference>
</visibleWhen>
</command>
</menu>
</menuContribution>
</extension>
@ -343,6 +357,14 @@
definitionId="com._1c.g5.v8.dt.bsl.Bsl.Editor.editable">
</reference></activeWhen>
</handler>
<handler
class="com.e1c.v8codestyle.internal.bsl.ui.ExecutableExtensionFactory:com.e1c.v8codestyle.internal.bsl.ui.handlers.FormatDocCommentModuleEditorHandler"
commandId="com.e1c.v8codestyle.bsl.ui.commands.formatDocCommentCommand">
<activeWhen>
<reference
definitionId="com._1c.g5.v8.dt.bsl.Bsl.Editor.editable">
</reference></activeWhen>
</handler>
</extension>
<extension point="com.e1c.g5.v8.dt.check.fixes">

View File

@ -14,6 +14,8 @@
command.enableStrictTypes.mnemonic = В
command.enableStrictTypes.name = Включить строгую типизацию (@strict-types) в модулях
command.formatDocComment.mnemonic = Ф
command.formatDocComment.name = Форматировать документирующий комментарий метода
menu.label = Исходники

View File

@ -19,10 +19,12 @@ import org.eclipse.xtext.resource.IResourceServiceProvider;
import com._1c.g5.v8.dt.bsl.common.IBslPreferences;
import com._1c.g5.v8.dt.bsl.documentation.comment.BslMultiLineCommentDocumentationProvider;
import com._1c.g5.v8.dt.bsl.ui.contentassist.BslProposalProvider;
import com._1c.g5.v8.dt.core.filesystem.IQualifiedNameFilePathConverter;
import com._1c.g5.v8.dt.core.model.IModelEditingSupport;
import com._1c.g5.v8.dt.core.platform.IResourceLookup;
import com._1c.g5.v8.dt.core.platform.IV8ProjectManager;
import com._1c.g5.v8.dt.lcore.ui.texteditor.IndentTextEditorProvider;
import com._1c.g5.wiring.AbstractServiceAwareModule;
import com.e1c.g5.v8.dt.check.qfix.IFixRepository;
import com.e1c.v8codestyle.bsl.IModuleStructureProvider;
@ -59,6 +61,8 @@ class ExternalDependenciesModule
bind(BslMultiLineCommentDocumentationProvider.class)
.toProvider(() -> rsp.get(BslMultiLineCommentDocumentationProvider.class));
bind(EObjectAtOffsetHelper.class).toProvider(() -> rsp.get(EObjectAtOffsetHelper.class));
bind(BslProposalProvider.class).toProvider(() -> rsp.get(BslProposalProvider.class));
bind(IndentTextEditorProvider.class).toProvider(() -> rsp.get(IndentTextEditorProvider.class));
// CodeStyle Services
bind(IModuleStructureProvider.class).toService();

View File

@ -0,0 +1,235 @@
/*******************************************************************************
* Copyright (C) 2024, 1C-Soft LLC and others.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* 1C-Soft LLC - initial API and implementation
*******************************************************************************/
package com.e1c.v8codestyle.internal.bsl.ui.handlers;
import java.util.List;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.handly.buffer.BufferChange;
import org.eclipse.handly.snapshot.NonExpiringSnapshot;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.ILeafNode;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.util.Triple;
import org.eclipse.xtext.util.Tuples;
import org.eclipse.xtext.util.concurrent.CancelableUnitOfWork;
import com._1c.g5.ides.ui.texteditor.xtext.embedded.EmbeddedEditorBuffer;
import com._1c.g5.v8.dt.bsl.common.IBslPreferences;
import com._1c.g5.v8.dt.bsl.documentation.comment.BslCommentUtils;
import com._1c.g5.v8.dt.bsl.documentation.comment.BslDocCommentSerializer;
import com._1c.g5.v8.dt.bsl.documentation.comment.BslDocumentationComment;
import com._1c.g5.v8.dt.bsl.documentation.comment.BslDocumentationComment.Description;
import com._1c.g5.v8.dt.bsl.documentation.comment.BslMultiLineCommentDocumentationProvider;
import com._1c.g5.v8.dt.bsl.documentation.comment.IDescriptionPart;
import com._1c.g5.v8.dt.bsl.documentation.comment.TextPart;
import com._1c.g5.v8.dt.bsl.model.Method;
import com._1c.g5.v8.dt.bsl.model.Module;
import com._1c.g5.v8.dt.bsl.ui.contentassist.BslProposalProvider;
import com._1c.g5.v8.dt.bsl.ui.menu.BslHandlerUtil;
import com._1c.g5.v8.dt.bsl.util.BslUtil;
import com._1c.g5.v8.dt.common.PreferenceUtils;
import com._1c.g5.v8.dt.common.StringUtils;
import com._1c.g5.v8.dt.core.model.EditingMode;
import com._1c.g5.v8.dt.core.model.IModelEditingSupport;
import com._1c.g5.v8.dt.core.platform.IV8Project;
import com._1c.g5.v8.dt.core.platform.IV8ProjectManager;
import com._1c.g5.v8.dt.lcore.nodemodel.util.CustomNodeModelUtils;
import com._1c.g5.v8.dt.lcore.ui.texteditor.IndentTextEditorProvider;
import com.e1c.v8codestyle.internal.bsl.ui.UiPlugin;
import com.google.inject.Inject;
/**
* The Handler to format current method's documentation comment in opened in BSL editor.
*
* @author Dmitriy Marmyshev
*/
public class FormatDocCommentModuleEditorHandler
extends AbstractHandler
{
@Inject
private BslMultiLineCommentDocumentationProvider commentProvider;
@Inject
private BslProposalProvider proposalProvider;
@Inject
private IBslPreferences bslPreferences;
@Inject
private IV8ProjectManager v8projectManager;
@Inject
private IndentTextEditorProvider indentProvider;
@Inject
private IModelEditingSupport modelEditingSupport;
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
IWorkbenchPart part = HandlerUtil.getActivePart(event);
XtextEditor target = BslHandlerUtil.extractXtextEditor(part);
if (target != null)
{
final ITextViewer viewer = BslHandlerUtil.getTextViewer(target);
IXtextDocument document = target.getDocument();
Triple<Integer, Integer, String> content =
document.readOnly(new CancelableUnitOfWork<Triple<Integer, Integer, String>, XtextResource>()
{
@Override
public Triple<Integer, Integer, String> exec(XtextResource resource, CancelIndicator monitor)
throws Exception
{
if (resource.getContents() != null && !resource.getContents().isEmpty())
{
EObject obj = resource.getContents().get(0);
if (obj instanceof Module)
return getFormatedDocComment((Module)obj, viewer);
}
return null;
}
});
if (content != null && content.getFirst() > -1 && content.getSecond() > -1 && content.getThird() != null)
{
replaceDocComment(document, content.getThird(), content.getFirst(), content.getSecond());
}
}
return null;
}
private void replaceDocComment(IXtextDocument document, String comment, int insertOffset, int length)
{
TextEdit change = new ReplaceEdit(insertOffset, length, comment);
try (EmbeddedEditorBuffer buffer = new EmbeddedEditorBuffer(document))
{
NonExpiringSnapshot snapshot = new NonExpiringSnapshot(buffer);
BufferChange bufferChange = new BufferChange(change);
bufferChange.setBase(snapshot);
buffer.applyChange(bufferChange, new NullProgressMonitor());
}
catch (CoreException e)
{
UiPlugin.logError(e);
}
}
private Triple<Integer, Integer, String> getFormatedDocComment(Module module, ITextViewer viewer)
{
if (!modelEditingSupport.canEdit(module, EditingMode.DIRECT))
{
return null;
}
Method method = getNearestMethod(module, (viewer.getSelectedRange()).x);
if (method != null)
{
List<INode> lines = commentProvider.getDocumentationNodes(method);
if (lines.isEmpty())
{
return null;
}
int methodOffset = lines.get(0).getOffset();
int length = lines.get(lines.size() - 1).getEndOffset() - methodOffset;
String lineFormatter = proposalProvider.getLineFormatter(module, methodOffset, viewer.getDocument());
IV8Project project = v8projectManager.getProject(module);
boolean oldFormat = (project != null && project.getProject() != null)
? this.bslPreferences.getDocumentCommentProperties(project.getProject()).oldCommentFormat() : true;
BslDocumentationComment docComment =
BslCommentUtils.parseTemplateComment(method, oldFormat, commentProvider);
if (isEmpty(docComment.getDescription()))
{
docComment.getDescription().getParts().clear();
}
boolean isRussian = BslUtil.isRussian(method, v8projectManager);
String indent = indentProvider.getIndent();
String lineSeparator = resolveLineSeparator(project);
String comment = BslDocCommentSerializer.newBuilder()
.setOldFormat(oldFormat)
.setScriptVariant(isRussian)
.lineSeparator(lineSeparator)
.ignoreLineNumbers()
.build()
.serialize(docComment, lineFormatter, indent)
.concat(lineSeparator);
return Tuples.create(methodOffset, length, comment);
}
return null;
}
private boolean isEmpty(Description description)
{
for (IDescriptionPart part : description.getParts())
{
if (part instanceof TextPart)
{
String text = ((TextPart)part).getText();
if (StringUtils.isNotBlank(text))
{
return false;
}
}
else
{
return false;
}
}
return true;
}
private Method getNearestMethod(Module module, int offset)
{
ICompositeNode iCompositeNode = NodeModelUtils.findActualNodeFor(module);
ILeafNode node = CustomNodeModelUtils.findLeafNodeAtOffset(iCompositeNode, offset);
EObject actualObject = NodeModelUtils.findActualSemanticObjectFor(node);
if (actualObject instanceof Method)
return (Method)actualObject;
return EcoreUtil2.getContainerOfType(actualObject, Method.class);
}
private static String resolveLineSeparator(IV8Project v8project)
{
if (v8project == null)
return System.lineSeparator();
return PreferenceUtils.getLineSeparator(v8project.getProject());
}
}

View File

@ -12,4 +12,5 @@ Import-Package: com._1c.g5.v8.dt.bsl.ui.editor;version="[9.0.0,10.0.0)",
com._1c.g5.v8.dt.testing;version="[3.1.0,4.0.0)",
com._1c.g5.v8.dt.ui.util;version="[7.0.0,8.0.0)",
org.junit;version="[4.13.0,5.0.0)"
Require-Bundle: org.eclipse.ui.forms;bundle-version="[3.11.0,4.0.0)"
Require-Bundle: org.eclipse.ui.forms;bundle-version="[3.11.0,4.0.0)",
org.eclipse.core.expressions;bundle-version="[3.8.0,4.0.0)"

View File

@ -0,0 +1,9 @@
// Method description
//
// Parameters:
// Parameters - Structure - :
// * Key1 - has not type for key
Procedure Test(Parameters) Export
// empty
EndProcedure

View File

@ -0,0 +1,11 @@
// Method description
//
//
//
// Parameters:
// Parameters - Structure:
// * Key1 - has not type for key
Procedure Test(Parameters) Export
// empty
EndProcedure

View File

@ -74,6 +74,16 @@ public class BslDocCommentViewTest
@Before
public void setUp() throws CoreException
{
IIntroPart introPart = PlatformUI.getWorkbench().getIntroManager().getIntro();
PlatformUI.getWorkbench().getIntroManager().closeIntro(introPart);
boolean closed = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeAllEditors(false);
assertTrue(closed);
Display display = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getDisplay();
while (!display.isDisposed() && display.readAndDispatch())
{
// do it
}
project = testingWorkspace.getProject(PROJECT_NAME);
@ -82,16 +92,17 @@ public class BslDocCommentViewTest
testingWorkspace.cleanUpWorkspace();
project = this.testingWorkspace.setUpProject(PROJECT_NAME, getClass());
}
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeAllEditors(false);
IIntroPart introPart = PlatformUI.getWorkbench().getIntroManager().getIntro();
PlatformUI.getWorkbench().getIntroManager().closeIntro(introPart);
}
@After
public void shutDown()
{
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeAllEditors(false);
Display display = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getDisplay();
while (!display.isDisposed() && display.readAndDispatch())
{
// do it
}
}
/**

View File

@ -0,0 +1,173 @@
/*******************************************************************************
* Copyright (C) 2024, 1C-Soft LLC and others.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* 1C-Soft LLC - initial API and implementation
*******************************************************************************/
package com.e1c.v8codestyle.bsl.ui.itests.handlers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.intro.IIntroPart;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com._1c.g5.v8.dt.bsl.ui.editor.BslXtextEditor;
import com._1c.g5.v8.dt.testing.TestingWorkspace;
import com._1c.g5.v8.dt.ui.util.OpenHelper;
import com.e1c.v8codestyle.internal.bsl.ui.handlers.FormatDocCommentModuleEditorHandler;
/**
* Test {@link FormatDocCommentModuleEditorHandler}
*
* @author Dmitriy Marmyshev
*/
public class FormatDocCommentModuleEditorHandlerTest
{
private static final String COMMAND_ID = "com.e1c.v8codestyle.bsl.ui.commands.formatDocCommentCommand";
private static final String PROJECT_NAME = "CommonModule";
private static final String COMMON_MODULE_FILE_NAME = "/src/CommonModules/CommonModule/Module.bsl";
@Rule
public TestingWorkspace testingWorkspace = new TestingWorkspace(true, false);
protected static final String FOLDER_RESOURCE = "/resources/";
private IProject project;
private OpenHelper openHelper = new OpenHelper();
private ICommandService commandService;
private IHandlerService handlerService;
@Before
public void setUp() throws CoreException
{
commandService = PlatformUI.getWorkbench().getService(ICommandService.class);
handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class);
IIntroPart introPart = PlatformUI.getWorkbench().getIntroManager().getIntro();
PlatformUI.getWorkbench().getIntroManager().closeIntro(introPart);
boolean closed = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeAllEditors(false);
assertTrue(closed);
Display display = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getDisplay();
while (!display.isDisposed() && display.readAndDispatch())
{
// do it
}
project = testingWorkspace.getProject(PROJECT_NAME);
if (!project.exists() || !project.isAccessible())
{
testingWorkspace.cleanUpWorkspace();
project = this.testingWorkspace.setUpProject(PROJECT_NAME, getClass());
}
}
@After
public void shutDown()
{
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeAllEditors(false);
Display display = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getDisplay();
while (!display.isDisposed() && display.readAndDispatch())
{
// do it
}
}
/**
* Test format of doc comment.
*
* @throws Exception the exception
*/
@Test
public void testFormatDocComment() throws Exception
{
updateModule(FOLDER_RESOURCE + "doc-comment-format.bsl");
IFile file = project.getFile(COMMON_MODULE_FILE_NAME);
ISelection selection = new TextSelection(14, 1);
IEditorPart fEditor = openHelper.openEditor(file, selection);
assertTrue(fEditor instanceof FormEditor);
IEditorPart editor = ((FormEditor)fEditor).getActiveEditor();
assertTrue(editor instanceof BslXtextEditor);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(editor);
BslXtextEditor bslEditor = (BslXtextEditor)editor;
String expected = getResourceText(FOLDER_RESOURCE + "doc-comment-format.bsl");
assertEquals(expected, bslEditor.getDocument().get());
Command command = commandService.getCommand(COMMAND_ID);
assertNotNull(command);
ExecutionEvent executionEvent = handlerService.createExecutionEvent(command, new Event());
assertNotNull(executionEvent);
command.executeWithChecks(executionEvent);
expected = getResourceText(FOLDER_RESOURCE + "doc-comment-format-result.bsl");
assertEquals(expected, bslEditor.getDocument().get());
}
private String getResourceText(String pathToResource) throws Exception
{
try (InputStream in = getClass().getResourceAsStream(pathToResource))
{
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
private void updateModule(String pathToResource) throws Exception
{
IFile file = project.getFile(COMMON_MODULE_FILE_NAME);
try (InputStream in = getClass().getResourceAsStream(pathToResource))
{
if (file.exists())
{
file.setContents(in, true, true, new NullProgressMonitor());
}
else
{
file.create(in, true, new NullProgressMonitor());
}
}
testingWorkspace.waitForBuildCompletion();
}
}