Пример #1
0
        private static void WarnBroken(string msg, string filePath, MBINFile mbin, NMSTemplate data = null, ulong expectedGUID = 0L)
        {
            #if ERROR_ON_BROKEN
            if (mbin != null)
            {
                throw new MbinException(msg, filePath, mbin);
            }
            throw new ExmlException(msg, filePath, data);
            #endif

            Async.SynchronizeTask(errorLock, ref errorTask, () => {
                warnedFiles.Add(filePath);
                warnings.Add(msg);
                if (Logger.LogStream.BaseStream.Position != lastPosition)
                {
                    msg = $"\n{msg}";
                }
                Logger.LogWarning($"{msg}");
                using (var indentInfo = new Logger.IndentScope()) {
                    Logger.LogMessage(false, Console.Out, null, "");   // newline, console only
                    Logger.LogMessage(Console.Out, $"[INFO]: {filePath}");
                    if (mbin != null)
                    {
                        Logger.LogMessage(false, Console.Out, null, "");   // newline, console only
                        Logger.LogMessage(null, "INFO", $"{CommandLine.GetFileInfo( mbin )}");
                        if (expectedGUID != 0L)
                        {
                            Logger.LogMessage(null, "EXPECTED INFO", $"GUID: {expectedGUID:X}\n");
                        }
                    }
                    //Logger.LogMessage( true, Console.Out, null, "" ); // newline, console and log
                }
                lastPosition = Logger.LogStream.BaseStream.Position;
            });
        }
Пример #2
0
        public static int Main(string[] args)
        {
            CommandLine.Initialize();

            Logger.Open(Path.ChangeExtension(Utils.GetExecutablePath(), ".log"));
            Logger.EnableTraceLogging = true;

#if DEBUG_STDOUT
            Logger.LogToConsole = true;
#endif

            Logger.LogMessage("VERSION", $"MBINCompiler v{Version.GetVersionStringCompact()}");
            Logger.LogMessage("ARGS", $"\"{string.Join( "\" \"", args )}\"\n");
            using (var indent = new Logger.IndentScope()) {
                Logger.LogMessage("If you encounter any errors, please submit a bug report and include this log file.\n" +
                                  "Please check that there isn't already a similar issue open before creating a new one.\n" +
                                  "https://github.com/monkeyman192/MBINCompiler/issues\n");
            }

            var options = new CommandLineParser(args);
            options.AddOptions(null, OPTIONS_GENERAL);
            options.AddOptions("help", OPTIONS_HELP);
            options.AddOptions("version", OPTIONS_VERSION);
            options.AddOptions("convert", OPTIONS_CONVERT);

            // save the error state
            bool invalidArguments = !options.Parse("convert");

            // get the Quiet option first, before we emit anything
            Quiet = options.GetOptionSwitch("quiet");
            if (Quiet)
            {
                Console.SetOut(new StreamWriter(Stream.Null));
                Console.SetError(Console.Out);
            }

            // now we can emit an error if we need to
            if (invalidArguments)
            {
                return(CommandLine.ShowInvalidCommandLineArg(options));
            }

            try {
                switch (options.Verb)
                {
                case "help": return(CommandLine.ShowHelp());

                case "version": return(HandleVersionMode(options));

                default: return(HandleConvertMode(options));
                }
            } catch (System.Exception e) {
                return(CommandLine.ShowException(e));
            }
        }
