Skip to content

Commit 545bd0c

Browse files
committed
New Method and tests to check if a script ast contains dot sourcing
1 parent 86e6287 commit 545bd0c

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed

src/PowerShellEditorServices/Services/PowerShell/Refactoring/Utilities.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,16 @@ public static FunctionDefinitionAst GetFunctionDefByCommandAst(string OldName, i
106106
return CorrectDefinition;
107107
}
108108

109+
public static bool AssertContainsDotSourced(Ast ScriptAst){
110+
Ast dotsourced = ScriptAst.Find(ast =>{
111+
return ast is CommandAst commandAst && commandAst.InvocationOperator == TokenKind.Dot;
112+
},true);
113+
if (dotsourced != null)
114+
{
115+
return true;
116+
}
117+
return false;
118+
}
109119
public static Ast GetAst(int StartLineNumber, int StartColumnNumber, Ast Ast)
110120
{
111121
Ast token = null;
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function New-User {
2+
param (
3+
[string]$Username,
4+
[string]$password
5+
)
6+
write-host $username + $password
7+
8+
$splat= @{
9+
Username = "JohnDeer"
10+
Password = "SomePassword"
11+
}
12+
New-User @splat
13+
}
14+
15+
$UserDetailsSplat= @{
16+
Username = "JohnDoe"
17+
Password = "SomePassword"
18+
}
19+
New-User @UserDetailsSplat
20+
21+
New-User -Username "JohnDoe" -Password "SomePassword"
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
$sb = { $var = 30 }
2+
$shouldDotSource = Get-Random -Minimum 0 -Maximum 2
3+
if ($shouldDotSource) {
4+
. $sb
5+
} else {
6+
& $sb
7+
}

test/PowerShellEditorServices.Test/Refactoring/RefactorUtilitiesTests.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,5 +149,17 @@ public void GetFunctionDefinitionAst()
149149
Assert.Equal(1,symbol.Extent.StartColumnNumber);
150150

151151
}
152+
[Fact]
153+
public void AssertContainsDotSourcingTrue()
154+
{
155+
ScriptFile scriptFile = GetTestScript("TestDotSourcingTrue.ps1");
156+
Assert.True(Utilities.AssertContainsDotSourced(scriptFile.ScriptAst));
157+
}
158+
[Fact]
159+
public void AssertContainsDotSourcingFalse()
160+
{
161+
ScriptFile scriptFile = GetTestScript("TestDotSourcingFalse.ps1");
162+
Assert.False(Utilities.AssertContainsDotSourced(scriptFile.ScriptAst));
163+
}
152164
}
153165
}

0 commit comments

Comments
 (0)