Example #1
0
        public static ColoredMessage[] TimeStampMessage(ColoredMessage[] message, ConsoleColor?color = null,
                                                        bool cloneMessages = false)
        {
            if (message == null)
            {
                return(null);
            }

            ColoredMessage[] newMessage = new ColoredMessage[message.Length + 1];
            newMessage[0] = new ColoredMessage($"{TimeStamp} ", color);

            if (cloneMessages)
            {
                for (int i = 0; i < message.Length; i++)
                {
                    newMessage[i + 1] = message[i]?.Clone();
                }
            }
            else
            {
                for (int i = 0; i < message.Length; i++)
                {
                    newMessage[i + 1] = message[i];
                }
            }

            return(newMessage);
        }
Example #2
0
        public static bool Send(this WatsonTcpClient client, string msg, Color color)
        {
            var coloredMsg = new ColoredMessage(color, msg);

            return(client.Send(
                       JsonConvert.SerializeObject(new TypeAdviser(coloredMsg.GetType().FullName))
                       + Environment.NewLine +
                       JsonConvert.SerializeObject(coloredMsg)));
        }
            public FromStringTemplate(string testString, string[] expectedSections, int sectionLength, ColoredMessage leftIndictator = null, ColoredMessage rightIndictator = null)
            {
                this.testString       = testString;
                this.expectedSections = expectedSections;

                this.sectionLength   = sectionLength;
                this.leftIndictator  = leftIndictator;
                this.rightIndictator = rightIndictator;
            }
Example #4
0
        public StringSection(ColoredMessage text, ColoredMessage leftIndicator, ColoredMessage rightIndicator, int minIndex, int maxIndex)
        {
            Text = text;

            LeftIndicator  = leftIndicator;
            RightIndicator = rightIndicator;

            MinIndex = minIndex;
            MaxIndex = maxIndex;
        }
Example #5
0
        public static void SetCurrentInput(string message)
        {
            ColoredMessage baseSection = BaseSection?.Clone();

            if (baseSection == null)
            {
                baseSection = new ColoredMessage(message);
            }
            else
            {
                baseSection.text = message;
            }

            SetCurrentInput(baseSection);
        }
Example #6
0
        public void Should_have_custom_equality_diff_color()
        {
            var a = new ColoredMessage();

            a.Parts.Add(new SetColorMessagePart(ConsoleColor.Green));
            a.Parts.Add(new WriteMessagePart("abc"));
            a.Parts.Add(new ResetColorMessagePart());

            var b = new ColoredMessage();

            b.Parts.Add(new SetColorMessagePart(ConsoleColor.Red));
            b.Parts.Add(new WriteMessagePart("abc"));
            b.Parts.Add(new ResetColorMessagePart());

            Assert.AreNotEqual(a, b);
        }
Example #7
0
        public static StringSections FromString(string fullString, int sectionLength, ColoredMessage leftIndicator, ColoredMessage rightIndicator, ColoredMessage sectionBase)
        {
            List <StringSection> sections = new List <StringSection>();

            if (string.IsNullOrEmpty(fullString))
            {
                return(new StringSections(sections.ToArray()));
            }

            // If the section base message is null, create a default one
            if (sectionBase == null)
            {
                sectionBase = new ColoredMessage(null);
            }

            // The starting index of the current section being created
            int sectionStartIndex = 0;

            // The text of the current section being created
            string curSecString = string.Empty;

            for (int i = 0; i < fullString.Length; i++)
            {
                curSecString += fullString[i];

                // If the section is less than the smallest possible section size, skip processing
                if (curSecString.Length < sectionLength - ((leftIndicator?.Length ?? 0) + (rightIndicator?.Length ?? 0)))
                {
                    continue;
                }

                // Decide what the left indicator text should be accounting for the leftmost section
                ColoredMessage leftIndicatorSection = sections.Count > 0 ? leftIndicator : null;
                // Decide what the right indicator text should be accounting for the rightmost section
                ColoredMessage rightIndicatorSection = i < fullString.Length - (1 + (rightIndicator?.Length ?? 0)) ? rightIndicator : null;

                // Check the section length against the final section length
                if (curSecString.Length >= sectionLength - ((leftIndicatorSection?.Length ?? 0) + (rightIndicatorSection?.Length ?? 0)))
                {
                    // Copy the section base message and replace the text
                    ColoredMessage section = sectionBase.Clone();
                    section.text = curSecString;

                    // Instantiate the section with the final parameters
                    sections.Add(new StringSection(section, leftIndicatorSection, rightIndicatorSection, sectionStartIndex, i));

                    // Reset the current section being worked on
                    curSecString      = string.Empty;
                    sectionStartIndex = i + 1;
                }
            }

            // If there's still text remaining in a section that hasn't been processed, add it as a section
            if (curSecString.Any())
            {
                // Only decide for the left indicator, as this last section will always be the rightmost section
                ColoredMessage leftIndicatorSection = sections.Count > 0 ? leftIndicator : null;

                // Copy the section base message and replace the text
                ColoredMessage section = sectionBase.Clone();
                section.text = curSecString;

                // Instantiate the section with the final parameters
                sections.Add(new StringSection(section, leftIndicatorSection, null, sectionStartIndex, fullString.Length));
            }

            return(new StringSections(sections.ToArray()));
        }