Пример #3
0
        public static int ShowException(Exception e, bool wait = true)
        {
            if (e is AggregateException ae)
            {
                foreach (var ie in ae.InnerExceptions)
                {
                    ShowException(ie, false);
                }
                WaitForKeypress(wait);
                return((int)ErrorCode.Unknown);
            }

            string msg = (e is CompilerException) ? e.InnerException?.Message : null;

            if ((Logger.LogStream?.BaseStream.Position ?? 0) != lastPosition)
            {
                Logger.LogMessage("");                                                                   // new line, log only
            }
            ShowError($"[{e.GetType().Name}]: {msg ?? e.Message}", wait: false);
            using (var indent = new Logger.IndentScope()) {
                var  b    = e;
                bool once = true;
                while (b.InnerException != null)
                {
                    b    = b.InnerException;
                    msg  = (once && (msg != null)) ? "" : null;
                    msg  = msg ?? $": {b.Message}";
                    once = false;
                    if (b is System.Reflection.TargetInvocationException)
                    {
                        continue;
                    }
                    Logger.LogMessage($"[{b.GetType().Name}]{msg}");
                }

                if (e is CompilerException)
                {
                    Logger.LogMessage("INFO", $"\n{((CompilerException) e).FileName}");
                    if (e is MbinException)
                    {
                        var mbin = ((MbinException)e).Mbin;
                        Logger.LogMessage("INFO", GetFileInfo(mbin));
                    }
                    e = e.InnerException;
                }

                Logger.LogMessage((e is System.IO.EndOfStreamException) ? "" : $"\n{b.StackTrace}\n");
            }
            lastPosition = Logger.LogStream?.BaseStream.Position ?? 0;
            WaitForKeypress(wait);
            return((int)ErrorCode.Unknown);
        }
Пример #4
0
 private static void EmitResults(bool error, List <string> files, List <string> results)
 {
     //#if !DEBUG
     using (var indentScope = new Logger.IndentScope( )) {
         for (int i = 0; i < files.Count; i++)
         {
             if (error)
             {
                 Logger.LogError("{0}", results[i]);
             }
             else
             {
                 Logger.LogWarning("{0}", results[i]);
             }
             Logger.LogMessage(Console.Out, "", "[FILE]: {0}\n", files[i]);
         }
     }
     //#endif
 }
Пример #5
0
        public static int ShowException(Exception e)
        {
            string msg = (e.GetType() == typeof(CompilerException)) ? e.InnerException.Message : null;

            ShowError($"[{e.GetType().Name}]: {msg ?? e.Message}", wait: false);
            using (var indent = new Logger.IndentScope()) {
                var  b    = e;
                bool once = true;
                while (b.InnerException != null)
                {
                    b    = b.InnerException;
                    msg  = (once && (msg != null)) ? "" : null;
                    msg  = msg ?? $": {b.Message}";
                    once = false;
                    if (b is System.Reflection.TargetInvocationException)
                    {
                        continue;
                    }
                    Logger.LogMessage($"[{b.GetType().Name}]{msg}");
                }

                if (e is CompilerException)
                {
                    Logger.LogMessage("INFO", $"\n{((CompilerException) e).FileName}");
                    if (e is MbinException)
                    {
                        var mbin = ((MbinException)e).Mbin;
                        Logger.LogMessage("INFO", $"MBIN\tversion:\t{mbin.Header.GetMBINVersion()}\tguid:\t{mbin.Header.TemplateGUID:X}\ttemplate:\t{mbin.Header.TemplateName}");
                    }
                    e = e.InnerException;
                }

                if (!(e is System.IO.EndOfStreamException))
                {
                    Logger.LogMessage($"\n{b.StackTrace}\n");
                }
            }
            return((int)ErrorCode.Unknown);
        }
