GithubHelp home page GithubHelp logo

dtw-danward / powershell-beautifier Goto Github PK

View Code? Open in Web Editor NEW
331.0 22.0 38.0 305 KB

A whitespace reformatter and code cleaner for Windows PowerShell and PowerShell Core

License: MIT License

PowerShell 100.00%
powershell beautifier formatter pretty-printer whitespace powershell-core indentation

powershell-beautifier's People

Contributors

cyberkhalil avatar dtw-danward avatar m-kostrzewa avatar n8v 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

powershell-beautifier's Issues

Local Docker test script: Docker on Windows 10 can't copy files into Windows container while container is running

This is a known issue for Docker for Windows on Windows 10 running a Windows container (i.e. nanoserver, not Ubuntu or any Linux OS). It would be most ideal to be able to copy into the container regardless of running/stopped in case user already has a separate session connection to triage an issue (don't want to kill that session). Unfortunately we can't, bummer, so perhaps we localize this only for Windows containers and explicitly check within the copy function before the copy - host OS and container (server daemon) OS and stop before copy and restart after. Bummer but probably necessary.

Also, this is lower priority issue; most testing is done on Linux OSes (and I have a VM of Nano running as well, so not a huge deal).

Error when attempting to import module

I see the error below when attempting to import the module. Any ideas how I can get it working? Thanks

PS C:\Users\buddyholly\Downloads\PowerShell-Beautifier-master> Import-Module -Name .\PowerShell-Beautifier.psd1
You must provide a value expression on the right-hand side of the '-' operator.
At C:\Users\buddyholly\Downloads\PowerShell-Beautifier-master\src/DTW.PS.FileSystem.Encoding.psm1:408 char:16
+       { $Name - <<<< in ('Ascii','ASCIIEncoding','System.Text.ASCIIEncoding','US-ASCII') } { New-Object -TypeName Sys
tem.Text.AsciiEncoding }
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedValueExpression

Import-Module : Could not load file or assembly 'src\/DTW.PS.FileSystem.Encoding.psm1' or one of its dependencies. The
given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
At line:1 char:14
+ Import-Module <<<<  -Name .\PowerShell-Beautifier.psd1
    + CategoryInfo          : NotSpecified: (:) [Import-Module], FileLoadException
    + FullyQualifiedErrorId : System.IO.FileLoadException,Microsoft.PowerShell.Commands.ImportModuleCommand

Revisit initial whitespace inside @( groupings

If arrays are tight with whitespace (no space after commas), does it make sense to have a space after the @( opening? Even if @( is followed by a newline, no need for space. Add more grouping examples and test.

Local Docker test script: switch parameter to always delete/recreate container before copying

Rather than re-copying over preexisting content on a container, delete the container and recreate each time if user passes switch param.

If performance tests are good, rather than specifying param, could make delete/recreate the default. Downside is if user is also connected to container (manually poking about, running tests, etc.), stopping and deleting container might not be a wise.... could prompt user...?

[Informational] PowerShells Default encoding is UTF-8 without a BOM for textfiles

Hi Dan!

In reaction to your great effort about File encoding, I like to point you to the following information about Microsofts decision about Textfile encoding. (fi you do not allready seem it):

Default encoding is UTF-8 without a BOM except for New-ModuleManifest

Please allow me some words about it and your module.
I am also a BIG fan of the BOM because files without BOM force us to guess the encoding ... so I am sad about MS decision too ...

I have the impressio that your Module try to serve 2 purposes. Encoding and Formatting.
I think it is better to separate this totally. So its better maintainable and contributors having it easier to contribute to one of this topic.

Anny way...
I really, really appreciate yout work done here.

Have a good time, stay well
Peter

Add option for whitespace changes only

If a user only wants whitespace cleaned (re-indented with spaces or tabs, fixed within a line) but doesn't want aliases changed to cmdlet names, casing fixed, etc. an option -WhiteSpaceOnly could be added to Edit-DTWBeautifyScript.

Add option to output updated script only via standard output

To better integrate with external editors (Atom-Beautify), rather than overwrite the original SourcePath or output to new DestinationPath, updated script will be output to standard output. This is an option - i.e. parameter -StandardOutput - to be added to function Edit-DTWBeautifyScript.

When this option is specified:

  • Content changes will still be written to temp file.
  • SourcePath file will not be updated
  • DestinationPath value will be ignored
  • All status output currently output will be suppressed - same as -Quiet option.
  • Updated script in temp file will be written via Write-Output second to last step; last step is removing temp file
  • Write-Error won't be used for errors, instead will use:
[Console]::Error.WriteLine("error message")

For more info about returning stderr to a host calling PowerShell, see:
https://stackoverflow.com/questions/4998173/how-do-i-write-to-standard-error-in-powershell
See mklement0 section

Update test framework for use on Non-Windows machines (line endings overrides)

The test framework takes preexisting script files, beautifies them and compares them to known correct result files. All these files - source incorrect and correct results files - have Windows-style line endings. While the beautifier will run correctly on Windows (Windows PowerShell and Core) it won't run correctly on non-Windows because when the script is beautified it will using the current environment line endings which won't match the correct results files.

Changing the diff process (which is very accurate and works well) would be a lot of work, as would having multiple sets of results files - more long term maintenance as well. The best option is to add an override parameter to the beautifier to explicitly use Windows line endings when beautifying the test files. This - plus having an override for using non-Windows endings on a Windows machine - would be handy for end-users as well.

import-module returns Error.

Hello i'm using powershell 7.
here's what i tried.


> Install-Module -Name PowerShell-Beautifier

> Import-Module .\PowerShell-Beautifier.psd1
Import-Module: The specified module '.\PowerShell-Beautifier.psd1' was not loaded because no valid module file was found in any module directory.

my module folder also didnt contain anything new.

file name in readme instuctions

Hello there , i am still beginner here but maybe that could help ..
When i typed readme instructions i found this ..

PS C:\scripts\PowerShell-Beautifier-1.2.5> Import-Module PowerShell-Beautifier.psd1
Import-Module : The specified module 'PowerShell-Beautifier.psd1' was not loaded because no valid module file was found in any 
module directory.
At line:1 char:1
+ Import-Module PowerShell-Beautifier.psd1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (PowerShell-Beautifier.psd1:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
 

PS C:\scripts\PowerShell-Beautifier-1.2.5> Import-Module .\PowerShell-Beautifier.psd1

External command parameters borked by ValidCommandParameterNames

During experiments, snippet

docker run -id blabla

was changed to

docker run -Id

I presume that -Id is a learned CommandParameter and is stored in ValidCommandParameterNames table. However, maybe it shouldn't be applied for parameters of external commands? Not sure how to fix it though. We would need to detect whether we're inside powershell or an external command.

Slightly related #41

Support for relative input and output file paths

Currently the Edit-DTWBeautifyScript cmdlet doesn't support relative file paths.
As I sometimes have quite long paths to deal with, I would like to be able refer to the input and output file as:

Edit-DTWBeautifyScript .\MySript.ps1 .\MySriptNew.ps1

Which is also common for cmdlets like Get-Content .\MyFile.txt.

Test script fails on Correct test fails because of NewLine modifications by git

Currently the test script beautifies all the sample scripts in 1_Input_Bad and uses the -NewLine CRLF parameter override to force the beautified files to have CRLF endings to match those in the hand-edited 3_Output_Correct. The files in 3_Output_Correct were created on Windows so for testing in makes sense to force the override. That said: anyone that uses git to pull these files might get CRLF in the 3_Output_Correct files IF they are on Windows or just LF for everyone else. Which means we can't trust the comparison.

Fastest step to fix this would be to change the 3_Output_Correct to all be just LF and change the test script override to be -NewLine LF. That would be a good step to make sure it's clean and consistent... but I'm not 100% positive that someone pulling it might override the default git line ending settings. A better fix: the file comparison function (or a new function?) should have a option for comparing files that ignores line endings. Rather than read each file as an entire byte array, comparing each byte, instead use Get-Content to read from each file the sets of lines (which ignores line endings) and then do a binary compare within the lines.

$i --

$i-- is formatted to $i -- with the reformatter.
Example:

for ($i = 99; $i -gt 1; $i--) {
  Write-Output -InputObject "$i bottles of beer on the wall, $i bottles of beer."
  Write-Output -InputObject "Take one down and pass it around, $($i - 1) bottles of beer on the wall."
}

is reformatted to:

for ($i = 99; $i -gt 1; $i --) {
  Write-Output -InputObject "$i bottles of beer on the wall, $i bottles of beer."
  Write-Output -InputObject "Take one down and pass it around, $($i - 1) bottles of beer on the wall."
}

On the other hand, $i++ is still $i++ after reformatting.
Is this a bug or a feature?

Refactor whitespace rules code

Refactor code that identifies whether or not to add whitespace (currently not ideal for adding user-configurable options). Change to lambda-based design...?

Rewrite file encoding detection for efficiency and UTF-32 support

The function for determining the file encoding (Get-DTWFileEncoding) - specifically the code if no BOM is present - is not as efficient as it could be. Also, it might also have an subtle bug (if a 3 byte character exists at the beginning of a UTF-16 file). And it doesn't handle UTF-32 files. Update Get-DTWFileEncoding to fixed these issues.

Also, add UTF-32 files to test/FileEncoding tests.

Seriously, though, does anyone actually store their code in UTF-32?

Custom class type qualifiers break things

If the file being processed refers to a custom type that is defined elsewhere, the beautifier barfs.
For example:
(as used in Microsoft's AzSK framework code)
in Constants.ps1
class Constants { .. }
in ConfigurationHelper.ps1
$rootConfigPath = [Constants]::AzSKAppFolderPath ;
Then edit-dtwBeautifyScript -Verbose -sourcepath ./src/AzSK.Framework/Helpers/ConfigurationHelper.ps1 -DestinationPath /tmp/foo.ps1
will produce many errors (see below) and no output

Hacky work-around: If I add this line to DTW.PS.Beautifier.Main.psm1 line 420
$Err = $Err | where { -not $_.Message.StartsWith("Unable to find type")}
Then it works better.


A few errors generated:
Invoke-TokenizeSourceScriptContent : An error occurred; is there invalid PowerShell or some formatting / syntax issue in the script? See error record below.
At ~/.local/share/powershell/Modules/PowerShell-Beautifier/1.2.5/src/DTW.PS.Beautifier.Main.psm1:1332 char:5

Invoke-TokenizeSourceScriptContent -EV Err

CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Unable to find type [Constants]. Content: Constants, line: 18, column: 22
At ~/.local/share/powershell/Modules/PowerShell-Beautifier/1.2.5/src/DTW.PS.Beautifier.Main.psm1:1332 char:5
Invoke-TokenizeSourceScriptContent -EV Err

CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent

Invoke-TokenizeSourceScriptContent : Unable to find type [Constants]. Content: Constants, line: 80, column: 28
At ~/.local/share/powershell/Modules/PowerShell-Beautifier/1.2.5/src/DTW.PS.Beautifier.Main.psm1:1332 char:5

Add missing alias to command mappings (Core support across OSes)

With Core we run into the situation where script is written on one OS then beautified on second, different OS - but Core on the second OS doesn't have the same aliases mappings. The way the beautifier generates the lookup table is by seeing what's in memory first time it's loaded, so the mappings are always specific to that OS. But with cat, ls, write, etc. (see #7) those aliases won't be in memory on MacOS. And I'm sure there will be other issues on other OSes.

The safest / easiest thing to do is to add manual entries for all possible missing aliases during module load. However, as Core gets updated we might get future issues with aliases being added or removed. So in addition, test case Rename / Alias.ps1 should have every alias - across all OSes - added to it and testing should be done across all platforms.

Dot notation on Hash Table reference.

$test = @{ "First Name" = "Bob"; "Last Name" = "Smith" }
Write-Host "First Name : " $test."First Name"
Write-Host "Last Name : " $test."Last Name"

gets changed to

$test = @{ "First Name" = "Bob"; "Last Name" = "Smith" }
Write-Host "First Name : " $test. "First Name"
Write-Host "Last Name : " $test. "Last Name"

it puts a space between $test. and "First Name"/"Last Name".

Latest PowerShell Core: Cannot bind parameter 'Encoding'. Cannot convert the "byte" value of type "System.String" to type "System.Text.Encoding"

PowerShell RC1: "byte" cast no longer working.

Get-DTWFileEncoding : Cannot bind parameter 'Encoding'. Cannot convert the "byte" value of type "System.String" to type "System.Text.Encoding".
At C:\code\GitHub\PowerShell-Beautifier\src\DTW.PS.Beautifier.Main.psm1:1282 char:25

  • ... $TempFileEncoding = Get-DTWFileEncoding -Path $DestinationPathTemp
  •                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  • CategoryInfo : InvalidArgument: (:) [Get-DTWFileEncoding], ParameterBindingException
  • FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Get-DTWFileEncoding

Dot source syntax gets clobbered

I have Pester scripts which dot-source another file in the current dir,

. .\File.ps1

Edit-DTWBeautifyScript turns this into the very broken

..\File.ps1

I see the test case stuff and will try to work on a failing test shortly, maybe even a fix

Breaks class definitions

I was experimenting with the beautifier on existing codebase, and it seems to break class definitions. Here's an example:

Input

class TestClass {
  [string] $aa
}

$inst = [TestClass]::new()

Used command

> Edit-DTWBeautifyScript ./test.ps1  -Verbose                                             
VERBOSE: Reading source: .../test.ps1
VERBOSE: Tokenizing script content
VERBOSE: Migrate source content to destination format
VERBOSE: Write destination file: .../test.ps1
VERBOSE: Finished in 0.149 seconds.

Expected output

class TestClass {
    [string]$aa
}

$inst = [testclass]::new()

Actual output

class [testclass]{
  [string]$aa
}

$inst = [testclass]::new()

Of course, our test script breaks:

./test.ps1                                                                              
At .../test.ps1:1 char:6
+ class [testclass]{
+      ~
Missing name after class keyword.
+ CategoryInfo          : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingNameAfterKeyword

Additional info

> $PSVersionTable                                                                         

Name                           Value
----                           -----
PSVersion                      6.1.0-preview.1
PSEdition                      Core
GitCommitId                    v6.1.0-preview.1
OS                             Linux 4.13.9-300.fc27.x86_64 #1 SMP Mon Oct 23 13:41:58 UTC 2017
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
> Get-Module *Beautifier*                                                                 

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.2.3      PowerShell-Beautifier               {Add-DTWFileEncodingByteOrderMarker, Compare-DTWFiles, Compare-DTWFilesIgnoringBOM, Comp...

This https://github.com/DTW-DanWard/PowerShell-Beautifier/blob/master/src/DTW.PS.Beautifier.Main.psm1#L910 seems like a candidate for the source of the issue, but I don't know the codebase.

Whitespace Broken in multiline sets

When breaking a longer set whitespaces aren't removed:

λ  MyDiff $a $b -CompareObjects -DisplayWhitespace | ?{$_.Line -in 124..129}

Line Left                                                                                            Right
---- ----                                                                                            -----
124  ········[ValidateSet("applypatch-msg",·"pre-applypatch",·"post-applypatch",·`                   ········[ValidateSet("applypatch-msg","pre-applypatch","post-applypatch",`
125  ·················"pre-commit","prepare-commit-msg","commit-msg","post-commit",                  ················"pre-commit",·"prepare-commit-msg",·"commit-msg",·"post-commit",
126  ············"pre-rebase","post-checkout","post-merge","pre-push",                               ············"pre-rebase",·"post-checkout",·"post-merge",·"pre-push",

As you can see whether by using backticks to break the line or not, after correcting the first line your code stops removing whistspaces.

Support PowerShell Core

Expect these changes:

  • OS-specific line endings, provide parameter to override environment (in case Windows user wants Unix line endings and vice-versa).
  • Changes to better support Linux default file encoding? If a file doesn't appear to have any Unicode, assume it is UTF-8-sans BOM?
  • Change for OS-specific temp file location? Or keep in same folder as script?
  • Any API changes? Any cmdlet changes?

Make parameter types for [System.IO.File]::WriteAllLines more explicit (error on NanoServer)

.NET Core on NanoServer is having difficulty finding the correct (only) [System.IO.File]::WriteAllLines method call. Probably need to define second param more explicitly as System.Collections.Generic.IEnumerable[string].

Add-DTWFileEncodingByteOrderMarker : Cannot find an overload for "WriteAllLines" and the argument count: "3".
At C:\temp\PowerShell-Beautifier\src\DTW.PS.Beautifier.Main.psm1:1288 char:7
Add-DTWFileEncodingByteOrderMarker -Path $DestinationPathTemp - ...
+ CategoryInfo : NotSpecified: (:) [Add-DTWFileEncodingByteOrderMarker], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest,Add-DTWFileEncodingByteOrderMarker

Can't parse valid RegEx PoSh Function

Hi,

The following function returns the error below. Any ideas?

The function works perfectly well in PoSh 5.1 - I got it from an MS blog so it should be "good" PoSh:
https://devblogs.microsoft.com/scripting/use-powershell-to-work-with-any-ini-file/

Thanks,
Phil.

function Get-IniContent ($filePath)
{
    $ini = @{}
    switch -regex -file $FilePath
    {
        ^\[(.+)\] # Section
        {
            $section = $matches[1]
            $ini[$section] = @{}
            $CommentCount = 0
        }
        ^(;.*)$ # Comment
        {
            $value = $matches[1]
            $CommentCount = $CommentCount + 1
            $name = Comment + $CommentCount
            $ini[$section][$name] = $value
        }
        (.+?)\s*=(.*) # Key
        {
            $name,$value = $matches[1..2]
            $ini[$section][$name] = $value
        }
    }
    return $ini
}
Invoke-TokenizeSourceScriptContent : An error occurred; is there invalid PowerShell or some formatting / syntax issue in the script? See error record below.
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing statement block in switch statement clause. Content: , line: 57, column: 13
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing statement block in switch statement clause. Content: , line: 57, column: 17
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing statement block in switch statement clause. Content: , line: 63, column: 11
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : An expression was expected after '('. Content: , line: 63, column: 12
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing closing ')' in expression. Content: , line: 63, column: 12
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing statement block in switch statement clause. Content: , line: 63, column: 12
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing statement block in switch statement clause. Content: , line: 63, column: 15
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing condition in switch statement clause. Content: , line: 63, column: 15
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Missing closing '}' in statement block or type definition. Content: {, line: 53, column: 1
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Unexpected token ')' in expression or statement. Content: ), line: 63, column: 15
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Unexpected token '}' in expression or statement. Content: }, line: 75, column: 5
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent
 
Invoke-TokenizeSourceScriptContent : Unexpected token '}' in expression or statement. Content: }, line: 77, column: 1
At \\NAS01\Users$\foo.bar\Documents\WindowsPowerShell\Modules\PowerShell-Beautifier\1.2.5\src\DTW.PS.Beautifier.Main.psm1:1329 char:5
+     Invoke-TokenizeSourceScriptContent -EV Err
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-TokenizeSourceScriptContent

External commands borked by alias replacement

I've encountered an issue, where the following snippet

netsh interface ipv4 set address blabla

gets transformed to

netsh interface ipv4 Set-Variable address blabla

Is there a nice way to fix it? It seems to be handled in CommandArgument handler function. I don't see a way to differentiate it from legitimate scenarios though...

Style compliancy

Hello Dan,

Your project is great!
I would like to give you some feedback about some styles which I think should be different but before going into detail, I would like to understand which style guide (if any) you using as a lead.
I am aware of two renowned style guides:

I see small discrepancies with your beautifier and the style guides where it concerns spaces around commas and semicolons in collections ($array = @('one', 'two', 'three') is reformatted to: `$array = @('one','two','three')). Which might go a lot deeper with regards to styling and technically (AST relations), e.g.:

  • removing the semicolon at the end of each line (including a HashTable items, as in your own ReadMe.me example)
  • { ,@('test') } where only the left space (between the curly bracket and comma is removed)

Type names have incorrect case

Hello there, I had a quick look into the script, and it appears that the accelorator/type names are found using:

[psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::get

However, if you look into the hashtable that this returns, the casing is correct:
$Table = [psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::get
$Table.Keys | % {$Table[$_] | select Name, BaseType}

Maybe it would be better to use these values

Update DestinationPath logic to handle short / relative paths

If a user does not specify a full path for DestinationPath and that file doesn't already exist (i.e. the Resolve-Path call doesn't work 100% correctly) then assume the user wants the DestinationPath relative to the SourcePath.

Probably something like Join-Path SourcePath DestinationPath but need to handle situation if user has adding ..-type path as prefix.

Cache lookup table values after initial load

Currently the lookup tables (Module.PrivateData[Valid*Names]) load their values the first time Edit-DTWBeautifyScript is called. It takes a few seconds to do this and that's OK if you are processing multiple files in the shell; future times Edit-DTWBeautifyScript is called will run fast. However, if you are running Edit-DTWBeautifyScript from an external editor (i.e. Atom-Beautify), you will be launching a new PowerShell each time, meaning a few seconds wait each time - this is slow for end users.

The fix will be to:

  • Cache the values to a text file in the same folder the first time these values are loaded.
  • Provide an exported function to allows users to regenerate the cache file manually. (They might want to do this if they load their own custom modules into memory and want to capture their own exported functions).

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.