GithubHelp home page GithubHelp logo

stephanevg / psclassutils Goto Github PK

View Code? Open in Web Editor NEW
87.0 9.0 21.0 23.4 MB

A set of utilities to work with Powershell Classes

Home Page: http://powershelldistrict.com/how-to-generate-a-uml-diagram-using-powershell/

PowerShell 100.00%
powershell graphviz classes uml powershell-modules

psclassutils's Introduction

PSClassUtils

Summary

PsClassUtils, is a Powershell module which contains tools to ease the work with Powershell Classes.

One cool feature is available is the fact that it can generate UML-like Class Diagrams in png format of your scripts / modules in a glimps! (See Write-CUClassDiagram)

Since version 2.6.0 we have also added the possibility to automatically generate your pester tests for your entiere module / script / file(s).( See Write-CUPesterTest below.)


Build Status

Master Dev Downloads
master dev PSClassUtils

How to install PSClassUtils

Find-module PSClassUtils | install-Module

Release Notes

Release notes can be found here --> Release Notes

Functions currently available:

Get-CUClass
Get-CUClassConstructor
Get-CUClassMethod
Get-CUClassProperty
Get-CUCommands
Get-CUEnum
Get-CULoadedClass
Install-CUDiagramPrerequisites
Write-CUClassDiagram
Write-CUInterfaceImplementation
Write-CUPesterTest

Write-CUClassDiagram

Allows to generate UML diagrams of powerShell scripts / modules that contain PowerShell classes.

Prerequisites

This module has a dependency on Kevin Marquette's PSGraph powershell module. The prerequisites can be installed either manually, or by using the following methodology:

Import-Module PSClassutils
Install-CUDiagramPreRequisites

Functionality

Drawings

Write-CUClassDiagram currently allows to draw diagrams (or components of diagrams) of the follow items:

  • Document a Class
    • it's Properties
    • it's Methods
    • it's Constructors
    • it's Inheritance

Has a relationships (Composition) is currently not supported. (But is planned for a future release)

Inputs

It is possible to draw diagrams from classes in the following different manners:

  • On a folder level
    • This will create a diagram and document each independant .ps1 file that contains a class. If no classes are found, it will be an empty square.
  • File base (.ps1)
    • you can point the function to a single .ps1 file, and will generate the diagram for all the classes located in that file.
  • File base (.psm1)
    • you can point the function to a single .psm1 file, and will generate the diagram for all the classes located in that file.

Examples

A script called inheritance.ps1 contains the following code:

Class Woop {
    [String]$String
    [int]$number

    Woop([String]$String,[int]$Number){

    }

    [String]DoSomething(){
        return $this.String
    }
}

Class Wap :Woop {
    [String]$prop3

    DoChildthing(){}

}

Class Wep : Woop {
    [String]$prop4

    DoOtherChildThing(){

    }
}

Calling Write-CUClassDiagram

Write-CUClassDiagram -Path ".\Inheritance.ps1"

Results

example with inheritance

Live examples from existing modules on the internet:

I took the 'liberty' to run Write-CUClassDiagram on some well known modules available on the internet that are classed based. These are all great modules, and I recommend you have a look at them!

PSClassUtils

This is the result of running Write-CUClassDiagram on this module itself

PSClassUtils

Class.HostsManagement

Below is the export of the Class Diagram of a module I wrote that helps to manage HostsFiles accross the network using PowerShell classes. (The project is accessible Here)

Class.HostsManagement

Poshbot

Write-CUClassDiagram allows to generate diagrams of complex class based modules, and gives you the ability to have a global picture of any project quickly, without reading through the code. PoshBot is probably the best example:

PoshBot https://github.com/Stephanevg/PSClassUtils/blob/master/PSClassUtils/Examples/06/PoshBot_Diagram.png

Write-CUPesterTest

Since version 2.6.0 the PsClassUtils module received a few new cmdlets related to pester tests. The most interesting one is without a doubt the: Write-CUPesterTest

As it's name implies, this function allows to automatically generate your pester tests. (Click on the image below for an example.)

