Skip to content

Commit

Permalink
refactoring and test
Browse files Browse the repository at this point in the history
  • Loading branch information
davidegiacometti committed Sep 26, 2021
1 parent 7f1d6b1 commit edb2a6a
Show file tree
Hide file tree
Showing 8 changed files with 271 additions and 48 deletions.
3 changes: 2 additions & 1 deletion .pipelines/ci/templates/build-powertoys-steps.yml
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ steps:
**\Microsoft.PowerToys.Run.Plugin.Calculator.UnitTest.dll
**\Microsoft.Plugin.Uri.UnitTests.dll
**\Wox.Test.dll
**\Microsoft.PowerToys.Run.Plugin.System.UnitTests.dll
**\Microsoft.PowerToys.Run.Plugin.System.UnitTests.dll
**\Microsoft.PowerToys.Run.Plugin.WindowsTerminal.UnitTests.dll
!**\obj\**
# Native dlls
Expand Down
11 changes: 11 additions & 0 deletions PowerToys.sln
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTests-PdfThumbnailProvi
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerToys.Run.Plugin.WindowsTerminal", "src\modules\launcher\Plugins\Microsoft.PowerToys.Run.Plugin.WindowsTerminal\Microsoft.PowerToys.Run.Plugin.WindowsTerminal.csproj", "{A2D583F0-B70C-4462-B1F0-8E81AFB7BA85}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.PowerToys.Run.Plugin.WindowsTerminal.UnitTests", "src\modules\launcher\Plugins\Microsoft.PowerToys.Run.Plugin.WindowsTerminal.UnitTests\Microsoft.PowerToys.Run.Plugin.WindowsTerminal.UnitTests.csproj", "{4ED320BC-BA04-4D42-8D15-CBE62151F08B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Expand Down Expand Up @@ -974,6 +976,14 @@ Global
{A2D583F0-B70C-4462-B1F0-8E81AFB7BA85}.Release|x64.ActiveCfg = Release|x64
{A2D583F0-B70C-4462-B1F0-8E81AFB7BA85}.Release|x64.Build.0 = Release|x64
{A2D583F0-B70C-4462-B1F0-8E81AFB7BA85}.Release|x86.ActiveCfg = Release|x64
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Debug|x64.ActiveCfg = Debug|Any CPU
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Debug|x64.Build.0 = Debug|Any CPU
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Debug|x86.ActiveCfg = Debug|Any CPU
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Debug|x86.Build.0 = Debug|Any CPU
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Release|x64.ActiveCfg = Release|Any CPU
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Release|x64.Build.0 = Release|Any CPU
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Release|x86.ActiveCfg = Release|Any CPU
{4ED320BC-BA04-4D42-8D15-CBE62151F08B}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -1090,6 +1100,7 @@ Global
{11491FD8-F921-48BF-880C-7FEA185B80A1} = {2F305555-C296-497E-AC20-5FA1B237996A}
{F40C3397-1834-4530-B2D9-8F8B8456BCDF} = {2F305555-C296-497E-AC20-5FA1B237996A}
{A2D583F0-B70C-4462-B1F0-8E81AFB7BA85} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{4ED320BC-BA04-4D42-8D15-CBE62151F08B} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.10.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.5" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.5" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\..\..\..\codeAnalysis\GlobalSuppressions.cs">
<Link>GlobalSuppressions.cs</Link>
</Compile>
<AdditionalFiles Include="..\..\..\..\codeAnalysis\StyleCop.json">
<Link>StyleCop.json</Link>
</AdditionalFiles>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Microsoft.PowerToys.Run.Plugin.WindowsTerminal\Microsoft.PowerToys.Run.Plugin.WindowsTerminal.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Text.Json;
using Microsoft.PowerToys.Run.Plugin.WindowsTerminal.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.PowerToys.Run.Plugin.WindowsTerminal.UnitTests
{
[TestClass]
public class TerminalHelperTests
{
[DataTestMethod]
[DataRow("Windows PowerShell", true, "--window 0 nt --profile \"Windows PowerShell\"")]
[DataRow("Windows PowerShell", false, "--profile \"Windows PowerShell\"")]
public void ArgumentsTest(string profile, bool openNewTab, string expectedArguments)
{
var arguments = TerminalHelper.GetArguments(profile, openNewTab);
Assert.AreEqual(arguments, expectedArguments);
}

[TestMethod]
public void ParseSettingsTest()
{
var terminal = new TerminalPackage(string.Empty, new Version(), string.Empty, string.Empty);

var settingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json");
var settings = File.ReadAllText(settingsPath);
var profiles = TerminalHelper.ParseSettings(terminal, settings);

Assert.AreEqual(profiles.Count, 4);
}

[DataTestMethod]
[DataRow(
@"{""guid"":""{61c54bbd-c2c6-5271-96e7-009a87ff44bf}"",""name"":""Windows PowerShell"",""commandline"":""powershell.exe"",""hidden"":true}",
"61c54bbd-c2c6-5271-96e7-009a87ff44bf",
"Windows PowerShell",
true)]
[DataRow(
@"{""name"":""Windows PowerShell"",""commandline"":""powershell.exe"",""hidden"":false}",
null,
"Windows PowerShell",
false)]
public void ParseProfilesTest(string json, string identifier, string name, bool hidden)
{
var profileElement = JsonDocument.Parse(json).RootElement;
var terminal = new TerminalPackage(string.Empty, new Version(), string.Empty, string.Empty);
var profile = TerminalHelper.ParseProfile(terminal, profileElement);

var expectedIdentifier = identifier != null ? new Guid(identifier) : null as Guid?;
Assert.AreEqual(profile.Terminal, terminal);
Assert.AreEqual(profile.Identifier, expectedIdentifier);
Assert.AreEqual(profile.Name, name);
Assert.AreEqual(profile.Hidden, hidden);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// This file was initially generated by Windows Terminal Preview 1.11.2421.0
// It should still be usable in newer versions, but newer versions might have additional
// settings, help text, or changes that you will not see unless you clear this file
// and let us generate a new one for you.

// To view the default settings, hold "alt" while clicking on the "Settings" button.
// For documentation on these settings, see: https://aka.ms/terminal-documentation
{
"$schema": "https://aka.ms/terminal-profiles-schema",

"defaultProfile": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",

// You can add more global application settings here.
// To learn more about global settings, visit https://aka.ms/terminal-global-settings

// If enabled, selections are automatically copied to your clipboard.
"copyOnSelect": false,

// If enabled, formatted data is also copied to your clipboard
"copyFormatting": false,

// A profile specifies a command to execute paired with information about how it should look and feel.
// Each one of them will appear in the 'New Tab' dropdown,
// and can be invoked from the commandline with `wt.exe -p xxx`
// To learn more about profiles, visit https://aka.ms/terminal-profile-settings
"profiles":
{
"defaults":
{
// Put settings here that you want to apply to all profiles.
},
"list":
[
{
// Make changes here to the powershell.exe profile.
"guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"name": "Windows PowerShell",
"commandline": "powershell.exe",
"hidden": false
},
{
// Make changes here to the cmd.exe profile.
"guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
"name": "Command Prompt",
"commandline": "cmd.exe",
"hidden": false
},
{
"guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}",
"name": "Azure Cloud Shell",
"source": "Windows.Terminal.Azure"
},
{
"guid": "{2ece5bfe-50ed-5f3a-ab87-5cd4baafed2b}",
"name": "Git Bash",
"source": "Git"
}
]
},

// Add custom color schemes to this array.
// To learn more about color schemes, visit https://aka.ms/terminal-color-schemes
"schemes": [],

// Add custom actions and keybindings to this array.
// To unbind a key combination from your defaults.json, set the command to "unbound".
// To learn more about actions and keybindings, visit https://aka.ms/terminal-keybindings
"actions":
[
// Copy and paste are bound to Ctrl+Shift+C and Ctrl+Shift+V in your defaults.json.
// These two lines additionally bind them to Ctrl+C and Ctrl+V.
// To learn more about selection, visit https://aka.ms/terminal-selection
{ "command": {"action": "copy", "singleLine": false }, "keys": "ctrl+c" },
{ "command": "paste", "keys": "ctrl+v" },

// Press Ctrl+Shift+F to open the search box
{ "command": "find", "keys": "ctrl+shift+f" },

// Press Alt+Shift+D to open a new pane.
// - "split": "auto" makes this pane open in the direction that provides the most surface area.
// - "splitMode": "duplicate" makes the new pane use the focused pane's profile.
// To learn more about panes, visit https://aka.ms/terminal-panes
{ "command": { "action": "splitPane", "split": "auto", "splitMode": "duplicate" }, "keys": "alt+shift+d" }
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,77 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text.Json;

namespace Microsoft.PowerToys.Run.Plugin.WindowsTerminal.Helpers
{
public static class TerminalHelper
{
/// <summary>
/// Return the arguments for launch Windows Terminal
/// </summary>
/// <param name="profileName">Name of the Terminal profile</param>
/// <param name="openNewTab">Whether to launch the profile in a new tab</param>
public static string GetArguments(string profileName, bool openNewTab)
{
return openNewTab ? $"--window 0 nt --profile \"{profileName}\"" : $"--profile \"{profileName}\"";
}

/// <summary>
/// Return a list of profiles for the Windows Terminal
/// </summary>
/// <param name="terminal">Windows Terminal package</param>
/// <param name="settingsJson">Content of the settings JSON file of the Terminal</param>
public static List<TerminalProfile> ParseSettings(TerminalPackage terminal, string settingsJson)
{
var profiles = new List<TerminalProfile>();

var options = new JsonDocumentOptions
{
CommentHandling = JsonCommentHandling.Skip,
};

var json = JsonDocument.Parse(settingsJson, options);

json.RootElement.TryGetProperty("profiles", out JsonElement profilesElement);
if (profilesElement.ValueKind != JsonValueKind.Object)
{
return profiles;
}

profilesElement.TryGetProperty("list", out JsonElement profilesList);
if (profilesList.ValueKind != JsonValueKind.Array)
{
return profiles;
}

foreach (var profile in profilesList.EnumerateArray())
{
profiles.Add(ParseProfile(terminal, profile));
}

return profiles;
}

/// <summary>
/// Return a profile for the Windows Terminal
/// </summary>
/// <param name="terminal">Windows Terminal package</param>
/// <param name="profileElement">Profile from the settings JSON file</param>
public static TerminalProfile ParseProfile(TerminalPackage terminal, JsonElement profileElement)
{
profileElement.TryGetProperty("name", out JsonElement nameElement);
var name = nameElement.ValueKind == JsonValueKind.String ? nameElement.GetString() : null;

profileElement.TryGetProperty("hidden", out JsonElement hiddenElement);
var hidden = (hiddenElement.ValueKind == JsonValueKind.False || hiddenElement.ValueKind == JsonValueKind.True) && hiddenElement.GetBoolean();

profileElement.TryGetProperty("guid", out JsonElement guidElement);
var guid = guidElement.ValueKind == JsonValueKind.String ? Guid.Parse(guidElement.GetString()) : null as Guid?;

return new TerminalProfile(terminal, name, guid, hidden);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text.Json;
using Windows.Management.Deployment;

namespace Microsoft.PowerToys.Run.Plugin.WindowsTerminal.Helpers
Expand Down Expand Up @@ -50,51 +49,11 @@ public IEnumerable<TerminalProfile> GetProfiles()
continue;
}

var jsonText = File.ReadAllText(terminal.SettingsPath);

var options = new JsonDocumentOptions
{
CommentHandling = JsonCommentHandling.Skip,
};

var json = JsonDocument.Parse(jsonText, options);

json.RootElement.TryGetProperty("profiles", out JsonElement profilesElement);
if (profilesElement.ValueKind != JsonValueKind.Object)
{
continue;
}

profilesElement.TryGetProperty("list", out JsonElement profilesList);
if (profilesList.ValueKind != JsonValueKind.Array)
{
continue;
}

foreach (var profile in profilesList.EnumerateArray())
{
profiles.Add(ParseProfile(terminal, profile));
}
var settingsJson = File.ReadAllText(terminal.SettingsPath);
profiles.AddRange(TerminalHelper.ParseSettings(terminal, settingsJson));
}

return profiles.OrderBy(p => p.Name);
}

private static TerminalProfile ParseProfile(TerminalPackage terminal, JsonElement profileElement)
{
profileElement.TryGetProperty("name", out JsonElement nameElement);
var name = nameElement.ValueKind == JsonValueKind.String ? nameElement.GetString() : null;

profileElement.TryGetProperty("hidden", out JsonElement hiddenElement);
var hidden = (hiddenElement.ValueKind == JsonValueKind.False || hiddenElement.ValueKind == JsonValueKind.True) && hiddenElement.GetBoolean();

profileElement.TryGetProperty("guid", out JsonElement guidElement);
var guid = guidElement.ValueKind == JsonValueKind.String ? Guid.Parse(guidElement.GetString()) : null as Guid?;

profileElement.TryGetProperty("icon", out JsonElement iconElement);
var icon = iconElement.ValueKind == JsonValueKind.String ? iconElement.GetString() : null;

return new TerminalProfile(terminal, name, guid, icon, hidden);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@ public class TerminalProfile

public Guid? Identifier { get; }

public string Icon { get; }

public bool Hidden { get; }

public TerminalProfile(TerminalPackage terminal, string name, Guid? identifier, string icon, bool hidden)
public TerminalProfile(TerminalPackage terminal, string name, Guid? identifier, bool hidden)
{
Terminal = terminal;
Name = name;
Identifier = identifier;
Icon = icon;
Hidden = hidden;
}
}
Expand Down

1 comment on commit edb2a6a

@github-actions
Copy link

@github-actions github-actions bot commented on edb2a6a Sep 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@check-spelling-bot Report

Unrecognized words, please review:

  • keybindings
Previously acknowledged words that are now absent Accessible available chrisharris CIEXYZ coc CTriage djsoref docsmsft dogancelik dupenv estdir Fody ftps gmx htt inprivate installpowertoys itsme listbox mfreadwrite mfuuid Nefario nitroin null nunit powertoyswiki PROGRAMFILES Radiobuttons sidepanel spamming systray ulazy windevbuildagents winstore xia XSmall xunit
Some files were were automatically ignored

These sample patterns would exclude them:

^src/modules/previewpane/UnitTests-MarkdownPreviewHandler/HelperFiles/MarkdownWithHTMLImageTag\.txt$

You should consider adding them to:

.github/actions/spell-check/excludes.txt

File matching is via Perl regular expressions.

To check these files, more of their words need to be in the dictionary than not. You can use patterns.txt to exclude portions, add items to the dictionary (e.g. by adding them to allow.txt), or fix typos.

To accept these unrecognized words as correct (and remove the previously acknowledged and now absent words), run the following commands

... in a clone of the [email protected]:microsoft/PowerToys.git repository
on the users/davidegiacometti/terminal-plugin branch:

update_files() {
perl -e '
my @expect_files=qw('".github/actions/spell-check/expect.txt"');
@ARGV=@expect_files;
my @stale=qw('"$patch_remove"');
my $re=join "|", @stale;
my $suffix=".".time();
my $previous="";
sub maybe_unlink { unlink($_[0]) if $_[0]; }
while (<>) {
if ($ARGV ne $old_argv) { maybe_unlink($previous); $previous="$ARGV$suffix"; rename($ARGV, $previous); open(ARGV_OUT, ">$ARGV"); select(ARGV_OUT); $old_argv = $ARGV; }
next if /^(?:$re)(?:(?:\r|\n)*$| .*)/; print;
}; maybe_unlink($previous);'
perl -e '
my $new_expect_file=".github/actions/spell-check/expect.txt";
use File::Path qw(make_path);
use File::Basename qw(dirname);
make_path (dirname($new_expect_file));
open FILE, q{<}, $new_expect_file; chomp(my @words = <FILE>); close FILE;
my @add=qw('"$patch_add"');
my %items; @items{@words} = @words x (1); @items{@add} = @add x (1);
@words = sort {lc($a)."-".$a cmp lc($b)."-".$b} keys %items;
open FILE, q{>}, $new_expect_file; for my $word (@words) { print FILE "$word\n" if $word =~ /\w/; };
close FILE;
system("git", "add", $new_expect_file);
'
(cat '.github/actions/spell-check/excludes.txt' - <<EOF
$should_exclude_patterns
EOF
) |grep .|
sort -f |
uniq > '.github/actions/spell-check/excludes.txt.temp' &&
mv '.github/actions/spell-check/excludes.txt.temp' '.github/actions/spell-check/excludes.txt'
}

comment_json=$(mktemp)
curl -L -s -S \
  --header "Content-Type: application/json" \
  "https://api.github.com/repos/microsoft/PowerToys/comments/57078587" > "$comment_json"
comment_body=$(mktemp)
jq -r .body < "$comment_json" > $comment_body
rm $comment_json

patch_remove=$(perl -ne 'next unless s{^</summary>(.*)</details>$}{$1}; print' < "$comment_body")
  

patch_add=$(perl -e '$/=undef;
$_=<>;
s{<details>.*}{}s;
s{^#.*}{};
s{\n##.*}{};
s{(?:^|\n)\s*\*}{}g;
s{\s+}{ }g;
print' < "$comment_body")
  

should_exclude_patterns=$(perl -e '$/=undef;
$_=<>;
exit unless s{(?:You should consider excluding directory paths|You should consider adding them to).*}{}s;
s{.*These sample patterns would exclude them:}{}s;
s{.*\`\`\`([^`]*)\`\`\`.*}{$1}m;
print' < "$comment_body" | grep . || true)

update_files
rm $comment_body
git add -u
If you see a bunch of garbage

If it relates to a ...

well-formed pattern

See if there's a pattern that would match it.

If not, try writing one and adding it to the patterns.txt file.

Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

Note that patterns can't match multiline strings.

binary-ish string

Please add a file path to the excludes.txt file instead of just accepting the garbage.

File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

Please sign in to comment.