private async Task PerformSyntaxTreeValidation(
            string file,
            string fileContents,
            CSharpierResult result,
            CancellationToken cancellationToken
            )
        {
            if (!this.CommandLineOptions.Fast)
            {
                var syntaxNodeComparer = new SyntaxNodeComparer(
                    fileContents,
                    result.Code,
                    cancellationToken
                    );

                try
                {
                    var failure = await syntaxNodeComparer.CompareSourceAsync(cancellationToken);

                    if (!string.IsNullOrEmpty(failure))
                    {
                        Interlocked.Increment(ref this.Result.FailedSyntaxTreeValidation);
                        WriteLine(GetPath(file) + " - failed syntax tree validation");
                        WriteLine(failure);
                    }
                }
                catch (Exception ex)
                {
                    Interlocked.Increment(ref this.Result.ExceptionsValidatingSource);
                    WriteLine(
                        GetPath(file)
                        + " - failed with exception during syntax tree validation"
                        + Environment.NewLine
                        + ex.Message
                        + ex.StackTrace
                        );
                }
            }
        }
Exemple #2
0
        private static async Task DoWork(
            string file,
            string?path,
            bool validate,
            bool check,
            CancellationToken cancellationToken)
        {
            if (
                file.EndsWith(".g.cs") ||
                file.EndsWith(".cshtml.cs") ||
                file.ContainsIgnoreCase("\\obj\\") ||
                file.ContainsIgnoreCase("/obj/") ||
                file.EndsWithIgnoreCase("AllInOne.cs")
                )
            {
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();

            using var reader = new StreamReader(file);
            var code = await reader.ReadToEndAsync();

            var detectionResult = CharsetDetector.DetectFromFile(file);
            var encoding        = detectionResult.Detected.Encoding;

            reader.Close();

            cancellationToken.ThrowIfCancellationRequested();

            CSharpierResult result;

            string GetPath()
            {
                return(PadToSize(file.Substring(path?.Length ?? 0)));
            }

            try
            {
                result = await new CodeFormatter().FormatAsync(
                    code,
                    new Options(),
                    cancellationToken
                    );
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref files);
                Console.WriteLine(
                    GetPath() + " - threw exception while formatting"
                    );
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine();
                Interlocked.Increment(ref exceptionsFormatting);
                return;
            }


            if (result.Errors.Any())
            {
                Interlocked.Increment(ref files);
                Console.WriteLine(GetPath() + " - failed to compile");
                return;
            }

            if (!result.FailureMessage.IsBlank())
            {
                Interlocked.Increment(ref files);
                Console.WriteLine(GetPath() + " - " + result.FailureMessage);
                return;
            }

            if (validate)
            {
                var syntaxNodeComparer = new SyntaxNodeComparer(
                    code,
                    result.Code,
                    cancellationToken
                    );

                try
                {
                    var failure =
                        await syntaxNodeComparer.CompareSourceAsync(
                            cancellationToken
                            );

                    if (!string.IsNullOrEmpty(failure))
                    {
                        Interlocked.Increment(ref sourceLost);
                        Console.WriteLine(
                            GetPath() + " - failed syntax tree validation"
                            );
                        Console.WriteLine(failure);
                    }
                }
                catch (Exception ex)
                {
                    Interlocked.Increment(ref exceptionsValidatingSource);
                    Console.WriteLine(
                        GetPath() + " - failed with exception during syntax tree validation" + Environment.NewLine + ex.Message + ex.StackTrace
                        );
                }
            }

            if (check)
            {
                if (result.Code != code)
                {
                    Console.WriteLine(GetPath() + " - was not formatted");
                    Interlocked.Increment(ref unformattedFiles);
                }
            }

            cancellationToken.ThrowIfCancellationRequested();
            Interlocked.Increment(ref files);

            if (!check)
            {
                // purposely avoid async here, that way the file completely writes if the process gets cancelled while running.
                File.WriteAllText(file, result.Code, encoding);
            }
        }
        private async Task FormatFile(string file, CancellationToken cancellationToken)
        {
            if (ShouldIgnoreFile(file))
            {
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();

            var fileReaderResult =
                await FileReader.ReadFile(file, this.FileSystem, cancellationToken);

            if (fileReaderResult.FileContents.Length == 0)
            {
                return;
            }
            if (fileReaderResult.DefaultedEncoding)
            {
                WriteLine(
                    $"{GetPath(file)} - unable to detect file encoding. Defaulting to {fileReaderResult.Encoding}"
                    );
            }

            cancellationToken.ThrowIfCancellationRequested();

            CSharpierResult result;

            try
            {
                result = await new CodeFormatter().FormatAsync(
                    fileReaderResult.FileContents,
                    this.PrinterOptions,
                    cancellationToken
                    );
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref this.Result.Files);
                WriteLine(GetPath(file) + " - threw exception while formatting");
                WriteLine(ex.Message);
                WriteLine(ex.StackTrace);
                WriteLine();
                Interlocked.Increment(ref this.Result.ExceptionsFormatting);
                return;
            }

            if (result.Errors.Any())
            {
                Interlocked.Increment(ref this.Result.Files);
                WriteLine(GetPath(file) + " - failed to compile");
                return;
            }

            if (!result.FailureMessage.IsBlank())
            {
                Interlocked.Increment(ref this.Result.Files);
                WriteLine(GetPath(file) + " - " + result.FailureMessage);
                return;
            }

            if (!this.CommandLineOptions.Fast)
            {
                var syntaxNodeComparer = new SyntaxNodeComparer(
                    fileReaderResult.FileContents,
                    result.Code,
                    cancellationToken
                    );

                try
                {
                    var failure = await syntaxNodeComparer.CompareSourceAsync(cancellationToken);

                    if (!string.IsNullOrEmpty(failure))
                    {
                        Interlocked.Increment(ref this.Result.FailedSyntaxTreeValidation);
                        WriteLine(GetPath(file) + " - failed syntax tree validation");
                        WriteLine(failure);
                    }
                }
                catch (Exception ex)
                {
                    Interlocked.Increment(ref this.Result.ExceptionsValidatingSource);
                    WriteLine(
                        GetPath(file)
                        + " - failed with exception during syntax tree validation"
                        + Environment.NewLine
                        + ex.Message
                        + ex.StackTrace
                        );
                }
            }

            if (this.CommandLineOptions.Check)
            {
                if (result.Code != fileReaderResult.FileContents)
                {
                    WriteLine(GetPath(file) + " - was not formatted");
                    StringDiffer.PrintFirstDifference(
                        result.Code,
                        fileReaderResult.FileContents,
                        this.Console
                        );
                    Interlocked.Increment(ref this.Result.UnformattedFiles);
                }
            }

            cancellationToken.ThrowIfCancellationRequested();
            Interlocked.Increment(ref this.Result.Files);

            if (
                !this.CommandLineOptions.Check &&
                !this.CommandLineOptions.SkipWrite &&
                result.Code != fileReaderResult.FileContents
                )
            {
                // purposely avoid async here, that way the file completely writes if the process gets cancelled while running.
                this.FileSystem.File.WriteAllText(file, result.Code, fileReaderResult.Encoding);
            }
        }