예제 #1
0
파일: Hash.cs 프로젝트: zhmyh1337/Terminal
        public override void Execute()
        {
            base.Execute();

            try
            {
                foreach (var filePath in Files)
                {
                    if (!File.Exists(filePath))
                    {
                        throw new FileNotFoundException(string.Format(Localization.errCommonFileNotExists, filePath));
                    }
                }

                var maxPathLength    = Files.Select(s => s.Length).Max();
                var algorithmHeader  = string.Format(Localization.hashHashingAlgorithm, HashAlgo);
                var hashingAlgorithm = HashAlgorithms.GetHashAlgorithm(HashAlgo);
                // We encode each byte with two symbols.
                var hashSumSymbolLength      = hashingAlgorithm.HashSize / 8 * 2;
                var consoleMinWidthToDoTable = Math.Max(algorithmHeader.Length + 2, hashSumSymbolLength + maxPathLength + 3) + 1;

                Func <string, string> filePathToHashSumString = filePath =>
                {
                    var fileBytes = File.ReadAllBytes(filePath);
                    var hashBytes = hashingAlgorithm.ComputeHash(fileBytes);
                    return(string.Join("", hashBytes.Select(x => x.ToString("x2"))));
                };

                // No space for table.
                if (Console.WindowWidth < consoleMinWidthToDoTable)
                {
                    const string pathHeaderTemplate = "===== {0} =====";
                    Logger.PrintLine($"[{algorithmHeader}]");

                    foreach (var filePath in Files)
                    {
                        Logger.PrintLine($"===== {filePath.PadRight(maxPathLength)} =====");
                        Logger.PrintLine(filePathToHashSumString(filePath));
                    }

                    // Not counting {0}.
                    Logger.PrintLine(new string('=', pathHeaderTemplate.Length - 3 + maxPathLength));
                }
                else
                {
                    var data = Enumerable.Range(0, Files.Count()).Select(i =>
                    {
                        var filePath = Files.ElementAt(i);
                        return(new string[] { filePath, filePathToHashSumString(filePath) });
                    }).ToArray();

                    // Keep in mind that (tableHeader[0].Length + tableHeader[1].Length)
                    // is gotta be < (algorithmHeader.Length).
                    var tableHeader = new string[2] {
                        Localization.hashFile, Localization.hashHashSum
                    };
                    var table = new Table(2, data, algorithmHeader, tableHeader);
                    table.Print();
                }
            }
            catch (Exception e)
            {
                Logger.PrintError(e.Message);
                OnError();
            }
        }