Пример #1
0
        public static IEnumerable<dynamic> ProcessScript(ScriptInfo scriptInfo, IEnumerable<ClassTemplateInfo> dataClassesInfo, Func<Type, object> deserializeToType)
        {
            var modelType = LoadModelTypesAppDomain(dataClassesInfo);

            // INFO: Configure Roslyn Script Engine
            var scriptEngine = ConfigureScriptEngine(scriptInfo, modelType.Assembly);

            // INFO: Read input data for Model of runtime types
            var models = LoadModelData(deserializeToType, modelType);

            Submission<object> submission;

            // INFO: Create Roslyn Script Submission
            var submissionModel = CreateSubmission(scriptInfo, modelType, scriptEngine, out submission);

            // INFO: Process all inputs
            return models
                    .Select(model =>
                        {
                            CopyPropertiesToSubmissionModel(modelType, submissionModel, model);

                            return submission.Execute();
                        })
                    .ToList();
        }
Пример #2
0
        public SensorManager()
        {
            sensorBridge.SensorDataAvailable += new EventHandler<SensorDataEventArgs>(sensorBridge_SensorDataAvailable);

            // add some common assemblies
            ScriptRuntime runtime = scriptEngine.Runtime;
            runtime.LoadAssembly(Assembly.GetExecutingAssembly());
            runtime.LoadAssembly(typeof(string).Assembly);
            runtime.LoadAssembly(typeof(Uri).Assembly);
            runtime.LoadAssembly(typeof(System.Diagnostics.Trace).Assembly);

            // enumerate the scripts, and prepare the scopes and sources
            foreach (string script in Directory.GetFiles(SensorMonitorDirectory, "*.py"))
            {
                try
                {
                    ScriptInfo info = new ScriptInfo();
                    info.CompiledCode = scriptEngine.CreateScriptSourceFromFile(script).Compile();
                    info.ScriptScope = scriptEngine.CreateScope();
                    sensorScripts.Add(script, info);
                }
                catch (Exception ex)
                {
                    ExceptionOperations eo;
                    eo = scriptEngine.GetService<ExceptionOperations>();
                    string error = eo.FormatException(ex);
                    Trace.WriteLine(String.Format("Initialising SensorMonitors:: {0}", error));
                }
            }
        }
Пример #3
0
        private static ScriptEngine ConfigureScriptEngine(ScriptInfo scriptInfo, Assembly modelAssembly)
        {
            var scriptEngine = new ScriptEngine();

            scriptEngine.AddReference(modelAssembly);
            scriptInfo.Assemblies.ToList().ForEach(scriptEngine.AddReference);
            scriptInfo.Namespaces.ToList().ForEach(scriptEngine.ImportNamespace);

            return scriptEngine;
        }
Пример #4
0
        public PublishingManager()
        {
            // add some common assemblies
            ScriptRuntime runtime = scriptEngine.Runtime;
            runtime.LoadAssembly(Assembly.GetExecutingAssembly());
            runtime.LoadAssembly(typeof(string).Assembly);
            runtime.LoadAssembly(typeof(Uri).Assembly);
            runtime.LoadAssembly(typeof(System.Xml.XmlDocument).Assembly);
            runtime.LoadAssembly(typeof(System.Diagnostics.Trace).Assembly);

            // enumerate the scripts, and prepare the scopes and sources
            foreach (string scriptPath in Directory.GetFiles(PublishingMonitorDirectory, "*.py"))
            {
                try
                {
                    ScriptInfo info = new ScriptInfo();
                    info.ScriptPath = scriptPath;
                    info.CompiledCode = scriptEngine.CreateScriptSourceFromFile(scriptPath).Compile();
                    info.ScriptScope = scriptEngine.CreateScope();

                    // execute it to run any initialization code in the publisher
                    info.CompiledCode.Execute(info.ScriptScope);

                    // get the topics that the publisher wants to be notified of.
                    Func<IEnumerable<string>> GetTopics = info.ScriptScope.GetVariable<Func<IEnumerable<string>>>("GetTopics");

                    // get the publish function provided by the publisher, the MQTT client will directly invoke it for us.
                    Func<string, object, bool> Publish = info.ScriptScope.GetVariable<Func<string, object, bool>>("Publish");

                    IEnumerable<string> topics = GetTopics();
                    foreach (var topic in topics)
                    {
                        MqttClientManager.Subscribe(topic, Nmqtt.MqttQos.AtMostOnce, Publish);
                    }

                    info.Topics.AddRange(topics);
                    PublishingScripts.Add(scriptPath, info);
                }
                catch (Exception ex)
                {
                    ExceptionOperations eo;
                    eo = scriptEngine.GetService<ExceptionOperations>();
                    string error = eo.FormatException(ex);
                    Trace.WriteLine(String.Format("Initialising Publishers:: {0}", error));
                }
            }
        }
Пример #5
0
 public SqlHarvester(SqlScripterFactory factory, ScriptInfo scriptInfo, string outputDirectory, int index)
 {
     if (scriptInfo == null)
     {
         throw new ArgumentException("scriptInfo");
     }
     if (factory == null)
     {
         throw new ArgumentException("factory");
     }
     this.index = index;
     sqlScripter = factory.CreateInstance(scriptInfo);
     this.scriptInfo = scriptInfo;
     file = GetFile(outputDirectory);
     Stream stream = file.Open(FileMode.Create, FileAccess.Write, FileShare.Read);
     writer = new StreamWriter(stream);
 }
