<commit_before>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using NuGet;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Resources;

namespace NuGetConsole.Host.PowerShell.Implementation {

    internal abstract class PowerShellHost : IHost, IPathExpansion, IDisposable {

        private readonly string _name;
        private readonly IRunspaceManager _runspaceManager;
        private readonly IPackageSourceProvider _packageSourceProvider;
        private readonly ISolutionManager _solutionManager;
        private readonly IVsPackageManagerFactory _packageManagerFactory;

        private IConsole _activeConsole;
        private Runspace _runspace;
        private NuGetPSHost _myHost;
        // indicates whether this host has been initialized. 
        // null = not initilized, true = initialized successfully, false = initialized unsuccessfully
        private bool? _initialized;

        // store the current command typed so far
        private ComplexCommand _complexCommand;

        protected PowerShellHost(string name, IRunspaceManager runspaceManager) {
            _runspaceManager = runspaceManager;

            // TODO: Take these as ctor arguments
            _packageSourceProvider = ServiceLocator.GetInstance<IPackageSourceProvider>();
            _solutionManager = ServiceLocator.GetInstance<ISolutionManager>();
            _packageManagerFactory = ServiceLocator.GetInstance<IVsPackageManagerFactory>();

            _name = name;
            IsCommandEnabled = true;
        }

        protected Pipeline ExecutingPipeline { get; set; }

        /// <summary>
        /// The host is associated with a particular console on a per-command basis. 
        /// This gets set every time a command is executed on this host.
        /// </summary>
        protected IConsole ActiveConsole {
            get {
                return _activeConsole;
            }
            set {
                _activeConsole = value;
                if (_myHost != null) {
                    _myHost.ActiveConsole = value;
                }
            }
        }

        public bool IsCommandEnabled {
            get;
            private set;
        }

        protected Runspace Runspace {
            get {
                Debug.Assert(_initialized != null);
                return _runspace;
            }
        }

        private ComplexCommand ComplexCommand {
            get {
                if (_complexCommand == null) {
                    _complexCommand = new ComplexCommand((allLines, lastLine) => {
                        Collection<PSParseError> errors;
                        PSParser.Tokenize(allLines, out errors);

                        // If there is a parse error token whose END is past input END, consider
                        // it a multi-line command.
                        if (errors.Count > 0) {
                            if (errors.Any(e => (e.Token.Start + e.Token.Length) >= allLines.Length)) {
                                return false;
                            }
                        }

                        return true;
                    });
                }
                return _complexCommand;
            }
        }

        public string Prompt {
            get {
                return ComplexCommand.IsComplete ? EvaluatePrompt() : ">> ";
            }
        }

        private string EvaluatePrompt() {            
            string prompt = "PM>";

            try {
                PSObject output = this.Runspace.Invoke("prompt", null, outputResults: false).FirstOrDefault();
                if (output != null) {
                    prompt = output.BaseObject.ToString();
                }
            }
            catch (RuntimeException ex) {
                ReportError(ex);
            }
            return prompt;
        }

        /// <summary>
        /// Doing all necessary initialization works before the console accepts user inputs
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public void Initialize(IConsole console) {
            ActiveConsole = console;

            if (_initialized.HasValue) {
                if (_initialized.Value && console.ShowDisclaimerHeader) {
                    DisplayDisclaimerAndHelpText();
                }
            }
            else {
                try {
                    Tuple<Runspace, NuGetPSHost> tuple = _runspaceManager.GetRunspace(console, _name);
                    _runspace = tuple.Item1;
                    _myHost = tuple.Item2;<commit_msg>updated as per review comments<commit_after>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using NuGet;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Resources;

namespace NuGetConsole.Host.PowerShell.Implementation {

    internal abstract class PowerShellHost : IHost, IPathExpansion, IDisposable {

        private readonly string _name;
        private readonly IRunspaceManager _runspaceManager;
        private readonly IPackageSourceProvider _packageSourceProvider;
        private readonly ISolutionManager _solutionManager;
        private readonly IVsPackageManagerFactory _packageManagerFactory;

        private IConsole _activeConsole;
        private Runspace _runspace;
        private NuGetPSHost _myHost;
        // indicates whether this host has been initialized. 
        // null = not initilized, true = initialized successfully, false = initialized unsuccessfully
        private bool? _initialized;

        // store the current command typed so far
        private ComplexCommand _complexCommand;

        protected PowerShellHost(string name, IRunspaceManager runspaceManager) {
            _runspaceManager = runspaceManager;

            // TODO: Take these as ctor arguments
            _packageSourceProvider = ServiceLocator.GetInstance<IPackageSourceProvider>();
            _solutionManager = ServiceLocator.GetInstance<ISolutionManager>();
            _packageManagerFactory = ServiceLocator.GetInstance<IVsPackageManagerFactory>();

            _name = name;
            IsCommandEnabled = true;
        }

        protected Pipeline ExecutingPipeline { get; set; }

        /// <summary>
        /// The host is associated with a particular console on a per-command basis. 
        /// This gets set every time a command is executed on this host.
        /// </summary>
        protected IConsole ActiveConsole {
            get {
                return _activeConsole;
            }
            set {
                _activeConsole = value;
                if (_myHost != null) {
                    _myHost.ActiveConsole = value;
                }
            }
        }

        public bool IsCommandEnabled {
            get;
            private set;
        }

        protected Runspace Runspace {
            get {
                Debug.Assert(_initialized != null);
                return _runspace;
            }
        }

        private ComplexCommand ComplexCommand {
            get {
                if (_complexCommand == null) {
                    _complexCommand = new ComplexCommand((allLines, lastLine) => {
                        Collection<PSParseError> errors;
                        PSParser.Tokenize(allLines, out errors);

                        // If there is a parse error token whose END is past input END, consider
                        // it a multi-line command.
                        if (errors.Count > 0) {
                            if (errors.Any(e => (e.Token.Start + e.Token.Length) >= allLines.Length)) {
                                return false;
                            }
                        }

                        return true;
                    });
                }
                return _complexCommand;
            }
        }

        public string Prompt {
            get {
                return ComplexCommand.IsComplete ? EvaluatePrompt() : ">> ";
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private string EvaluatePrompt() {            
            string prompt = "PM>";

            try {
                PSObject output = this.Runspace.Invoke("prompt", null, outputResults: false).FirstOrDefault();
                if (output != null) {
                    prompt = output.BaseObject.ToString();
                }
            }
            catch (Exception ex) {                
                ExceptionHelper.WriteToActivityLog(ex);
            }
            return prompt;
        }

        /// <summary>
        /// Doing all necessary initialization works before the console accepts user inputs
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public void Initialize(IConsole console) {
            ActiveConsole = console;

            if (_initialized.HasValue) {
                if (_initialized.Value && console.ShowDisclaimerHeader) {
                    DisplayDisclaimerAndHelpText();
                }
            }
            else {
                try {
                    Tuple<Runspace, NuGetPSHost> tuple = _runspaceManager.GetRunspace(console, _name);
                    _runspace = tuple.Item1;
                    _myHost = tuple.Item2;
{'fraction_non_alphanumeric': 0.07121812455552169, 'fraction_numerical': 0.001828710758914965, 'mean_word_length': 1.640557939914163, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 35, 'https://': 0, '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': '3129883', 'n_tokens_mistral': 2296, 'n_tokens_neox': 2156, 'n_words': 585}