Example #8
0
 public static ColoredMessage[] TimeStampMessage(ColoredMessage message, ConsoleColor?color = null,
                                                 bool cloneMessages = false)
 {
     return(TimeStampMessage(new ColoredMessage[] { message }, color, cloneMessages));
 }
Example #9
0
 public static void LogColored(ColoredMessage message) => Server.LogColored(message.ToString());
Example #10
0
        public void HandleMessage(object source, ServerSocket.MessageEventArgs message)
        {
            if (message.message == null)
            {
                return;
            }

            ColoredMessage coloredMessage = new ColoredMessage(message.message, ConsoleColor.White);

            if (!coloredMessage.text.IsEmpty())
            {
                // Parse the color byte
                coloredMessage.textColor = (ConsoleColor)message.color;

                // Smod2 loggers pretty printing
                Match match = SmodRegex.Match(coloredMessage.text);
                if (match.Success)
                {
                    if (match.Groups.Count >= 3)
                    {
                        ConsoleColor levelColor = ConsoleColor.Green;
                        ConsoleColor tagColor   = ConsoleColor.Yellow;
                        ConsoleColor msgColor   = coloredMessage.textColor ?? ConsoleColor.White;

                        switch (match.Groups[1].Value.Trim())
                        {
                        case "DEBUG":
                            levelColor = ConsoleColor.DarkGray;
                            break;

                        case "INFO":
                            levelColor = ConsoleColor.Green;
                            break;

                        case "WARN":
                            levelColor = ConsoleColor.DarkYellow;
                            break;

                        case "ERROR":
                            levelColor = ConsoleColor.Red;
                            break;
                        }

                        server.Write(
                            new[]
                        {
                            new ColoredMessage($"[{match.Groups[1].Value}] ", levelColor),
                            new ColoredMessage($"{match.Groups[2].Value} ", tagColor),
                            new ColoredMessage(match.Groups[3].Value, msgColor)
                        }, msgColor);

                        // P.S. the format is [Info] [courtney.exampleplugin] Something interesting happened
                        // That was just an example

                        // This return should be here
                        return;
                    }
                }

                string lowerMessage = coloredMessage.text.ToLower();
                if (!server.supportedModFeatures.HasFlag(ModFeatures.CustomEvents))
                {
                    switch (lowerMessage.Trim(TrimChars))
                    {
                    case "the round is about to restart! please wait":
                        if (!roundEndCodeUsed)
                        {
                            server.ForEachHandler <IEventRoundEnd>(roundEnd => roundEnd.OnRoundEnd());
                        }
                        break;

                    /* Replaced by OutputCodes.RoundRestart
                     * case "waiting for players":
                     *      server.IsLoading = false;
                     *      server.ForEachHandler<IEventWaitingForPlayers>(waitingForPlayers => waitingForPlayers.OnWaitingForPlayers());
                     *      break;
                     */

                    case "new round has been started":
                        server.ForEachHandler <IEventRoundStart>(roundStart => roundStart.OnRoundStart());
                        break;

                    case "level loaded. creating match":
                        server.ForEachHandler <IEventServerStart>(serverStart => serverStart.OnServerStart());
                        break;

                    case "server full":
                        server.ForEachHandler <IEventServerFull>(serverFull => serverFull.OnServerFull());
                        break;
                    }
                }

                if (lowerMessage.StartsWith("multiadmin:"))
                {
                    // 11 chars in "multiadmin:"
                    string eventMessage = coloredMessage.text.Substring(11);

                    // Split event and event data
                    string[] eventSplit = eventMessage.Split(EventSplitChars, 2);

                    string @event    = eventSplit[0].ToLower();
                    string eventData = eventSplit.Length > 1 ? eventSplit[1] : null;                     // Handle events with no data

                    switch (@event)
                    {
                    case "round-end-event":
                        if (!roundEndCodeUsed)
                        {
                            server.ForEachHandler <IEventRoundEnd>(roundEnd => roundEnd.OnRoundEnd());
                        }
                        break;

                    /* Replaced by OutputCodes.RoundRestart
                     * case "waiting-for-players-event":
                     *      server.IsLoading = false;
                     *      server.ForEachHandler<IEventWaitingForPlayers>(waitingForPlayers => waitingForPlayers.OnWaitingForPlayers());
                     *      break;
                     */

                    case "round-start-event":
                        server.ForEachHandler <IEventRoundStart>(roundStart => roundStart.OnRoundStart());
                        break;

                    case "server-start-event":
                        server.ForEachHandler <IEventServerStart>(serverStart => serverStart.OnServerStart());
                        break;

                    case "server-full-event":
                        server.ForEachHandler <IEventServerFull>(serverFull => serverFull.OnServerFull());
                        break;

                    case "set-supported-features":
                        if (int.TryParse(eventData, out int supportedFeatures))
                        {
                            server.supportedModFeatures = (ModFeatures)supportedFeatures;
                        }
                        break;
                    }

                    // Don't print any MultiAdmin events
                    return;
                }
            }

            server.Write(coloredMessage);
        }
