tafuji's blog

C#, Xamarin, Azure DevOps を中心に書いています。

Xamarin.Essentials メモ #1:コードスタイルの規約

はじめに

Xamarin.Essentials でコードのスタイルをどのように定めていて、それが守られるようになっているかを調べたときのメモです。

Xamarin.Essentials のコードスタイルのルール

Xamarin.Essentials では二つのツールが使われています。

StyleCop.Analyzer は NuGet パッケージとしてプロジェクトにインストールができ、ビルド時にコーディングルールにしたがっているかを調べてくれるツールです。 どのようなチェックを行うかのルールの選択が可能で、ルールセットファイルを作成することができます。

Xamarin.Essentials のルールファイルは以下のようになっていて、スタイルチェック時にルール違反があった場合は、警告にしているようです。

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Rules for Xamarin.Essentials" Description="Code analysis rules for Xamarin.Essentials." ToolsVersion="15.0">
  <IncludeAll Action="Warning" />
  <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
    <Rule Id="SA0001" Action="None" />
    <Rule Id="SA0002" Action="Warning" />
    <Rule Id="SA1000" Action="Warning" />
    <Rule Id="SA1001" Action="Warning" />

    <!-- 省略 -->

  </Rules>
</RuleSet>

StyleCop Analyzers は、stypecop.json ファイルに設定値を定義するこで、ルールのカスタマイズも可能です。(例えば、using ディレクティブを namespace 宣言の中にいれるか、いれないかなど)

{
  "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",

  "settings": {
    "layoutRules": {
      "newlineAtEndOfFile": "require"
    },
    "orderingRules": {
      "systemUsingDirectivesFirst": true,
      "usingDirectivesPlacement": "outsideNamespace"
    }
  }
}

これを見ると、ファイルの末尾には改行が必要で、using ディレクティブのルールは、System.xxx 系のネームスペースを先にならべる、namespace 宣言の外側に書くということがわかります。

では、「editorconfig は何をしているのか?」ということになりますが、StypeCop Analyzer のドキュメントに以下のように書かれていました。

💡 When working in Visual Studio, the IDE will not automatically adjust editor settings according to the values in stylecop.json. To provide this functionality as well, we recommend duplicating the basic indentation settings in a .editorconfig file. Users of the EditorConfig extension for Visual Studio will not need to update their C# indentation settings in order to match your project style.

Visual Studio などの IDE が stylecop.json の設定をみてコードのスタイルの自動補完をしないので、editorconfig などに同じインデントの設定を書いておくことをおすすめしますと書かれています。

IDE に自動補完を行わせるために、StyleCop Analyzer と editorconfig を併用しているとのことでした。