来自命令行的autoformat代码

问题描述 投票:22回答:4

是否可以为解决方案中的所有或特定文件运行自动格式化代码,例如在Visual Studio中的(Ctrl + K,Ctrl + D)格式,但是从它的命令行?或者从解决方案文件的命令行中使用Resharper的清理?

c# visual-studio resharper autoformatting
4个回答
1
投票

要格式化net core c#source,请使用https://github.com/dotnet/format

按照项目自述文件安装工具。

我需要格式化一些我从Razor模板生成的代码文件。我在输出文件夹的根目录中创建了一个shell .CSProj文件,使用dotnet new console为您提供了这个基本文件:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <RootNamespace>dotnet_format</RootNamespace>
  </PropertyGroup>

</Project>

然后从该文件夹中的VS命令提示符运行dotnet format。它将递归到子目录并格式化它找到的所有内容。要格式化特定文件,您可以使用--files开关提供文件名列表。


12
投票

创建自己的工具。您可以使用EnvDTEEnvDTE80创建Visual Studio项目并加载要动态格式化的文件。完成后,删除Visual Studio项目。您可以指定在格式化时不显示Visual Studio窗口。如果您有兴趣,请告诉我,我可以给您一些代码来完成这项工作。

更新:我正在复制我的代码。我用它来格式化* .js文件。我删除了一些你不需要的代码。随意询问它是否不起作用。

    //You need to make a reference to two dlls:
    envdte
    envdte80



    void FormatFiles(List<FileInfo> files)
    {       
        //If it throws exeption you may want to retry couple more times
        EnvDTE.Solution soln = System.Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.Solution.11.0")) as EnvDTE.Solution;
        //try this if you have Visual Studio 2010
        //EnvDTE.Solution soln = System.Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.Solution.10.0")) as EnvDTE.Solution;
        soln.DTE.MainWindow.Visible = false;
        EnvDTE80.Solution2 soln2 = soln as EnvDTE80.Solution2;
        //Creating Visual Studio project
        string csTemplatePath = soln2.GetProjectTemplate("ConsoleApplication.zip", "CSharp");
        soln.AddFromTemplate(csTemplatePath, tempPath, "FormattingFiles", false);
        //If it throws exeption you may want to retry couple more times
        Project project = soln.Projects.Item(1);

        foreach (FileInfo file in files)
        {
            ProjectItem addedItem;
            bool existingFile = false;
            int _try = 0;
            while (true)
            {            
                try
                {
                    string fileName = file.Name;
                    _try++;
                    if (existingFile)
                    {
                        fileName = file.Name.Substring(0, (file.Name.Length - file.Extension.Length) - 1);
                        fileName = fileName + "_" + _try + file.Extension;
                    }
                    addedItem = project.ProjectItems.AddFromTemplate(file.FullName, fileName);
                    existingFile = false;
                    break;
                }
                catch(Exception ex)
                {
                    if (ex.Message.Contains(file.Name) && ex.Message.Contains("already a linked file"))
                    {
                        existingFile = true;
                    }
                }
            }
            while (true)
            {
                //sometimes formatting file might throw an exception. Thats why I am using loop.
                //usually first time will work
                try
                {
                    addedItem.Open(Constants.vsViewKindCode);
                    addedItem.Document.Activate();
                    addedItem.Document.DTE.ExecuteCommand("Edit.FormatDocument");
                    addedItem.SaveAs(file.FullName);
                    break;
                }
                catch
                {
                    //repeat
                }
            }
        }
        try
        {
            soln.Close();
            soln2.Close();
            soln = null;
            soln2 = null;
        }
        catch
        {
            //for some reason throws exception. Not all the times.
            //if this doesn't closes the solution CleanUp() will take care of this thing
        }
        finally
        {
            CleanUp();
        }
    }   

    void CleanUp()
    {
        List<System.Diagnostics.Process> visualStudioProcesses = System.Diagnostics.Process.GetProcesses().Where(p => p.ProcessName.Contains("devenv")).ToList();
        foreach (System.Diagnostics.Process process in visualStudioProcesses)
        {
            if (process.MainWindowTitle == "")
            {
                process.Kill();
                break;
            }
        }
        tempPath = System.IO.Path.GetTempPath();
        tempPath = tempPath + "\\FormattingFiles";
        new DirectoryInfo(tempPath).Delete(true);
    } 

我希望这有帮助。


4
投票

作为Dilshod帖子的后续内容,如果您只是想要格式化单个文件,这里有一种不需要临时路径的方法:

static void FormatFile(string file)
{
    EnvDTE.Solution soln = System.Activator.CreateInstance(
        Type.GetTypeFromProgID("VisualStudio.Solution.10.0")) as EnvDTE.Solution;

    soln.DTE.ItemOperations.OpenFile(file);

    TextSelection selection = soln.DTE.ActiveDocument.Selection as TextSelection;
    selection.SelectAll();
    selection.SmartFormat();

    soln.DTE.ActiveDocument.Save();
}

请注意,“file”将需要在磁盘上拥有完整路径。相对路径似乎不起作用(虽然我没有尝试那么难)。


2
投票

使用.NET团队中的CodeFormatter

  1. 安装MSBuild Tools 2015
  2. 下载CodeFormatter 1.0.0-alpha6
  3. CodeFormatter.csproj添加到项目的根目录:

CodeFormatter.csproj

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Compile Include="**\*.cs" />
  </ItemGroup>
  <Target Name="Compile">
    <Csc Sources="@(Compile)"/>
  </Target>
</Project>

然后从命令行运行它。

> codeformatter.exe CodeFormatter.csproj /nocopyright

结果是:所有项目的C#文件现在都遵循大多数.NET Foundation coding guidelines

备注

  • 安装MSBuild Tools 2015意味着我们不需要Visual Studio。
  • CodeFormatter.csproj添加到根目录递归地包括所有C#文件,这意味着上面的工作与project.json和基于* .xproj的设置一起使用。

也可以看看

http://bigfontblog.azurewebsites.net/autoformat/


1
投票

使用Visual Studio是不可能的,但是有一些命令行实用程序:http://astyle.sourceforge.net/astyle.html

© www.soinside.com 2019 - 2024. All rights reserved.