Example #11
0
        public static StringSections FromString(string fullString, int sectionLength, ColoredMessage leftIndicator = null, ColoredMessage rightIndicator = null, ColoredMessage sectionBase = null)
        {
            int rightIndicatorLength = rightIndicator?.Length ?? 0;
            int totalIndicatorLength = (leftIndicator?.Length ?? 0) + rightIndicatorLength;

            if (fullString.Length > sectionLength && sectionLength <= totalIndicatorLength)
            {
                throw new ArgumentException($"{nameof(sectionLength)} must be greater than the total length of {nameof(leftIndicator)} and {nameof(rightIndicator)}", nameof(sectionLength));
            }

            List <StringSection> sections = new List <StringSection>();

            if (string.IsNullOrEmpty(fullString))
            {
                return(new StringSections(sections.ToArray()));
            }

            // If the section base message is null, create a default one
            if (sectionBase == null)
            {
                sectionBase = new ColoredMessage(null);
            }

            // The starting index of the current section being created
            int sectionStartIndex = 0;

            // The text of the current section being created
            StringBuilder curSecBuilder = new StringBuilder();

            for (int i = 0; i < fullString.Length; i++)
            {
                curSecBuilder.Append(fullString[i]);

                // If the section is less than the smallest possible section size, skip processing
                if (curSecBuilder.Length < sectionLength - totalIndicatorLength)
                {
                    continue;
                }

                // Decide what the left indicator text should be accounting for the leftmost section
                ColoredMessage leftIndicatorSection = sections.Count > 0 ? leftIndicator : null;
                // Decide what the right indicator text should be accounting for the rightmost section
                ColoredMessage rightIndicatorSection = i < fullString.Length - (1 + rightIndicatorLength) ? rightIndicator : null;

                // Check the section length against the final section length
                if (curSecBuilder.Length >= sectionLength - ((leftIndicatorSection?.Length ?? 0) + (rightIndicatorSection?.Length ?? 0)))
                {
                    // Copy the section base message and replace the text
                    ColoredMessage section = sectionBase.Clone();
                    section.text = curSecBuilder.ToString();

                    // Instantiate the section with the final parameters
                    sections.Add(new StringSection(section, leftIndicatorSection, rightIndicatorSection, sectionStartIndex, i));

                    // Reset the current section being worked on
                    curSecBuilder.Clear();
                    sectionStartIndex = i + 1;
                }
            }

            // If there's still text remaining in a section that hasn't been processed, add it as a section
            if (!curSecBuilder.IsEmpty())
            {
                // Only decide for the left indicator, as this last section will always be the rightmost section
                ColoredMessage leftIndicatorSection = sections.Count > 0 ? leftIndicator : null;

                // Copy the section base message and replace the text
                ColoredMessage section = sectionBase.Clone();
                section.text = curSecBuilder.ToString();

                // Instantiate the section with the final parameters
                sections.Add(new StringSection(section, leftIndicatorSection, null, sectionStartIndex, fullString.Length));
            }

            return(new StringSections(sections.ToArray()));
        }
Example #12
0
 public static ColoredMessage[] TimeStampMessage(ColoredMessage message, ConsoleColor?color = null)
 {
     return(TimeStampMessage(new ColoredMessage[] { message }, color));
 }
