Skip to content

Commit

Permalink
Getting things working with the changes that were in main
Browse files Browse the repository at this point in the history
  • Loading branch information
belav committed Sep 16, 2024
1 parent 21b7185 commit a8ffa77
Show file tree
Hide file tree
Showing 12 changed files with 104 additions and 60 deletions.
3 changes: 2 additions & 1 deletion Src/CSharpier.Cli.Tests/ServerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ public void RunTwo()

async Task NewFunction()
{
var command = Cli.Wrap("dotnet")
var command = CliWrap
.Cli.Wrap("dotnet")
.WithArguments(path + " --server")
.WithValidation(CommandResultValidation.None);

Expand Down
17 changes: 6 additions & 11 deletions Src/CSharpier.Cli/CommandLineFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ CancellationToken cancellationToken
cancellationToken
);

var originalDirectoryOrFile = commandLineOptions
.OriginalDirectoryOrFilePaths[x]
.Replace("\\", "/");
var originalDirectoryOrFile = commandLineOptions.OriginalDirectoryOrFilePaths[
x
].Replace("\\", "/");

var formattingCache = await FormattingCacheFactory.InitializeAsync(
commandLineOptions,
Expand Down Expand Up @@ -254,12 +254,8 @@ await FormatPhysicalFile(
return 1;
}

var tasks = fileSystem
.Directory.EnumerateFiles(
directoryOrFilePath,
"*.*",
SearchOption.AllDirectories
)
var tasks = fileSystem.Directory
.EnumerateFiles(directoryOrFilePath, "*.*", SearchOption.AllDirectories)
.Select(o =>
{
var normalizedPath = o.Replace("\\", "/");
Expand Down Expand Up @@ -385,7 +381,6 @@ CancellationToken cancellationToken
{
codeFormattingResult = await CodeFormatter.FormatAsync(
fileToFormatInfo.FileContents,
Path.GetExtension(fileToFormatInfo.Path),
printerOptions,
cancellationToken
);
Expand Down Expand Up @@ -435,7 +430,7 @@ CancellationToken cancellationToken
// TODO xml what about allowing lines between elements?
if (!commandLineOptions.Fast && fileToFormatInfo.Path.EndsWithIgnoreCase(".cs"))
{
// TODO the thing above should do this if we are using the csharp formatter
// TODO xml the thing above should do this if we are using the csharp formatter
var sourceCodeKind = Path.GetExtension(fileToFormatInfo.Path).EqualsIgnoreCase(".csx")
? SourceCodeKind.Script
: SourceCodeKind.Regular;
Expand Down
10 changes: 7 additions & 3 deletions Src/CSharpier.Cli/EditorConfig/EditorConfigSections.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@ internal class EditorConfigSections

var formatter =
resolvedConfiguration.Formatter
?? (filePath.EndsWith(".cs") || filePath.EndsWith(".csx") ? "csharp" : null);
?? (
filePath.EndsWith(".cs") ? "CSharp"
: filePath.EndsWith(".csx") ? "CSharpScript"
: null
);

if (formatter == null)
if (!Enum.TryParse<Formatter>(formatter, ignoreCase: true, out var parsedFormatter))
{
return null;
}

var printerOptions = new PrinterOptions { Formatter = formatter };
var printerOptions = new PrinterOptions { Formatter = parsedFormatter };

if (resolvedConfiguration.MaxLineLength is { } maxLineLength)
{
Expand Down
15 changes: 13 additions & 2 deletions Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,24 @@ internal class ConfigurationFileOptions
var matchingOverride = this.Overrides.LastOrDefault(o => o.IsMatch(filePath));
if (matchingOverride is not null)
{
if (
!Enum.TryParse<Formatter>(
matchingOverride.Formatter,
ignoreCase: true,
out var parsedFormatter
)
)
{
return null;
}

return new PrinterOptions
{
IndentSize = matchingOverride.TabWidth,
UseTabs = matchingOverride.UseTabs,
Width = matchingOverride.PrintWidth,
EndOfLine = matchingOverride.EndOfLine,
Formatter = matchingOverride.Formatter,
Formatter = parsedFormatter,
};
}

Expand All @@ -38,7 +49,7 @@ internal class ConfigurationFileOptions
UseTabs = this.UseTabs,
Width = this.PrintWidth,
EndOfLine = this.EndOfLine,
Formatter = "csharp",
Formatter = filePath.EndsWith(".cs") ? Formatter.CSharp : Formatter.CSharpScript,
};
}

Expand Down
19 changes: 17 additions & 2 deletions Src/CSharpier.Cli/Options/OptionsProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,24 @@ public static async Task<OptionsProvider> Create(
return resolvedEditorConfig.ConvertToPrinterOptions(filePath);
}

if (filePath.EndsWith(".cs") || filePath.EndsWith(".csx"))
if (filePath.EndsWith(".cs"))
{
return new PrinterOptions { Formatter = "csharp" };
return new PrinterOptions { Formatter = Formatter.CSharp };
}

if (filePath.EndsWith(".csx"))
{
return new PrinterOptions { Formatter = Formatter.CSharpScript };
}

if (
filePath.EndsWith(".csproj")
|| filePath.EndsWith(".props")
|| filePath.EndsWith(".targets")
|| filePath.EndsWith(".xml")
)
{
return new PrinterOptions { Formatter = Formatter.XML };
}

return null;
Expand Down
8 changes: 4 additions & 4 deletions Src/CSharpier.Playground/ClientApp/src/AppContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class AppState {
printWidth = getNumber("printWidth", 100);
indentSize = getNumber("indentSize", 4);
useTabs = getBoolean("useTabs", false);
parser = getString("parser", "CSharp");
formatter = getString("formatter", "CSharp");
showAst = getBoolean("showAst", false);
showDoc = getBoolean("showDoc", false);
hideNull = getBoolean("hideNull", false);
Expand All @@ -48,9 +48,9 @@ class AppState {
makeAutoObservable(this);
}

setParser = (value: string) => {
window.sessionStorage.setItem("parser", value);
this.parser = value;
setFormatter = (value: string) => {
window.sessionStorage.setItem("formatter", value);
this.formatter = value;
};

setIndentSize = (value: number) => {
Expand Down
8 changes: 3 additions & 5 deletions Src/CSharpier.Playground/ClientApp/src/Controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import "./Controls.css";
import { observer } from "mobx-react-lite";
import { useAppContext } from "./AppContext";

// TODO review this, looks like I was changing it to use mobx
// https://github.com/belav/csharpier/pull/858/files#diff-fe7eb3d9ce08803cc37869645e835dda3ecb5cf2e87991e6b73a7a246091f37b
export const Controls = observer(() => {
const {
printWidth,
Expand All @@ -13,8 +11,8 @@ export const Controls = observer(() => {
setIndentSize,
useTabs,
setUseTabs,
parser,
setParser,
formatter,
setFormatter,
showDoc,
setShowDoc,
hideNull,
Expand Down Expand Up @@ -44,7 +42,7 @@ export const Controls = observer(() => {
Use Tabs
</label>
<label>Parser</label>
<select value={parser} onChange={e => setParser(e.target.value)}>
<select value={formatter} onChange={e => setFormatter(e.target.value)}>
<option value="CSharp">C#</option>
<option value="CSharpScript">C# Script</option>
<option value="XML">XML</option>
Expand Down
17 changes: 8 additions & 9 deletions Src/CSharpier.Playground/Controllers/FormatController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class PostModel
public int PrintWidth { get; set; }
public int IndentSize { get; set; }
public bool UseTabs { get; set; }
public string Parser { get; set; } = string.Empty;
public string Formatter { get; set; } = string.Empty;
}

[HttpPost]
Expand All @@ -45,33 +45,32 @@ public async Task<FormatResult> Post(
CancellationToken cancellationToken
)
{
// TODO
var sourceCodeKind = false // model.FileExtension.EqualsIgnoreCase(".csx")
? SourceCodeKind.Script
: SourceCodeKind.Regular;
if (!Enum.TryParse<Formatter>(model.Formatter, ignoreCase: true, out var parsedFormatter))
{
throw new Exception("Invalid formatter " + model.Formatter);
}

var result = await CodeFormatter.FormatAsync(
model.Code,
// TODO
".cs",
new PrinterOptions
{
IncludeAST = true,
IncludeDocTree = true,
Width = model.PrintWidth,
IndentSize = model.IndentSize,
UseTabs = model.UseTabs,
Formatter = parsedFormatter,
},
cancellationToken
);

// TODO what about xml?
// TODO xml what about this?
var comparer = new SyntaxNodeComparer(
model.Code,
result.Code,
result.ReorderedModifiers,
result.ReorderedUsingsWithDisabledText,
sourceCodeKind,
parsedFormatter is Formatter.CSharp ? SourceCodeKind.Regular : SourceCodeKind.Script,
cancellationToken
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,6 @@ public void GetSets_Should_Handle_Nested_If()
#endif
#endif
",
// TODO because the second is a subset of the first, we don't actually need it
// but it's more work to figure that out for now
"ONE,TWO",
"ONE"
);
Expand Down
18 changes: 15 additions & 3 deletions Src/CSharpier.Tests/FormattingTests/BaseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,22 @@ protected async Task RunTest(
CancellationToken.None
);

var formatter = fileExtensionWithoutDot switch
{
"cs" => Formatter.CSharp,
"csx" => Formatter.CSharpScript,
"xml" => Formatter.XML,
_ => Formatter.Unknown,
};

var result = await CodeFormatter.FormatAsync(
fileReaderResult.FileContents,
"." + fileExtensionWithoutDot,
new PrinterOptions { Width = PrinterOptions.WidthUsedByTests, UseTabs = useTabs },
// TODO fileExtensionWithoutDot.EqualsIgnoreCase("csx") ? SourceCodeKind.Script : SourceCodeKind.Regular,
new PrinterOptions
{
Width = PrinterOptions.WidthUsedByTests,
UseTabs = useTabs,
Formatter = formatter,
},
CancellationToken.None
);

Expand All @@ -62,6 +73,7 @@ protected async Task RunTest(
normalizedCode = normalizedCode.Replace("\r\n", "\n");
}

// TODO xml what about this?
var comparer = new SyntaxNodeComparer(
expectedCode,
normalizedCode,
Expand Down
37 changes: 20 additions & 17 deletions Src/CSharpier/CodeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static Task<CodeFormatterResult> FormatAsync(
IndentSize = options.IndentSize,
EndOfLine = options.EndOfLine,
IncludeGenerated = options.IncludeGenerated,
Formatter = "csharp",
Formatter = Formatter.CSharp,
},
cancellationToken
);
Expand Down Expand Up @@ -59,7 +59,7 @@ public static Task<CodeFormatterResult> FormatAsync(
UseTabs = options.IndentStyle == IndentStyle.Tabs,
IndentSize = options.IndentSize,
EndOfLine = options.EndOfLine,
Formatter = "csharp",
Formatter = Formatter.CSharp,
},
SourceCodeKind.Regular,
cancellationToken
Expand All @@ -68,25 +68,28 @@ public static Task<CodeFormatterResult> FormatAsync(

internal static async Task<CodeFormatterResult> FormatAsync(
string fileContents,
string fileExtension,
PrinterOptions options,
CancellationToken cancellationToken
)
{
var loweredExtension = fileExtension.ToLower();

if (loweredExtension is ".cs")
{
return await CSharpFormatter.FormatAsync(fileContents, options, cancellationToken);
}

// TODO XML maybe make this opt in until it is better tested?
// TODO XML maybe don't include xml by default?
if (loweredExtension is ".csproj" or ".props" or ".targets" or ".xml")
return options.Formatter switch
{
return XmlFormatter.Format(fileContents, options);
}

return new CodeFormatterResult { FailureMessage = "Is an unsupported file type." };
Formatter.CSharp
=> await CSharpFormatter.FormatAsync(
fileContents,
options,
SourceCodeKind.Regular,
cancellationToken
),
Formatter.CSharpScript
=> await CSharpFormatter.FormatAsync(
fileContents,
options,
SourceCodeKind.Script,
cancellationToken
),
Formatter.XML => XmlFormatter.Format(fileContents, options),
_ => new CodeFormatterResult { FailureMessage = "Is an unsupported file type." }
};
}
}
10 changes: 9 additions & 1 deletion Src/CSharpier/PrinterOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ internal class PrinterOptions
public EndOfLine EndOfLine { get; set; } = EndOfLine.Auto;
public bool TrimInitialLines { get; init; } = true;
public bool IncludeGenerated { get; set; }
public string Formatter { get; init; } = string.Empty;
public Formatter Formatter { get; init; } = Formatter.Unknown;

public const int WidthUsedByTests = 100;

Expand All @@ -34,3 +34,11 @@ internal static string GetLineEnding(string code, PrinterOptions printerOptions)
return "\n";
}
}

internal enum Formatter
{
Unknown,
CSharp,
CSharpScript,
XML,
}

0 comments on commit a8ffa77

Please sign in to comment.