2 * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 using GenDummy.Processors;
18 using Microsoft.CodeAnalysis;
19 using Microsoft.CodeAnalysis.CSharp.Syntax;
20 using Microsoft.CodeAnalysis.Editing;
21 using Microsoft.CodeAnalysis.Text;
24 using System.Threading.Tasks;
28 public class DummyProject
30 readonly Project _project;
31 readonly IProcessor _processor;
35 AdhocWorkspace workSpace = new AdhocWorkspace();
36 ProjectInfo projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "DummyProject", "DummyAssembly", LanguageNames.CSharp);
37 _project = workSpace.AddProject(projectInfo);
39 _processor = new DummyProcessor();
42 public Task GenerateDummy(string source, string dest = null)
44 if (string.IsNullOrEmpty(source))
45 throw new ArgumentNullException("source");
47 return GenerateDummyInternal(source, dest);
50 async Task GenerateDummyInternal(string source, string dest = null)
52 var sourceText = File.ReadAllText(source);
53 var document = _project.AddDocument(Path.GetFileName(source), SourceText.From(sourceText));
54 document = await UpdateMembers(document);
55 var destText = await document.GetTextAsync();
57 string destPath = dest;
58 if (string.IsNullOrEmpty(dest))
60 destPath = Path.ChangeExtension(source, "dummy.cs");
62 File.WriteAllText(destPath, destText.ToString());
65 async Task<Document> UpdateMembers(Document document)
67 var documentRoot = (CompilationUnitSyntax)await document.GetSyntaxRootAsync();
68 var editor = await DocumentEditor.CreateAsync(document);
70 foreach (var member in documentRoot.DescendantNodes())
72 var newMember = _processor.Process(member as MemberDeclarationSyntax);
73 if (newMember != null)
75 editor.ReplaceNode(member, newMember);
78 return editor.GetChangedDocument();