public async Task <FixUsingsResponse> FixUsings(FixUsingsRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);
            var response = new FixUsingsResponse();

            if (document != null)
            {
                response = await new FixUsingsWorker().FixUsings(_workspace, document);

                if (!request.WantsTextChanges)
                {
                    // return the new document
                    var docText = await _workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync();

                    response.Buffer = docText.ToString();
                }
                else
                {
                    // return the text changes
                    var changes = await _workspace.CurrentSolution.GetDocument(document.Id).GetTextChangesAsync(document);

                    response.Changes = await LinePositionSpanTextChange.Convert(document, changes);
                }
            }

            return(response);
        }
Esempio n. 2
0
        public async Task Can_extract_method()
        {
            const string code =
                @"public class Class1
{
    public void Whatever()
    {
        [|Console.Write(""should be using System;"");|]
    }
}";

            var expected = new LinePositionSpanTextChange
            {
                NewText     = "NewMethod();\n    }\n\n    private static void NewMethod()\n    {\n        ",
                StartLine   = 4,
                StartColumn = 8,
                EndLine     = 4,
                EndColumn   = 8
            };

            var response = await RunRefactoringAsync(code, "Extract Method");

            var modifiedFile = response.Changes.FirstOrDefault() as ModifiedFileResponse;

            Assert.Single(response.Changes);
            Assert.NotNull(modifiedFile);
            Assert.Single(modifiedFile.Changes);
            Assert.Equal(expected, modifiedFile.Changes.FirstOrDefault());
        }
        public async Task <FixUsingsResponse> Handle(FixUsingsRequest request)
        {
            var document = _workspace.GetDocument(request.FileName);
            var response = new FixUsingsResponse();

            if (document != null)
            {
                var fixUsingsResponse = await new FixUsingsWorker(_loggerFactory, _loader).FixUsings(_workspace.CurrentSolution, _codeActionProviders, request.FileName);
                response.AmbiguousResults = fixUsingsResponse.AmbiguousResults;

                if (request.ApplyTextChanges)
                {
                    _workspace.TryApplyChanges(fixUsingsResponse.Solution);
                }

                if (!request.WantsTextChanges)
                {
                    // return the new document
                    var docText = await fixUsingsResponse.Solution.GetDocument(document.Id).GetTextAsync();

                    response.Buffer = docText.ToString();
                }
                else
                {
                    // return the text changes
                    var changes = await fixUsingsResponse.Solution.GetDocument(document.Id).GetTextChangesAsync(document);

                    response.Changes = await LinePositionSpanTextChange.Convert(document, changes);
                }
            }

            return(response);
        }
Esempio n. 4
0
        public static async Task <IEnumerable <LinePositionSpanTextChange> > GetFormattingChangesForRange(Workspace workspace, OptionSet options, Document document, int start, int end)
        {
            var changedDocument = await Formatter.FormatAsync(document, TextSpan.FromBounds(start, end), options);

            var textChanges = await changedDocument.GetTextChangesAsync(document);

            return((await LinePositionSpanTextChange.Convert(document, textChanges)).Select(change =>
            {
                change.NewText = EnsureProperNewLine(change.NewText, options);
                return change;
            }));
        }
        public async Task ExtendsTextChangeAtEnd()
        {
            var workspace = TestHelpers.CreateSimpleWorkspace("class {\n}");
            var document  = workspace.GetDocument("dummy.cs");

            var lineChanges = await LinePositionSpanTextChange.Convert(document, new TextChange[] {
                new TextChange(TextSpan.FromBounds(5, 7), "\r\n {\r")
            });

            Assert.Equal("\r\n {\r\n", lineChanges.ElementAt(0).NewText);
            Assert.Equal(1, lineChanges.ElementAt(0).StartLine);
            Assert.Equal(6, lineChanges.ElementAt(0).StartColumn);
            Assert.Equal(2, lineChanges.ElementAt(0).EndLine);
            Assert.Equal(1, lineChanges.ElementAt(0).EndColumn);
        }
Esempio n. 6
0
        public async Task <RunCodeActionResponse> Handle(RunCodeActionRequest request)
        {
            var actions = new List <CodeAction>();
            var context = await GetContext(request, actions);

            await GetContextualCodeActions(context);

            if (request.CodeAction > actions.Count())
            {
                return(new RunCodeActionResponse());
            }

            var action = actions.ElementAt(request.CodeAction);

            var operations = await action.GetOperationsAsync(CancellationToken.None);

            foreach (var o in operations)
            {
                o.Apply(_workspace, CancellationToken.None);
            }

            var originalDocument = context.Value.Document;
            var response         = new RunCodeActionResponse();

            if (!request.WantsTextChanges)
            {
                // return the new document
                var sourceText = await _workspace.CurrentSolution.GetDocument(originalDocument.Id).GetTextAsync();

                response.Text = sourceText.ToString();
            }
            else
            {
                // return the text changes
                var changes = await _workspace.CurrentSolution.GetDocument(originalDocument.Id).GetTextChangesAsync(originalDocument);

                response.Changes = await LinePositionSpanTextChange.Convert(originalDocument, changes);
            }

            return(response);
        }