PesterTest]

Contributing guide

You feel like contributing to this project? Awesome! We are happy to hear that, and will to help you succeed in that. You can start by reading our Contribution guide.

Please don't hesitate to open an issue so we can quickly discuss about implementation details and design of your, perhaps to be, new feature of PSClassutils :)

Community contributions

for 'HacktOberFest' I created an issue to push people to use the module on their classes, and PR us their classes + examples.

Here under is the list of community driven contributions:

AclApp

Thanks to LxLeChat !!

Acl class is used to create a 3 levels folder structure in a standardized way. The acl creates both folders and corresponding groups and set acl.

AclApp

psclassutils's People

Contributors

bateskevin avatar iisresetme avatar laurentlienhard avatar lxlechat avatar mdavis332 avatar oasaleh avatar stephanevg avatar tigerfansga avatar tomlarse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

psclassutils's Issues

Enums are displayed as 'Classes'

Issue

Version -> 2.3.0

image

Expected bahaviour

It should look like this:

Enum EnumName
Value1
Value2

I also think it should not be drawed on the diagram immediatley, as we might not always want to have it displayed.

I would suggest adding a switch `-ShowEnums'

Add -Path parameter to functions

I would like to add the possiblity to get class information of classes located in files.
For this, adding -Path parameter seems to be the best solution.

The parameter should be added to the following functions:

  • Get-CuClass
  • Get-CUClassMethod
  • Get-CUClassConstructor
  • Get-CUClassProperty (Not sure about this one though)

The -Path parameter should be allowed to receive only either .ps1 or .psm1 files, any other types should be ignored.

edits after discussions

As suggested by @LxLeChat we could make -Path accept pipelineinput, and set an alias on it. It will allow us to avoid an extra complicated design choise, and handle folder input.
It will also make the cmdlet more user friendly, as one could use it like this:

Get-ChildItem -Path C:\MyFolderWithClasses\ -Recurse | Get-CuXXX

Also, what should not be forgoten, is that currently, the Get-CUXXX cmdlets have only one parameter -ClassName and it should be kept.

When no -Path is passed, the -ClassName should look into the current loaded classes (current existing code).
When -ClassName & -Path are together, -ClassName should filter the file out, that has a class having the name $ClassName

end of edits

This functionality has already been implmemented in Write-CUClassDiagram as in the following snippet:

$PathObject = Get-Item $Path
    if ($PathObject -is [System.IO.DirectoryInfo]) {
        $ExportFileName = "Diagram" + "." + $OutputFormat
        $FolderPath = $Path

        if ($Recurse) {

            $AllItems = Get-ChildItem -path "$($Path)\*" -Include "*.ps1", "*.psm1" -Recurse
        } else {
            $AllItems = Get-ChildItem -path "$($Path)\*" -Include "*.ps1", "*.psm1"
        }
        #$Path = $null
    }
    elseif ($PathObject -is [System.IO.FileInfo]) {
        [System.IO.FileInfo]$File = (Resolve-Path -Path $Path).Path
        $ExportFileName = $File.BaseName + "." + $OutputFormat
        $AllItems = $File
    }
    else {
        throw 'Path provided was not a file or folder'
    }

and we could reuse this to save some time.

(A switch would be even better ;))

Return type

i would imagine that the return type should be extended as well. I could see something similar to this:

Source ClassName Object
[System.IO.FileInfo] TheNameOfTheClass The object request
C:\Files\Myclass.ps1 CustomUser [CUClass]

Once we agree on the design, I will create individual issues per function, so work could be done by severals persons in parallel.
`

Add possibility to give outputName

since the introduction of excludes, It is possible for example to add only a few classes in a specific export which would represent a thing of my class models.

Often, I want to give them another name then the one of the file where I got it from. Therefor I would like to introduce the possibility to add the output name.

I am bit unsure of how we should call this parameter.

Here are a few Suggestions:

-Name | -FileName | -OutputFileName

Please advise

Get-CUClassProperty Throws error when using -Path