Пример #6
0
        public static void ConvertFile(string fileIn, string fileOut, FormatType inputFormat, FormatType outputFormat)
        {
            fileOut = ChangeFileExtension(fileOut, outputFormat);

            FileMode fileMode = GetFileMode(fileOut);

            Directory.CreateDirectory(Path.GetDirectoryName(fileOut));

            try {
                using (var indentScope = new Logger.IndentScope())
                    using (var fIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read))
                        using (var ms = new MemoryStream()) {
                            if (inputFormat == FormatType.MBIN)
                            {
                                var mbin = new MBINFile(fIn);
                                if (!mbin.Load() || !mbin.Header.IsValid)
                                {
                                    throw new InvalidDataException("Not a valid MBIN file!");
                                }

                                var sw = new StreamWriter(ms);

                                NMSTemplate data = null;
                                try {
                                    data = mbin.GetData();
                                    if (data is null)
                                    {
                                        throw new InvalidDataException("Invalid MBIN data.");
                                    }
                                } catch (Exception e) {
                                    throw new MbinException($"Failed to read {mbin.Header.GetXMLTemplateName()} from MBIN.", e, fileIn, mbin);
                                }

                                try {
                                    sw.Write(EXmlFile.WriteTemplate(data));
                                    sw.Flush();
                                    if (ms.Length == 0)
                                    {
                                        throw new InvalidDataException("Invalid EXML data.");
                                    }
                                } catch (Exception e) {
                                    throw new MbinException($"Failed serializing {mbin.Header.GetXMLTemplateName()} to EXML.", e, fileIn, mbin);
                                }
                            }
                            else if (inputFormat == FormatType.EXML)
                            {
                                NMSTemplate data = null;
                                try {
                                    data = EXmlFile.ReadTemplateFromStream(fIn);
                                    if (data is null)
                                    {
                                        throw new InvalidDataException($"Failed to deserialize EXML.");
                                    }
                                    if (data is TkGeometryData)
                                    {
                                        fileOut += ".PC";
                                    }
                                    var mbin = new MBINFile(ms)
                                    {
                                        Header = new MBINHeader()
                                    };
                                    mbin.Header.SetDefaults(data.GetType());
                                    mbin.SetData(data);
                                    mbin.Save();
                                } catch (Exception e) {
                                    throw new ExmlException(e, fileIn, data);
                                }
                            }

                            ms.Flush();
                            using (var fOut = new FileStream(fileOut, fileMode, FileAccess.Write)) ms.WriteTo(fOut);
                        }
            } catch (Exception e) {
                File.Delete(fileOut);
                if (e is CompilerException)
                {
                    throw;
                }
                throw new CompilerException(e, fileIn);
            }
        }
Пример #7
0
        public static int Main(string[] args)
        {
            CommandLine.Initialize();

            var options = new CommandLineParser(args);

            options.AddOptions(null, OPTIONS_GENERAL);
            options.AddOptions("help", OPTIONS_HELP);
            options.AddOptions("version", OPTIONS_VERSION);
            options.AddOptions("convert", OPTIONS_CONVERT);
            options.AddOptions("list", OPTIONS_LIST);
            options.AddOptions("register", OPTIONS_REGISTER);

            // save the error state
            bool invalidArguments = !options.Parse("convert");

            // get the Quiet option first, before we emit anything
            Quiet = options.GetOptionSwitch("quiet");
            if (Quiet)
            {
                Console.SetOut(new StreamWriter(Stream.Null));
                Console.SetError(Console.Out);
            }

            NoLog = options.GetOptionSwitch("nolog");
            if (!NoLog)
            {
                Process   running_proc = Process.GetCurrentProcess();
                Process[] mbinc_procs  = Process.GetProcessesByName(running_proc.ProcessName);

                // If we only have one instance of MBINCompiler running create the usual log.
                // If a process starts and there is already a running MBINCompiler process, then
                // add the PID to the log file name so that there is no issue with two processes
                // attempting to write to the same log file.
                if (mbinc_procs.Length == 1)
                {
                    Logger.Open(Path.ChangeExtension(Utils.GetExecutablePath(), ".log"));
                }
                else
                {
                    Logger.Open(Path.ChangeExtension(Utils.GetExecutablePath(), $".{running_proc.Id}.log"));
                }

                Logger.EnableTraceLogging = true;

                Logger.LogMessage("VERSION", $"MBINCompiler v{Version.GetVersionStringCompact()}");
                Logger.LogMessage("ARGS", $"\"{string.Join("\" \"", args)}\"\n");
                using (var indent = new Logger.IndentScope()) {
                    Logger.LogMessage("If you encounter any errors, please submit a bug report and include this log file.\n" +
                                      "Please check that there isn't already a similar issue open before creating a new one.\n" +
                                      "https://github.com/monkeyman192/MBINCompiler/issues\n");
                }
            }

            // now we can emit an error if we need to
            if (invalidArguments)
            {
                return(CommandLine.ShowInvalidCommandLineArg(options));
            }

            // initialize remaining global options
            DebugMode = options.GetOptionSwitch("debug");

            // execute the appropriate mode
            try {
                switch (options.Verb)
                {
                case "help":     return(HelpCommand.Execute(options));

                case "version":  return(VersionCommand.Execute(options));

                case "list":     return(ListCommand.Execute(options));

                case "register": return(RegisterCommand.Execute(options));

                default:         return(ConvertCommand.Execute(options));
                }
            } catch (System.Exception e) {
                return(CommandLine.ShowException(e));
            }
        }