Skip to content

Commit

Permalink
Add initial functionality (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
fossbrandon authored May 24, 2023
1 parent 1c17606 commit 4b953d7
Show file tree
Hide file tree
Showing 30 changed files with 3,012 additions and 3 deletions.
12 changes: 12 additions & 0 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"csharpier": {
"version": "0.24.2",
"commands": [
"dotnet-csharpier"
]
}
}
}
15 changes: 15 additions & 0 deletions .csharpierrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Configures the CSharpier dotnet tool.
# More info: https://csharpier.com/docs/Configuration

# The line length where the formatter will wrap content.
# Note: This is not a hard limit and some lines will extend slightly past the limit.
# More info: https://csharpier.com/docs/Configuration#print-width
printWidth: 100

# Indent with spaces instead of tabs.
# More info: https://csharpier.com/docs/Configuration#use-tabs
useTabs: false

# The number of spaces per indentation level.
# More info: https://csharpier.com/docs/Configuration#tab-width
tabWidth: 4
625 changes: 625 additions & 0 deletions .editorconfig

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Assigns Git attributes to specified pathnames.
# More info: https://git-scm.com/docs/gitattributes

# ------------------
# General settings |
# ------------------
# Set default behaviour to automatically normalize line endings of text files.
* text=auto

# ----------------------------------------------------------------------
# Specify the line endings for files that should have a specific style |
# ----------------------------------------------------------------------
# Checkout with CRLF
*.sln text eol=crlf
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,4 @@ FodyWeavers.xsd
*.msp

# JetBrains Rider
*.sln.iml
*.sln.iml
23 changes: 23 additions & 0 deletions .prettierrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Configures the Prettier tool with settings not available in the .editorconfig file.
# More info: https://prettier.io/docs/en/configuration.html

# Specify the line length that the printer will wrap on.
# Overrides max_line_length from the .editorconfig file.
# More info: https://prettier.io/docs/en/options.html#print-width
printWidth: 100

# Prefer to use double quotes.
# More info: https://prettier.io/docs/en/options.html#quotes
singleQuote: false

# Only add quotes around object parameters when required.
# More info: https://prettier.io/docs/en/options.html#quote-props
quoteProps: "as-needed"

# Wrap markdown prose if it exceeds the print width.
# More info: https://prettier.io/docs/en/options.html#prose-wrap
proseWrap: "always"

# Allow formatting quoted code embedded in the file.
# More info: https://prettier.io/docs/en/options.html#embedded-language-formatting
embeddedLanguageFormatting: "auto"
30 changes: 30 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!-- Share build properties and packages with all projects -->
<Project>
<PropertyGroup>
<!-- Build-related Properties -->
<!-- Generate XML documentation of code from code comments -->
<GenerateDocumentationFile>true</GenerateDocumentationFile>

<!-- C# Compiler Options -->
<Nullable>enable</Nullable>

<!-- Generated File Properties -->
<ImplicitUsings>enable</ImplicitUsings>

<!-- Code Analysis Properties -->
<!-- Set the code analysis level to the latest recommended analyzers that have been released -->
<AnalysisLevel>latest-recommended</AnalysisLevel>
<!-- Enable code style analysis diagnostics for .NET projects to be reported on a build -->
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<!-- Do not allow warnings in a release build. Leave them as is during debug builds for developer sanity. -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

<!-- Commands to run before builds -->
<Target Name="Prebuild Actions" BeforeTargets="PreBuildEvent">
<Exec Command="dotnet tool restore"/>
</Target>
</Project>
File renamed without changes.
176 changes: 174 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,174 @@
# dotnet-style
A dotnet tool that provides a consistent style for C# files using configurable code formatters.
# Style

`dotnet-style` is a .NET tool that enables users to maintain a consistent and configurable C# code
style throughout projects.

It wraps existing and reputable tooling with the goal of providing a single interface for managing
C# code style functionality that would otherwise require running these other tools separately. As a
developer, this is less ideal because it requires me to remember the unique syntax and overall
knowledge for each of the separate tools rather than just learning and using this tool instead to
perform the same actions.

## Install