Example #13
0
		void Process(string file, bool printFileName, Dictionary<ColoredMessage, CaptureResult> ctxGroups = null)
		{
			var output = new ColoredMessage();

			var body = ReadAllText(file, out var encoding);

			var matchLines = new SortedDictionary<int, Line>();

			var replaced = body;
			foreach (var regex in _regexes)
			{
				var matches = regex.Matches(body);

				// var currentlnStart = -2; // initially unknown
				foreach (Match match in matches)
				{
					if (match.Length == 0)
					{
						continue; // ignore zero-length matches and prevent index out of range when index >= length (zero length match at the end of a string)
					}
					// find the start of the line
					var lineStart = body.LastIndexOf('\n', match.Index);
					lineStart++;
					if (!matchLines.TryGetValue(lineStart, out var line))
					{
						matchLines[lineStart] = line = new Line
						{
							Start = lineStart,
						};
					}

					line.Matches.Add(match.Index, new LineMatch(regex, match));
				}

				if (ReplaceTo != null)
				{
					replaced = regex.Replace(replaced, ReplaceTo);
					// var rr = regex.ReplaceBreakout(replaced, ReplaceTo);
				}

			}

			if (ctxGroups == null && printFileName && matchLines.Any())
			{
				PrintFileName(file);
			}

			if (!OutputControlOptions.FilesWithMatches)
			{
				// fill context lines
				if (ContextCaptureOptions.ContextAround != 0
				    || ContextCaptureOptions.Before != 0
				    || ContextCaptureOptions.After != 0)
				{
					foreach (var line in matchLines.Values.ToArray())
					{
						var prev = line.Start;
						var before = Math.Max(ContextCaptureOptions.Before, ContextCaptureOptions.ContextAround);
						for (; before > 0; before--)
						{
							if (prev >= 2)
							{
								prev = body.LastIndexOf('\n', prev - 2);
								prev++;
								if (!matchLines.ContainsKey(prev))
								{
									matchLines[prev] = new Line
									{
										Start = prev,
									};
								}
							}
						}
						prev = line.Start;
						var after = Math.Max(ContextCaptureOptions.After, ContextCaptureOptions.ContextAround);
						for (; after > 0; after--)
						{
							prev = body.IndexOf('\n', prev);
							if (prev > 0)
							{
								prev++;
								if (!matchLines.ContainsKey(prev))
								{
									matchLines[prev] = new Line
									{
										Start = prev,
									};
								}
							}
						}
					}
				}

				foreach (var line in matchLines.Values)
				{
					var eol = body.IndexOf('\n', line.Start);
					if (eol == -1)
					{
						eol = body.Length - 1; // jump to last char
					}
					else
					{
						eol--; // jump to char before \n
					}

					// Windows CR LF file
					if (body[eol] == '\r')
					{
						eol--; // jump one more time
					}

					// var str = body.Substring(line.Key, eol);
					void PrintLine(bool replaceMode = false)
					{
						var printPosition = line.Start;
						foreach (var lineMatch in line.Matches.Values)
						{
							var match = lineMatch.Match;

							if (match.Index > printPosition)
							{
								output.Write(ConsoleColor.Gray,
									body.Substring(printPosition, match.Index - printPosition));
							}

							if (!replaceMode)
							{
								output.Write(ConsoleColor.Red, match.Value);
							}
							else
							{
								output.Write(ConsoleColor.Green,
									GetReplacementString(lineMatch.Regex, match, body, ReplaceTo));
							}

							printPosition = match.Index + match.Length;
						}

						var len = eol + 1 - printPosition;
						if (len >= 0 && printPosition < body.Length && (len - printPosition) < body.Length)
						{
							output.Write(ConsoleColor.Gray, body.Substring(printPosition, len) + Environment.NewLine);
						}
						else
						{
							output.Write(null, Environment.NewLine);
						}
					}

					PrintLine();
					if (ReplaceTo != null)
					{
						PrintLine(true);
					}
				}
			}

			if (Save && matchLines.Any() && body != replaced)
			{
				// open existing file for replace!
				using var fileStream = new FileStream(file,
					FileMode.Open,
					FileAccess.Write,
					FileShare.Read,
					FileBufferSize,
					FileOptions.SequentialScan);

				using var sw = new StreamWriter(fileStream, encoding);
				sw.Write(replaced);
				sw.Flush();
				fileStream.SetLength(fileStream.Position); // truncate!
			}

			if (ctxGroups != null)
			{
				// context grouping... will print later
				if (output.Parts.Count > 0)
				{
					if (!ctxGroups.TryGetValue(output, out var capture))
					{
						ctxGroups[output] = capture = new CaptureResult();
					}
					capture.FileNames.Add(file);
				}
			}
			else
			{
				// no context grouping, print directly now
				if (!OutputControlOptions.FilesWithMatches)
				{
					output.ToConsole();
				}
			}
		}