<commit_before>﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using RestSharp;

namespace AppHarbor.Commands
{
	[CommandHelp("Get application log", alias: "log")]
	public class LogAppCommand : ApplicationCommand
	{
		private readonly string _accessToken;
		private readonly TextWriter _writer;
		private readonly IRestClient _restClient;

		private bool _tail;
		private int _limit = 15;
		private string _processFilter;
		private string _sourceFilter;

		public LogAppCommand(IApplicationConfiguration applicationConfiguration, IAccessTokenConfiguration accessTokenConfiguration, TextWriter writer)
			: base(applicationConfiguration)
		{
			_accessToken = accessTokenConfiguration.GetAccessToken();
			_writer = writer;
			_restClient = new RestClient("https://appharbor.com/");

			OptionSet.Add("t|tail", "Tail log", x => _tail = true);
			OptionSet.Add("n|num=", "Number of log messages", (int x) => _limit = x);
			OptionSet.Add("p|process=", "Filter log to this process (case-sensitive)", x => _processFilter = x);
			OptionSet.Add("s|source=", "Filter log to this source", x => _sourceFilter = x);
		}

		protected override void  InnerExecute(string[] arguments)
		{
			var request = new RestRequest("applications/{slug}/logsession", Method.POST)
			{
				RequestFormat = DataFormat.Json
			}
				.AddUrlSegment("slug", ApplicationId)
				.AddHeader("Authorization", string.Format("BEARER {0}", _accessToken))
				.AddBody(new
				{
					tail = _tail,
					limit = _limit - 1,
					sourcefilter = _sourceFilter,
					processFilter = _processFilter,
				});

			var response = _restClient.Execute(request);
			var locationHeader = response.Headers.FirstOrDefault(x =>
				string.Equals(x.Name, "location",StringComparison.InvariantCultureIgnoreCase));
			if (response.StatusCode != HttpStatusCode.Created || locationHeader.Value == null)
			{
				throw new CommandException("Couldn't create log session. Try again later.");
			}

			var sessionUrl = new Uri(locationHeader.Value.ToString());
			try
			{
				using (var webClient = new WebClient())
				{
					using (var stream = webClient.OpenRead(sessionUrl))
					using (var reader = new StreamReader(stream))
					{
						while (true)
						{
							var line = reader.ReadLine();
							if (line != null)
							{
								WriteColorizedLine(line);
							}

							if (reader.EndOfStream)
							{
								break;
							}
						}
					}
				}
			}
			catch (WebException exception)
			{
				Console.WriteLine("Log session ended with message: {0}", exception.Message);
			}
		}

		private static void WriteColorizedLine(string line)
		{
			var parsed = Regex.Match(line, @"^(.*?\[([\w-]+)([\d\.]+)?\]:)(.*)?$");
			var defaultColor = Console.ForegroundColor;

			Console.ForegroundColor = ConsoleColor.Cyan;
			Console.Write(parsed.Groups[1].Value);
			Console.ForegroundColor = defaultColor;
			Console.WriteLine(parsed.Groups[4].Value);
		}
	}
}
<commit_msg>Make LogAppCommand#WriteColorizedLine an instance method<commit_after>﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using RestSharp;

namespace AppHarbor.Commands
{
	[CommandHelp("Get application log", alias: "log")]
	public class LogAppCommand : ApplicationCommand
	{
		private readonly string _accessToken;
		private readonly TextWriter _writer;
		private readonly IRestClient _restClient;

		private bool _tail;
		private int _limit = 15;
		private string _processFilter;
		private string _sourceFilter;

		public LogAppCommand(IApplicationConfiguration applicationConfiguration, IAccessTokenConfiguration accessTokenConfiguration, TextWriter writer)
			: base(applicationConfiguration)
		{
			_accessToken = accessTokenConfiguration.GetAccessToken();
			_writer = writer;
			_restClient = new RestClient("https://appharbor.com/");

			OptionSet.Add("t|tail", "Tail log", x => _tail = true);
			OptionSet.Add("n|num=", "Number of log messages", (int x) => _limit = x);
			OptionSet.Add("p|process=", "Filter log to this process (case-sensitive)", x => _processFilter = x);
			OptionSet.Add("s|source=", "Filter log to this source", x => _sourceFilter = x);
		}

		protected override void  InnerExecute(string[] arguments)
		{
			var request = new RestRequest("applications/{slug}/logsession", Method.POST)
			{
				RequestFormat = DataFormat.Json
			}
				.AddUrlSegment("slug", ApplicationId)
				.AddHeader("Authorization", string.Format("BEARER {0}", _accessToken))
				.AddBody(new
				{
					tail = _tail,
					limit = _limit - 1,
					sourcefilter = _sourceFilter,
					processFilter = _processFilter,
				});

			var response = _restClient.Execute(request);
			var locationHeader = response.Headers.FirstOrDefault(x =>
				string.Equals(x.Name, "location",StringComparison.InvariantCultureIgnoreCase));
			if (response.StatusCode != HttpStatusCode.Created || locationHeader.Value == null)
			{
				throw new CommandException("Couldn't create log session. Try again later.");
			}

			var sessionUrl = new Uri(locationHeader.Value.ToString());
			try
			{
				using (var webClient = new WebClient())
				{
					using (var stream = webClient.OpenRead(sessionUrl))
					using (var reader = new StreamReader(stream))
					{
						while (true)
						{
							var line = reader.ReadLine();
							if (line != null)
							{
								WriteColorizedLine(line);
							}

							if (reader.EndOfStream)
							{
								break;
							}
						}
					}
				}
			}
			catch (WebException exception)
			{
				Console.WriteLine("Log session ended with message: {0}", exception.Message);
			}
		}

		private void WriteColorizedLine(string line)
		{
			var parsed = Regex.Match(line, @"^(.*?\[([\w-]+)([\d\.]+)?\]:)(.*)?$");
			var defaultColor = Console.ForegroundColor;

			Console.ForegroundColor = ConsoleColor.Cyan;
			Console.Write(parsed.Groups[1].Value);
			Console.ForegroundColor = defaultColor;
			Console.WriteLine(parsed.Groups[4].Value);
		}
	}
}

{'fraction_non_alphanumeric': 0.12362362362362363, 'fraction_numerical': 0.002335669002335669, 'mean_word_length': 3.661741835147745, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2875211', 'n_tokens_mistral': 2211, 'n_tokens_neox': 1762, 'n_words': 415}