The issue seems to come from the 'Resolve-PAth' cmdlet, as it points it to --> C:\Windows\system32\Tests\woop.psm1' instead of the real path (in .\Tests\woop.psm folder of the module)

>  Get-CUClassProperty -Path .\Tests\woop.psm1
Resolve-Path : Cannot find path 'C:\Windows\system32\Tests\woop.psm1' because it does not exist.
At C:\Users\taavast3\OneDrive\Repo\Projects\OpenSource\PSClassUtils\PSClassUtils\Functions\Public\Get-CUClass.ps1:72 char:56
+ ...             $ClassParams.Path = (Get-Item (Resolve-Path $Path).Path). ...
+                                                ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Windows\system32\Tests\woop.psm1:String) [Resolve-Path], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand

Inheritence doesn't work when names have not the same sensititity

there is an issue with the 'edge' cmdlet of PSGraph. This one only accept 'exect' case sensitivy.

The example below will NOT display properly

Class Parent {

}

Class Child1 : parent {

}

The following work (Look closley at the Case sensitivty of 'Parent' in Child1:

Class Parent {

}

Class Child1 : Parent {

}

I opened a ticket to try and made 'edge' case insensitive.

Enhance Functions to get Class information from files (using AST )

I would like to update the following functions to not only show 'only loaded' classes, but also get the same class information from a class located in a file.

The following functions should be enhanced:

  • Get-CUClass
  • Get-CUClassConstructor
  • Get-CUClassMethod
  • Get-CUClassProperty

These are the technical details I think this could work at best:

Add Parameter: -Path

  • Possibility to read class from .PSM1 file
  • Possibility to read class from .PS1 file
  • Should Throw if not of type [System.IO.FileInfo]
  • Should throw if doesn't have extension .psm1 or .ps1

I think the best and easiest way for that, would be to add a call to Get-CUAST in each of these functions, and add some filtering.
This could also mean, that by extension, Get-CUAST might need some need options - Will see.

Write-CUClassDiagram -Show doens't open the generated file

It seems that with version 2.3.0, the -Show broke.

>  Write-CUClassDiagram -Path C:\Users\taavast3\OneDrive\Repo\Projects\OpenSource\PSHTML\Code\Classes\001.pshtml.utilities.configuration.ps1 -Show


    Directory: C:\Users\taavast3\OneDrive\Repo\Projects\OpenSource\PSHTML\Code\Classes


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        1/25/2019   2:00 PM         125319 001.pshtml.utilities.configuration.png

It doesn't open the file

Add support for Enums in Diagrams

This should not be that complicated, as the ASTDocument returns the following object:

image

The Enum property, contains an array of 'ClassEnums' (Which is defined here)

Discussion: Add / validate support for Linux / MacOSx

Edit

All issues related to Linux support are tracked here --> https://github.com/Stephanevg/PSClassUtils/projects/5


Hi all,

I think it is about time we takle the cross platformness of this module.
I belive we dont have anything that is blocking us from running this module on Linux / MacOSx, but I can't say for sure. I know that @tigerfansga has been using the module on Linux, but unsure on how sucessfully he was (You perhaps have some info to share with us?)

It would be great if someone could try this module out on a linux and/or macos box.

Perhaps, we could also add a Pester test or two, which would test if the module works on Windows, Linux and MacOSx.

Perhaps this means changing the CI? I am open for the discussion. @bateskevin Any insights on this one?

Add help + Wiki page

All commandlets have Comment based help + examples
It would be great to have help extracted into individual markdown pages (using PlatyPS for example).

Add 'include' parameter

It would be nice to have the possibility to select 'ONLY' the classes we would like to have in the export.

Filtering on the script file name doesn't help in all cases, as some files have more than one class in it.

Idea

Write-CUClassDiagram -Include "*Asset","Setting*" -Show

It should return classes (and enums) that have Either 'Asset' or 'Setting' in their name.

'Include' might be the wrong wording. The idea is to be able to 'select' the ones we want to output.

Perhaps a '-FilterScript' could be a path to dig?

Refactor Write-CUClassDiagram code

I am planning to refactor the complete code of Write-CUClassDiagram in order to seperate some of the bits, and isolate them for easier testability.
More details will follow.

Create a simple issue page

In order to give some guidance to users that would open an issue to report a bug / and / or that would like to request a feature, we would like to offer them a predefined page, which simple questions, to:

Standardise the way issues are filled.
Offer a way to the end users to correctly express them self.
Avoid that developers ask more info, by ensure all the information needed is already in the issue when first created.

RFC 001: Add feature Display Abastract syntax tree

Consider creating an abastract syntax tree visulisation for scripts:

Ideally, I would imagine a command having the following syntax:

Write-CUAbastractSyntaxTree -Path * -ExportPath 

-Path: should be capable of handeling FileInfo, FolderInfo, and strings as inputs (just like Write-CUClassDiagram),

-ExportPath : Should default to the current directory.
If no name is specified, it should be 'ScriptName.AbastractSyntaxTree.png'

By default, it should create one image per script file (to avoid a clustered image).

some information on AST:
https://geekeefy.wordpress.com/2017/06/07/powershell-tokenization-and-abstract-syntax-tree/

Refactor: Write-CUClassDiagram

having parameter $Path and $FolderPath is cumbersome for the end user.
Perhaps it make sense to add a little bit of logic, and get rid of the FolderPath parameter.

Function Write-CUClassDiagram {

  
    [CmdletBinding()]
    Param(
    
        
        [Parameter(Mandatory=$true,ParameterSetName='File')]
        [ValidateScript({
                test-Path $_
        })]
        [String]
        $Path,

        [Parameter(Mandatory=$true,ParameterSetName='Folder')]
        [ValidateScript({
                test-Path $_
        })]

        [String]
        $FolderPath,

        [Parameter(Mandatory=$False,ParameterSetName='Folder')]
        [Switch]
        $Recurse,

side effects:

This might have side effects on:

  • Out-CUPsGraph
  • Export-PsGraph

splines='ortho' points row edges to center of row instead of on the side

splines='ortho' allows to specifiy that the edges have a straight line style, instead of a curved one:

in https://github.com/Stephanevg/PSClassUtils/blob/Feature_Composition/PSClassUtils/Functions/Private/Out-CUPSGraph.ps1

when setting:

$Graph = Graph -ScriptBlock {

(No attributes are added)
we have the correct result (but with 'curved' lines)

image

$Graph = Graph -Attributes @{splines='ortho'} -ScriptBlock {

Attributes @{splines='ortho'} is added

Generates the following graph:

image

The issue, is that without splines=ortho the graph looks really messy when there are a lot of edges involved.

Write-CUClassDiagram -FolderPath throws error when Relative path is passed.

This works:

Write-CUClassDiagram -FolderPath C:\Users\plop\OneDrive\Scripting\Repository\Projects\OpenSource\PowershellClassUtils\Classes\

this throws an System Error:

Write-CUClassDiagram -FolderPath  .\Classes

Export-PSGraph : System error.
At C:\Users\plop\OneDrive\Scripting\Repository\Projects\OpenSource\PowershellClassUtils\Functions\public\Write-CUClassDiagram.ps1:293 char:24
+ ...  = $Graph | Export-PSGraph -DestinationPath $FullExportPath  -OutputF ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], ParseException
    + FullyQualifiedErrorId : System.Management.Automation.ParseException,Export-PSGraph

Installing PSClassUtils

In the readme.md maybe you should change the install part from:
Find-Module PSClassUtils | Install-Module PSClassUtils

to:
Find-Module PSClassUtils | Install-Module

else an error is thrown !

Write-CUPesterTests.ps1 : error in the pester file with ENUM

In my class I use an ENUM "company" which is stored in a ps1 file.
In the file pester during the test "It '[User] - [Constructor]" he expects a parameter of the type COMPANY but he does not know this type since for the test he does not load my file with my ENUM
     + [COMPANY] $ Company
     + ~~~~~~~
     Unable to find type [COMPANY]
I don't know if I'm clear :-)

Feature Request: Add -Raw parameter to functions

currently, the following functions return a specifc, dilated, information from the AST.

  • Get-CUClassMethod
  • Get-CUClassConstructor
  • Get-CUClassProperty

** Edit **

After dfiscussions, we thought it would be interesting to add the following parameters as well:

  • ClassName
  • $TypeName (Where $typeName is either Constructor, Method or Property).

Also, we want to extend the ASTDocument to return the Name of the class


I think it could be itnerested, to offer the possibility to instead return the specific types (properietary of the modules) that we could return the RAW AST object back.

Do you think this could be something usefull?

Add Class Diagram Example (3)

Add examples of your ClassDiagrams, and show the world, how cool your Classes are.

Instructions:

  1. Fork this repo
  2. Create a new folder under /Examples
  3. Include a .PS1 with your demo code
  4. Include a screenshot of the resulting Class diagram
  5. Add your example under the Examples section of the README for all to see!
  6. Send your Pull Request

Simplify Write-CUClassDiagram

We have reached a level of complexity which makes maintaining (addind a parameter or so) to write-CUClassDiagram pretty difficult.

I would like to open a discussion on how we could simplify this.

Paths we should consider:

Write-CUClassDiagram generated image only contains class name

When running the following:
Write-CUClassDiagram -Path .\class.ps1

the generated image contains only the file name
image

When specifying the complete path of the class file it works fine
Write-CUClassDiagram -Path c:\temp\class.ps1

the genrated image is alright
image

First command is buggy, second one works fine:
image

Erreur dans les tests sur les paramètres présent

Quand tu fais dans tes tests Pester un (Get-Command Install-CUDiagramPrerequisites).Parameters.keys -contains "proxy" le résultat est toujours vrai quelque soit la valeur que tu mets à la place de proxy.
Pour être certain qu'il test bien la présence du bon paramètre il faut ajouter | Should Be $true

cela donne
(Get-Command Install-CUDiagramPrerequisites).Parameters.keys -contains "proxy" | Should Be $true
et la effectivement si tu mets autre chose que proxy tu recois une erreur

Add ClassName property to ASTDocument Class

Hello Stephane,
Maybe we can add a simple property to the ASTDocument class called "ClassName".
Depending on the direction you are willing to take regarding #47 this could be useful, because i see that Get-CUClassConstructor, Get-CUClassMethod, Get-CUClassProperty take "classname" as theirs primary argument.

Add Class Diagram Example (1)

Add examples of your ClassDiagrams, and show the world, how cool your Classes are.

Instructions:

  1. Fork this repo
  2. Create a new folder under /Examples
  3. Include a .PS1 with your demo code
  4. Include a screenshot of the resulting Class diagram
  5. Add your example under the Examples section of the README for all to see!
  6. Send your Pull Request

Write-CUClassDiagram Throws error on PSCore (Windows)

PS C:\Users\taavast3> Write-CUClassDiagram -Path C:\MyHomeRepos\PSHTML\PSHTML\Classes\Public\Chart.ps1 -Show
The module PSGraph is a prerequisite for this script to work. Please Install PSGraph first using Install-Module PSGraph
At C:\MyHomeRepos\PSClassUtils\PSClassUtils\Functions\Public\Write-CUClassDiagram.ps1:113 char:13
+             throw 'The module PSGraph is a prerequisite for this scri ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (The module PSGr...-Module PSGraph:String) [], RuntimeException
+ FullyQualifiedErrorId : The module PSGraph is a prerequisite for this script to work. Please Install PSGraph first using Install-Module PSGraph

Add class Diagram Example (2)

Add examples of your ClassDiagrams, and show the world, how cool your Classes are.

Instructions:

  1. Fork this repo
  2. Create a new folder under /Examples
  3. Include a .PS1 with your demo code
  4. Include a screenshot of the resulting Class diagram
  5. Add your example under the Examples section of the README for all to see!
  6. Send your Pull Request

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.