Пример #6
0
        public static ScriptInfo GetScriptInfo(string url)
        {
            ScriptInfo info = new ScriptInfo();

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                info.Owner = response.GetResponseHeader("X-SecondLife-Owner-Name");
                info.Region = response.GetResponseHeader("X-SecondLife-Region");
                info.Server = response.GetResponseHeader("Server");
            }
            catch
            {

            }

            return info;
        }
Пример #7
0
        public CommandProcessorBase CreateCommandProcessor(Command command)
        {
            string cmdText = command.CommandText;

            CommandInfo commandInfo = null;
            bool useLocalScope = command.UseLocalScope;

            if (command.IsScript) //CommandText contains a script block. Parse it
            {
                command.ScriptBlockAst = Parser.ParseInput(cmdText);
            }

            //either we parsed something like "& { foo; bar }", or the CommandText was a script and was just parsed
            if (command.ScriptBlockAst != null)
            {
                commandInfo = new ScriptInfo("", command.ScriptBlockAst.GetScriptBlock(), 
                                             useLocalScope ? ScopeUsages.NewScope : ScopeUsages.CurrentScope);
            }
            else //otherwise it's a real command (cmdlet, script, function, application)
            {
                commandInfo = FindCommand(cmdText, useLocalScope);
            }
            // make sure we only create a valid command processor if it's a valid command
            commandInfo.Validate();

            switch (commandInfo.CommandType)
            {
                case CommandTypes.Application:
                    return new ApplicationProcessor((ApplicationInfo)commandInfo);

                case CommandTypes.Cmdlet:
                    return new CommandProcessor(commandInfo as CmdletInfo);

                case CommandTypes.Script:
                case CommandTypes.ExternalScript:
                case CommandTypes.Function:
                    return new ScriptBlockProcessor(commandInfo as IScriptBlockInfo, commandInfo);
                default:
                    throw new NotImplementedException("Invalid command type");
            }
        }
Пример #8
0
        private bool InternalSet(ScriptInfo script)
        {
            bool isStatic = !CodeDomUtils.AreMemberAttributesSet(script.TypeDeclaration, MemberAttributes.Final);

            if (isStatic && !CodeDomUtils.AreMemberAttributesSet(script.TypeDeclaration, MemberAttributes.Static))
            {
                isStatic = !CollectionUtils.Contains(
                                CodeObjectMetaData.GetFields(script.TypeDeclaration).Values,
                                delegate(CodeMemberField memberField)
                                    {
                                        return (!CodeDomUtils.AreMemberAttributesSet(memberField, MemberAttributes.Const));
                                    });

                if (isStatic)
                {
                    isStatic = !CollectionUtils.Contains(
                                    script.Dependencies.Values,
                                    delegate(ScriptInfo dependencyScript)
                                        {
                                            return (!dependencyScript.IsInvalid && !InternalSet(dependencyScript));
                                        });
                }

                MemberAttributes attribute = (isStatic
                                                  ? MemberAttributes.Static
                                                  : MemberAttributes.Final);
                CodeDomUtils.SetMemberAttributes(script.TypeDeclaration, attribute);

                foreach (CodeTypeMember typeMember in script.TypeDeclaration.Members)
                {
                    if (!(typeMember is CodeTypeDeclaration ||
                          (typeMember is CodeMemberField &&
                           CodeDomUtils.AreMemberAttributesSet(typeMember, MemberAttributes.Const))))
                    {
                        CodeDomUtils.SetMemberAttributes(typeMember, attribute);
                    }
                }
            }

            return isStatic;
        }
        //////////////////////////////////////////////////////////////////////////
        public static string[] GetClassProperties(string NativeClass)
        {
            if(ClassProps==null)
            {
                ClassProps = new Dictionary<string, string[]>();
                try
                {
                    string XmlDocsPath = "";
                    using (RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"Software\DEAD:CODE\Wintermute Tools\Settings"))
                    {
                        XmlDocsPath = Key.GetValue("ToolsPath", "").ToString();
                    };
                    XmlDocsPath = Path.Combine(XmlDocsPath, "wme_docs_core_en.xml");
                    if (File.Exists(XmlDocsPath))
                    {
                        ScriptInfo Info = new ScriptInfo();
                        if (Info.ReadXml(XmlDocsPath))
                        {
                            foreach (ScriptObject Obj in Info.Objects)
                            {
                                if (Obj.NativeClass == null || Obj.NativeClass == string.Empty) continue;

                                List<string> Attrs = new List<string>(Obj.Attributes.Count);
                                foreach (ScriptAttribute Attr in Obj.Attributes)
                                {
                                    Attrs.Add(Attr.Name);
                                }
                                ClassProps[Obj.NativeClass] = Attrs.ToArray();
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            if (ClassProps.ContainsKey(NativeClass)) return ClassProps[NativeClass];
            else return null;
        }
        private static void Test(Language language, CodeDomProvider provider)
        {
            MigrationSettings settings = new MigrationSettings();
            settings.VSProjectName = "ClassLibrary1";
            settings.Namespace = "ClassLibrary1";
            settings.Language = language;

            MigrationContext context = new MigrationContext(
                settings,
                null,
                null,
                null,
                null,
                provider,
                null,
                null,
                new EmptyOperationStatus(),
                null);
            context.LocalizedStrings.Add("One", "Uno");
            context.References.Add("AxSLXControls, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL", @"AxSLXControls.dll");
            context.References.Add(typeof (Form).Assembly.GetName().Name, null);

            Plugin plugin = new Plugin();
            plugin.Family = "Test";
            plugin.Name = "Class1";
            plugin.Blob.Data = new byte[0];
            ScriptInfo script = new ScriptInfo(plugin);
            context.Scripts.Add("0", script);

            MigrationContextHolderService holder = new MigrationContextHolderService();
            holder.Context = context;

            VSProjectService p = new VSProjectService();
            p.ContextHolder = holder;
            p.Generate();
        }
Пример #11
0
 public ScriptProcessor(ScriptInfo scriptInfo)
     : base(scriptInfo)
 {
 }
Пример #12
0
        protected IMohidTask LoadLibrary(FileName library_file_path, string task_class)
        {
            ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == library_file_path.FullPath; });
             if (si != null)
             {
            si.Interface.Reset();
            return si.Interface;
             }
             else
             {
            Assembly ass;
            try
            {
               ass = Assembly.LoadFrom(library_file_path.FullPath);
            }
            catch (Exception ex)
            {
               throw new Exception("Error when trying to compile " + library_file_path.FullPath + ". The message returned was " + ex.Message);
            }

            si = new ScriptInfo();
            si.ScriptFile = library_file_path;

            Type t = ass.GetType(task_class);
            if (t.GetInterface("IMohidTask", true) != null)
               si.Interface = (IMohidTask)ass.CreateInstance(t.FullName);

            scripts.Add(si);

            return si.Interface;
             }
        }
Пример #13
0
        protected IMohidTask LoadScript(FileName script_file_path)
        {
            ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == script_file_path.FullPath;  });
             if (si != null)
             {
            si.Interface.Reset();
            return si.Interface;
             }
             else
             {
            ScriptCompiler sc = new ScriptCompiler();
            Assembly ass;
            try
            {
               ass = sc.Compile(script_file_path);
            }
            catch (Exception ex)
            {
               throw new Exception("Error when trying to compile " + script_file_path.FullPath + ". The message returned was " + ex.Message);
            }

            si = new ScriptInfo();
            si.ScriptFile = script_file_path;
            si.Interface = (IMohidTask)sc.FindScriptInterface("IMohidTask", ass);

            scripts.Add(si);

            return si.Interface;
             }
        }