The .NET tool is available via [NuGet](https://www.nuget.org/packages/Style).

### Global Tool

If you want to run the .NET tool from any directory on your machine without specifying the tool's
location, install it as a global tool so that it is added to a directory visible to your PATH
environment variable.

Install `dotnet-style` as a global .NET tool using the command `dotnet tool install style --global`

### Local Tool

If you prefer to run the .NET tool from select directories, install it as a local tool. This can be
beneficial in instances such as working on a shared code repository where you want any developer who
clones the repo to have easy access to installing the same tools and versions as everyone else
working on the same code.

Install `dotnet-style` as a local .NET tool using the following steps:

1. Add a `dotnet-tools.json` manifest file in a `.config` directory under the current directory
using the command `dotnet new tool-manifest` if the files does not currently exist.
2. Install the .NET tool using the command `dotnet tool install style` without any additional
options.
- This updates the `dotnet-tools.json` manifest file with information such as the tool's name and
version so that all developers use the same tool.
3. Anyone who wants to use the local tool can run the command `dotnet tool restore` from within the
repo to restore their local .NET tool(s) to match the manifest file.

- 💡 `Quick Tip:` You can add this as an `MSBuild` `PreBuildEvent` so that devs don't have to
worry about manually checking for changes and restoring tools when applicable.

- Ex:

```xml
<!-- Commands to run before builds -->
<Target Name="Prebuild Actions" BeforeTargets="PreBuildEvent">
<Exec Command="dotnet tool restore"/>
</Target>
```

## Setup

`dotnet-style` wraps existing tools so you will need to setup the tools you plan to use along with
the code style configuration you want to enforce. More information regarding each configurable tool
is listed below:

- [dotnet-format](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-format):
- This tool is bundled with the `.NET 6 SDK` and later.
- If you are using an older version of .NET you'll have to install an older version of the tool
as a .NET tool.
- This tool uses an [EditorConfig](https://editorconfig.org/) as the configurable source of truth
for C# code style.
- Create your own `.editorconfig` file with customized settings and severities if you want to
manage code style using this tool.
- Examples:
- [Roslyn](https://github.com/dotnet/roslyn/blob/main/.editorconfig) has a pretty
comprehensive and highly used EditorConfig.
- Reference the `.editorconfig` files throughout
[dotnet-style repository](https://github.com/fossbrandon/dotnet-style) for extremely
customized (probably overkill 😁) examples where there is a default root configuration
that is overridden by more specific configurations when needed.
- [CSharpier](https://csharpier.com/):
- Install the tool following tool-specific documentation at the resource listed above.
- Because this is an opinionated code formatter, it only allows for a few configuration options to
be specified in a `.csharpierrc` file as explained in the tool-specific documentation.
- Example: Reference the `.csharpierrc.yaml` file located in the the
[dotnet-style repository](https://github.com/fossbrandon/dotnet-style) for an example of how
that repository configures and uses the tool.

## Usage

After the `dotnet-style` is installed you can run the tool by typing `dotnet style` in a terminal to
run the tool as a CLI application.

### General CLI Usage

```text
Style v1.0.0
A customizable dotnet tool that helps maintain a consistent C# coding style.

USAGE
dotnet style [options]
dotnet style [command] [...]

OPTIONS
-h|--help Shows help text.
--version Shows version information.

COMMANDS
format Formats C# files according to a defined coding style.
verify Verifies that C# files comply with the defined coding style.

You can run `dotnet style [command] --help` to show help on a specific command.
```

### Format Command Usage

```text
Style v1.0.0
A customizable dotnet tool that helps maintain a consistent C# coding style.
USAGE
dotnet style format [options]
DESCRIPTION
Formats C# files according to a defined coding style.
OPTIONS
-p|--path The directory containing files to recursively format. Default: "C:\Users\branfoss\source\repos\Style\src".
-s|--style Whether to format code using the 'dotnet format' formatter to run code style analyzers and apply fixes. Default: "True".
-a|--analyzers Whether to format code using the 'dotnet format' formatter to run third party code style analyzers and apply fixes. Default: "True".
-w|--whitespace Whether to format code using the 'dotnet format' formatter to run whitespace formatting. Default: "False".
-c|--csharpier Whether to format code using the 'CSharpier' opinionated formatter. Note: If formatting with --whitespace, this option must be disabled to avoid conflicts as they both handle whitespace formatting. Default: "True".
-v|--verbosity The output verbosity level. Choices: "Quiet", "Normal", "Verbose". Default: "Normal".
-h|--help Shows help text.
```

### Verify Command Usage

```text
Style v1.0.0
A customizable dotnet tool that helps maintain a consistent C# coding style.
USAGE
dotnet style verify [options]
DESCRIPTION
Verifies that C# files comply with the defined coding style.
OPTIONS
-p|--path The directory containing files to recursively verify the coding style compliance of. Default: "C:\Users\branfoss\source\repos\Style\src".
-s|--style Whether to verify code complies with the coding style used by the 'dotnet format' formatter for code style analyzer settings. Default: "True".
-a|--analyzers Whether to verify code complies with the coding style used by the 'dotnet format' formatter for third party code style analyzer settings. Default: "True".
-w|--whitespace Whether to verify code complies with the coding style used by the 'dotnet format' formatter for whitespace settings. Default: "False".
-c|--csharpier Whether to verify code complies with the coding style used by the 'CSharpier' opinionated formatter. Note: If verifying with --whitespace, this option must be disabled to avoid conflicts as they both handle whitespace formatting. Default: "True".
-v|--verbosity The output verbosity level. Choices: "Quiet", "Normal", "Verbose". Default: "Normal".
-h|--help Shows help text.
```

### Common Usage Examples

- Simple format usage: `dotnet style format`
- This will recursively format C# files starting in your current directory using the C# formatters
that are enabled by default.
- Customized format usage:
`dotnet style format -p ./src -s true -a true -w true -c false -v verbose`
- This will only format code in the .NET project defined within the relative `./src` directory
using the `dotnet-format` formatter instead of the `CSharpier` formatter to avoid opinionated
formatting. It also outputs additional information for potential debugging in the event there
are errors or you want more details throughout the process.

**Note:** You can replace `format` with `verify` in any of the above examples to verify whether the
current C# files comply with coding standards rather than actually modifying any code.

## Disclaimers

Since this .NET tool relies on other tools to perform the actual code style functions, there are
limitations. For instance, the `dotnet format` formatter tool does not automatically fix all
warnings/errors at the time of writing this. So, depending on how strict you make your
configuration, you may still have to manually fix code to ensure compliance with your coding
standards.
38 changes: 38 additions & 0 deletions Style.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33530.505
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Style", "src\Style.csproj", "{73E18D56-925E-4D8F-B2C6-42061D6B2F26}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Style.Tests", "test\Style.Tests.csproj", "{69FF95CA-2051-4E48-85E9-D8A2A7CBED91}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B11F635D-C86C-4056-BF64-8DDC58E65D36}"
ProjectSection(SolutionItems) = preProject
.csharpierrc.yaml = .csharpierrc.yaml
.gitignore = .gitignore
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{73E18D56-925E-4D8F-B2C6-42061D6B2F26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{73E18D56-925E-4D8F-B2C6-42061D6B2F26}.Debug|Any CPU.Build.0 = Debug|Any CPU
{73E18D56-925E-4D8F-B2C6-42061D6B2F26}.Release|Any CPU.ActiveCfg = Release|Any CPU
{73E18D56-925E-4D8F-B2C6-42061D6B2F26}.Release|Any CPU.Build.0 = Release|Any CPU
{69FF95CA-2051-4E48-85E9-D8A2A7CBED91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{69FF95CA-2051-4E48-85E9-D8A2A7CBED91}.Debug|Any CPU.Build.0 = Debug|Any CPU
{69FF95CA-2051-4E48-85E9-D8A2A7CBED91}.Release|Any CPU.ActiveCfg = Release|Any CPU
{69FF95CA-2051-4E48-85E9-D8A2A7CBED91}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {43769B75-8EB2-4A93-855A-47D11EB8B6A1}
EndGlobalSection
EndGlobal
10 changes: 10 additions & 0 deletions nuget.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- Define the package sources to get NuGet packages from -->
<packageSources>
<!-- Ensure no additional sources are inherited from another config file -->
<clear />
<!-- Sources listed here are used in order -->
<add key="nuget" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
22 changes: 22 additions & 0 deletions src/Attributes/FormatterOptionAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace Style.Attributes;

/// <summary>
/// Represents a CLI formatter option.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class FormatterOptionAttribute : Attribute
{
/// <summary>
/// Gets or initializes an identifier for this CLI formatter option.
/// </summary>
/// <remarks>
/// This value should be unique so that other attributes can reference the expected attribute.
/// </remarks>
public string Identifier { get; init; }

/// <summary>
/// Initializes a new instance of <see cref="FormatterOptionAttribute"/>.
/// </summary>
/// <param name="identifier">A unique identifier for this CLI formatter option.</param>
public FormatterOptionAttribute(string identifier) => Identifier = identifier;
}
Loading

0 comments on commit 4b953d7

Please sign in to comment.