Esempio n. 7
0
        public static async Task <IEnumerable <ModifiedFileResponse> > GetFileChangesAsync(Solution newSolution, Solution oldSolution, string newFileDirectory, bool wantTextChanges)
        {
            var changes         = new Dictionary <string, ModifiedFileResponse>();
            var solutionChanges = newSolution.GetChanges(oldSolution);

            foreach (var projectChange in solutionChanges.GetProjectChanges())
            {
                foreach (var changedDocumentId in projectChange.GetAddedDocuments())
                {
                    var document = newSolution.GetDocument(changedDocumentId);
                    var source   = await document.GetTextAsync();

                    var modifiedFileResponse = new ModifiedFileResponse(document.Name);
                    var change = new LinePositionSpanTextChange();
                    change.NewText = source.ToString();
                    var newPath = Path.Combine(newFileDirectory, document.Name);
                    modifiedFileResponse.FileName = newPath;
                    modifiedFileResponse.Changes  = new[] { change };
                    changes[newPath] = modifiedFileResponse;

                    // This is a little weird. The added document doesn't have a filepath
                    // and we need one so that future operations on this document work
                    var id           = DocumentId.CreateNewId(document.Project.Id);
                    var version      = VersionStamp.Create();
                    var documentInfo = DocumentInfo.Create(id, document.Name, filePath: newPath, loader: TextLoader.From(TextAndVersion.Create(source, version)));

                    var workspace = newSolution.Workspace as OmnisharpWorkspace;
                    workspace.RemoveDocument(changedDocumentId);
                    workspace.AddDocument(documentInfo);
                }

                foreach (var changedDocumentId in projectChange.GetChangedDocuments())
                {
                    var changedDocument = newSolution.GetDocument(changedDocumentId);
                    ModifiedFileResponse modifiedFileResponse;
                    var filePath = changedDocument.FilePath;

                    if (!changes.TryGetValue(filePath, out modifiedFileResponse))
                    {
                        modifiedFileResponse = new ModifiedFileResponse(filePath);
                        changes[filePath]    = modifiedFileResponse;
                    }

                    if (!wantTextChanges)
                    {
                        var changedText = await changedDocument.GetTextAsync();

                        modifiedFileResponse.Buffer = changedText.ToString();
                    }
                    else
                    {
                        var originalDocument = oldSolution.GetDocument(changedDocumentId);
                        IEnumerable <TextChange> textChanges;
                        textChanges = await changedDocument.GetTextChangesAsync(originalDocument);

                        var linePositionSpanTextChanges = await LinePositionSpanTextChange.Convert(originalDocument, textChanges);

                        modifiedFileResponse.Changes = modifiedFileResponse.Changes != null
                            ? modifiedFileResponse.Changes.Union(linePositionSpanTextChanges)
                            : linePositionSpanTextChanges;
                    }
                }
            }
            return(changes.Values);
        }
Esempio n. 8
0
        public async Task <RenameResponse> Rename(RenameRequest request)
        {
            var response = new RenameResponse();

            var document = _workspace.GetDocument(request.FileName);

            if (document != null)
            {
                var sourceText = await document.GetTextAsync();

                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));

                var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position);

                Solution solution = _workspace.CurrentSolution;

                if (symbol != null)
                {
                    try
                    {
                        solution = await Renamer.RenameSymbolAsync(solution, symbol, request.RenameTo, _workspace.Options);
                    }
                    catch (ArgumentException e)
                    {
                        response.ErrorMessage = e.Message;
                    }
                }

                var changes         = new Dictionary <string, ModifiedFileResponse>();
                var solutionChanges = solution.GetChanges(_workspace.CurrentSolution);

                foreach (var projectChange in solutionChanges.GetProjectChanges())
                {
                    foreach (var changedDocumentId in projectChange.GetChangedDocuments())
                    {
                        var changedDocument = solution.GetDocument(changedDocumentId);

                        ModifiedFileResponse modifiedFileResponse;
                        if (!changes.TryGetValue(changedDocument.FilePath, out modifiedFileResponse))
                        {
                            modifiedFileResponse = new ModifiedFileResponse(changedDocument.FilePath);
                            changes[changedDocument.FilePath] = modifiedFileResponse;
                        }

                        if (!request.WantsTextChanges)
                        {
                            var changedText = await changedDocument.GetTextAsync();

                            modifiedFileResponse.Buffer = changedText.ToString();
                        }
                        else
                        {
                            var originalDocument = _workspace.CurrentSolution.GetDocument(changedDocumentId);
                            var textChanges      = await changedDocument.GetTextChangesAsync(originalDocument);

                            var linePositionSpanTextChanges = await LinePositionSpanTextChange.Convert(originalDocument, textChanges);

                            modifiedFileResponse.Changes = modifiedFileResponse.Changes != null
                                ? modifiedFileResponse.Changes.Union(linePositionSpanTextChanges)
                                : linePositionSpanTextChanges;
                        }
                    }
                }

                if (request.ApplyTextChanges)
                {
                    // Attempt to update the workspace
                    if (_workspace.TryApplyChanges(solution))
                    {
                        response.Changes = changes.Values;
                    }
                }
                else
                {
                    response.Changes = changes.Values;
                }
            }

            return(response);
        }
        private static async Task <(string, LinePositionSpanTextChange)> TranslateAsync(this LinePositionSpanTextChange change, OmniSharpWorkspace workspace, string fileName)
        {
            var(line, newFileName) = await LineIndexHelper.TranslateFromGenerated(fileName, change.StartLine, workspace, false);

            change.StartLine = line;

            (line, _) = await LineIndexHelper.TranslateFromGenerated(fileName, change.EndLine, workspace, false);

            change.EndLine = line;

            return(newFileName, change);
        }
Esempio n. 10
0
 /// <summary>
 /// Converts an OmniSharp <see cref="Range"/> to a <see cref="TextSpan"/> within a <see cref="SourceText"/>.
 /// </summary>
 public static TextSpan GetSpanFromLinePositionSpanTextChange(this SourceText text, LinePositionSpanTextChange change)
 => TextSpan.FromBounds(
     start: text.GetPositionFromLineAndOffset(change.StartLine, change.StartColumn),
     end: text.GetPositionFromLineAndOffset(change.EndLine, change.EndColumn));