Пример #14
0
 private static CommandProcessorBase CreateCommandProcessorForScript(ScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
 {
     sessionState = sessionState ?? (scriptInfo.ScriptBlock.SessionStateInternal ?? context.EngineSessionState);
     CommandProcessorBase base2 = GetScriptAsCmdletProcessor(scriptInfo, context, useNewScope, true, sessionState);
     if (base2 != null)
     {
         return base2;
     }
     return new DlrScriptCommandProcessor(scriptInfo, context, useNewScope, sessionState);
 }
Пример #15
0
        internal static bool RunScript(IWin32Window owner, GitModule aModule, ScriptInfo scriptInfo, RevisionGrid revisionGrid)
        {
            string originalCommand = scriptInfo.Command;
            string argument = scriptInfo.Arguments;

            string command = OverrideCommandWhenNecessary(originalCommand);
            var allSelectedRevisions = new List<GitRevision>();

            GitRevision selectedRevision = null;
            GitRevision currentRevision = null;

            var selectedLocalBranches = new List<GitRef>();
            var selectedRemoteBranches = new List<GitRef>();
            var selectedRemotes = new List<string>();
            var selectedBranches = new List<GitRef>();
            var selectedTags = new List<GitRef>();
            var currentLocalBranches = new List<GitRef>();
            var currentRemoteBranches = new List<GitRef>();
            var currentRemote = "";
            var currentBranches = new List<GitRef>();
            var currentTags = new List<GitRef>();

            foreach (string option in Options)
            {
                if (string.IsNullOrEmpty(argument) || !argument.Contains(option))
                    continue;
                if (option.StartsWith("{c") && currentRevision == null)
                {
                    currentRevision = GetCurrentRevision(aModule, revisionGrid, currentTags, currentLocalBranches, currentRemoteBranches, currentBranches, currentRevision);

                    if (currentLocalBranches.Count == 1)
                        currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote", currentLocalBranches[0].Name));
                    else
                    {
                        currentRemote = aModule.GetCurrentRemote();
                        if (string.IsNullOrEmpty(currentRemote))
                            currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote",
                                askToSpecify(currentLocalBranches, "Current Revision Branch")));
                    }
                }
                else if (option.StartsWith("{s") && selectedRevision == null && revisionGrid != null)
                {
                    allSelectedRevisions = revisionGrid.GetSelectedRevisions();
                    allSelectedRevisions.Reverse(); // Put first clicked revisions first
                    selectedRevision = CalculateSelectedRevision(revisionGrid, selectedRemoteBranches, selectedRemotes, selectedLocalBranches, selectedBranches, selectedTags);
                }

                string remote;
                string url;
                switch (option)
                {
                    case "{sHashes}":
                        argument = argument.Replace(option,
                            string.Join(" ", allSelectedRevisions.Select(revision => revision.Guid).ToArray()));
                        break;
                    case "{sTag}":
                        if (selectedTags.Count == 1)
                            argument = argument.Replace(option, selectedTags[0].Name);
                        else if (selectedTags.Count != 0)
                            argument = argument.Replace(option, askToSpecify(selectedTags, "Selected Revision Tag"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sBranch}":
                        if (selectedBranches.Count == 1)
                            argument = argument.Replace(option, selectedBranches[0].Name);
                        else if (selectedBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(selectedBranches, "Selected Revision Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sLocalBranch}":
                        if (selectedLocalBranches.Count == 1)
                            argument = argument.Replace(option, selectedLocalBranches[0].Name);
                        else if (selectedLocalBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(selectedLocalBranches,
                                                                     "Selected Revision Local Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sRemoteBranch}":
                        if (selectedRemoteBranches.Count == 1)
                            argument = argument.Replace(option, selectedRemoteBranches[0].Name);
                        else if (selectedRemoteBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(selectedRemoteBranches,
                                                                     "Selected Revision Remote Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sRemote}":
                        if (selectedRemotes.Count == 0)
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        if (selectedRemotes.Count == 1)
                            remote = selectedRemotes[0];
                        else
                            remote = askToSpecify(selectedRemotes, "Selected Revision Remote");
                        argument = argument.Replace(option, remote);
                        break;
                    case "{sRemoteUrl}":
                        if (selectedRemotes.Count == 0)
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        if (selectedRemotes.Count == 1)
                            remote = selectedRemotes[0];
                        else
                            remote = askToSpecify(selectedRemotes, "Selected Revision Remote");
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote));
                        argument = argument.Replace(option, url);
                        break;
                    case "{sRemotePathFromUrl}":
                        if (selectedRemotes.Count == 0)
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        if (selectedRemotes.Count == 1)
                            remote = selectedRemotes[0];
                        else
                            remote = askToSpecify(selectedRemotes, "Selected Revision Remote");
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote));
                        argument = argument.Replace(option, GetRemotePath(url));
                        break;
                    case "{sHash}":
                        argument = argument.Replace(option, selectedRevision.Guid);
                        break;
                    case "{sMessage}":
                        argument = argument.Replace(option, selectedRevision.Message);
                        break;
                    case "{sAuthor}":
                        argument = argument.Replace(option, selectedRevision.Author);
                        break;
                    case "{sCommitter}":
                        argument = argument.Replace(option, selectedRevision.Committer);
                        break;
                    case "{sAuthorDate}":
                        argument = argument.Replace(option, selectedRevision.AuthorDate.ToString());
                        break;
                    case "{sCommitDate}":
                        argument = argument.Replace(option, selectedRevision.CommitDate.ToString());
                        break;
                    case "{cTag}":
                        if (currentTags.Count == 1)
                            argument = argument.Replace(option, currentTags[0].Name);
                        else if (currentTags.Count != 0)
                            argument = argument.Replace(option, askToSpecify(currentTags, "Current Revision Tag"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cBranch}":
                        if (currentBranches.Count == 1)
                            argument = argument.Replace(option, currentBranches[0].Name);
                        else if (currentBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(currentBranches, "Current Revision Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cLocalBranch}":
                        if (currentLocalBranches.Count == 1)
                            argument = argument.Replace(option, currentLocalBranches[0].Name);
                        else if (currentLocalBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(currentLocalBranches,
                                                                     "Current Revision Local Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cRemoteBranch}":
                        if (currentRemoteBranches.Count == 1)
                            argument = argument.Replace(option, currentRemoteBranches[0].Name);
                        else if (currentRemoteBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(currentRemoteBranches,
                                                                     "Current Revision Remote Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cHash}":
                        argument = argument.Replace(option, currentRevision.Guid);
                        break;
                    case "{cMessage}":
                        argument = argument.Replace(option, currentRevision.Message);
                        break;
                    case "{cAuthor}":
                        argument = argument.Replace(option, currentRevision.Author);
                        break;
                    case "{cCommitter}":
                        argument = argument.Replace(option, currentRevision.Committer);
                        break;
                    case "{cAuthorDate}":
                        argument = argument.Replace(option, currentRevision.AuthorDate.ToString());
                        break;
                    case "{cCommitDate}":
                        argument = argument.Replace(option, currentRevision.CommitDate.ToString());
                        break;
                    case "{cDefaultRemote}":
                        if (string.IsNullOrEmpty(currentRemote))
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        argument = argument.Replace(option, currentRemote);
                        break;
                    case "{cDefaultRemoteUrl}":
                        if (string.IsNullOrEmpty(currentRemote))
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote));
                        argument = argument.Replace(option, url);
                        break;
                    case "{cDefaultRemotePathFromUrl}":
                        if (string.IsNullOrEmpty(currentRemote))
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote));
                        argument = argument.Replace(option, GetRemotePath(url));
                        break;
                    case "{UserInput}":
                        using (SimplePrompt Prompt = new SimplePrompt())
                        {
                            Prompt.ShowDialog();
                            argument = argument.Replace(option, Prompt.UserInput);
                        }
                        break;
                    case "{WorkingDir}":
                        argument = argument.Replace(option, aModule.WorkingDir);
                        break;
                }
            }
            command = ExpandCommandVariables(command,aModule);

            if (!scriptInfo.RunInBackground)
                FormProcess.ShowDialog(owner, command, argument, aModule.WorkingDir, null, true);
            else
            {
                if (originalCommand.Equals("{openurl}", StringComparison.CurrentCultureIgnoreCase))
                    Process.Start(argument);
                else
                    aModule.RunExternalCmdDetached(command, argument);
            }
            return !scriptInfo.RunInBackground;
        }
Пример #16
0
        private void btnSaveScript_Click(object sender, EventArgs e)
        {
            string scriptName = txtScriptName.Text;

            if (string.IsNullOrEmpty(scriptName))
            {
                MessageBox.Show("Script name can't be empty.", Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            ScriptInfo scriptInfo = Scripts.FirstOrDefault(x => x.Name.Equals(scriptName, StringComparison.InvariantCultureIgnoreCase));

            if (scriptInfo != null)
            {
                scriptInfo.Script = rtbInput.Text;
                scriptInfo.LineDelay = (int)nudLineDelay.Value;
            }
            else
            {
                scriptInfo = new ScriptInfo()
                {
                    Name = scriptName,
                    Script = rtbInput.Text,
                    LineDelay = (int)nudLineDelay.Value
                };
                Scripts.Add(scriptInfo);
                AddScript(scriptInfo);
            }
        }
Пример #17
0
 private void AddScript(ScriptInfo scriptInfo)
 {
     lvScripts.Items.Add(scriptInfo.Name).Tag = scriptInfo;
 }
Пример #18
0
        internal static void RunScript(IWin32Window owner, GitModule aModule, ScriptInfo scriptInfo, RevisionGrid revisionGrid)
        {
            string command = scriptInfo.Command;
            string argument = scriptInfo.Arguments;

            command = OverrideCommandWhenNecessary(command);

            GitRevision selectedRevision = null;
            GitRevision currentRevision = null;

            var selectedLocalBranches = new List<GitRef>();
            var selectedRemoteBranches = new List<GitRef>();
            var selectedRemotes = new List<string>();
            var selectedBranches = new List<GitRef>();
            var selectedTags = new List<GitRef>();
            var currentLocalBranches = new List<GitRef>();
            var currentRemoteBranches = new List<GitRef>();
            var currentRemote = "";
            var currentBranches = new List<GitRef>();
            var currentTags = new List<GitRef>();

            foreach (string option in Options)
            {
                if (string.IsNullOrEmpty(argument) || !argument.Contains(option))
                    continue;
                if (!option.StartsWith("{s") || selectedRevision != null)
                {
                    currentRevision = GetCurrentRevision(aModule, revisionGrid, currentTags, currentLocalBranches, currentRemoteBranches, currentBranches, currentRevision, option);

                    if (currentLocalBranches.Count == 1)
                        currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote", currentLocalBranches[0].Name));
                    else
                    {
                        currentRemote = aModule.GetCurrentRemote();
                        if (string.IsNullOrEmpty(currentRemote))
                            currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote",
                                askToSpecify(currentLocalBranches, "Current Revision Branch")));
                    }
                }
                else
                {
                    selectedRevision = CalculateSelectedRevision(revisionGrid, selectedRemoteBranches, selectedRemotes, selectedLocalBranches, selectedBranches, selectedTags);
                }

                string remote;
                string url;
                switch (option)
                {
                    case "{sTag}":
                        if (selectedTags.Count == 1)
                            argument = argument.Replace(option, selectedTags[0].Name);
                        else if (selectedTags.Count != 0)
                            argument = argument.Replace(option, askToSpecify(selectedTags, "Selected Revision Tag"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sBranch}":
                        if (selectedBranches.Count == 1)
                            argument = argument.Replace(option, selectedBranches[0].Name);
                        else if (selectedBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(selectedBranches, "Selected Revision Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sLocalBranch}":
                        if (selectedLocalBranches.Count == 1)
                            argument = argument.Replace(option, selectedLocalBranches[0].Name);
                        else if (selectedLocalBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(selectedLocalBranches,
                                                                     "Selected Revision Local Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sRemoteBranch}":
                        if (selectedRemoteBranches.Count == 1)
                            argument = argument.Replace(option, selectedRemoteBranches[0].Name);
                        else if (selectedRemoteBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(selectedRemoteBranches,
                                                                     "Selected Revision Remote Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{sRemote}":
                        if (selectedRemotes.Count == 0)
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        if (selectedRemotes.Count == 1)
                            remote = selectedRemotes[0];
                        else
                            remote = askToSpecify(selectedRemotes, "Selected Revision Remote");
                        argument = argument.Replace(option, remote);
                        break;
                    case "{sRemoteUrl}":
                        if (selectedRemotes.Count == 0)
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        if (selectedRemotes.Count == 1)
                            remote = selectedRemotes[0];
                        else
                            remote = askToSpecify(selectedRemotes, "Selected Revision Remote");
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote));
                        argument = argument.Replace(option, url);
                        break;
                    case "{sRemotePathFromUrl}":
                        if (selectedRemotes.Count == 0)
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        if (selectedRemotes.Count == 1)
                            remote = selectedRemotes[0];
                        else
                            remote = askToSpecify(selectedRemotes, "Selected Revision Remote");
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote));
                        argument = argument.Replace(option, GetRemotePath(url));
                        break;
                    case "{sHash}":
                        argument = argument.Replace(option, selectedRevision.Guid);
                        break;
                    case "{sMessage}":
                        argument = argument.Replace(option, selectedRevision.Message);
                        break;
                    case "{sAuthor}":
                        argument = argument.Replace(option, selectedRevision.Author);
                        break;
                    case "{sCommitter}":
                        argument = argument.Replace(option, selectedRevision.Committer);
                        break;
                    case "{sAuthorDate}":
                        argument = argument.Replace(option, selectedRevision.AuthorDate.ToString());
                        break;
                    case "{sCommitDate}":
                        argument = argument.Replace(option, selectedRevision.CommitDate.ToString());
                        break;
                    case "{cTag}":
                        if (currentTags.Count == 1)
                            argument = argument.Replace(option, currentTags[0].Name);
                        else if (currentTags.Count != 0)
                            argument = argument.Replace(option, askToSpecify(currentTags, "Current Revision Tag"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cBranch}":
                        if (currentBranches.Count == 1)
                            argument = argument.Replace(option, currentBranches[0].Name);
                        else if (currentBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(currentBranches, "Current Revision Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cLocalBranch}":
                        if (currentLocalBranches.Count == 1)
                            argument = argument.Replace(option, currentLocalBranches[0].Name);
                        else if (currentLocalBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(currentLocalBranches,
                                                                     "Current Revision Local Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cRemoteBranch}":
                        if (currentRemoteBranches.Count == 1)
                            argument = argument.Replace(option, currentRemoteBranches[0].Name);
                        else if (currentRemoteBranches.Count != 0)
                            argument = argument.Replace(option,
                                                        askToSpecify(currentRemoteBranches,
                                                                     "Current Revision Remote Branch"));
                        else
                            argument = argument.Replace(option, "");
                        break;
                    case "{cHash}":
                        argument = argument.Replace(option, currentRevision.Guid);
                        break;
                    case "{cMessage}":
                        argument = argument.Replace(option, currentRevision.Message);
                        break;
                    case "{cAuthor}":
                        argument = argument.Replace(option, currentRevision.Author);
                        break;
                    case "{cCommitter}":
                        argument = argument.Replace(option, currentRevision.Committer);
                        break;
                    case "{cAuthorDate}":
                        argument = argument.Replace(option, currentRevision.AuthorDate.ToString());
                        break;
                    case "{cCommitDate}":
                        argument = argument.Replace(option, currentRevision.CommitDate.ToString());
                        break;
                    case "{cDefaultRemote}":
                        if (string.IsNullOrEmpty(currentRemote))
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        argument = argument.Replace(option, currentRemote);
                        break;
                    case "{cDefaultRemoteUrl}":
                        if (string.IsNullOrEmpty(currentRemote))
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote));
                        argument = argument.Replace(option, url);
                        break;
                    case "{cDefaultRemotePathFromUrl}":
                        if (string.IsNullOrEmpty(currentRemote))
                        {
                            argument = argument.Replace(option, "");
                            break;
                        }
                        url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote));
                        argument = argument.Replace(option, GetRemotePath(url));
                        break;
                    case "{UserInput}":
                        using (SimplePrompt Prompt = new SimplePrompt())
                        {
                            Prompt.ShowDialog();
                            argument = argument.Replace(option, Prompt.UserInput);
                        }
                        break;
                }
            }

            if (scriptInfo.ShowProgress)
                FormProcess.ShowDialog(owner, command, argument, aModule.WorkingDir, null, true);
            else
                aModule.RunExternalCmdDetached(command, argument);
        }
Пример #19
0
 internal DlrScriptCommandProcessor(ScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState) : base(scriptInfo, context, useNewScope, sessionState)
 {
     this._input = new ArrayList();
     this.Init();
 }
Пример #20
0
 // HACK: all functions are currently stored as scripts. But I'm confused, so I don't know how to fix it.
 internal void SetFunction(/*FunctionInfo */ScriptInfo functionInfo)
 {
     this._scripts[functionInfo.Name] = functionInfo;
 }
Пример #21
0
 public void SystemInitialize(ScriptInfo info)
 {
     _info = info;
 }
        private void ParseNew(ScriptInfo script)
        {
            if (!_context.Scripts.ContainsKey(script.PrefixedFullName))
            {
                _context.Scripts.Add(script.PrefixedFullName, script);
            }

            _dependencyBuilder.Build(script);
            Parse(script);
        }
 private void Build(ScriptInfo script)
 {
     _staticSetter.Set(script);
     _returnValueCorrector.Correct(script.TypeDeclaration);
     _stringLocalizer.Localize(script.TypeDeclaration);
 }
        public void Parse(ScriptInfo script)
        {
            try
            {
                script.TypeDeclaration = _parser.Parse(script.Code);
            }
            catch (ParserException ex)
            {
                LogError(ex.Message);
                script.IsInvalid = true;
            }

            if (script.TypeDeclaration != null)
            {
                script.TypeDeclaration.Name = script.ClassName;
                CodeObjectMetaData.SetNamespaceName(script.TypeDeclaration, script.NamespaceName);

                _propertySetValueCorrector.Correct(script.TypeDeclaration);
                _propertyPartConsolidator.Consolidate(script.TypeDeclaration);
                _createObjectStrongTyper.Process(script.TypeDeclaration);
                _nestedClassConstructorCorrector.Process(script.TypeDeclaration);
                _identifierDiscoverer.Process(script.TypeDeclaration);
            }
        }
            public void GetItemInfo(
                string name,
                ScriptInfo returnMask,
                [Out] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.IUnknown)] object[] item,
                [Out] [MarshalAs(UnmanagedType.LPArray)] IntPtr[] typeInfo)
            {
                GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() name:" + ValidationHelper.ToString(name));
                if (name == null)
                {
                    throw new ArgumentNullException("name");
                }

                if (name != c_ScriptHelperName)
                {
                    throw new COMException(null, (int) HRESULT.TYPE_E_ELEMENTNOTFOUND);
                }

                if ((returnMask & ScriptInfo.IUnknown) != 0)
                {
                    if (item == null)
                    {
                        throw new ArgumentNullException("item");
                    }

                    GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() Setting item.");
                    item[0] = helper;
                }

                if ((returnMask & ScriptInfo.ITypeInfo) != 0)
                {
                    if (typeInfo == null)
                    {
                        throw new ArgumentNullException("typeInfo");
                    }

                    typeInfo[0] = IntPtr.Zero;
                }

                GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() Done.");
            }
        //////////////////////////////////////////////////////////////////////////
        private void OnIntegrate(object sender, EventArgs e)
        {
            string ScitePath = Path.Combine(WmeUtils.ToolsPath, "scite");
            if (!Directory.Exists(ScitePath)) Directory.CreateDirectory(ScitePath);

            string[] Extensions = ParentForm.GetExtensions();
            string Extensions2 = "";
            foreach (string Ext in Extensions)
            {
                if (Extensions2 != "") Extensions2 += ";";
                Extensions2 += "*." + Ext;
            }

            // generate syntax file
            try
            {
                // read XML docs
                ScriptInfo Info = new ScriptInfo();
                Info.ReadXml(WmeUtils.XmlDocsPath);

                string KwdFile = Path.Combine(ScitePath, "wme_kwd.properties");

                using (StreamWriter sw = new StreamWriter(KwdFile, false, Encoding.Default))
                {
                    sw.WriteLine(FileHeader);

                    sw.WriteLine("file.patterns.script=" + Extensions2);
                    sw.WriteLine("filter.script=WME Scripts|$(file.patterns.script)|");
                    sw.WriteLine();

                    WordHolder wh;

                    // keywords
                    sw.WriteLine("keywords.$(file.patterns.script)=\\");
                    wh = new WordHolder();
                    foreach (string Keyword in ScriptTokenizer.Keywords)
                    {
                        wh.AddWord(Keyword);
                    }
                    sw.WriteLine(wh.GetWords());

                    // methods
                    sw.WriteLine("keywords2.$(file.patterns.script)=\\");
                    wh = new WordHolder();
                    foreach (ScriptObject Obj in Info.Objects)
                    {
                        foreach (ScriptMethod Method in Obj.Methods)
                        {
                            foreach (string Header in Method.Headers)
                            {
                                int Brace = Header.IndexOf("(");
                                if (Brace >= 0)
                                {
                                    wh.AddWord(Header.Substring(0, Brace).Trim());
                                }
                            }
                        }
                    }
                    sw.WriteLine(wh.GetWords());

                    // attributes
                    sw.WriteLine("keywords4.$(file.patterns.script)=\\");
                    wh = new WordHolder();
                    foreach (ScriptObject Obj in Info.Objects)
                    {
                        foreach (ScriptAttribute Attr in Obj.Attributes)
                        {
                            if (Attr.Name.StartsWith("[")) continue;
                            wh.AddWord(Attr.Name);
                        }
                    }
                    sw.WriteLine(wh.GetWords());
                }

                // tools
                string ToolsFile = Path.Combine(ScitePath, "wme_tools.properties");

                using (StreamWriter sw = new StreamWriter(ToolsFile, false, Encoding.Default))
                {
                    sw.WriteLine(FileHeader);

                    sw.WriteLine("command.compile.$(file.patterns.script)=\"" + WmeUtils.CompilerPath + "\" -script \"$(FilePath)\" -format scite");
                    sw.WriteLine("command.help.$(file.patterns.script)=reference!" + Path.Combine(WmeUtils.ToolsPath, "wme.chm"));
                    sw.WriteLine("command.help.subsystem.$(file.patterns.script)=4");
                    sw.WriteLine("api.$(file.patterns.script)=" + Path.Combine(WmeUtils.ToolsPath, "SciTE\\wme.api"));
                }

                // api
                string ApiFile = Path.Combine(ScitePath, "wme.api");

                using (StreamWriter sw = new StreamWriter(ApiFile, false, Encoding.Default))
                {
                    WordHolder wh;

                    wh = new WordHolder();
                    foreach (ScriptObject Obj in Info.Objects)
                    {
                        foreach (ScriptMethod Method in Obj.Methods)
                        {
                            foreach (string Header in Method.Headers)
                            {
                                wh.AddWord(Header + Method.Desc);
                            }
                        }
                    }
                    foreach (ScriptObject Obj in Info.Objects)
                    {
                        foreach (ScriptAttribute Attr in Obj.Attributes)
                        {
                            if (Attr.Name.StartsWith("[")) continue;
                            wh.AddWord(Attr.Name);
                        }
                    }

                    sw.WriteLine(wh.GetWordsApi());
                }

            }
            catch
            {
            }
        }
Пример #27
0
        public CommandProcessorBase CreateCommandProcessor(Command command)
        {
            string cmdName = command.CommandText;

            CommandInfo commandInfo = null;

            if (command.IsScript)
            {
                // TODO: take care of the script commands
                throw new NotImplementedException(this.ToString());
            }

            if (commandInfo == null && _aliases.ContainsKey(cmdName))
            {
                commandInfo = _aliases[cmdName].ReferencedCommand;
            }

            if (commandInfo == null && _cmdLets.ContainsKey(cmdName))
            {
                commandInfo = _cmdLets[cmdName].First();
            }

            if (commandInfo == null && _scripts.ContainsKey(cmdName))
            {
                commandInfo = _scripts[cmdName];
            }

            // TODO: if the command wasn't found should we treat is as a Script?
            if (commandInfo == null)
            {
                var parseTree = PowerShellGrammar.ParseInteractiveInput(command.CommandText);
                var statements = parseTree.EndBlock.Statements;
                if (statements.Count == 1 && statements.Single() is PipelineAst)
                {
                    var pipelineAst = statements.Single() as PipelineAst;
                    if (pipelineAst.PipelineElements.Count == 1 && pipelineAst.PipelineElements.Single() is CommandAst)
                    {
                        var commandAst = pipelineAst.PipelineElements.Single() as CommandAst;
                        if (commandAst.CommandElements.Count == 1 && commandAst.CommandElements.Single() is StringConstantExpressionAst)
                        {
                            var stringAst = commandAst.CommandElements.Single() as StringConstantExpressionAst;

                            if (File.Exists(stringAst.Value) && Path.GetExtension(stringAst.Value) == ".ps1")
                            {
                                // I think we should be using a ScriptFile parser, but this will do for now.
                                commandInfo = new ScriptInfo(stringAst.Value, new ScriptBlock(PowerShellGrammar.ParseInteractiveInput(File.ReadAllText(stringAst.Value))));
                            }

                            else
                            {
                                throw new Exception(string.Format("Command '{0}' not found.", cmdName));
                            }
                        }
                    }
                }

                if (commandInfo == null)
                    commandInfo = new ScriptInfo("", new ScriptBlock(parseTree));
            }

            if (commandInfo != null)
            {
                switch (commandInfo.CommandType)
                {
                    case CommandTypes.Cmdlet:
                        return new CommandProcessor(commandInfo as CmdletInfo);

                    case CommandTypes.Function:
                        // TODO: teat the function as a script
                        break;

                    case CommandTypes.Script:
                        return new ScriptProcessor(commandInfo as ScriptInfo);
                }
            }

            throw new Exception(string.Format("Command '{0}' not found.", cmdName));
        }
Пример #28
0
        private static void AddDefaultScripts()
        {
            ScriptInfo fetchAfterCommitScript = new ScriptInfo();
            fetchAfterCommitScript.HotkeyCommandIdentifier = 9000;
            fetchAfterCommitScript.Name = "Fetch changes after commit";
            fetchAfterCommitScript.Command = "git";
            fetchAfterCommitScript.Arguments = "fetch";
            fetchAfterCommitScript.AskConfirmation = true;
            fetchAfterCommitScript.OnEvent = ScriptEvent.AfterCommit;
            fetchAfterCommitScript.AddToRevisionGridContextMenu = false;
            fetchAfterCommitScript.Enabled = false;
            Scripts.Add(fetchAfterCommitScript);

            ScriptInfo updateSubmodulesAfterPullScript = new ScriptInfo();
            updateSubmodulesAfterPullScript.HotkeyCommandIdentifier = 9001;
            updateSubmodulesAfterPullScript.Name = "Update submodules after pull";
            updateSubmodulesAfterPullScript.Command = "git";
            updateSubmodulesAfterPullScript.Arguments = "submodule update";
            updateSubmodulesAfterPullScript.AskConfirmation = true;
            updateSubmodulesAfterPullScript.OnEvent = ScriptEvent.AfterPull;
            updateSubmodulesAfterPullScript.AddToRevisionGridContextMenu = false;
            updateSubmodulesAfterPullScript.Enabled = false;
            Scripts.Add(updateSubmodulesAfterPullScript);

            ScriptInfo userMenuScript = new ScriptInfo();
            userMenuScript.HotkeyCommandIdentifier = 9002;
            userMenuScript.Name = "Example";
            userMenuScript.Command = "c:\\windows\\system32\\calc.exe";
            userMenuScript.Arguments = "";
            userMenuScript.AskConfirmation = false;
            userMenuScript.OnEvent = ScriptEvent.ShowInUserMenuBar;
            userMenuScript.AddToRevisionGridContextMenu = false;
            userMenuScript.Enabled = false;
            Scripts.Add(userMenuScript);
        }
        private void Persist(ScriptInfo script)
        {
            _assemblyReferenceGatherer.Gather(script.TypeDeclaration);

            CodeGeneratorOptions generatorOptions = new CodeGeneratorOptions();
            generatorOptions.VerbatimOrder = true;
            string nameSpacePrefix = (string.IsNullOrEmpty(_context.Settings.Namespace)
                                          ? null
                                          : _context.Settings.Namespace + ".");
            CodeNamespace nameSpace = new CodeNamespace(nameSpacePrefix + script.NamespaceName);
            nameSpace.Types.Add(script.TypeDeclaration);
            _namespaceFactorizer.Factorize(nameSpace);
            string outputDirectory = (string.IsNullOrEmpty(_context.Settings.OutputDirectory)
                                          ? script.NamespaceName
                                          : Path.Combine(_context.Settings.OutputDirectory, script.NamespaceName));

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            string fileName = string.Format("{0}.{1}", script.ClassName, _context.CodeProvider.FileExtension);

            using (TextWriter writer = new StreamWriter(Path.Combine(outputDirectory, fileName)))
            {
                _context.CodeProvider.GenerateCodeFromNamespace(nameSpace, writer, generatorOptions);
            }
        }
Пример #30
0
        private static void DeserializeFromOldFormat(string inputString)
        {
            const string PARAM_SEPARATOR = "<_PARAM_SEPARATOR_>";
            const string SCRIPT_SEPARATOR = "<_SCRIPT_SEPARATOR_>";

            if (inputString.Contains(PARAM_SEPARATOR) || inputString.Contains(SCRIPT_SEPARATOR))
            {
                Scripts = new BindingList<ScriptInfo>();

                string[] scripts = inputString.Split(new string[] { SCRIPT_SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < scripts.Length; i++)
                {
                    string[] parameters = scripts[i].Split(new string[] { PARAM_SEPARATOR }, StringSplitOptions.None);

                    ScriptInfo scriptInfo = new ScriptInfo();
                    scriptInfo.Name = parameters[0];
                    scriptInfo.Command = parameters[1];
                    scriptInfo.Arguments = parameters[2];
                    scriptInfo.AddToRevisionGridContextMenu = parameters[3].Equals("yes");
                    scriptInfo.Enabled = true;

                    Scripts.Add(scriptInfo);
                }
            }
        }