Last active
December 13, 2015 22:49
-
-
Save nesteruk/4987154 to your computer and use it in GitHub Desktop.
R# plugin class creation sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static class ReadOnlyIntefaceBuilderWorkflow | |
{ | |
public static WorkflowResult Start([CanBeNull] CSharpGeneratorContext context, CSharpElementFactory factory) | |
{ | |
if (context.ClassDeclaration == null) return WorkflowResult.Inapplicable; | |
return CreateNewInterfaceDeclaration(context, factory); | |
} | |
private static WorkflowResult CreateNewInterfaceDeclaration(CSharpGeneratorContext context, CSharpElementFactory factory) | |
{ | |
string interfaceName = "IReadOnly" + context.ClassDeclaration.DeclaredName; | |
var itfDecl = (IInterfaceDeclaration)factory.CreateTypeMemberDeclaration("interface " + interfaceName + " {}"); | |
return AddInterfaceToContainingNamespace(context, itfDecl, factory); | |
} | |
private static WorkflowResult AddInterfaceToContainingNamespace(CSharpGeneratorContext context, IInterfaceDeclaration itfDecl, CSharpElementFactory factory) | |
{ | |
var ns = context.ClassDeclaration.GetContainingNamespaceDeclaration(); | |
if (ns == null) return WorkflowResult.Inapplicable; | |
else | |
{ | |
var typeDecl = ns.AddTypeDeclarationBefore(itfDecl, context.ClassDeclaration); | |
return PopulateInterfaceDeclaration(context, factory, (IInterfaceDeclaration)typeDecl); | |
} | |
} | |
private static WorkflowResult PopulateInterfaceDeclaration(CSharpGeneratorContext context, CSharpElementFactory factory, IInterfaceDeclaration itfDecl) | |
{ | |
var props = context.InputElements.OfType<GeneratorDeclaredElement<ITypeOwner>>().ToList(); | |
foreach (var prop in props) | |
{ | |
var propDecl = (IClassMemberDeclaration)factory.CreateTypeMemberDeclaration("public $0 $1 { get; }", prop.DeclaredElement.Type, prop.DeclaredElement.ShortName); | |
itfDecl.AddClassMemberDeclaration(propDecl); | |
} | |
return EnsureClassImplementsInterface(context, itfDecl); | |
} | |
private static WorkflowResult EnsureClassImplementsInterface(CSharpGeneratorContext context, IInterfaceDeclaration itfDecl) | |
{ | |
var interfaceType = TypeFactory.CreateType(itfDecl.DeclaredElement); | |
context.ClassDeclaration.AddSuperInterface(interfaceType, false); | |
return WorkflowResult.Success; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment